<?php

namespace App\Jobs;

use App\Mail\BulkPdfMail;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use App\Helpers\GeneralHelper;
use ZipArchive;

class PharmacyBulkPdf implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $bulk_report;
    protected $userEmail;


    public $tries = 5;
    public $timeout = 1200;
    public function __construct($bulk_report, $userEmail)
    {
        $this->bulk_report = $bulk_report;
        $this->userEmail = $userEmail;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $zip = new ZipArchive;
        $zipFileName = 'pharmacy_bulk_reports_' . time() . '.zip';
        $zipFilePath = Storage::path($zipFileName);
        $pdfFilePaths = [];

        if ($zip->open($zipFilePath, ZipArchive::CREATE) === TRUE) {

                foreach ($this->bulk_report as $index => $report) {
                    $reportArray = json_decode(json_encode($report), true);
                    // Generate PDF File
                    $pdf = Pdf::loadView('services.pharmacy.single-report-pdf', ['single_reports' => array($reportArray)]);
                    $cptcode = $report->{'NDC Number'};
                    $pdfFileName = "ndc_".$cptcode."_"."report".$index.'.pdf';
                    $pdfFilePath = Storage::path($pdfFileName);
                    Storage::put($pdfFileName, $pdf->output());
                    $zip->addFile($pdfFilePath, $pdfFileName);
                    $pdfFilePaths[] = $pdfFilePath;

                }


            $zip->close();
        }


        Mail::to($this->userEmail)->send(new BulkPdfMail($zipFilePath));

        //delete zip file
        unlink($zipFilePath);

        // Delete the PDF files
        foreach ($pdfFilePaths as $pdfFilePath) {
            unlink($pdfFilePath);
        }
    }
}
