<?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 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\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\ShowCancel;
use App\Models\Sales\Refund;
use App\Models\Sales\CancelTicket;
use App\Models\Settings\HolidayMaster;
use App\Models\Settings\WeeklyOffMaster;
use App\Helpers\BookingClass;
use App\Helpers\SMSClass;
use Request as req;

class SpecialShowController 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 special_show_tickets()
    {   
        $page_title = 'Special Show 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/special_show_tickets', 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_special_show(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 special_show_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);
        $paymentmethods = PaymentMethod::all();
        $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
        $ticket_booking_max_days ="";
        $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.nospecialshowoffline', 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
        $seats =[];
        $seatcount=[];
        $showon=[];
        $layouts = [];
        $facilityon =[];
        $facilities = Facility::where('organisation_id',$inputCentre)->where('active_flag',1)->orderBy('order_by','asc')->with('showtimings')->whereHas('showtimings',function($showt) use($date_of_visit) { $showt->where('show_flag',1)->where('date',$date_of_visit); })->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;
                $show_flag = $show->show_flag;
                $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);
                    $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;
                }
            }
        }
        return view('Sales.special_show_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'));
    }

    /////////show cancel//////////////////////////////
    public function show_cancellation()
    {   
        $page_title = 'Show Cancellation';
        $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__;
        $role_id_arr =[];
        $permission_arr = [];
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->first();
        $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;
        }

        $organisation_id = Auth::user()->organisation_id;
        if($organisation_id!="")
        {
            $facilities = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->with('organisation')->get();  
            $organisations = Organisation::where('id',$organisation_id)->get();
            $cancelshows = ShowCancel::with('facility','showtime','approvedby','cancelledby')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->get();
        }
        else
        {
            $facilities = Facility::where('active_flag',1)->with('organisation')->get();  
            $organisations = Organisation::all();
            $cancelshows = ShowCancel::with('facility','showtime','approvedby','cancelledby')->get();
        }
        return view('Sales/show_cancellation', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','facilities','users','organisation_id','cancelshows','permission_arr','organisations'));
    }

    public function get_ticket_count($facility_id, $show_id, $show_date)
    {
        $canceldata = 0;
        $totaladultcount = Ticket::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_id)->where('status',1)->sum('noof_adult');
        $totalchildcount = Ticket::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_id)->where('status',1)->sum('noof_child');
        $seats[0] = $totaladultcount + $totalchildcount;
        $seats[1] = Ticket::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_id)->where('status',1)->count();
        $canceldata = ShowCancel::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_id)->where('approval_flag',1)->count();
        if($canceldata!=0)
        {
            $seats[2] = "This Show is Already Cancelled";
        }
        else
        {
            $seats[2] = "";
        }
        return $seats;
    }

    public function show_cancellation_post(Request $request)
    {
        $show_date = $request->show_date;
        $facility_id = $request->facility_id;
        $show_time_id = $request->show_time_id;
        $cancel_datetime = date("Y-m-d h:i:s");
        $cancelled_by = Auth::user()->id; 
        $showcancel_count = ShowCancel::where('facility_id',$facility_id)->where('show_date',$show_date)->where('show_time_id',$show_time_id)->count();
        if($showcancel_count==0)
        {
            $cancel_insert = ShowCancel::create([
                'facility_id' => $facility_id,
                'show_time_id' => $show_time_id,
                'show_date' => $show_date,
                'cancelled_time' => $cancel_datetime,
                'cancelled_by' => $cancelled_by,
                'approval_flag' => 0,
            ]);
        }
        //////////////////////////////////////////////////
        return redirect()->back()->with('success', 'Success! Show Cancellation is sent for Approval.');
    }  
    /////offline tickets////////////////
    public function offline_tickets($cancel_id)
    {   
        $page_title = 'Offline 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__;
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $cancelshows = ShowCancel::where('id',$cancel_id)->with('facility','showtime')->first();
        if(isset($cancelshows))
        {
            $show_date = $cancelshows->show_date;
            $facility_id = $cancelshows->facility_id;
            $show_time_id = $cancelshows->show_time_id;
        }
        $tickets = Ticket::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_time_id)->where('status',1)->with('invoice','facility')->whereHas('invoice',function($showt) { $showt->where('payment_type',2); })->get();
        //dd($tickets);
        return view('Sales/offline_tickets', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','tickets','cancelshows'));
    }

    /////offline tickets////////////////
    public function online_tickets($cancel_id)
    {   
        $page_title = 'Online 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__;
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }
        $cancelshows = ShowCancel::where('id',$cancel_id)->with('facility','showtime')->first();
        if(isset($cancelshows))
        {
            $show_date = $cancelshows->show_date;
            $facility_id = $cancelshows->facility_id;
            $show_time_id = $cancelshows->show_time_id;
        }
        $tickets = Ticket::where('show_date',$show_date)->where('facility_id',$facility_id)->where('show_time_id',$show_time_id)->where('status',1)->with('invoice','facility')->whereHas('invoice',function($showt) { $showt->where('payment_type',1); })->get();
        //dd($tickets);
        return view('Sales/online_tickets', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','tickets','cancelshows'));
    }

    public function approve_cancellation(Request $request)
    {
        $cancel_id = $request->cancel_id;
        $approve_date = date("Y-m-d");
        $approved_by = Auth::user()->id; 
        $showcancel_update = ShowCancel::where('id',$cancel_id)->first();

        $facility_id = $showcancel_update->facility_id;
        $show_time_id = $showcancel_update->show_time_id;
        $show_date = $showcancel_update->show_date;

        $showcancel_update->approval_flag = 1;
        $showcancel_update->approved_by = $approved_by;
        $showcancel_update->approved_date = $approve_date;
        $showcancel_update->save();

        ////refund table insertion/////////////////////
        

        $id = Auth::user()->id;  
        $invoice_user_id= "";
        $invoice_publicuser_id = "";
        $mobileNumber ="";
        $tickets = Ticket::where('facility_id',$facility_id)->where('show_time_id',$show_time_id)->where('show_date',$show_date)->where('status',1)->get();
        foreach($tickets as $ticket)
        {
            $invoice_id = $ticket->invoice_id;
            $invoice_user_id = $ticket->invoice->user_id;
            $invoice_publicuser_id = $ticket->invoice->public_user_id;
            if($invoice_publicuser_id==NULL)
                continue;
            if($invoice_user_id!=NULL)
            {
                $mobileNumber = $ticket->invoice->visitor_phone_number;
            }
            if($invoice_publicuser_id!=NULL)
            {
                $publicusers = PublicUser::where('id',$invoice_publicuser_id)->where('status',1)->first();
                if(isset($publicusers))
                {
                    $mobileNumber = $publicusers->phone;
                }
            }
            $refund_count = Refund::where('user_id',$id)->where('show_time_id',$show_time_id)->where('show_date',$show_date)->where('invoice_id',$invoice_id)->where('ticket_id',$ticket->id)->count();
            if($refund_count==0)
            {
                $refund_insert = Refund::create([
                    'show_time_id' => $show_time_id,
                    'show_date' => $show_date,
                    'invoice_id' => $ticket->invoice_id,
                    'payment_type' => 1,  //online
                    'ticket_id' => $ticket->id,
                    'adult_count' =>$ticket->noof_adult,
                    'child_count' => $ticket->noof_child,
                    'refund_amount' => $ticket->amount,
                    'refund_status' => 0,
                    'user_id' =>    $id,         
                ]);

                //entry to cancel ticket table
                $cancel_date = date('Y-m-d');
                $time_of_cancellation = time();
                $cancelticket_insert = CancelTicket::create([
                    'invoice_id' => $ticket->invoice_id,
                    'cancel_date' => $cancel_date,
                    'cancel_time' => date("Y-m-d H:i:s",$time_of_cancellation),
                    'user_id' => $id,
                    'refund_amount' => $ticket->amount,
                    'refund_status' => 0,
                    'partial_cancellation_flag' => 1,
                ]);
            }
            //cancel in tickets table with status 2
            $ticket_id = $ticket->id;
            $ticketobj = Ticket::where('id',$ticket_id)->first();
            $ticketobj->status = 2;
            $ticketobj->save();

            /////send sms to each mobile number///////////////////////
            if($mobileNumber!="")
            {
                $smssend = new SMSClass;
                $smsarr = $smssend->sendSMSCancelShows($facility_id, $show_time_id, $show_date, $mobileNumber, $country_code='+91');
            }
            ////////////////////////////////////////////////

        }

        return redirect('show_cancellation');
    }

}
