<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;


use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Support\Facades\File;
use ZipArchive;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\ValueObjects\Constants\ApprovalStatus;

class DownloadBookingDocumentLogic
{


    /**
     * @param Request $request
     * @return void
     * @throws MalformedRequestException
     */
    public function execute(Request $request)
    {

        Auth::login(User::findOrFail(1));
        $zip_file = $request->input('type').'.zip';
        $attachment = storage_path().'/app/documents/collections/' . $zip_file;

        $zip = new ZipArchive();
        if ($zip->open($attachment, ZIPARCHIVE::CREATE | ZipArchive::OVERWRITE)) {

            $bookings = Booking::where('status', ApprovalStatus::COMPLETED)
                ->whereDate('created_at', '>=', Carbon::parse($request->input('startDate')))
                ->whereDate('created_at', '<=', Carbon::parse($request->input('endDate')))->whereHas('transactions', function ($query) use ($request){
                    return $query->where('type', TransactionType::PAYMENT)->whereHas('transactions', function ($query) use ($request){
                        return $query->where('type', TransactionType::BILL)->where('issuer', $request->input('supplier'));
                    });
                })->get();

            if (!count($bookings)) throw new MalformedRequestException('No available file to download');

            foreach ($bookings as $booking) {
                $file = $booking->documents()->where('document_type', $request->input('type'))->first()->files()->first();
                $zip->addFile(Storage::disk('documents')->path($file->file->file_info->original->file), $booking->created_at->format('d_m_Y') . '_' . $booking->marking . '.pdf');
            }

            $zip->close();
            while (ob_get_level()) {
                ob_end_clean();
            }
            ob_start();
            header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");
            header("Content-Length: " . filesize($attachment));
            header('Pragma: no-cache');
            header("Content-Disposition: attachment; filename=\"" . basename($attachment) . "\"");
            ob_flush();
            ob_clean();

            readfile($attachment);
            File::delete($attachment);

            exit;

//            header('Content-Type: application/zip');
//            header('Content-Length: ' . filesize($attachment));
//            readfile($attachment);
//            unlink($attachment);

        }
    }
}
