<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Settings\Organisation;
use Session;
use Auth;
use DB;
use PDF;

use App\Models\Facility\Facility;
use App\Models\Facility\Rates;
use App\Models\Facility\Layout;
use App\Models\Facility\Seats;
use App\Models\Facility\ShowTimings;
use App\Models\Sales\Invoice;
use App\Models\Sales\Transaction;
use App\Models\Sales\Ticket;
use App\Models\Sales\TicketSeat;
use App\Models\Sales\PaymentMethod;
use App\Models\Sales\PaymentType;
use App\Models\Sales\Refund;
use App\Models\Sales\CancelTicket;
use App\Models\Sales\ShowCancel;
use App\Helpers\BookingClass;
use App\Helpers\SMSClass;
use App\Models\Settings\HolidayMaster;
use App\Models\Settings\WeeklyOffMaster;
use App\Models\Settings\Configuration;
use App\Models\Settings\CancelConfiguration;
use App\Models\Mail\MailTicket;
use App\Mail\TicketMail;
use App\Models\PublicUser;


class PublicController extends Controller
{
    public function index()
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;


        //get organisations
        $organisations = Organisation::all();

        $configration = Configuration::first();
        if(isset($configration))
        {
            $ticket_booking_max_days = $configration->ticket_booking_max_days;
        }

        
        
        return view('tickets.index', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','organisations','ticket_booking_max_days'));
    }

    public function setcentre(Request $request)
    {
        $centre = $request->centre;

        Session::put('centre', $centre);

        return json_encode(array('statusCode'=>200,'msg'=>'centre set successfully'.$centre));
    }

    public function setinputs(Request $request)
    {
        $date_of_visit = $request->date_of_visit;
        $visitor_name = $request->visitor_name;
        $inputCentre = $request->inputCentre;
        $adultCount = $request->adultCount;
        $childCount = $request->childCount;
        $bookingType = $request->bookingType;

        Session::put('date_of_visit', $date_of_visit);
        Session::put('visitor_name', $visitor_name);
        Session::put('inputCentre', $inputCentre);
        Session::put('adultCount', $adultCount);
        Session::put('childCount', $childCount);
        Session::put('bookingType', $bookingType);

        return json_encode(array('statusCode'=>200,'msg'=>'inputs set successfully' ));


    }

    public function booktickets()
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;


        $date_of_visit = session('date_of_visit');
        $visitor_name = session('visitor_name');
        $inputCentre = session('inputCentre');
        $adultCount = session('adultCount');
        $childCount = session('childCount');
        $bookingType = session('bookingType');
        $seats = [];
        $seatcount = [];

        //dd($bookingType);

        if($bookingType=='groupBooking')
        {
            $groupBook = 1;
        }
        else
        {
            $groupBook = 0;
        }

        //get group book configurations
        $edustaffCount = 0;
        $educhildCount = 0;
        $conf = Configuration::first();
        $childperstaff = $conf->children_staff_rate;
        if($groupBook==1)
        {
            $edustaffCount = round($childCount/$childperstaff);

            if($edustaffCount>$adultCount)
            {
                $edustaffCount = $adultCount;
                $educhildCount = $childCount;
            }
            else
            {
                $educhildCount = $childCount + $edustaffCount;
                $edustaffCount = $adultCount - $edustaffCount;
                            
            }            
        }

        $startTime=date("d-m-y h:i:s");
        $startTimestring = strtotime($startTime);

        $organisation = Organisation::where('id',$inputCentre)->first();


        //check if the show is already past the pre booking time
        date_default_timezone_set("Asia/Kolkata");
        $time = time();

        //if date is less than current date then go to an error page
        if(strtotime($date_of_visit)<strtotime(date('Y-m-d')))
        {
            return view('tickets.noshow', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','date_of_visit','bookingType'));
        }

        //get pre booking time
        $configration = Configuration::first();
        $prebookingtime = $configration->pre_ticket_book_time;

        //subtract with the pre booking time
        $time = $time + (1 * $prebookingtime * 60);




        //get all facilities of the centre
        $facilities = Facility::where('organisation_id',$inputCentre)->where('active_flag',1)->orderBy('order_by','asc')->with('showtimings')->whereHas('showtimings',function($showt) { $showt->where('show_flag',0); })->get();

        foreach($facilities as $facility)
        {
            $facility_id = $facility->id;

            $facilityon[$facility_id] = 1;


            //check for weekly off for this selected date and facility

            //get day from date
           // echo strtotime($date_of_visit);
            $day_of_visit = date('l', strtotime($date_of_visit));

            $checkday = WeeklyOffMaster::where('organisation_id',$inputCentre)->where('active_flag',1)->where('weekly_off_day',$day_of_visit)->whereNull('facility_id')->count();
            if($checkday)
                $facilityon[$facility_id] = 0;

            if($facilityon[$facility_id])
            {
                $checkday = WeeklyOffMaster::where('facility_id',$facility_id)->where('active_flag',1)->where('weekly_off_day',$day_of_visit)->count();
                if($checkday)
                    $facilityon[$facility_id] = 0;
                
            }

            //check if this day has holiday off too
            if($facilityon[$facility_id])
            {
                $checkday = HolidayMaster::where('organisation_id',$inputCentre)->where('active_flag',1)->where('holiday_date',$date_of_visit)->whereNull('facility_id')->count();
                if($checkday)
                    $facilityon[$facility_id] = 0;
            }
            if($facilityon[$facility_id])
            {
                $checkday = HolidayMaster::where('facility_id',$facility_id)->where('active_flag',1)->where('holiday_date',$date_of_visit)->count();
                if($checkday)
                    $facilityon[$facility_id] = 0;
            }


            //get layout
            $layouts[$facility_id] = Layout::where('facility_id', $facility_id)->first();

            if(isset($layouts[$facility_id]))
            {
                $rows = $layouts[$facility_id]->total_row;
                $layout_id = $layouts[$facility_id]->id;

                //get seats
                for($i=1;$i<=$rows;$i++)
                {
                    $seats[$facility_id][$i] = Seats::where('facility_id',$facility_id)->where('layout_id',$layout_id)->where('row_no',$i)->get();
                    $seatcount[$facility_id][$i] = Seats::where('facility_id',$facility_id)->where('layout_id',$layout_id)->where('row_no',$i)->count();
                }
                
            } 

            

            foreach($facility->showtimings as $show)
            {
                $show_id = $show->id;
                $showon[$show_id] = 1;
                $show_from_time = $show->from_time;
                //get showtime
                $showtime=$date_of_visit.' '.$show_from_time;
                //$showtime = '2022-04-30 10:00:00';
                
                //check if show date corresponds to the selected date if date is not null
                $checkdate = $show->date;
                if($checkdate)
                {
                    if($date_of_visit!=$checkdate)
                        $showon[$show_id] = 0;
                }

                if((strtotime($showtime)<$time) && $facility->noofseats)
                    $showon[$show_id] = 0;

                //check if this show has minimum adult plus child seats available if not mark showon to 0//
                if($facility->noofseats)
                {
                    $booking = new BookingClass;
                    $availableSeats = $booking->getAvailableSeats($facility_id, $show_id, $date_of_visit);
                    $totalneededseats = $adultCount+$childCount;
                    if($availableSeats<$totalneededseats)
                        $showon[$show_id] = 0;

                }

                //check if show is cancelled for the show date
                $checkshow = ShowCancel::where('show_time_id',$show_id)->where('show_date',$date_of_visit)->where('approval_flag',1)->count();
                if($checkshow)
                {
                    $showon[$show_id] = 0;
                }

                

            }

        }

        //dd($seats);
        //dd($facilityon);
        //dd($showon); 
        return view('tickets.book', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','date_of_visit','visitor_name','inputCentre','adultCount','childCount','facilities','organisation','layouts','seats','seatcount','facilityon','showon','bookingType','groupBook','edustaffCount','educhildCount','childperstaff'));

    }

    public function fetchAvailableSeats($facility_id, $show_id, $show_date)
    {
        $booking = new BookingClass;
        $availableSeats = $booking->getAvailableSeats($facility_id, $show_id, $show_date);

        return $availableSeats;
    }

     public function fetchBookedSeats($facility_id, $show_id, $show_date)
    {
        $booking = new BookingClass;
        $bookedSeats = $booking->getBookedSeats($facility_id, $show_id, $show_date);

        return $bookedSeats;
    }

    public function paymentprocessing(Request $request)
    {
        //dd("here");

        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;

         $organisation = Organisation::where('id',$request->inputCentre)->first();
         $show_date = $request->showDate;

        //trnsaction variables
        
        $organisation_id = $request->inputCentre;
        $amount = $request->totalamountpayable;
        
        $transaction_status = 0;
        $public_user_id = Auth::guard('publicuser')->user()->id;

        $transaction_name = 'Ticket Sale ';
        $paisaamt = $amount*100;
        $currency = config('worldline.currency');
        $request_type = config('worldline.request_type');
        $mid = config('worldline.mid');
        $enckey = config('worldline.enckey');
        $responseURL = url('user/payment-response');


        //lock tables and check if these seats are already booked or this much seats are available

        DB::beginTransaction();
        

        //save to invoice and tickets, transaction table with status 0 and then redirect to our/merchant payment page
        //save to transaction table
        $transaction_insert = Transaction::create([
            'transaction_name' => $transaction_name,
            'organisation_id' => $organisation_id,
            'amount' => $amount,
            'currency' => $currency,
            'request_type' => $request_type,
            'mid' => $mid,
            'enckey' => $enckey,
            'response_url' => $responseURL,
            'status' => $transaction_status,
            'public_user_id' => $public_user_id
        ]);

        if(isset($transaction_insert))
        {
            $transaction_id = $transaction_insert->id;
        }
        else
        {
            DB::rollback();
            return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        //generate orderid
        $now=strtotime(date('Y-m-d H:i:s'));
        $orderId = $transaction_id.$now;

        //update order_id in transaction table
        $updateobj = Transaction::where('id',$transaction_id)->first();
        $updateobj->order_id = $orderId;
        $updateobj->save();

        $transaction_name = 'Ticket Sale '.$transaction_id;



        //save to invoice table with status 0
        $invoice_status = 0;
        $payment_type = 1;//Online
        $invoice_date = date('Y-m-d');

        $invoice_insert = Invoice::create([
            'organisation_id' => $organisation_id,
            'invoice_date' => $invoice_date,
            'show_date' => $show_date,
            'public_user_id' => $public_user_id,
            'status' => $invoice_status,
            'payment_type' => $payment_type,
            'amount' => $amount,
            'transaction_id' => $transaction_id
        ]);
        if(isset($invoice_insert))
        {
            $invoice_id = $invoice_insert->id;
        }
        else
        {
             DB::rollback();
             return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        

        //save to ticket and ticket_seat
        $ticket_status = 0;
        $ticket_verify_status = 0;
        $adultCount = $request->adultCount;
        $childCount = $request->childCount;
        
        //get all facilities of the centre
        $facilities = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->get();
        DB::raw('LOCK TABLES ticket WRITE');
        DB::raw('LOCK TABLES ticket_seat WRITE');
        foreach($facilities as $facility)
        {
            $facility_id = $facility->id;
            //check if this facility is selected by public user
            $checkval = 'iffacilitySelected'.$facility_id;
            $isfacilityselected = $request->$checkval;
            if($isfacilityselected)
            {
                //facility is selected
                $showcheckval = 'showSelected'.$facility_id;
                $show_id = $request->$showcheckval;

                $showamountval = 'famount'.$facility_id;
                $showamount = $request->$showamountval;

                //check availability of this adultcount+childcount for this facility, showdate and showid if not available throw error tocheck wht to do with status....?
                if($facility->noofseats)
                {
                    

                    $booking = new BookingClass;
                    $availableSeats = $booking->getAvailableSeats($facility_id, $show_id, $show_date);

                    $totalneededseats = $adultCount + $childCount;
                    if($availableSeats<$totalneededseats)
                    {
                        DB::rollback();
                        return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));   
                    }
                }
                
                $checkvaladult = 'rateadult'.$facility_id;
                $adult_rate = $request->$checkvaladult;

                $checkvalchild = 'ratechild'.$facility_id;
                $child_rate = $request->$checkvalchild;

                

                $ticket_insert = Ticket::create([
                    'facility_id' => $facility_id,
                    'show_date' => $show_date,
                    'show_time_id' => $show_id,
                    'noof_adult' => $adultCount,
                    'noof_child' => $childCount,
                    'adult_rate' => $adult_rate,
                    'child_rate' => $child_rate,
                    'invoice_id' => $invoice_id,
                    'amount' => $showamount,
                    'status' => $ticket_status,
                    'verify_status' => $ticket_verify_status
                ]);

                if(isset($ticket_insert))
                {
                    $ticket_id = $ticket_insert->id;
                }
                else
                {
                     DB::rollback();
                     return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
                }
                


                //check if facility has fixed seats
                $fixedval = 'iffacilityfixed'.$facility_id;
                $iffixedseat = $request->$fixedval;
                if($iffixedseat)
                {
                    //insert into ticketseat

                    //getseats
                    $seatscheckval = 'selectedseats'.$facility_id;
                    $seatsstring = $request->$seatscheckval;
                    $seatsarr = explode(",",$seatsstring);

                    $seat_status = 0;
                    $booking = new BookingClass;
                    $bookedSeats = $booking->getBookedSeats($facility_id,$show_id,$show_date);
                    foreach($seatsarr as $seat)
                    {
                        //check if this seat is already selected for this show_id and ticket date tocheck
                        if(in_array($seat,$bookedSeats))
                        {
                            DB::rollback();
                            return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
                        }    


                        $ticket_seat_insert = TicketSeat::create([
                            'ticket_id' => $ticket_id,
                            'show_time_id' => $show_id,
                            'seat_id' => $seat,
                            'status' => $seat_status
                        ]);
                        if(!isset($ticket_seat_insert))
                        {
                            DB::rollback();
                            return view('tickets.noseatsavailable',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
                        }
                    }
                }
            }


        }
        
        
        DB::commit();

       // dd($request);


        //generate merchant request 
        

         include 'worldline/AWLMEAPI.php';

        

        //generate merchant request from Helper file
        //create an Object of the above included class
        $obj = new \AWLMEAPI();

        //create an object of Request Message
        $reqMsgDTO = new \ReqMsgDTO();

        /* Populate the above DTO Object On the Basis Of The Received Values */
        // PG MID
        $reqMsgDTO->setMid($mid);
        // Merchant Unique order id
        $reqMsgDTO->setOrderId($orderId);
        //Transaction amount in paisa format
        $reqMsgDTO->setTrnAmt($paisaamt);
        //Transaction remarks
        $reqMsgDTO->setTrnRemarks($transaction_name);
        // Merchant transaction type (S/P/R)
        $reqMsgDTO->setMeTransReqType($request_type);
        // Merchant encryption key
        $reqMsgDTO->setEnckey($enckey);
        // Merchant transaction currency
        $reqMsgDTO->setTrnCurrency($currency);
        // Recurring period, if merchant transaction type is R
        $reqMsgDTO->setRecurrPeriod('');
        // Recurring day, if merchant transaction type is R
        $reqMsgDTO->setRecurrDay('');
        // No of recurring, if merchant transaction type is R
        $reqMsgDTO->setNoOfRecurring('');
        // Merchant response URl
        $reqMsgDTO->setResponseUrl($responseURL);
        // Optional additional fields for merchant
        $reqMsgDTO->setAddField1('');
        $reqMsgDTO->setAddField2('');
        $reqMsgDTO->setAddField3('');
        $reqMsgDTO->setAddField4('');
        $reqMsgDTO->setAddField5('');
        $reqMsgDTO->setAddField6('');
        $reqMsgDTO->setAddField7('');
        $reqMsgDTO->setAddField8('');
        
        /* 
         * After Making Request Message Send It To Generate Request 
         * The variable `$urlParameter` contains encrypted request message
         */
         //Generate transaction request message
        $merchantRequest = "";
        
        $reqMsgDTO = $obj->generateTrnReqMsg($reqMsgDTO);
        
        if ($reqMsgDTO->getStatusDesc() == "Success"){
            $merchantRequest = $reqMsgDTO->getReqMsg();
        }
        //dd($reqMsgDTO);

        $starttime = time();
        $configuration = Configuration::where('id',1)->first(); 
        $ticket_time_out = $configuration->ticket_time_out;
        $endtime = $starttime + ($ticket_time_out*60);

        return view('tickets.paymentprocessing', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','merchantRequest','mid','show_date','organisation','adultCount','childCount','amount','reqMsgDTO','starttime','endtime','ticket_time_out'));
    }

    public function my_bookings()
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;

        $public_user_id = Auth::guard('publicuser')->user()->id;

        //get invoices
        $invoices = Invoice::where('public_user_id',$public_user_id)->where(function ($query) {
            $query->where('status', 1)
                  ->orWhere('status', 2);
        })->with('organisation')->get();

        return view('tickets.my_bookings', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoices'));

    }

    public function invoice($invoice_id,$invoicemd5)
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;

        $checkmd5 = md5($invoice_id);
        if($checkmd5!=$invoicemd5)
        {
            //dd('Error');
            //need to point to an error view
            return view('tickets.error', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        $invoice = Invoice::where('id',$invoice_id)->where('status',1)->with('organisation','tickets')->first();

        $seatid =[];
        $seatname_ticket = [];
        $seat_count=0;
        $seat_name_row= [];
        $totalrows = "";
        $tickets = Ticket::where('invoice_id',$invoice_id)->where('status',1)->with('showtime','facility','invoice')->get();
        foreach($tickets as $ticket)
        {
            if($ticket->facility->fixedseatflag)
            {
                $ticket_id = $ticket->id;
                $facility_id = $ticket->facility_id;
                $layouts[$facility_id] = Layout::where('facility_id', $facility_id)->first();
                if(isset($layouts[$facility_id]))
                {
                    $totalrows = $layouts[$facility_id]->total_row;
                    $layout_id = $layouts[$facility_id]->id;
                    //get seats
                    for($i=1;$i<=$totalrows;$i++)
                    {
                        $seats[$facility_id][$i] = Seats::where('facility_id',$facility_id)->where('layout_id',$layout_id)->where('row_no',$i)->get();
                        foreach($seats[$facility_id][$i] as $seatobj)
                        {
                            $seat_name_row[$i][] = $seatobj->seat_name;
                        }
                    }
                }
                $ticket_seats = TicketSeat::where('ticket_id',$ticket_id)->where('status',1)->with('seat')->get();
                foreach($ticket_seats as $ticket_seat)
                {
                    $seat_count++;
                    $seatid[] = $ticket_seat->seat_id;
                    $seatname_ticket[] = $ticket_seat->seat->seat_name;
                }
            }
        }

        return view('tickets.invoice', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoice','totalrows','seat_name_row','seatname_ticket'));

        //dd($invoice);
    }

    public function invoiceprint($invoice_id,$invoicemd5)
    {
        
        $checkmd5 = md5($invoice_id);
        if($checkmd5!=$invoicemd5)
        {
            //dd('Error');
            //need to point to an error view
            return view('tickets.error');
        }

        $invoice = Invoice::where('id',$invoice_id)->where('status',1)->with('organisation','tickets')->first();

        $seatid =[];
        $seatname_ticket = [];
        $seat_count=0;
        $seat_name_row= [];
        $totalrows = "";
        $tickets = Ticket::where('invoice_id',$invoice_id)->where('status',1)->with('showtime','facility','invoice')->get();
        foreach($tickets as $ticket)
        {
            if($ticket->facility->fixedseatflag)
            {
                $ticket_id = $ticket->id;
                $facility_id = $ticket->facility_id;
                $layouts[$facility_id] = Layout::where('facility_id', $facility_id)->first();
                if(isset($layouts[$facility_id]))
                {
                    $totalrows = $layouts[$facility_id]->total_row;
                    $layout_id = $layouts[$facility_id]->id;
                    //get seats
                    for($i=1;$i<=$totalrows;$i++)
                    {
                        $seats[$facility_id][$i] = Seats::where('facility_id',$facility_id)->where('layout_id',$layout_id)->where('row_no',$i)->get();
                        foreach($seats[$facility_id][$i] as $seatobj)
                        {
                            $seat_name_row[$i][] = $seatobj->seat_name;
                        }
                    }
                }
                $ticket_seats = TicketSeat::where('ticket_id',$ticket_id)->where('status',1)->with('seat')->get();
                foreach($ticket_seats as $ticket_seat)
                {
                    $seat_count++;
                    $seatid[] = $ticket_seat->seat_id;
                    $seatname_ticket[] = $ticket_seat->seat->seat_name;
                }
            }
        }

        //return view('tickets.invoicepdf', compact('invoice'));

        //dd($invoice);
         $invoice_pdf = \PDF::loadView('tickets.invoicepdf', compact('invoice','totalrows','seat_name_row','seatname_ticket'));
        
         $ticket_name = $checkmd5.'.pdf';
         return $invoice_pdf->download($ticket_name);
    }

    public function ticket_print($invoice_id,$invoicemd5)
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;

        $checkmd5 = md5($invoice_id);
        if($checkmd5!=$invoicemd5)
        {
            //dd('Error');
            //need to point to an error view
            return view('tickets.error', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        $invoice = Invoice::where('id',$invoice_id)->where('status',1)->with('organisation','tickets')->first();

        $tickets = Ticket::where('invoice_id',$invoice_id)->where('status',1)->with('showtime','facility','invoice')->get();

        return view('tickets.tickets_print', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','tickets','invoice'));

    }
    public function cancel_landing($invoice_id,$invoicemd5)
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;
         date_default_timezone_set("Asia/Kolkata");
        $checkmd5 = md5($invoice_id);
        if($checkmd5!=$invoicemd5)
        {
            //dd('Error');
            //need to point to an error view
            return view('tickets.error', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        //check if invoice id is this user's invoice id else return error
        $public_user_id = Auth::guard('publicuser')->user()->id;
        $invoice = Invoice::where('id',$invoice_id)->with('tickets')->first();
        $invoice_user = $invoice->public_user_id;
        $show_date = $invoice->show_date;
        if($invoice_user!=$public_user_id)
        {
            //dd('Error');
            return view('tickets.error', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        //check if this invoice can be cancelled based on the date of cancellation
        $cancel_date = date('Y-m-d');
        if(strtotime($cancel_date)>strtotime($show_date))
        {
            return view('tickets.cannotcancel', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        //get amount which will be refunded based on showtime
        $cancelconf = CancelConfiguration::where('status',1)->get();
        $time_of_cancellation = time();
        $totalrefund = 0;
        $refundticket = [];
        foreach($invoice->tickets as $ticket)
        {

            $show_id = $ticket->show_time_id;

            //get showtime from show table
            $showtime = ShowTimings::where('id',$show_id)->first();
            $show_from_time = $showtime->from_time;
            //$showtimeval =$show_date.' '.$show_from_time;
            $showtimeval =$show_date.' '.'10:00:00';
            $showtimeval = strtotime($showtimeval);
            if(!$ticket->noofseats)
            {
                $show_from_time = $showtime->to_time;
                $showtimeval =$show_date.' '.'10:00:00';
                $showtimeval = strtotime($showtimeval);
                //$showtimeval =$show_date.' '.$show_from_time;
                //$showtimeval = strtotime($showtimeval) - (1 * 1 * 60);//subtracting 1 hour for galleries kind of shows
            }
            //dd($show_from_time);
            //echo date('Y-m-d H:i:s',$showtimeval);
            //echo date('Y-m-d H:i:s',$time_of_cancellation);
            $diffhours = abs($showtimeval- $time_of_cancellation)/(60*60);
            //dd($diffhours);

            if($diffhours>0)
            {
                //get how much refund to be applied
                $refundcount =  CancelConfiguration::where('cancellation_before_hours','<=',$diffhours)->count();
                if($refundcount)
                {
                     $refundobj =  CancelConfiguration::where('cancellation_before_hours','<=',$diffhours)->orderBy('cancellation_before_hours','DESC')->limit(1)->first();
                     $refundperc = $refundobj->refund;
                     //dd($refundperc);

                     $ticketamount = $ticket->amount;

                     $refundamount = $ticketamount*$refundperc/100;
                }
                else
                {
                    $refundamount = 0;
                }
            }
            else
            {
                $refundamount = 0;
            }
            
            $refundticket[$ticket->id] = $refundamount;

        }
        return view('tickets.cancel_landing', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','refundticket','invoice','cancelconf'));

    }
    public function cancel_ticket(Request $request)
    {
        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;

        $invoice_id = $request->invoice_id;

        //check if invoice id is this user's invoice id else return error
        $public_user_id = Auth::guard('publicuser')->user()->id;
        $invoice = Invoice::where('id',$invoice_id)->with('tickets')->first();
        $invoice_user = $invoice->public_user_id;
        $show_date = $invoice->show_date;
        if($invoice_user!=$public_user_id)
        {
            //dd('Error');
            return view('tickets.error', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        //check if this invoice is already cancelled
        $invoice_cancel_check = CancelTicket::where('invoice_id',$invoice_id)->count();
        if($invoice_cancel_check)
        {
            //dd('This invoice is already cancelled');
            return view('tickets.alreadycancel', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        //check if this invoice can be cancelled based on the date of cancellation
        $cancel_date = date('Y-m-d');
        if(strtotime($cancel_date)>strtotime($show_date))
        {
            return view('tickets.cannotcancel', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }

        //get amount which will be refunded based on showtime
        $cancelconf = CancelConfiguration::where('status',1)->get();
        $time_of_cancellation = time();
        $totalrefund = 0;
        foreach($invoice->tickets as $ticket)
        {
            $show_id = $ticket->show_time_id;

            //get showtime from show table
            $showtime = ShowTimings::where('id',$show_id)->first();
            $show_from_time = $showtime->from_time;
            //$showtimeval =$show_date.' '.$show_from_time;
            $showtimeval =$show_date.' '.'10:00:00';
            $showtimeval = strtotime($showtimeval);
            if(!$ticket->noofseats)
            {
                $show_from_time = $showtime->to_time;
                $showtimeval =$show_date.' '.'10:00:00';
                $showtimeval = strtotime($showtimeval);
                //$showtimeval =$show_date.' '.$show_from_time;
                //$showtimeval = strtotime($showtimeval) - (1 * 1 * 60);//subtracting 1 hour for galleries kind of shows
            }

            $diffhours = abs($showtimeval- $time_of_cancellation)/(60*60);

            if($diffhours>0)
            {
                //get how much refund to be applied
                $refundcount =  CancelConfiguration::where('cancellation_before_hours','<=',$diffhours)->count();
                if($refundcount)
                {
                    $refundobj =  CancelConfiguration::where('cancellation_before_hours','<=',$diffhours)->orderBy('cancellation_before_hours','DESC')->limit(1)->first();
                    $refundperc = $refundobj->refund;

                    $ticketamount = $ticket->amount;

                    $refundamount = $ticketamount*$refundperc/100;
                    $totalrefund += $refundamount;
                    $refund_count = Refund::where('public_user_id',$public_user_id)->where('show_time_id',$show_id)->where('show_date',$show_date)->where('invoice_id',$invoice_id)->count();
                    //dd($refund_count);
                    if($refund_count==0)
                    {
                         //entry to refund table
                         $refund_insert = Refund::create([
                            'show_date' => $show_date,
                            'show_time_id' => $show_id,
                            'invoice_id' => $invoice_id,
                            'payment_type' => 1,
                            'ticket_id' => $ticket->id,
                            'adult_count' => $ticket->noof_adult,
                            'child_count' => $ticket->noof_child,
                            'refund_amount' => $refundamount,
                            'refund_status' => 0,
                            'public_user_id' => $public_user_id
                         ]);
                    }
                }
                else
                {
                    $refundamount = 0;
                }
            }
            else
            {
                $refundamount = 0;
            }
            

        }
        //dd("here");
        $cancel_count = CancelTicket::where('public_user_id',$public_user_id)->where('cancel_date',$cancel_date)->where('invoice_id',$invoice_id)->count();
        //dd($cancel_count);
        if($cancel_count==0)
        {
            //entry to cancel ticket table
            $cancelticket_insert = CancelTicket::create([
                'invoice_id' => $invoice_id,
                'cancel_date' => $cancel_date,
                'cancel_time' => date("Y-m-d H:i:s",$time_of_cancellation),
                'public_user_id' => $public_user_id,
                'refund_amount' => $totalrefund,
                'refund_status' => 0
            ]);
        }

        //cancel in invoice table with status 2
        $invoice_update = Invoice::where('id',$invoice_id)->first();
        $invoice_update->status = 2;
        $invoice_update->save();


        //cancel in tickets table with status 2
        $ticket_update = Ticket::where('invoice_id',$invoice_id)->get();
        foreach($ticket_update as $updateticket)
        {
            $ticket_id = $updateticket->id;
            $ticketobj = Ticket::where('id',$ticket_id)->first();
            $ticketobj->cancel_date = $cancel_date;
            $ticketobj->status = 2;
            $ticketobj->save();
        }
        //dd("here");
        /*$publicusers = PublicUser::where('id',$public_user_id)->where('status',1)->first();
        dd("here");
        if(isset($publicusers))
        {
            $mobileNumber = $publicusers->phone;
        }*/
        $mobileNumber = Auth::guard('publicuser')->user()->phone;
       // dd($mobileNumber);
        ////sms send to the registered mobile number
        if($mobileNumber!="")
        {
            $smssend = new SMSClass;
            $smsarr = $smssend->sendSMSCancelTicket($invoice_id, $mobileNumber, $country_code='+91');
        }

        return view('tickets.cancel_success', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','totalrefund'));
    }

    public function testpayment(){

        include 'worldline/AWLMEAPI.php';

        $transaction_name = 'Any Remarks';
        $amount = 1;
        $paisaamt = $amount*100;
        $currency = 'INR';
        $request_type = 'S';
        $mid = 'WL0000000027698';
        $enckey = '6375b97b954b37f956966977e5753ee6';
        $responseURL = 'http://localhost/worldline/meTrnSuccess.php';
        $orderId = '1650879661134119';

        //generate merchant request from Helper file
        //create an Object of the above included class
        $obj = new \AWLMEAPI();

        //create an object of Request Message
        $reqMsgDTO = new \ReqMsgDTO();

        /* Populate the above DTO Object On the Basis Of The Received Values */
        // PG MID
        $reqMsgDTO->setMid($mid);
        // Merchant Unique order id
        $reqMsgDTO->setOrderId($orderId);
        //Transaction amount in paisa format
        $reqMsgDTO->setTrnAmt($paisaamt);
        //Transaction remarks
        $reqMsgDTO->setTrnRemarks($transaction_name);
        // Merchant transaction type (S/P/R)
        $reqMsgDTO->setMeTransReqType($request_type);
        // Merchant encryption key
        $reqMsgDTO->setEnckey($enckey);
        // Merchant transaction currency
        $reqMsgDTO->setTrnCurrency($currency);
        // Recurring period, if merchant transaction type is R
        $reqMsgDTO->setRecurrPeriod('');
        // Recurring day, if merchant transaction type is R
        $reqMsgDTO->setRecurrDay('');
        // No of recurring, if merchant transaction type is R
        $reqMsgDTO->setNoOfRecurring('');
        // Merchant response URl
        $reqMsgDTO->setResponseUrl('http://localhost/worldline/meTrnSuccess.php');
        // Optional additional fields for merchant
        $reqMsgDTO->setAddField1('');
        $reqMsgDTO->setAddField2('');
        $reqMsgDTO->setAddField3('');
        $reqMsgDTO->setAddField4('');
        $reqMsgDTO->setAddField5('');
        $reqMsgDTO->setAddField6('');
        $reqMsgDTO->setAddField7('');
        $reqMsgDTO->setAddField8('');
        
        /* 
         * After Making Request Message Send It To Generate Request 
         * The variable `$urlParameter` contains encrypted request message
         */
         //Generate transaction request message
        $merchantRequest = "";
        
        $reqMsgDTO = $obj->generateTrnReqMsg($reqMsgDTO);
        
        if ($reqMsgDTO->getStatusDesc() == "Success"){
            $merchantRequest = $reqMsgDTO->getReqMsg();
        }

        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;
        //dd($reqMsgDTO);
        return view('tickets.testpaymentprocessing', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','merchantRequest','mid','reqMsgDTO'));

    }

    public function testmail()
    {
        $mails = MailTicket::where('status',0)->where('mail_type',1)->get();
        //dd($mails);
        foreach($mails as $mail)
        {
            $email = $mail->email;
            $invoice_id = $mail->invoice_id;

            $invoicemd5 = md5($invoice_id);

            //generate ticket pdf
            $invoice = Invoice::where('id',$invoice_id)->where('status',1)->with('organisation','tickets')->first();
            $invoice_pdf = \PDF::loadView('tickets.invoicepdf', compact('invoice'));
            //return $invoice_pdf->output();
            \Storage::put('temp/'.$invoicemd5.'.pdf', $invoice_pdf->output());
            //echo $invoicemd5;
            $ticketname = $invoicemd5.'.pdf';
            $path = public_path()."/temp/".$ticketname;
            $data= ['message' => 'Congrats, You have booked the tickets. Please find ticket in attachment!', 'mailto'=>$email, 'ticketname'=>$ticketname, 'attached_data'=>$path ];
            //mailing to the registered email
            \Mail::to($email)->send(new TicketMail($data));

            $id = $mail->id;
            $mailobj = MailTicket::where('id',$id)->first();
            $mailobj->status=1;
            $mailobj->save();
        }

    }

    public function payment_response(Request $request)
    {
        //dd($request);
        include 'worldline/AWLMEAPI.php';

        //create an Object of the above included class
        $obj = new \AWLMEAPI();
        
        /* This is the response Object */
        $resMsgDTO = new \ResMsgDTO();

        /* This is the request Object */
        $reqMsgDTO = new \ReqMsgDTO();
        
        //This is the Merchant Key that is used for decryption also
        $enc_key = config('worldline.enckey');

        /* Get the Response from the WorldLine */
        $responseMerchant = $request->merchantResponse;
        
        $response = $obj->parseTrnResMsg( $responseMerchant , $enc_key );
        //var_dump($response);

        $transaction_refno = $response->getPgMeTrnRefNo();
        $status_code = $response->getStatusCode();
        $status_desc = $response->getStatusDesc();
        $trans_req_date = $response->getTrnReqDate();
        $response_code = $response->getResponseCode();
        $rrn = $response->getRrn();
        $auth_zcode = $response->getAuthZCode();
        $order_id = $response->getOrderId();

        //for time being....
        //$response->getStatusCode='S';

        //update transaction table with response
        $updateobj = Transaction::where('order_id',$order_id)->first();
        if(isset($updateobj))
        {
            $updateobj->transaction_refno = $transaction_refno;
            $updateobj->status_code = $status_code;
            $updateobj->status_desc = $status_desc;
            $updateobj->transaction_req_date = $trans_req_date;
            $updateobj->response_code = $response_code;
            $updateobj->rrn = $rrn;
            $updateobj->auth_zcode = $auth_zcode;
            $updateobj->save();
        }

        $page_title = 'KSSTM Ticketing Application';
        $page_description = 'Some description for the page';
        $logo = "images/logo.png";
        $logoText = "images/logo-text.png";
        $active="active";
        $event_class="schedule-event";
        $button_class="btn-primary";
        $action = __FUNCTION__;
        
        


        //get details from transaction table with orderId and update the status if it is success
        if($response->getStatusCode()=="S")
        {
            //update transaction table
            $transactionupdate = Transaction::where('order_id',$order_id)->first();
            $transaction_id = $transactionupdate->id;
            $transactionupdate->status = 1; //Paid
            $transactionupdate->save();

            //update invoice
            $invoiceupdate = Invoice::where('transaction_id',$transaction_id)->first();
            $invoiceupdate->status = 1;
            $invoice_id = $invoiceupdate->id;
            $organisation_id = $invoiceupdate->organisation_id;

            //update invoice number and invoice_time
            $booking = new BookingClass;
            $invoicearr = $booking->getnewInvoice($organisation_id);
            $invoiceupdate->invoice_no = $invoicearr[0];
            $invoiceupdate->invoice_time = $invoicearr[1];
            $invoiceupdate->save();

            //update tickets table
            $tickets = Ticket::where('invoice_id',$invoice_id)->get();
            foreach($tickets as $ticket)
            {
                $ticket_id = $ticket->id;
                $ticketupdate = Ticket::where('id',$ticket_id)->first();
                $ticketupdate->status = 1;
                $facility_id = $ticketupdate->facility_id;
                //to do update ticket number
                $booking = new BookingClass;
                $ticketno = $booking->getnewTicket($facility_id);
                $ticketupdate->ticket_no = $ticketno;
                $ticketupdate->save();

                //update ticket seat table
                $ticketseatupdate = TicketSeat::where('ticket_id',$ticket_id)->update(['status' => 1]);

            }

            //mail ticket
            $email = Auth::guard('publicuser')->user()->email;
            $public_user_id = Auth::guard('publicuser')->user()->id;
            $mailobj = MailTicket::create([
                'email' => $email,
                'invoice_id' => $invoice_id,
                'status' => 0,
                'public_user_id' => $public_user_id,
                'mail_type' => 1
            ]);


            //show success page and print ticket button
             return view('tickets.payment_success', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','status_code','invoice_id'));

        }
        else //transaction failed
        {
            //update transaction table
            $transactionupdate = Transaction::where('order_id',$order_id)->first();
            $transaction_id = $transactionupdate->id;
            $transactionupdate->status = 2; //Failed
            $transactionupdate->save();

            //show failed page
             return view('tickets.payment_fail', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','status_code'));
        }
    }
}
