<?php

namespace App\Classes\Modules\Companies\ControllersLogic;


use App\Classes\ValueObjects\Constants\TransactionType;
use ZipArchive;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Support\Facades\File;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Company;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class BulkDownloadCustomerInvoicesLogic
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function execute(Request $request)
    {
        try {
            $company = Company::where('reference', $request->input('marking'))->first();

            if (!$company) {
                return response()->json([
                    'status' => 'Failed',
                    'message' => 'Customer not found.',
                ]);
            }

            $startDate = Carbon::createFromFormat('d-m-Y', $request->input('startDate'))->startOfDay();
            $endDate = Carbon::createFromFormat('d-m-Y', $request->input('endDate'))->endOfDay();

            $invoicebookings = $company->bookings()
                ->whereDate('created_at', '>=', $startDate)
                ->whereDate('created_at', '<=', $endDate)
                ->whereHas('transactions', function ($query) {
                    $query->where('transactions.type', TransactionType::INVOICE)
                        ->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
                })
                ->orderBy('created_at')
                ->get();

            if ($invoicebookings->isEmpty()) {
                return response()->json([
                    'status' => 'Failed',
                    'message' => 'No invoices found for this customer in the given date range.',
                ]);
            }

            $zipDirectory = storage_path('app/bulk_invoice'); // Update this with the actual directory path

            if (!file_exists($zipDirectory)) {
                mkdir($zipDirectory, 0755, true);
            }

            $filesystemDriver = Storage::getDefaultDriver();
            if($filesystemDriver === 's3'){
                $startDate = $startDate->format('d-m-Y');
                $endDate = $endDate->format('d-m-Y');
                $zipFileName = "invoices_{$startDate}_to_{$endDate}_{$company->reference}.zip";
                $zip_file = "{$zipDirectory}/{$zipFileName}";

                $zip = new ZipArchive();
                if ($zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
                    foreach ($invoicebookings as $booking) {
                        $invoice_file = $booking->documents()->where('document_type', DocumentType::INVOICE)->whereNull('deleted_at')->first()->files()->first();
                        $fileContent = Storage::disk('s3')->get($invoice_file->file->file_info->original->file);
                        $zip->addFromString('invoice-' . $booking->created_at->format('d_m_Y') . '_' . $booking->marking . '.pdf', $fileContent);
                    }
                    $zip->close();

                    $filePathForS3 = 'bulk_invoice/'.$zipFileName;
                    Storage::disk('s3')->put($filePathForS3, file_get_contents($zip_file));

                    Log::info('BulkDownloadCustomerInvoicesLogic finished processing files to zip count: '.count($invoicebookings));

                    $temporaryUrl = Storage::disk('s3')->temporaryUrl(
                        $filePathForS3,
                        Carbon::now()->addMinutes(10)
                    );

                    return response(['src' =>  $temporaryUrl ]);

                } else {
                    return response()->json([
                        'status' => 'Error',
                        'message' => 'Failed to create the Zip archive.',
                    ]);
                }
            }
            else{
                $zip_file = "{$zipDirectory}/invoices_{$request->input('startDate')}_to_{$request->input('endDate')}_{$company->reference}.zip";

                $zip = new ZipArchive();
                if ($zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
                    foreach ($invoicebookings as $booking) {
                        $invoice_file = $booking->documents()->where('document_type', DocumentType::INVOICE)->whereNull('deleted_at')->first()->files()->first();
                        $zip->addFile(Storage::disk('documents')->path($invoice_file->file->file_info->original->file), 'invoice-' . $booking->created_at->format('d_m_Y') . '_' . $booking->marking . '.pdf');
                    }

                    $zip->close();

                    while (ob_get_level()) {
                        ob_end_clean();
                    }

                    return response()->download($zip_file);
                } else {
                    return response()->json([
                        'status' => 'Error',
                        'message' => 'Failed to create the Zip archive.',
                    ]);
                }
            }
        } catch (\Exception $e) {
            // Log the exception for debugging
            Log::error('Error in BulkDownloadCustomerInvoicesLogic: ' . $e->getMessage());

            return response()->json([
                'status' => 'Error',
                'message' => 'An error occurred while processing the request.',
            ]);
        }
    }
}
