<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Classiebit\Eventmie\Http\Controllers\DownloadsController as BaseDownloadsController;
use Auth;
use App\Models\Booking;
use Classiebit\Eventmie\Scopes\BulkScope;
use App\Http\Controllers\InvoicesController;
use App\Models\User;
use ZipArchive;
use Illuminate\Support\Arr;
use App\Models\Event;

class DownloadsMultipleController extends Controller
{

    public function __construct()
    {   
        $this->booking = new Booking;
        $this->event = new Event;
    }

     /**
     * Show my booking
     *
     * @return array
     */
    public function index($id = NULL, $common_order = NULL)
    {

        
        if(!empty(setting('booking.hide_ticket_download')) &&(Auth::user()->hasRole('organiser') || Auth::user()->hasRole('customer')))
            abort('404');
            
        $id             = (int) $id;
        $common_order   = trim($common_order);

        // get the booking
        //CUSTOM
        if(!Auth::user()->hasRole('admin'))
        {
            $bookings = $this->booking->get_event_multiple_bookings(['common_order'=>$common_order]);
        }
        
        
        //CUSTOM
        if(empty($bookings))
            abort('404');


        // customer can see only their bookings
        if(Auth::user()->hasRole('customer'))
            if($bookings[0]['customer_id'] != Auth::id())
                abort('404');

        // organiser can see only their events bookings
        if(Auth::user()->hasRole('organiser'))
            if($bookings[0]['organiser_id'] != Auth::id())
                abort('404');

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

        //CUSTOM
        if(!empty($event->currency)){
            $currency   = $event->currency;
        }  
        //CUSTOM
        
       
        // use http url only
        $img_path   = str_replace('https://', 'http://', url(''));
        
        $ticket = \App\Models\Ticket::whereIn('id', Arr::pluck($bookings, 'ticket_id'))->get();
        
        // generate PDF
        // test PDF
        // $img_path = '';
        // return view('vendor.eventmie-pro.tickets.multiple_pdf', compact('bookings', 'event', 'currency', 'img_path', 'ticket'));

        // production
        $pdf_html   = (string) \View::make('vendor.eventmie-pro.tickets.multiple_pdf', compact('bookings', 'event', 'currency', 'img_path', 'ticket'));
        
        $pdf_name   = $bookings[0]['id'].'-'.$bookings[0]['common_order'];
        
        $this->generatePdf($pdf_html, $pdf_name, $bookings);
        
        // download PDF
        $path           = '/storage/ticketpdfs/'.$bookings[0]['customer_id'];
        $pdf_file    = public_path().$path.'/'.$bookings[0]['id'].'-'.$bookings[0]['common_order'].'-all.pdf';

        if (!\File::exists($pdf_file))
            abort('404');

        return response()->download($pdf_file);
        
    }


    public function createQrcode($data = [], $qrcode_data = [])
    {
        
        foreach($data as $item)
        {
            $qrcode_data = [
                'id'            => $item['id'],
                'order_number'  => $item['order_number'],
            ];
            
            $path           = '/storage/qrcodes/'.$item['customer_id'];
            // first check if directory exists or not
            if (! \File::exists(public_path().$path))
                \File::makeDirectory(public_path().$path, 0755, true);
        
            $qrcode_file    = public_path().$path.'/'.$qrcode_data['id'].'-'.$qrcode_data['order_number'].'.png';

            // generate QrCode
            \QrCode::format('png')->size(256)->generate(json_encode($qrcode_data), $qrcode_file);
        
        }

        return TRUE;        
    }


    /**
     *  generate pdf
     */
    public function generatePdf($html = null, $pdf_name = null, $data = [])
    {

        $path           = '/storage/ticketpdfs/'.$data[0]['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[0]['id'].'-'.$data[0]['common_order'].'-all.pdf';

        // 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;
    } 
    
}
