<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Attachment;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use ZipArchive;

class AttachmentController extends Controller
{
    public function getAttachmentsByStock(Request $request)
    {
        $attachments = Attachment::where('stocktransaction_id', $request->id)->get();

        if ($attachments->isEmpty()) {
            return response([
                'success' => false,
                'message' => "No attachments found for the given stocktransaction_id.",
            ], 404);
        }

        $attachments = $attachments->map(function ($attachment) {
            $filePath = storage_path('app/' . $attachment->file_name);

            if (file_exists($filePath)) {
                $fileData = file_get_contents($filePath);
                $base64Image = 'data:image/' . pathinfo($filePath, PATHINFO_EXTENSION) . ';base64,' . base64_encode($fileData);
                $attachment->file_base64 = $base64Image;
            } else {
                $attachment->file_base64 = null;
            }

            return $attachment;
        });

        return response([
            'success' => true,
            'message' => "Attachments retrieved successfully.",
            'attachments' => $attachments,
        ], 200);
    }
    
    public function getAttachmentsByCash(Request $request)
    {
        $attachments = Attachment::where('cashtransaction_id', $request->id)->get();

        if ($attachments->isEmpty()) {
            return response([
                'success' => false,
                'message' => "No attachments found for the given cashtransaction_id.",
            ], 404);
        }

        $attachments = $attachments->map(function ($attachment) {
            $filePath = storage_path('app/' . $attachment->file_name);

            if (file_exists($filePath)) {
                $fileData = file_get_contents($filePath);
                $base64Image = 'data:image/' . pathinfo($filePath, PATHINFO_EXTENSION) . ';base64,' . base64_encode($fileData);
                $attachment->file_base64 = $base64Image;
            } else {
                $attachment->file_base64 = null;
            }

            return $attachment;
        });

        return response([
            'success' => true,
            'message' => "Attachments retrieved successfully.",
            'attachments' => $attachments,
        ], 200);
    }

    public function createAttachment(Request $request)
    {
        $request->validate([
            'file_name' => 'required|file',
            'cashtransaction_id' => 'nullable',
            'stocktransaction_id' => 'nullable',
        ]);
    
        if ($request->hasFile('file_name')) {
            $file = new Attachment();
            $file->file_name = '';
            $file->cashtransaction_id = $request->cashtransaction_id;
            $file->stocktransaction_id = $request->stocktransaction_id;
            $file->save();

            $uniqueName = 'attachment-' . $file->id . '.' . $request->file('file_name')->getClientOriginalExtension();
            $path = Storage::putFileAs('attachment', $request->file('file_name'), $uniqueName);
    
            $file->file_name = $path;
            $file->save();
    
            $response = [
                'success' => true,
                'message' => "done",
                'attachment' => $file
            ];
    
            return response($response, 200);
        } else {
            $response = [
                'success' => false,
                'message' => "Silahkan upload file_name",
            ];
            return response($response, 400);
        }
    }

    public function updateAttachment(Request $request)
    {
        $request->validate([
            'file_name' => 'required|file',
        ]);

        $file = Attachment::find($request->id);

        if (!$file) {
            return response([
                'success' => false,
                'message' => "Attachment not found",
            ], 404);
        }

        if (Storage::exists($file->file_name)) {
            Storage::delete($file->file_name);
        }

        $uniqueName = 'attachment-' . $file->id . '.' . $request->file('file_name')->getClientOriginalExtension();
        $path = Storage::putFileAs('attachment', $request->file('file_name'), $uniqueName);

        $file->file_name = $path;
        $file->save();

        $response = [
            'success' => true,
            'message' => "Attachment updated successfully",
            'attachment' => $file,
        ];

        return response($response, 200);
    }
    
    public function downloadAttachment(Request $request)
    {
        $file = Attachment::find($request->id);

        if (!$file) {
            return response([
                'success' => false,
                'message' => "Attachment not found",
            ], 404);
        }

        $filePath = storage_path('app/' . $file->file_name);

        if (Storage::disk('local')->exists($file->file_name)) {
            $fileName = basename($file->file_name);
            return response()->download($filePath, $fileName, [
                'Content-Type' => mime_content_type($filePath),
                'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
            ]);
        }

        return response([
            'success' => false,
            'message' => 'File not found.',
        ], 404);
    }

    public function downloadAllAttachments()
    {
        // Check if there are any files in the attachment folder
        $files = Storage::allFiles('attachment');
        
        if (empty($files)) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada file yang tersedia untuk didownload.',
            ], 404);
        }

        // Nama file zip yang akan dihasilkan
        $zipFileName = 'attachments_' . date('Y-m-d_H-i-s') . '.zip';
        $zipFilePath = storage_path('app/' . $zipFileName);

        // Inisialisasi objek ZipArchive
        $zip = new ZipArchive;

        try {
            // Buat file zip
            if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                // Tambahkan setiap file ke dalam zip
                foreach ($files as $file) {
                    $filePath = storage_path('app/' . $file);
                    if (file_exists($filePath)) {
                        // Gunakan nama file relatif di dalam zip
                        $zip->addFile($filePath, basename($file));
                    }
                }

                // Tutup file zip
                $zip->close();

                // Periksa apakah file zip berhasil dibuat
                if (!file_exists($zipFilePath)) {
                    throw new \Exception('Gagal membuat file zip.');
                }

                // Kembalikan respons API dengan file zip
                return response()->download($zipFilePath, $zipFileName, [
                    'Content-Type' => 'application/zip',
                    'Content-Disposition' => 'attachment; filename="' . $zipFileName . '"',
                ])->deleteFileAfterSend(true);
            }

            throw new \Exception('Gagal membuat file zip.');
        } catch (\Exception $e) {
            // Hapus file zip jika ada error
            if (file_exists($zipFilePath)) {
                unlink($zipFilePath);
            }

            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function deleteAttachment($id)
    {
        $file = Attachment::find($id);

        if (!$file) {
            return response([
                'success' => false,
                'message' => 'Attachment not found',
            ], 404);
        }

        if (Storage::exists($file->file_name)) {
            Storage::delete($file->file_name);
        }

        $file->delete();

        $response = [
            'success' => true,
            'message' => 'Attachment deleted successfully',
        ];

        return response($response, 200);
    }
}
