<?php
namespace App\Http\Controllers;
use Illuminate\Support\Collection;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Helper\MailHelper as MailHelper;
use Session;
use Auth;
use DatePeriod;
use DateTime;
use DateInterval;
use PDF;
use Mail;
use DB;
use App\Mail\ReportMail;
use App\Models\User;
use App\Models\PublicUser;
use App\Models\Settings\Organisation;
use App\Models\Settings\Department;
use App\Models\Settings\Section;
use App\Models\Settings\Roles;
use App\Models\Settings\Permissions;
use App\Models\Settings\RolePermission;
use App\Models\Settings\UserRoles;
use App\Models\Settings\MenuSettings;
use App\Models\Settings\MenuRolePermission;
use App\Models\Settings\Configuration;
use App\Models\Settings\CancelConfiguration;
use App\Models\Settings\HolidayMaster;
use App\Models\Settings\WeeklyOffMaster;
use App\Models\Settings\State;
use App\Models\Facility\Facility;
use App\Models\Facility\ShowTimings;
use App\Models\Facility\Layout;
use App\Models\Facility\Seats;
use App\Models\Facility\Rates;
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\FeeWaiverApproval;
use App\Models\Sales\FeeWaiverApprovalUpload;
use App\Models\Sales\ShowCancel;
use App\Models\Sales\TicketCancelApprove;
use App\Models\Sales\Refund;
use App\Models\Sales\CancelTicket;
use App\Models\Sales\TicketApproval;
use App\Models\Sales\TicketApprovalUpload;
use App\Models\Sales\TicketPrint;
use App\Helpers\BookingClass;
use App\Helpers\SMSClass;
use Request as req;
use App\Models\Settings\Science_Trivia;

class SalesController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
    */

    public function get_facility_org($organisation_id)
    {
        $facilities=Facility::where('organisation_id',$organisation_id)->orderBy('order_by','asc')->whereNotNull('noofseats')->get();
        return $facilities->pluck('facility_name', 'id');
    }

    public function get_showtime($facility_id,$show_date)
    {
        $noofseats = "";
        $show_start_time ="";
        $show_timings =[];
        $n=1;
        $shows=ShowTimings::where('facility_id',$facility_id)->with('facility')->where(function($st) use($show_date) { $st->where('date',$show_date)->orWhereNull('date'); })->get();
        foreach($shows as $show)
        {
            $show_id = $show->id;
            $showon[$show_id] = 1;
            $date_of_visit = date("Y-m-d");
            $show_from_time = $show->from_time;
            //get showtime
            $showtime=$date_of_visit.' '.$show_from_time;
            $noofseats = $show->facility->noofseats;
            //check if the show is already past the pre booking time
            date_default_timezone_set("Asia/Kolkata");
            $time = time();
            //get pre booking time
            $configration = Configuration::first();
            $prebookingtime = $configration->pre_ticket_book_time;
            //subtract with the pre booking time
            $time = $time + (1 * $prebookingtime * 60);
            if(strtotime($showtime) && $noofseats)
            {
                $show_start_time = date("g:i A", strtotime($show->from_time));
                if(!$show->dont_show_to_time)
                {
                    $show_start_time .=  "-". date("g:i A", strtotime($show->to_time));
                } 
                $show_timings[$n]['show_time'] = $show_start_time;             
                $show_timings[$n]['show_id'] = $show_id;
                $n++;
            }
        }
        //dd($show_timings);
        //return $facilities->pluck('facility_name', 'id');
        return $show_timings;
    }    

    public function ticket_sales()
    {   
        $page_title = 'Ticket Sales';
        $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__;
        $id = Auth::user()->id;     
        $organisations = Organisation::all();
        $users = User::where('id',$id)->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $ticket_booking_max_days ="";
        $configration = Configuration::first();
        if(isset($configration))
        {
            $ticket_booking_max_days = $configration->ticket_booking_max_days;
        }
        return view('Sales/ticket_sales', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','organisations','users','organisation_id','ticket_booking_max_days'));
    }

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

        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('phone_number', $phone_number);

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

    public function book_tickets()
    {
        $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');
        $phone_number = session('phone_number');
        $startTime=date("d-m-y h:i:s");
        $startTimestring = strtotime($startTime);
        $user_id = Auth::user()->id;
        $slugrolename= "";
        $seats = [];
        $seatcount = [];
        $showon = [];
        $userarr = UserRoles::where('user_id',$user_id)->where('status',1)->with('role')->first();
        if(isset($userarr))
        {
            $slugrolename = $userarr->role->guard_name;
        }
        if(($slugrolename=="admin") || ($slugrolename=="manager"))
        {
        	$paymentmethods = PaymentMethod::where('id','!=',4)->get();
        }
        else
        {
        	$paymentmethods = PaymentMethod::where('id','!=',4)->get();
        }
        
        $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();
        //get pre booking time
        $configration = Configuration::first();
        if(isset($configration))
        {
            $prebookingtime = $configration->pre_ticket_book_time;
            $ticket_booking_max_days = $configration->ticket_booking_max_days;
        }
        //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('Sales.noshowoffline', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','date_of_visit'));
        }
           
        ///to do -- todate>ticketmaxdays////
        $todate = date("Y-m-d");
        $ticket_max_date = "";
        if($ticket_booking_max_days)
        {
            $ticket_max_date = date("Y-m-d", strtotime("+".$ticket_booking_max_days."days"));
        }
        if(strtotime($date_of_visit)>strtotime($ticket_max_date))
        {
            return view('Sales.noshowoffline', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','date_of_visit'));
        }
        //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')->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';
                //if((strtotime($showtime)<$time) && $facility->noofseats)
                   // $showon[$show_id] = 0;

                //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;
                }
                
                //check if this show has minimum adult plus child seats available if not mark showon to 0//todo
                if($facility->noofseats)
                {

                    $booking = new BookingClass;
                    $availableSeats = $booking->getAvailableSeats($facility_id, $show_id, $date_of_visit);
                    //if($facility_id==2)
                        //dd($availableSeats);
                    $totalneededseats = $adultCount+$childCount;
                    if($availableSeats<$totalneededseats)
                        $showon[$show_id] = 0;

                }
                //check if show is cancelled for the show date
                $checkshow = ShowCancel::where('facility_id',$facility_id)->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('Sales.book_tickets', 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','paymentmethods','phone_number','slugrolename'));
    }
    public function fetchallseatss($facility_id, $rowno, $middlecol)
    {
        $seat = [];
        $seats = Seats::where('row_no',$rowno)->where('facility_id',$facility_id)->where('seat_no','<=',$middlecol)->get();
        foreach($seats as $seat)
        {
            $seat_id[] = $seat->id;
        }
        //dd($seat_id);
        return $seat_id;
    }
    public function fetchsecondhalfseatss($facility_id, $rowno, $middlecol)
    {
        $seat = [];
        $seats = Seats::where('row_no',$rowno)->where('facility_id',$facility_id)->where('seat_no','>',$middlecol)->orderBy('seat_no','desc')->get();
        foreach($seats as $seat)
        {
            $seat_id[] = $seat->id;
        }
        //dd($seat_id);
        return $seat_id;
    }
    public function fetchAvailableSeatsOffline($facility_id, $show_id, $show_date)
    {
        $booking = new BookingClass;
        $availableSeats = $booking->getAvailableSeats($facility_id, $show_id, $show_date);

        return $availableSeats;
    }

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

        return $bookedSeats;
    }

    public function ticketpaymentprocessing(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__;

        $organisation = Organisation::where('id',$request->inputCentre)->first();
        $show_date = $request->showDate;
        //trnsaction variables
        $organisation_id = $request->inputCentre;
        $amount = $request->totalamountpayable;
        $payment_method = $request->paymentmethods;
        $visitor_name = $request->loggedinUsername;
        $visitor_phone_number = $request->phone_number;
        $ticket_type = $request->ticket_type;
        $remark_initiator =$request->remark_initiator;
        $transaction_status = 1;
        $user_id = Auth::user()->id; 
        //save to invoice and tickets, transaction table with status 0 and then redirect to our/merchant payment page
        //lock tables and check if these seats are already booked or this much seats are available
        DB::beginTransaction();
        //save to invoice table 
        ///payment_method==4 -> fee waiver///////
        /*if($payment_method=="4")
        {
            $invoice_status=0;
            $invoice_no = NULL;
            $invoice_time = NULL;
        }
        else
        {
            $invoice_status = 1;
            $booking = new BookingClass;
            $invoicearr = $booking->getnewInvoice($organisation_id);
            $invoice_no = $invoicearr[0];
            $invoice_time = $invoicearr[1];
        }*/
        if($ticket_type==0)   /////normal
        {
            $invoice_status = 1;
            $booking = new BookingClass;
            $invoicearr = $booking->getnewInvoice($organisation_id);
            $invoice_no = $invoicearr[0];
            $invoice_time = $invoicearr[1];
        }
        else   /////differently abled and packaged user-- save invoice table with status=1 and num is null
        {
            $invoice_status=1;
            $invoice_no = NULL;
            $invoice_time = NULL;
        }

        $payment_type = 2;//Offline
        $invoice_date = date('Y-m-d');
        $invoice_insert = Invoice::create([
            'organisation_id' => $organisation_id,
            'invoice_date' => $invoice_date,
            'invoice_no' => $invoice_no,
            'invoice_time' => $invoice_time,
            'show_date' => $show_date,
            'user_id' => $user_id,
            'status' => $invoice_status,
            'payment_type' => $payment_type,
            'payment_method' => $payment_method,
            'amount' => $amount,
            'visitor_name' => $visitor_name,
            'visitor_phone_number' => $visitor_phone_number,
            'ticket_type' => $ticket_type,
        ]);
        if(isset($invoice_insert))
        {
            $invoice_id = $invoice_insert->id;

            if($ticket_type!=0)
            {
                $percentage ="";
                $differently_abled_percentage ="";
                $packaged_user_percentage = "";
                ////configuration table////////
                $configration = Configuration::first();
                if(isset($configration))
                {
                    $differently_abled_percentage = $configration->differently_abled_percentage;
                    $packaged_user_percentage = $configration->packaged_user_percentage;
                }
                if($ticket_type==1)
                {
                    $percentage = $differently_abled_percentage;
                }
                if($ticket_type==2)
                {
                    $percentage = $packaged_user_percentage;
                }
                if(!$percentage)
                    $percentage = 0;
                ////insert ticket approval table///////////////////
                $ticketapproval_insert = TicketApproval::create([
                        'invoice_id' => $invoice_id,
                        'request_user_id' => $user_id,
                        'approve_flag' => 0,
                        'percentage' => $percentage,
                        'remark_initiator' => $remark_initiator,
                    ]);
                $ticket_approval_id = $ticketapproval_insert->id;
                //////if any upload////////////////
                if ($request->hasFile('documentfile')) 
                {
                    $fileobj=$request->file('documentfile')->getClientOriginalName();
                    $destpath="uploads/ticketdocument";
                    $custom_file_name =$ticket_approval_id.'-'.$fileobj;
                    $documentpath = $request->file('documentfile')->move(public_path().'/uploads/ticketdocument/', $custom_file_name);
                    $insert_id1 = TicketApprovalUpload::create([//model name database field name
                      'ticket_approval_id' => $ticket_approval_id,
                      'file_upload' => $custom_file_name,
                      'user_id' => $user_id,
                    ]);
                }
                ////////////////////////////////////
            }
        }
        else
        {
             DB::rollback();

             return view('Sales.noseatsavailableticket',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        //save to ticket and ticket_seat
        //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 
            $checkval = 'iffacilitySelected'.$facility_id;
            $adults = 'adultCount'.$facility_id;
            $childs = 'childCount'.$facility_id;
            $adultCount = $request->$adults;
            $childCount = $request->$childs;
            $isfacilityselected = $request->$checkval;
            if($isfacilityselected)
            {
                //facility is selected
                $showcheckval = 'showSelected'.$facility_id;
                $show_id = $request->$showcheckval;

                $showamountval = 'famount'.$facility_id;
                $showamount = $request->$showamountval;
                
                if($ticket_type=="0")
                {
                    $ticket_status = 1;
                    $ticket_verify_status = 1;
                    //to do update ticket number
                    $booking = new BookingClass;
                    $ticketno = $booking->getnewTicket($facility_id);
                    
                }
                else
                {
                    $ticket_status = 1;
                    $ticket_verify_status = 0;
                    $ticketno =NULL;
                }
                //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('Sales.noseatsavailableticket',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;

                ///todo ticketnum exist roll back////
                $ticket_insert = Ticket::create([
                    'facility_id' => $facility_id,
                    'ticket_no' => $ticketno,
                    '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,
                    'ticket_type' => $ticket_type,
                    'print_flag' => 0,
                ]);

                if(isset($ticket_insert))
                {
                    $ticket_id = $ticket_insert->id;
                }
                else
                {
                     DB::rollback();
                     return view('Sales.noseatsavailableticket',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 = 1;
                    
                    $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('Sales.noseatsavailableticket',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('Sales.noseatsavailableticket',compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
                        }
                    }
                }
            }
        }
        DB::commit();
        $invoicemd5=md5($invoice_id);
        if($ticket_type=="0")
        {
            if($visitor_phone_number!="")
            {
                $smssend = new SMSClass;
                //$smsarr = $smssend->sendSMSticket($invoice_id, $visitor_phone_number, $country_code='+91');
            }
            return redirect('print_tickets/'.$invoice_id."/".$invoicemd5);            
        }
        else
        {
            return redirect('show_ticket/'.$invoice_id."/".$invoicemd5);
        }
        
    }

    public function show_ticket($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
        }
        $invoice = Invoice::where('id',$invoice_id)->first();
        if(isset($invoice))
        {

        }
        return view('Sales.show_ticket', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoice_id','invoice'));
    }

    public function print_tickets($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
        }
        /////update verify status in ticket table//////
        $print_flag_count=0;
        $tickets = Ticket::where('invoice_id',$invoice_id)->get();
        foreach($tickets as $ticket)
        {
            $ticket_id = $ticket->id;
            $print_flg = $ticket->print_flag;
            $userid = Auth::user()->id;
            $userarr = UserRoles::where('user_id',$userid)->where('status',1)->with('role')->first();
            if(isset($userarr))
            {
                $slugrolename = $userarr->role->guard_name;
            } 
            if($print_flg>=1 && $slugrolename=='counteruser')
            {
                return view('Sales.alreadyprint_ticket', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
            }
            $ticket_update = Ticket::where('id',$ticket_id)->first();
            if(isset($ticket_update))
            {
                if(!$print_flg)
                {
                    $print_flag_count = 1;
                }
                else
                {
                    $print_flag_count++;
                }
                $ticket_update->verify_status = 1;
                $ticket_update->print_flag = $print_flag_count;
                $ticket_update->save();
            }
        }
        $counter_user = Auth::user()->id; 
        $users = User::where('id',$counter_user)->where('status',1)->first();
        if(isset($users))
        {
            $counter_user_name= $users->name;
        }
        ////////////////////////////////////////////////
        $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;
                }
            }
        }
        
        //==dd($seatname_ticket);
        $trivia = Science_Trivia::all();

        //print table entry////////////////////////
        $print_date = date("Y-m-d");
        $ticketprint_insert = TicketPrint::create([
                        'print_flag' => 1,
                        'print_date' => $print_date,
                        'user_id' => $userid,
                        'ticket_id' => $ticket_id,
                    ]);
        ////////////////////////////////////

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

    }

    public function view_tickets()
    {
        $page_title = 'View Tickets';
        $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__;

        $users = User::where('status',1)->get();
        return view('Sales/view_tickets', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users'));
    }

    public function view_ticket_list(Request $request)
    {
        $page_title = 'View Tickets';
        $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 = $request->date_of_visit;
        $user_id = $request->user_id;
        $users = User::where('id',$user_id)->where('status',1)->first();
        $invoices = Invoice::where('user_id',$user_id)->where('show_date',$date_of_visit)->where('status',1)->with('tickets','paymentmethod')->get();
        return view('Sales/view_ticket_list', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoices','date_of_visit','users'));
    }

    public function print_last_ticket()
    {
        $page_title = 'View Tickets';
        $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__;

        $users = User::where('status',1)->get();
        return view('Sales/print_last_ticket', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users'));
    }
    public function ticket_list_print(Request $request)
    {
        $user_id = $request->user_id;
        $invoice = Invoice::where('user_id',$user_id)->where('status',1)->with('organisation','tickets','paymentmethod')->orderBy('id','desc')->first();
        $invoice_id = $invoice->id;
        $invoicemd5=md5($invoice_id);
        return redirect('print_tickets/'.$invoice_id.'/'.$invoicemd5);
    }

    ////counter side ticket printing without otp -- for public user/////////////////
    public function getticket_publicuser()
    {   
        $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__;
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->with('organisation')->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }

        return view('Sales/getticket_publicuser', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users','organisation_id'));
    }
    public function getticket_publicuser_list(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__;

        $id = Auth::user()->id;     
        $users = User::where('id',$id)->with('organisation')->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $invoices = [];
        $phone_number = $request->phone_number;
        $invoice_number = $request->invoice_number;
        if($phone_number && $invoice_number)
        {
            $publicusers = PublicUser::where('phone',$phone_number)->first();
            if(isset($publicusers))
            {
                $public_user_id = $publicusers->id;
                //echo "public_user_id=$public_user_id...<br>";
                $invoices = Invoice::where('public_user_id',$public_user_id)->where('invoice_no',$invoice_number)->where('organisation_id',$organisation_id)->where('payment_type',1)->with('publicuser','tickets')->get();
            }
        }
        /*if($invoice_number)
        {
            $invoices = Invoice::where('invoice_no',$invoice_number)->where('organisation_id',$organisation_id)->where('payment_type',1)->with('publicuser','tickets')->get();
        }*/
        return view('Sales/getticket_publicuser_list', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users','organisation_id','invoices'));
    }

    ////fee waiver approval///////
    public function feewaiver_approval()
    {
        $page_title = 'Fee Waiver Approval';
        $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__;
        $id = Auth::user()->id;
        $users = User::where('status',1)->get();
        $feewaiver_status=[];
        //get ticket_time_out
        $ticket_time_out  = "";
        $configration = Configuration::first();
        if(isset($configration))
        {
            $ticket_time_out = $configration->ticket_time_out;
        }
        $feewaiver_approval_list = Invoice::where('status',0)->where('payment_type',2)->where('payment_method',4)->orderBy('id','desc')->get();
        $invoice_list = Invoice::where('payment_type',2)->where('payment_method',4)->orderBy('id','desc')->get();
        foreach($invoice_list as $invoices)
        {
            $invoice_id = $invoices->id;
            $feewaiver_list = FeeWaiverApproval::where('invoice_id',$invoice_id)->where('approval_user',$id)->first();
            if(isset($feewaiver_list))
            {
                $feewaiver_status[$invoice_id] = $feewaiver_list->status;
            }
        }
        //dd($ticket_time_out);
        return view('Sales/feewaiver_approval', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users','feewaiver_approval_list','feewaiver_list','invoice_list','feewaiver_status','ticket_time_out'));
    }
    public function feewaiver_invoicedetails(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;
        $invoice = Invoice::where('id',$invoice_id)->with('organisation','tickets','user')->first();
        return view('Sales/feewaiver_invoicedetails', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoice'));
    }

    public function feewaiver_approval_post(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;
        $btnValue = $request->btnValue;
        $fee_waiver_percentage = $request->fee_waiver_percentage;
        $id = Auth::user()->id;  
        $approval_date = date("Y-m-d");
        $approval_status = 0;
        $invoice = Invoice::where('id',$invoice_id)->first();
        if(isset($invoice))
        {
            if($btnValue=="Approve")
            {
                //get ticket_time_out
                $ticket_time_out  = "";
                $configration = Configuration::first();
                if(isset($configration))
                {
                    $ticket_time_out = $configration->ticket_time_out;
                }
                $invoice_created_time = $invoice->created_at;
                $invoice_created_timeplus5min = date("Y-m-d H:i:s",strtotime($invoice_created_time." +".$ticket_time_out."minutes"));
                $invoice_created_timeplus5min_new = strtotime($invoice_created_timeplus5min);
                $currentdatetime = date("Y-m-d H:i:s");
                $currentdatetimestr = strtotime($currentdatetime);
                if($currentdatetimestr<$invoice_created_timeplus5min_new)
                {  
                    $approval_status = 1;
                    $organisation_id = $invoice->organisation_id;
                    ////update invoice table///////////////
                    $booking = new BookingClass;
                    $invoicearr = $booking->getnewInvoice($organisation_id);
                    $invoice_no = $invoicearr[0];
                    $invoice_time = $invoicearr[1];
                    $invoice_status = 1;
                    $invoice->invoice_no = $invoice_no;
                    $invoice->invoice_time = $invoice_time;
                    $invoice->status=$invoice_status;
                    $invoice->save();
                    /////////////////////////////////////////////////////
                    ////update ticket table///////////////////////////
                    $diff_amount =0;
                    $amount_new =0;
                    $invoice_amount =0;
                    $tickets = Ticket::where('invoice_id',$invoice_id)->get();
                    foreach($tickets as $ticket)
                    {
                        $ticket_id = $ticket->id;
                        $facility_id = $ticket->facility_id;
                        $ticket_amount = $ticket->amount;                        
                        $ticket_status = 1;
                        $ticket_verify_status = 1;
                        //to do update ticket number
                        $booking = new BookingClass;
                        $ticketno = $booking->getnewTicket($facility_id);
                        $ticket_update = Ticket::where('id',$ticket_id)->first();
                        if(isset($ticket_update))
                        {
                            if($fee_waiver_percentage)
                            {
                                $diff_amount = ($ticket_amount*$fee_waiver_percentage)/100;
                                $amount_new = $ticket_amount-$diff_amount;
                                $adult_rate = $ticket->adult_rate;
                                $diff_amount_adult = ($adult_rate*$fee_waiver_percentage)/100;
                                $adult_rate_new = $adult_rate-$diff_amount_adult;
                                $child_rate = $ticket->child_rate;
                                $diff_amount_child = ($child_rate*$fee_waiver_percentage)/100;
                                $child_rate_new = $child_rate-$diff_amount_child;
                            }
                            else
                            {
                                $amount_new = $ticket_amount;
                            }
                            if($invoice_amount)
                            {
                                $invoice_amount = $invoice_amount+$amount_new;
                            }
                            else
                            {
                                $invoice_amount = $amount_new;
                            }
                            $ticket_update->verify_status = 1;
                            $ticket_update->status = 1;
                            $ticket_update->ticket_no = $ticketno;
                            $ticket_update->amount = $amount_new;
                            $ticket_update->adult_rate = $adult_rate_new;
                            $ticket_update->child_rate = $child_rate_new;
                            $ticket_update->save();
                        }

                        /////update ticket seat table/////////////
                        $ticket_seats = TicketSeat::where('ticket_id',$ticket_id)->get();
                        foreach($ticket_seats as $ticket_seat)
                        {
                            $ticket_seat_id = $ticket_seat->id;
                            $ticket_seat_update = TicketSeat::where('id',$ticket_seat_id)->first();
                            if(isset($ticket_seat_update))
                            {
                                $ticket_seat_update->status = 1;
                                $ticket_seat_update->save();
                            }
                        }
                        ////////////////////////////////////

                        $invoice_obj = Invoice::where('id',$invoice_id)->first();
                        $invoice_obj->amount = $invoice_amount;
                        $invoice_obj->save();
                    }
                }
                else
                {
                    $approval_status = 3;
                }
            }
            if($btnValue=="Reject")
            {
                $approval_status = 2;
            }
            $feewaive_insert = FeeWaiverApproval::create([
                'invoice_id' => $invoice_id,
                'approval_date' => $approval_date,
                'approval_user' => $id,
                'status' => $approval_status,
                'fee_waiver_percentage' => $fee_waiver_percentage,
            ]);

            $fee_waiver_id = $feewaive_insert->id;

            $upload_count = $request->upload_count;
            if($upload_count>0)
            {
                for($i=1;$i<=$upload_count;$i++)
                {
                    $documentfile="documentfile".$i;                      
                    if ($request->hasFile($documentfile)) 
                    {
                        $fileobj=$request->file($documentfile)->getClientOriginalName();
                        $destpath="uploads/feewaiverdocument";
                        $custom_file_name =$fee_waiver_id.'-'.$fileobj;
                        echo "fileobj=$fileobj....custom_file_name=$custom_file_name....<br>";
                        $documentpath = $request->file($documentfile)->move(public_path().'/uploads/feewaiverdocument/', $custom_file_name);
                        $insert_id1 = FeeWaiverApprovalUpload::create([//model name database field name
                          'fee_waiver_id' => $fee_waiver_id,
                          'upload_desc' => $custom_file_name,
                        ]);
                    }
                        
                }
            }
            
        }
       return redirect('feewaiver_approval');
    }
    /////////////////////////////////////////////////

    ////ticket approval///////
    public function ticket_approval()
    {
        $page_title = 'Ticket Approval';
        $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__;
        $user_organisation_id = "";
        $id = Auth::user()->id;
        $user_organisation_id = Auth::user()->organisation_id;
        $users = User::where('status',1)->get();
        ///list with differently abled and packaged used
        if($user_organisation_id!="")
        {
            $invoice_sts_list= Invoice::where('status',0)->where('payment_type',2)->where('organisation_id',$user_organisation_id)->orderBy('id','desc')->get();
            $invoice_list = Invoice::where('payment_type',2)->where('organisation_id',$user_organisation_id)->orderBy('id','desc')->get();
            $ticket_approval_list = TicketApproval::where('approve_flag',0)->with('invoice','requestuser','approveduser')->whereHas('invoice', function($inv) use($user_organisation_id){ $inv->where('organisation_id',$user_organisation_id); })->orderBy('id','desc')->get();
            $approved_ticket_list = TicketApproval::where('approve_flag',1)->with('invoice','requestuser','approveduser')->whereHas('invoice', function($inv) use($user_organisation_id){ $inv->where('organisation_id',$user_organisation_id); })->orderBy('id','desc')->get();
        }
        else
        {
            $invoice_sts_list= Invoice::where('status',0)->where('payment_type',2)->orderBy('id','desc')->get();
            $invoice_list = Invoice::where('payment_type',2)->orderBy('id','desc')->get();
            $ticket_approval_list = TicketApproval::where('approve_flag',0)->with('invoice','requestuser','approveduser')->orderBy('id','desc')->get();
            $approved_ticket_list = TicketApproval::where('approve_flag',1)->with('invoice','requestuser','approveduser')->orderBy('id','desc')->get();
        }

        //dd($ticket_time_out);
        return view('Sales/ticket_approval', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users','ticket_approval_list','invoice_list','approved_ticket_list'));
    }
    public function ticket_invoicedetails(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__;
        $user_id = Auth::user()->id;
        $slugrolename= "";
        $userarr = UserRoles::where('user_id',$user_id)->where('status',1)->with('role')->first();
        if(isset($userarr))
        {
            $slugrolename = $userarr->role->guard_name;
        }
        
        $invoice_id = $request->invoice_id;
        $invoice = Invoice::where('id',$invoice_id)->with('organisation','tickets','user')->first();
        $configration = Configuration::first();
        //$ticket_approval_list = TicketApproval::where('invoice_id',$invoice_id)->where('approve_flag',0)->with('invoice','requestuser','approveduser','ticketuploads')->first();
        $ticket_approval_list = TicketApproval::where('invoice_id',$invoice_id)->with('invoice','requestuser','approveduser','ticketuploads')->first();
        return view('Sales/ticket_invoicedetails', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','invoice','configration','ticket_approval_list','slugrolename'));
    }

    public function ticket_approval_post(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;
        $btnValue = $request->btnValue;
        $ticket_percentage = $request->ticket_percentage;
        $remark_approver = $request->remark_approver;
        $id = Auth::user()->id;  
        $approval_date = date("Y-m-d");
        $approval_status = 0;
        $invoice = Invoice::where('id',$invoice_id)->first();
        if(isset($invoice))
        {
            if($btnValue=="Approve")
            {
                $approval_status = 1;
                $organisation_id = $invoice->organisation_id;
                ////update invoice table///////////////
                $booking = new BookingClass;
                $invoicearr = $booking->getnewInvoice($organisation_id);
                $invoice_no = $invoicearr[0];
                $invoice_time = $invoicearr[1];
                $invoice->invoice_no = $invoice_no;
                $invoice->invoice_time = $invoice_time;
                $invoice->save();
                /////////////////////////////////////////////////////
                ////update ticket table///////////////////////////
                $diff_amount =0;
                $amount_new =0;
                $invoice_amount =0;
                $tickets = Ticket::where('invoice_id',$invoice_id)->get();
                foreach($tickets as $ticket)
                {
                    $ticket_id = $ticket->id;
                    $facility_id = $ticket->facility_id;
                    $ticket_amount = $ticket->amount;                        
                    $ticket_status = 1;
                    $ticket_verify_status = 1;
                    //to do update ticket number
                    $booking = new BookingClass;
                    $ticketno = $booking->getnewTicket($facility_id);
                    $ticket_update = Ticket::where('id',$ticket_id)->first();
                    if(isset($ticket_update))
                    {
                        if($ticket_percentage)
                        {
                            $diff_amount = ($ticket_amount*$ticket_percentage)/100;
                            $amounts = $ticket_amount-$diff_amount;
                            $amount_new = ceil($amounts / 5) * 5; ///////////////rounded to multiple of 5////////////////////////////////
                            $adult_rate = $ticket->adult_rate;
                            $diff_amount_adult = ($adult_rate*$ticket_percentage)/100;
                            $adult_rate_new = $adult_rate-$diff_amount_adult;
                            $child_rate = $ticket->child_rate;
                            $diff_amount_child = ($child_rate*$ticket_percentage)/100;
                            $child_rate_new = $child_rate-$diff_amount_child;
                        }
                        else
                        {
                            $amount_new = $ticket_amount;
                        }
                        if($invoice_amount)
                        {
                            $invoice_amount = $invoice_amount+$amount_new;
                        }
                        else
                        {
                            $invoice_amount = $amount_new;
                        }
                        $ticket_update->verify_status = 1;
                        $ticket_update->ticket_no = $ticketno;
                        $ticket_update->amount = $amount_new;
                        $ticket_update->adult_rate = $adult_rate_new;
                        $ticket_update->child_rate = $child_rate_new;
                        $ticket_update->save();
                    }
                    ////////////////////////////////////

                    $invoice_obj = Invoice::where('id',$invoice_id)->first();
                    $invoice_obj->amount = $invoice_amount;
                    $invoice_obj->save();
                }
                
            }
            if($btnValue=="Reject")
            {
                $approval_status = 2;
                ///////////invoice
                $invoice->status=3;
                $invoice->save();
                ///////////////////////////////
                $tickets = Ticket::where('invoice_id',$invoice_id)->get();
                foreach($tickets as $ticket)
                {
                    $ticket_id = $ticket->id;
                    $ticket_update = Ticket::where('id',$ticket_id)->first();
                    if(isset($ticket_update))
                    {
                        $ticket_update->verify_status = 0;
                        $ticket_update->status = 3;
                        $ticket_update->save();
                    }
                    $ticket_seats = TicketSeat::where('ticket_id',$ticket_id)->get();
                    foreach($ticket_seats as $ticket_seat)
                    {
                        $ticket_seat_id = $ticket_seat->id;
                        $ticket_seat_update = TicketSeat::where('id',$ticket_seat_id)->first();
                        if(isset($ticket_seat_update))
                        {
                            $ticket_seat_update->status = 0;
                            $ticket_seat_update->save();
                        }
                    }
                }
            }

            $ticket_approval_list = TicketApproval::where('invoice_id',$invoice_id)->where('approve_flag',0)->first();
            if(isset($ticket_approval_list))
            {
                $ticket_approval_list->approve_flag = $approval_status;
                $ticket_approval_list->approved_date = $approval_date;
                $ticket_approval_list->percentage = $ticket_percentage;
                $ticket_approval_list->approved_user_id = $id;
                $ticket_approval_list->remark_approver = $remark_approver;
                $ticket_approval_list->save();
            }
            $ticket_approval_id = $ticket_approval_list->id;
            $upload_count = $request->upload_count;
            if($upload_count>0)
            {
                for($i=1;$i<=$upload_count;$i++)
                {
                    $documentfile="documentfile".$i;                      
                    if ($request->hasFile($documentfile)) 
                    {
                        $fileobj=$request->file($documentfile)->getClientOriginalName();
                        $destpath="uploads/ticketdocument";
                        $custom_file_name =$ticket_approval_id.'-'.$fileobj;
                        $documentpath = $request->file($documentfile)->move(public_path().'/uploads/ticketdocument/', $custom_file_name);

                        $insert_id1 = TicketApprovalUpload::create([    //model name database field name
                          'ticket_approval_id' => $ticket_approval_id,
                          'file_upload' => $custom_file_name,
                          'user_id' => $id,
                        ]);
                    }
                        
                }
            }
            
        }
       return redirect('ticket_approval');
    }

    ////view approved tickets///////
    public function approved_ticket_list()
    {
        $page_title = 'Approved Requests';
        $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__;
        $id = Auth::user()->id;
        $user_organisation_id = Auth::user()->organisation_id;
        $users = User::where('status',1)->get();
        $approved_ticket_list = TicketApproval::where('approve_flag',1)->with('invoice','requestuser','approveduser')->whereHas('invoice', function($inv) use($user_organisation_id){ $inv->where('organisation_id',$user_organisation_id); })->orderBy('id','desc')->get();
        //dd($ticket_time_out);
        return view('Sales/approved_ticket_list', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','approved_ticket_list'));
    }

    ////view pending tickets///////
    public function pending_ticket_list()
    {
        $page_title = 'Pending Requests';
        $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__;
        $id = Auth::user()->id;
        $user_organisation_id = Auth::user()->organisation_id;
        $users = User::where('status',1)->get();
        $pending_ticket_lists = TicketApproval::where('approve_flag',0)->with('invoice','requestuser','approveduser')->whereHas('invoice', function($inv) use($user_organisation_id){ $inv->where('organisation_id',$user_organisation_id); })->orderBy('id','desc')->get();
        //dd($ticket_time_out);
        return view('Sales/pending_ticket_list', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','pending_ticket_lists'));
    }


    //////cancel ticket and approve///////////////////
    public function ticket_cancellation()
    {   
        $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__;
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->with('organisation')->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $facility_short_codes = Facility::where('organisation_id',$organisation_id)->get();

        $permission_arr = [];
        $userroles=UserRoles::where('user_id',$id)->get();
        foreach($userroles as $userrole)
        {
            $role_id_arr[] = $userrole->role_id;
        }
        $rolepermissions = RolePermission::whereIn('role_id',$role_id_arr)->with('permission')->get();
        foreach($rolepermissions as $rolepermission)
        {
            $permission_arr[] = $rolepermission->permission->name;
        }
        $ticket_cancel_list = TicketCancelApprove::with('ticket','showtime','user')->orderBy('id','desc')->get();
        
        return view('Sales/ticket_cancellation', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','users','organisation_id','facility_short_codes','ticket_cancel_list','permission_arr'));
    }

    public function ticket_cancel_view(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__;
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->with('organisation')->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $tickets = [];
        $ticket_number = $request->ticket_number;
        $facility_id = $request->facility_id;
        if($ticket_number && $facility_id)
        {
            $tickets = Ticket::where('ticket_no',$ticket_number)->where('facility_id',$facility_id)->where('status',1)->with('invoice')->whereHas('invoice',function($showt) use($organisation_id) { $showt->where('payment_type',2)->where('organisation_id',$organisation_id); })->first();
            $ticket_count = Ticket::where('ticket_no',$ticket_number)->where('facility_id',$facility_id)->where('status',1)->with('invoice')->whereHas('invoice',function($showt) use($organisation_id) { $showt->where('payment_type',2)->where('organisation_id',$organisation_id); })->count();
        }
        $show_date ="";
        $totalrefund = 0;
        $refundticket = [];
        $cancelconf="";
        $ticket_cancel_list_count =0;
        //check if this invoice can be cancelled based on the date of cancellation
        if(isset($tickets))
        {
            $show_date = $tickets->show_date;
            $cancel_date = date('Y-m-d');
            if(strtotime($cancel_date)>strtotime($show_date))
            {
                return view('Sales.cannotcancel_ticket', 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();
            
            $show_id = $tickets->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(!$tickets->noofseats)
            {
                $show_from_time = $showtime->to_time;
                //$showtimeval =$show_date.' '.$show_from_time;
                $showtimeval =$show_date.' '.'10:00:00';
                //$showtimeval = strtotime($showtimeval) - (1 * 1 * 60);//subtracting 1 hour for galleries kind of shows
                $showtimeval = strtotime($showtimeval);
            }
            $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;
                     $ticketamount = $tickets->amount;
                     $refundamount = $ticketamount*$refundperc/100;
                     $refundticket[$tickets->id] = $refundamount;
                }
                else
                {
                    $refundamount = 0;
                    $refundticket[$tickets->id] = $refundamount;
                }
            }
            else
            {
                $refundamount = 0;
                $refundticket[$tickets->id] = $refundamount;
            }

            //check if show is cancelled
            $checkshowcancel = ShowCancel::where('facility_id',$facility_id)->where('show_date',$show_date)->where('show_time_id',$show_id)->where('approval_flag',1)->count();
            if($checkshowcancel)
            {
                //refund 100%
                $refundamount = $ticketamount*100/100;
                $refundticket[$tickets->id] = $refundamount;

            }

            $ticket_cancel_list_count = TicketCancelApprove::where('approval_status',1)->where('ticket_id',$tickets->id)->count();
        }
        return view('Sales/ticket_cancel_view', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','tickets','refundticket','cancelconf','ticket_cancel_list_count','ticket_count'));
    }

    /////save the ticket cancel approve table for initiate the approval request/////////////////////////////////
    public function ticket_cancellation_approval(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;
        $ticket_id = $request->ticket_id;

        //check if invoice id is this user's invoice id else return error
        $id = Auth::user()->id;  
        $invoice = Invoice::where('id',$invoice_id)->with('tickets')->first();
        

        $show_date ="";
        $tickets = Ticket::where('id',$ticket_id)->where('status',1)->first();
        if(isset($tickets))
        {
            $show_date = $invoice->show_date;
            $invoice_user = $tickets->invoice->user_id;
        }

        if($invoice_user!=$id)
        {
            //dd('Error');
            return view('Sales.error_ticket', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        $ticketcancelapproval_insert = "";
        //check if this invoice is already cancelled
        $invoice_cancel_check = TicketCancelApprove::where('ticket_id',$ticket_id)->count();
        if($invoice_cancel_check)
        {
            //dd('This invoice is already cancelled');
            return view('Sales.alreadycancel_ticket', 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('Sales.cannotcancel_ticket', 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;
        if(isset($tickets))
        {
            $show_id = $tickets->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(!$tickets->noofseats)
            {
                $show_from_time = $showtime->to_time;
                //$showtimeval =$show_date.' '.$show_from_time;
                $showtimeval =$show_date.' '.'10:00:00';
                //$showtimeval = strtotime($showtimeval) - (1 * 1 * 60);//subtracting 1 hour for galleries kind of shows
                $showtimeval = strtotime($showtimeval);
            }

            $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 = $tickets->amount;

                    $refundamount = $ticketamount*$refundperc/100;

                    //check if show is cancelled
                    $checkshowcancel = ShowCancel::where('show_date',$show_date)->where('show_time_id',$show_id)->where('approval_flag',1)->count();
                    if($checkshowcancel)
                    {
                        //refund 100%
                        $refundamount = $ticketamount*100/100;
                        
                    }


                    $totalrefund += $refundamount;
                    $refund_count = TicketCancelApprove::where('user_id',$id)->where('show_time_id',$show_id)->where('show_date',$show_date)->where('ticket_id',$ticket_id)->count();
                    if($refund_count==0)
                    {
                         //entry to refund table
                         $ticketcancelapproval_insert = TicketCancelApprove::create([
                            'show_date' => $show_date,
                            'show_time_id' => $show_id,
                            'ticket_id' => $ticket_id,
                            'payment_type' => 2,
                            'ticket_no' => $tickets->ticket_no,
                            'noof_adult' => $tickets->noof_adult,
                            'noof_child' => $tickets->noof_child,
                            'refund_amount' => $refundamount,
                            'approval_status' => 0,
                            'user_id' => $id
                         ]);
                        
                    }
                }
            }
        }
        if($ticketcancelapproval_insert)
        {
            return redirect('ticket_cancellation')->with('success', 'Ticket has been send to cancellation approval');
        }
        else
        {
            return redirect('ticket_cancellation')->with('error', 'Failed! ');
        }
    }

    ///////final cancellation approval ////////////////////////////////////////
    public function ticket_cancel_final_approval(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__;

        $ticket_cancel_id = $request->ticket_cancel_id;
        $ticket_id = $request->ticket_id;

        //check if invoice id is this user's invoice id else return error
        $id = Auth::user()->id;  
        
        $show_date ="";
        $tickets = Ticket::where('id',$ticket_id)->where('status',1)->with('invoice')->first();
        if(isset($tickets))
        {
            $show_date = $tickets->show_date;
            $invoice_user = $tickets->invoice->user_id;
            $invoice_id = $tickets->invoice_id;
        }

        /*if($invoice_user!=$id)
        {
            //dd('Error');
            return view('Sales.error_ticket', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class'));
        }
        */
        $ticketcancelapproval_insert = "";
        //check if this invoice is already cancelled
        $invoice_cancel_check = TicketCancelApprove::where('ticket_id',$ticket_id)->where('approval_status',1)->count();
        if($invoice_cancel_check)
        {
            //dd('This invoice is already cancelled');
            return view('Sales.alreadycancel_ticket', 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('Sales.cannotcancel_ticket', 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;
        if(isset($tickets))
        {
            $show_id = $tickets->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(!$tickets->noofseats)
            {
                $show_from_time = $showtime->to_time;
                //$showtimeval =$show_date.' '.$show_from_time;
                $showtimeval =$show_date.' '.'10:00:00';
                //$showtimeval = strtotime($showtimeval) - (1 * 1 * 60);//subtracting 1 hour for galleries kind of shows
                $showtimeval = strtotime($showtimeval);
            }

            $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 = $tickets->amount;
                    $flg = 0;
                    $refundamount = $ticketamount*$refundperc/100;
                    //check if show is cancelled
                    $checkshowcancel = ShowCancel::where('show_date',$show_date)->where('show_time_id',$show_id)->where('approval_flag',1)->count();
                    if($checkshowcancel)
                    {
                        //refund 100%
                        $refundamount = $ticketamount*100/100;
                        
                    }
                    $totalrefund += $refundamount;
                    $refund_count = TicketCancelApprove::where('user_id',$id)->where('show_time_id',$show_id)->where('show_date',$show_date)->where('ticket_id',$ticket_id)->count();
                    //dd($refund_count);
                    if(!$refund_count)
                    {
                        $approvaltime = now();
                        $ticketcancellist = TicketCancelApprove::where('id',$ticket_cancel_id)->where('approval_status',0)->first();
                        $ticketcancellist->approval_status = 1;
                        $ticketcancellist->approval_user_id = $id;
                        $ticketcancellist->approval_datetime = $approvaltime;
                        $ticketcancellist->cancel_date = $cancel_date;
                        $ticketcancellist->save();
                    
                        $refund_insert = Refund::create([
                                'show_time_id' => $show_id,
                                'show_date' => $show_date,
                                'invoice_id' => $invoice_id,
                                'payment_type' => 2,
                                'ticket_id' => $tickets->id,
                                'adult_count' =>$tickets->noof_adult,
                                'child_count' => $tickets->noof_child,
                                'refund_amount' => $totalrefund,
                                'refund_status' => 1,
                                'user_id' =>    $id,         
                            ]);

                        $cancel_count = CancelTicket::where('user_id',$id)->where('cancel_date',$cancel_date)->where('invoice_id',$invoice_id)->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),
                                'user_id' => $id,
                                'refund_amount' => $totalrefund,
                                'refund_status' => 1,
                            ]);
                        }

                        //cancel in tickets table with status 2
                        $ticketobj = Ticket::where('id',$ticket_id)->first();
                        $ticketobj->status = 2;
                        $ticketobj->cancel_date = $cancel_date;
                        $ticketobj->save();

                        $flg=1;
                                               
                    }
                }
            }
        }
        if($flg==1)
        {
            return redirect('ticket_cancellation')->with('success', 'cancellation Approved for the Ticket');
        }
        else
        {
            return redirect('ticket_cancellation')->with('error', 'Failed! ');
        }
        //return view('Sales.ticket_cancellation', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','mess'));
    }

}
