<?php

namespace App\Service;

use App\Models\Event;
use App\Models\Booking;
use App\Http\Controllers\DownloadsMultipleController;
use Illuminate\Support\Facades\Storage;
/* From the DownloadsController */
class TicketPdfGenerator
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // language change
        $this->event     = new Event;
        $this->booking   = new Booking;

    }
    
    /**
     * Show my booking
     *
     * @return array
     */
    public function generateTicketPdf($id = NULL, $order_number = NULL)
    {
        $id             = (int) $id;
        $order_number   = trim($order_number);
        
        // get the booking
        $booking = $this->booking->get_event_bookings(['id'=>$id, 'order_number'=>$order_number]);
        if(empty($booking))
            return false;
        
        $booking = $booking[0];
        
        // generate QrCode
        $qrcode_data = [
            'id'            => $booking['id'],
            'order_number'  => $booking['order_number'],
        ];
        $this->createQrcode($booking, $qrcode_data);

        // get event data for ticket pdf
        $event      = $this->event->get_event(null, $booking['event_id']);
        $currency   = setting('regional.currency_default');
        
        // generate PDF
        // test PDF
        // $img_path = '';
        // return Eventmie::view('eventmie::tickets.pdf', compact('booking', 'event', 'currency', 'img_path'));
        $img_path = str_replace('https://', 'http://', url(''));

        $pdf_html   = (string) \View::make('vendor.eventmie-pro.tickets.pdf', compact('booking', 'event', 'currency', 'img_path'));

        $pdf_name   = $booking['id'].'-'.$booking['order_number'];
        $this->generatePdf($pdf_html, $pdf_name, $booking);
        
        // download PDF
        $path           = '/storage/ticketpdfs/'.$booking['customer_id'];
        $pdf_file    = public_path().$path.'/'.$booking['id'].'-'.$booking['order_number'].'.pdf';
        if (!\File::exists($pdf_file))
            return false;
        
        return  $pdf_file;
        
    }

    /**
     * Generate multiple tickets in a single PDF file
     * 
     * @param array $booking_data Array of booking data
     * @return string|false Path to the generated PDF file or false on failure
     */
    // public function generateMultipleTicketsPdf($booking_data)
    public function generateAllTicketsPdf($id = NULL, $common_order = NULL)
    {   
        $id             = (int) $id;
        $order_number   = trim($common_order);

        // Get the first booking to get common data
        $booking = $this->booking->get_event_multiple_bookings(['common_order'=>$common_order]);

        
        // generate QrCode
        $qrcode_data = [
            'common_order'  => $booking[0]['common_order'],
        ];

        

        // Generate QR codes for all tickets
        $all_downloads = new DownloadsMultipleController;
        $all_downloads->createQrcode($booking, $qrcode_data);

        // get event data for ticket pdf
        $event      = $this->event->get_event(null, $booking[0]['event_id']);
        $currency   = setting('regional.currency_default');


        
        if(!empty($event->currency)){
            $currency   = $event->currency;
        }  
        
        // Get ticket data
        $ticket = $booking->pluck('ticket');


        $img_path = str_replace('https://', 'http://', url(''));

        $bookings = $booking;

        // Generate PDF using multiple tickets template
        $pdf_html = (string) \View::make('vendor.eventmie-pro.tickets.multiple_pdf', compact('bookings', 'event', 'currency', 'img_path', 'ticket'));
        
        $pdf_name   = $booking[0]['id'].'-'.$booking[0]['common_order'];
        $all_downloads->generatePdf($pdf_html, $pdf_name, $booking);
        
        // Get the generated PDF file path
        $path           = '/storage/ticketpdfs/'.$booking[0]['customer_id'];
        $pdf_file    = public_path().$path.'/'.$booking[0]['id'].'-'.$booking[0]['common_order'].'-all.pdf';
        
        return $pdf_file;
    }

    protected function createQrcode($data = [], $qrcode_data = [])
    {
        try {
            $storageDisk = getDisk(); // Get current storage disk
            $qrcodeFilename = $data['id'] . '-' . $data['order_number'] . '.png';
            $relativePath = 'qrcodes/' . $data['customer_id'] . '/' . $qrcodeFilename;

            if (getDisk() == 's3') {
                // Generate QR code in memory
                $qrCodeContent = \QrCode::format('png')->size(256)->generate(json_encode($qrcode_data));
                // Store in S3
                Storage::disk('s3')->put($relativePath, $qrCodeContent, 'public');
            } else {
                $localPath = public_path('/storage/' . $relativePath);

                // Ensure directory exists
                $dirPath = dirname($localPath);
                if (!\File::exists($dirPath)) {
                    \File::makeDirectory($dirPath, 0755, true);
                }

                // Always regenerate qrcode
                \QrCode::format('png')->size(256)->generate(json_encode($qrcode_data), $localPath);

                return \File::exists($localPath);
            }
        } catch (\Exception $e) {
            \Log::error('QR Code Generation Failed: ' . $e->getMessage());
        }

        return true;
    }

    /**
     *  generate pdf
     */
    protected function generatePdf($html = null, $pdf_name = null, $data = [])
    {
        $path           = '/storage/ticketpdfs/'.$data['customer_id'];

        // first check if directory exists or not
        if (! \File::exists(public_path().$path))
            \File::makeDirectory(public_path().$path, 0755, true);

        $pdf_file    = public_path().$path.'/'.$data['id'].'-'.$data['order_number'].'.pdf';
        
        // start PDF generation

        // remove white spaces and comments
        $html =  preg_replace('/>\s+</', '><', $html);
        if(empty($html))
            return false;

        $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');

        $options = [
            'defaultFont' => 'sans-serif',
            'isRemoteEnabled' => TRUE,
            'isJavascriptEnabled' => FALSE,
            'debugKeepTemp' => TRUE,
            'isHtml5ParserEnabled' => TRUE,
            'enable_html5_parser' => TRUE,
        ];
        \PDF::setOptions($options)
        ->loadHTML($html)
        ->setWarnings(false)
        // Standard ticket size: 5.5" × 2.125" (396 × 153 points) - optimal for both print and digital
        ->setPaper([0, 0, 396, 153], 'landscape')
        ->save($pdf_file);
        
        return TRUE;
    } 


}
