<?php

namespace App\Http\Controllers;
use Illuminate\Support\Collection;
use Validator;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Helper\MailHelper as MailHelper;
use Mail;
use DatePeriod;
use DateTime;
use DateInterval;
use App\Mail\ForgotPassword;
use App\Models\User;
use App\Models\Sales\Invoice;
use App\Models\Sales\Ticket;
use App\Models\Sales\ShowCancel;
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\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\Helpers\BookingClass;

class HomeController 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 index()
    {
        if(isset(Auth::user()->id))
        {
            $user_id = Auth::user()->id;
        }
        else
        {
            $user_id = 0;
        }
        $slugrolename= "";
        $userarr = UserRoles::where('user_id',$user_id)->where('status',1)->with('role')->first();
        if(isset($userarr))
        {
            $slugrolename = $userarr->role->guard_name;
        }
        //dd($slugrolename);
        if($slugrolename=="counteruser")
        {
            return redirect('/ticket_sales');
        }
        $user_organisation_id = Auth::user()->organisation_id;
        $page_title = 'Dashboard';
        $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__;
        $organisations = Organisation::all();
        $month = 'January'.','.'February'.','.'March'.','.'April'.','.'May'.','.'June'.','.'July'.','.'August'.','.'September'.','.'October'.','.'November'.','.'December';
        $invoice_amt =[];
        $invoice_amt_count ="";
        $month_arr=explode(",",$month);
        $invoice_amt_max = 0;
        $s=0;

        $facility_name_arr= [];
        $organisation_name_arr = [];
        $organisations_facility = Organisation::all();
        foreach($organisations_facility as $org_fac)
        {
            $org_id = $org_fac->id;
            $org_name = $org_fac->organisation_name;
            $organisation_name_arr[] = $org_name;
            //echo "org_id=$org_id...<br>";
            $fac_org_lists = Facility::where('organisation_id',$org_id)->get();
            foreach($fac_org_lists as $fac_org)
            {
                $fac_id = $fac_org->id;
                $fac_name = $fac_org->facility_name;
                //echo "fac_id=$fac_id....fac_name=$fac_name...<br>";
                $facility_name_arr[$org_id][] = $fac_name;
            }
        }
        ////sales revenue line chart ///////////////////////
        $current_year = date("Y");
            foreach ($month_arr as $month_value) 
            {
                $invoice_amt[$month_value] = Invoice::where(\DB::raw("DATE_FORMAT(invoice_date, '%M')"),$month_value)->where(\DB::raw("DATE_FORMAT(invoice_date, '%Y')"),$current_year)->where('status',1)->sum('amount');
                if($invoice_amt_max < $invoice_amt[$month_value])
                {
                    $invoice_amt_max  =$invoice_amt[$month_value]; 
                }
                if($s)
                {
                    $invoice_amt_count = $invoice_amt_count.",".$invoice_amt[$month_value];
                }
                else
                {
                    $invoice_amt_count = $invoice_amt[$month_value];
                }
                $s++;
                //echo "invoice_amt_count=$invoice_amt_count...<br>";
            }
            $invoice_step_size = $invoice_amt_max/5;
        ///////////////////////////////////////////////////

        ///// faiclitywise visitor count --donut chart//////////////////
            $ticket_facility = "";
            $org_facility = Organisation::first();
            if(isset($org_facility))
            {
                $organisation_id = $org_facility->id;
            }
            $f=0;
            $facilities = Facility::where('organisation_id',$organisation_id)->get();
            foreach($facilities as $facility)
            {
                $facility_id = $facility->id;
                $facility_name = $facility->facility_name;               
                $currentdate = date("Y-m-d");
                $adult_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$currentdate)->where('status',1)->sum('noof_adult');
                $child_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$currentdate)->where('status',1)->sum('noof_child');
                $tickets_count[$facility_name] = $adult_count[$facility_name] + $child_count[$facility_name];
                if($f)
                {
                    $ticket_facility = $ticket_facility.",".$tickets_count[$facility_name];
                }
                else
                {
                    
                    $ticket_facility = $tickets_count[$facility_name];
                }
                $f++;
            }
            $tickets_count = json_encode($tickets_count);
        /////////////////////////////////////////////////////

        ////////////facility wise visitor count weekly -- simple line graph/./////////////////
            /////ticket faiclity//////////////////
            $ticket_facility_org = 0;
            $org_facility_tickets_count ="";
            $current_date = date("Y-m-d");
            $ts = strtotime($current_date);
            $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
            $start_date = date('Y-m-d', $start);
            $end_date = date('Y-m-d', strtotime('next saturday', $start));
            $end_date_plus_onday = date( "Y-m-d", strtotime( $end_date ."+1 day" ) );
            $weekly_dates = new DatePeriod(
                            new DateTime($start_date),
                            new DateInterval('P1D'),
                            new DateTime($end_date_plus_onday)
                         );
            $i=0;
            $date_show =[];
            foreach ($weekly_dates as $weekly_dates_value) 
            {
                $date_show[$i]= $weekly_dates_value->format('Y-m-d');
                $i++;      
            }
           // dd($date_show);
            $org_fac = Organisation::first();
            if(isset($org_fac))
            {
                $organisation_id = $org_fac->id;
                $k=0;
                $child_count_week = 0;
                    $adult_count_week = 0;
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->get();
                foreach($facilities_org as $facility_org)
                {
                    $facility_org_id = $facility_org->id;                    
                    $fac_name_linegraph = $facility_org->facility_name;
                    $org_facility_tickets[$k]['name'] = $fac_name_linegraph;
                    $org_facility_tickets[$k]['data'] = [];
                    
                    foreach($date_show as $date_shows)
                    {          
                        $adult_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_adult');
                        $child_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_child');            
                        $org_facility_tickets[$k]['data'][] = $adult_count_week + $child_count_week;  
                    }
                    $k++;
                }
            }
            $org_facility_tickets = json_encode($org_facility_tickets);
            //dd($org_facility_tickets);
        //////////////////////////////////////////////////////////////

        ///////organisation wise visitor count -- bar chart////////////////////
            $organisations_bar = Organisation::all();
            foreach($organisations_bar as $org_bar)
            {
                $orgn_id = $org_bar->id;
                $current_date = date("Y-m-d");
                $adult_count_org[$orgn_id] = Ticket::where('show_date',$currentdate)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_adult');
                $child_count_org[$orgn_id] = Ticket::where('show_date',$currentdate)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_child');
                $organisation_tickets_count[$orgn_id] = $adult_count_org[$orgn_id] + $child_count_org[$orgn_id];
            }
            //$organisation_tickets_count = json_encode($organisation_tickets_count);
        /////////////////////////////////////////////////////////////////////

        //////total number of monthly visitors in each organisation////////////////////////////////
            $tickets_count_org =[];
            $tickets_count_org_daily = [];
            $tickets_org_percentage= [];
            $today_date = date("Y-m-d");
            $current_year = date("Y");
            $current_month = date("m");
            $totaladultcount = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->sum('noof_adult');

            $totalchildcount = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->sum('noof_child');
            $total_ticket_count = $totaladultcount + $totalchildcount;
            foreach($organisations as $organisations_tickets)
            {
                $organisation_id = $organisations_tickets->id;
                $date_sel = date("Y-m-d");
                $adult_count_monthly_org[$organisation_id] = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_adult');
                //dd($adult_count_monthly_org[$organisation_id]);
                
                $child_count_monthly_org[$organisation_id] = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_child');
                
                $tickets_count_org[$organisation_id] = $adult_count_monthly_org[$organisation_id] + $child_count_monthly_org[$organisation_id];
                //dd($tickets_count_org[$organisation_id]);
                if($total_ticket_count)
                {
                    $tickets_org_percentage[$organisation_id] = ($tickets_count_org[$organisation_id] / $total_ticket_count) * 100;
                }

                $adult_count_daily = Ticket::where('show_date',$today_date)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_adult');
                $child_count_daily = Ticket::where('show_date',$today_date)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_child');
                $tickets_count_org_daily[$organisation_id] = $adult_count_daily + $child_count_daily;

            }
            //dd($tickets_count_org);
        //////////////////////////////////////////////////////////////////////////////////////

        ////////////sales revenue in block/////////////////////////////
            $todate = date("Y-m-d");
            $sales_revenue_organisation =[];
            $salesrevenue_org_percentage =[];
            $total_sales_revenue = Invoice::where('invoice_date',$todate)->where('status',1)->sum('amount');
            foreach($organisations as $organisation_sales_revenue)
            {
                $organisation_revenue_id = $organisation_sales_revenue->id;               
                $sales_revenue_organisation[$organisation_revenue_id] = Invoice::where('organisation_id',$organisation_revenue_id)->where('invoice_date',$todate)->where('status',1)->sum('amount');
                if($total_sales_revenue)
                {
                    $salesrevenue_org_percentage[$organisation_id] = ($sales_revenue_organisation[$organisation_revenue_id] / $total_sales_revenue) * 100;
                }
            }

        ///////////////////////////////////////////////////////////

        /////chack seat availability ///////
            $id = Auth::user()->id;     
            $users = User::where('id',$id)->where('status',1)->first();
            if(isset($users))
            {
                $organisation_id = $users->organisation_id;
            }
            $noofseats = "";
            $show_start_time ="";
            $show_timings =[];
            $facility_arr = [];
            $n=1;
            $facility_id ="";
            $showon = [];
            if(!$organisation_id)
            {
                $org_facility = Organisation::first();
                if(isset($org_facility))
                {
                    $organisation_id = $org_facility->id;
                }
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->whereNotNull('noofseats')->get();
            }
            else
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->whereNotNull('noofseats')->get();
            foreach($facilities_org as $facilities)
            {
                $facility_id = $facilities->id;
                foreach($facilities->showtimings as $show)
                {
                    $date_of_visit = date("Y-m-d");
                    $show_id = $show->id;
                    $showon[$show_id] = 1;
                    $show_from_time = $show->from_time;
                    //get showtime
                    $showtime=$date_of_visit.' '.$show_from_time;
                    /*if(strtotime($showtime) && $facilities->noofseats)
                        $showon[$show_id] = 0;
                    //check if this show has minimum adult plus child seats available if not mark showon to 0//todo
                    if($facilities->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 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 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($invoice_amt);
        //////////////////////////////////////

        //dd($salesrevenue_org_percentage);
        return view('home', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','month','invoice_amt','invoice_amt_count','facilities','ticket_facility','organisations','invoice_amt_max','invoice_step_size','tickets_count_org','tickets_org_percentage','total_ticket_count','ticket_facility_org','org_facility_tickets_count','facilities_org','showon','facility_name_arr','tickets_count','organisation_name_arr','organisation_tickets_count','org_facility_tickets','sales_revenue_organisation','total_sales_revenue','salesrevenue_org_percentage','user_organisation_id','tickets_count_org_daily','date_show'));   
    }

    public function index2()
    {
        $user_organisation_id = Auth::user()->organisation_id;
        $page_title = 'Dashboard';
        $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__;
        $organisations = Organisation::all();
        $month = 'January'.','.'February'.','.'March'.','.'April'.','.'May'.','.'June'.','.'July'.','.'August'.','.'September'.','.'October'.','.'November'.','.'December';
        $invoice_amt =[];
        $invoice_amt_count ="";
        $month_arr=explode(",",$month);
        $invoice_amt_max = 0;
        $s=0;

        $facility_name_arr= [];
        $organisation_name_arr = [];
        $organisations_facility = Organisation::all();
        foreach($organisations_facility as $org_fac)
        {
            $org_id = $org_fac->id;
            $org_name = $org_fac->organisation_name;
            $organisation_name_arr[] = $org_name;
            //echo "org_id=$org_id...<br>";
            $fac_org_lists = Facility::where('organisation_id',$org_id)->get();
            foreach($fac_org_lists as $fac_org)
            {
                $fac_id = $fac_org->id;
                $fac_name = $fac_org->facility_name;
                //echo "fac_id=$fac_id....fac_name=$fac_name...<br>";
                $facility_name_arr[$org_id][] = $fac_name;
            }
        }
        ////sales revenue line chart ///////////////////////
         $current_year = date("Y");
            foreach ($month_arr as $month_value) 
            {
                $invoice_amt[$month_value] = Invoice::where(\DB::raw("DATE_FORMAT(invoice_date, '%M')"),$month_value)->where(\DB::raw("DATE_FORMAT(invoice_date, '%Y')"),$current_year)->where('status',1)->sum('amount');
                if($invoice_amt_max < $invoice_amt[$month_value])
                {
                    $invoice_amt_max  =$invoice_amt[$month_value]; 
                }
                if($s)
                {
                    $invoice_amt_count = $invoice_amt_count.",".$invoice_amt[$month_value];
                }
                else
                {
                    $invoice_amt_count = $invoice_amt[$month_value];
                }
                $s++;
                //echo "invoice_amt_count=$invoice_amt_count...<br>";
            }
            $invoice_step_size = $invoice_amt_max/5;
        ///////////////////////////////////////////////////

        ///// faiclitywise visitor count --donut chart//////////////////
            $ticket_facility = "";
            $org_facility = Organisation::first();
            if(isset($org_facility))
            {
                $organisation_id = $org_facility->id;
            }
            $f=0;
            $facilities = Facility::where('organisation_id',$organisation_id)->get();
            foreach($facilities as $facility)
            {
                $facility_id = $facility->id;
                $facility_name = $facility->facility_name;               
                $currentdate = date("Y-m-d");
                $adult_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$currentdate)->where('status',1)->sum('noof_adult');
                $child_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$currentdate)->where('status',1)->sum('noof_child');
                $tickets_count[$facility_name] = $adult_count[$facility_name] + $child_count[$facility_name];
                if($f)
                {
                    $ticket_facility = $ticket_facility.",".$tickets_count[$facility_name];
                }
                else
                {
                    
                    $ticket_facility = $tickets_count[$facility_name];
                }
                $f++;
            }
            $tickets_count = json_encode($tickets_count);
        /////////////////////////////////////////////////////

        ////////////facility wise visitor count weekly -- simple line graph/./////////////////
            /////ticket faiclity//////////////////
            $ticket_facility_org = 0;
            $org_facility_tickets_count ="";
            $current_date = date("Y-m-d");
            $ts = strtotime($current_date);
            $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
            $start_date = date('Y-m-d', $start);
            $end_date = date('Y-m-d', strtotime('next saturday', $start));
            $end_date_plus_onday = date( "Y-m-d", strtotime( $end_date ."+1 day" ) );
            $weekly_dates = new DatePeriod(
                            new DateTime($start_date),
                            new DateInterval('P1D'),
                            new DateTime($end_date_plus_onday)
                         );
            $i=0;
            $date_show =[];
            foreach ($weekly_dates as $weekly_dates_value) 
            {
                $date_show[$i]= $weekly_dates_value->format('Y-m-d');
                $i++;      
            }
           // dd($date_show);
            $org_fac = Organisation::first();
            if(isset($org_fac))
            {
                $organisation_id = $org_fac->id;
                $k=0;
                $child_count_week = 0;
                    $adult_count_week = 0;
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->get();
                foreach($facilities_org as $facility_org)
                {
                    $facility_org_id = $facility_org->id;                    
                    $fac_name_linegraph = $facility_org->facility_name;
                    $org_facility_tickets[$k]['name'] = $fac_name_linegraph;
                    $org_facility_tickets[$k]['data'] = [];
                    
                    foreach($date_show as $date_shows)
                    {          
                        $adult_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_adult');
                        $child_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_child');            
                        $org_facility_tickets[$k]['data'][] = $adult_count_week + $child_count_week;  
                    }
                    $k++;
                }
            }
            $org_facility_tickets = json_encode($org_facility_tickets);
            //dd($org_facility_tickets);
        //////////////////////////////////////////////////////////////

        ///////organisation wise visitor count -- bar chart////////////////////
            $organisations_bar = Organisation::all();
            foreach($organisations_bar as $org_bar)
            {
                $orgn_id = $org_bar->id;
                $current_date = date("Y-m-d");
                $adult_count_org[$orgn_id] = Ticket::where('show_date',$currentdate)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_adult');
                $child_count_org[$orgn_id] = Ticket::where('show_date',$currentdate)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_child');
                $organisation_tickets_count[$orgn_id] = $adult_count_org[$orgn_id] + $child_count_org[$orgn_id];
            }
            //$organisation_tickets_count = json_encode($organisation_tickets_count);
        /////////////////////////////////////////////////////////////////////

        //////total number of monthly visitors in each organisation////////////////////////////////
            $tickets_count_org =[];
            $tickets_count_org_daily = [];
            $tickets_org_percentage= [];
            $today_date = date("Y-m-d");
            $current_year = date("Y");
            $current_month = date("m");
            $totaladultcount = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->sum('noof_adult');

            $totalchildcount = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->sum('noof_child');
            $total_ticket_count = $totaladultcount + $totalchildcount;
            foreach($organisations as $organisations_tickets)
            {
                $organisation_id = $organisations_tickets->id;
                $date_sel = date("Y-m-d");
                $adult_count_monthly_org[$organisation_id] = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_adult');
                //dd($adult_count_monthly_org[$organisation_id]);
                
                $child_count_monthly_org[$organisation_id] = Ticket::whereMonth('show_date',$current_month)->whereYear('show_date', $current_year)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_child');
                
                $tickets_count_org[$organisation_id] = $adult_count_monthly_org[$organisation_id] + $child_count_monthly_org[$organisation_id];
                //dd($tickets_count_org[$organisation_id]);
                if($total_ticket_count)
                {
                    $tickets_org_percentage[$organisation_id] = ($tickets_count_org[$organisation_id] / $total_ticket_count) * 100;
                }

                $adult_count_daily = Ticket::where('show_date',$today_date)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_adult');
                $child_count_daily = Ticket::where('show_date',$today_date)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_child');
                $tickets_count_org_daily[$organisation_id] = $adult_count_daily + $child_count_daily;

            }
            //dd($tickets_count_org);
        //////////////////////////////////////////////////////////////////////////////////////

        ////////////sales revenue in block/////////////////////////////
            $todate = date("Y-m-d");
            $sales_revenue_organisation =[];
            $salesrevenue_org_percentage =[];
            $total_sales_revenue = Invoice::where('invoice_date',$todate)->where('status',1)->sum('amount');
            foreach($organisations as $organisation_sales_revenue)
            {
                $organisation_revenue_id = $organisation_sales_revenue->id;               
                $sales_revenue_organisation[$organisation_revenue_id] = Invoice::where('organisation_id',$organisation_revenue_id)->where('invoice_date',$todate)->where('status',1)->sum('amount');
                if($total_sales_revenue)
                {
                    $salesrevenue_org_percentage[$organisation_id] = ($sales_revenue_organisation[$organisation_revenue_id] / $total_sales_revenue) * 100;
                }
            }

        ///////////////////////////////////////////////////////////

        /////chack seat availability ///////
            $id = Auth::user()->id;     
            $users = User::where('id',$id)->where('status',1)->first();
            if(isset($users))
            {
                $organisation_id = $users->organisation_id;
            }
            $noofseats = "";
            $show_start_time ="";
            $show_timings =[];
            $facility_arr = [];
            $n=1;
            $facility_id ="";
            $showon = [];
            if(!$organisation_id)
            {
                $org_facility = Organisation::first();
                if(isset($org_facility))
                {
                    $organisation_id = $org_facility->id;
                }
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->whereNotNull('noofseats')->get();
            }
            else
                $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->whereNotNull('noofseats')->get();
            foreach($facilities_org as $facilities)
            {
                $facility_id = $facilities->id;
                foreach($facilities->showtimings as $show)
                {
                    $date_of_visit = date("Y-m-d");
                    $show_id = $show->id;
                    $showon[$show_id] = 1;
                    $show_from_time = $show->from_time;
                    //get showtime
                    $showtime=$date_of_visit.' '.$show_from_time;
                    /*if(strtotime($showtime) && $facilities->noofseats)
                        $showon[$show_id] = 0;
                    //check if this show has minimum adult plus child seats available if not mark showon to 0//todo
                    if($facilities->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 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 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($invoice_amt);
        //////////////////////////////////////

        //dd($salesrevenue_org_percentage);
        return view('home', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','month','invoice_amt','invoice_amt_count','facilities','ticket_facility','organisations','invoice_amt_max','invoice_step_size','tickets_count_org','tickets_org_percentage','total_ticket_count','ticket_facility_org','org_facility_tickets_count','facilities_org','showon','facility_name_arr','tickets_count','organisation_name_arr','organisation_tickets_count','org_facility_tickets','sales_revenue_organisation','total_sales_revenue','salesrevenue_org_percentage','user_organisation_id','tickets_count_org_daily','date_show'));   
    }

    public function get_showdetails($dateofvisit)
    {
        $id = Auth::user()->id;     
        $users = User::where('id',$id)->where('status',1)->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
        }

        if(!$organisation_id)
        {
            $org_facility = Organisation::first();
            if(isset($org_facility))
            {
                $organisation_id = $org_facility->id;
            }
        }

        $noofseats = "";
        $show_start_time ="";
        $show_timings =[];
        $facility_arr = [];
        $n=1;
        $facility_id ="";
        $label_str = '<table width="100%" class="table table-sm table-responsive-lg mb-0" style="font-size:90%">';
        $facilities_org = Facility::where('organisation_id',$organisation_id)->whereNotNull('noofseats')->get();
        foreach($facilities_org as $facilities)
        {
            $facility_id = $facilities->id;
            $label_str .=   "<script>facilitiesarray.push($facilities->id)</script>";
            $label_str .=   '<tr class="btn-reveal-trigger">
                                <td class="py-2" style="height: 50px;">'.$facilities->facility_name.'</td>';
            $label_str .=       '<td class="py-2" style="height: 50px;">
                                    <div class="showtime-pill-wrapper">';
                                        foreach($facilities->showtimings as $show)
                                        {
                                            $date_of_visit = $dateofvisit;
                                            $show_id = $show->id;
                                            $showon[$show_id] = 1;
                                            $show_from_time = $show->from_time;
                                            //get showtime
                                            $showtime=$date_of_visit.' '.$show_from_time;

                                            if($show->date)
                                            {
                                                if($show->date != $dateofvisit)
                                                    continue;
                                            }
                                            /*if(strtotime($showtime) && $facilities->noofseats)
                                                $showon[$show_id] = 0;
                                            //check if this show has minimum adult plus child seats available if not mark showon to 0//todo
                                            if($facilities->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;
                                            }
                                            if($showon[$show->id])  
                                            {   
                                                $from_time = date("g:i A", strtotime($show->from_time));
                                                $to_time = date("g:i A", strtotime($show->to_time));                                                 
            $label_str .=                       '<div class="showtime-pill-container '.$facilities->id.'" onclick="showselect(this, '.$facilities->id.', '.$show->id.');">
                                                    <a class="showtime-pill" href="#!"  data-attributes=""  >
                                                        <div class="__details">
                                                            <div class="__text">'.$from_time;
                                                            if(!$show->dont_show_to_time)
                                                            {
            $label_str .=                                      '-'.$to_time;
                                                            }
            $label_str .=                                   '</div>
                                                        </div>
                                                    </a>
                                                </div> ';
                                            }
                                        }
        $label_str .=               '</div>
                                </td>
                                <td>
                                    <span id="available'.$facilities->id.'" style="color:blue; font-size: small; font-weight: bold;"></span></p> 
                                </td>
                            </tr>';
        }
        $label_str .= '</table>';
        return $label_str;
    }

    public function get_details($organisation_id,$page)
    {
        //echo "page=$page...organisation_id=$organisation_id...<br>";
        $month = 'January'.','.'February'.','.'March'.','.'April'.','.'May'.','.'June'.','.'July'.','.'August'.','.'September'.','.'October'.','.'November'.','.'December';
        $weeks = 'Monday'.','.'Tuesday'.','.'Wednesday'.','.'Thursday'.','.'Friday'.','.'Saturday'.','.'Sunday';
        $invoice_amt =[];
        $invoice_amt_count =0;
        $week_arr=explode(",",$weeks);
        $month_arr=explode(",",$month);
        if($organisation_id=="All")
        {
            if($page == "monthly")
            {
                foreach ($month_arr as $month_value) 
                {
                    $year = date("Y");
                    $invoice_amt[$month_value] = Invoice::where(\DB::raw("DATE_FORMAT(invoice_date, '%M')"),$month_value)->whereYear('invoice_date', $year)->where('status',1)->sum('amount');
                }
            }

            if($page == "weekly")
            {
                $todate = date("Y-m-d");
                foreach ($week_arr as $days) 
                {
                    $ts = strtotime($todate);
                    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
                    $start_date = date('Y-m-d', $start);
                    $end_date = date('Y-m-d', strtotime('next saturday', $start));
                    $invoice_amt[$days] = Invoice::where(\DB::raw("DATE_FORMAT(invoice_date, '%W')"),$days)->where('invoice_date','>=',$start_date)->where('invoice_date','<=',$end_date)->where('status',1)->sum('amount');
                }
            }
            if($page == "today")
            {
                $today = date("Y-m-d");
                $first_interval1 = date("Y-m-d 10:0:0");
                $last_interval1 = date("Y-m-d 12:0:0");
                $invoice_amount1 = Invoice::where('invoice_time','<=', $first_interval1)->where('status',1)->where('invoice_date',$today)->sum('amount');
                $invoice_amt[] = $invoice_amount1;
                $first_interval2 = date("Y-m-d 12:0:0");
                $last_interval2 = date("Y-m-d 14:0:0");
                $invoice_amount2 = Invoice::where('invoice_time','<=', $first_interval2)->where('invoice_time','>', $first_interval1)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount2;
                $first_interval3 = date("Y-m-d 14:0:0");
                $last_interval3 = date("Y-m-d 16:0:0");
                $invoice_amount3 = Invoice::where('invoice_time','<=', $first_interval3)->where('invoice_time','>', $first_interval2)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount3;
                $first_interval4 = date("Y-m-d 16:0:0");
                $last_interval4 = date("Y-m-d 18:0:0");
                $invoice_amount4 = Invoice::where('invoice_time','<=', $first_interval4)->where('invoice_time','>', $first_interval3)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount4;

            }
        }
        else
        {
            if($page == "monthly")
            {
                foreach ($month_arr as $month_value) 
                {
                    $year = date("Y");
                    $invoice_amt[$month_value] = Invoice::where('organisation_id',$organisation_id)->where(\DB::raw("DATE_FORMAT(invoice_date, '%M')"),$month_value)->whereYear('invoice_date', $year)->where('status',1)->sum('amount');
                }
            }
            if($page == "weekly")
            {
                $todate = date("Y-m-d");
                foreach ($week_arr as $days) 
                {
                    $ts = strtotime($todate);
                    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
                    $start_date = date('Y-m-d', $start);
                    $end_date = date('Y-m-d', strtotime('next saturday', $start));
                    $invoice_amt[$days] = Invoice::where('organisation_id',$organisation_id)->where(\DB::raw("DATE_FORMAT(invoice_date, '%W')"),$days)->where('invoice_date','>=',$start_date)->where('invoice_date','<=',$end_date)->where('status',1)->sum('amount');
                }
            }
            if($page == "today")
            {
                //$today = date("Y-m-d H:i:s");
                $today = date("Y-m-d");
                $first_interval1 = date("Y-m-d 10:0:0");
                $last_interval1 = date("Y-m-d 12:0:0");
                $invoice_amount1 = Invoice::where('organisation_id',$organisation_id)->where('invoice_time','<=', $first_interval1)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount1;
                $first_interval2 = date("Y-m-d 12:0:0");
                $last_interval2 = date("Y-m-d 14:0:0");
                $invoice_amount2 = Invoice::where('organisation_id',$organisation_id)->where('invoice_time','<=', $first_interval2)->where('invoice_time','>', $first_interval1)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount2;
                $first_interval3 = date("Y-m-d 14:0:0");
                $last_interval3 = date("Y-m-d 16:0:0");
                $invoice_amount3 = Invoice::where('organisation_id',$organisation_id)->where('invoice_time','<=', $first_interval3)->where('invoice_time','>', $first_interval2)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount3;
                $first_interval4 = date("Y-m-d 16:0:0");
                $last_interval4 = date("Y-m-d 18:0:0");
                $invoice_amount4 = Invoice::where('organisation_id',$organisation_id)->where('invoice_time','<=', $first_interval4)->where('invoice_time','>', $first_interval3)->where('invoice_date',$today)->where('status',1)->sum('amount');
                $invoice_amt[] = $invoice_amount4;
            }
        }
        //dd($invoice_amt);
        $invoice_amt = json_encode($invoice_amt);
        return $invoice_amt;
    }

    public function get_tickets($organisation_id, $date_sel)
    {
        $tickets_count= [];
        $facilities = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->get();
        foreach($facilities as $facility)
        {
            $facility_id = $facility->id;
            $facility_name = $facility->facility_name;
            $adult_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$date_sel)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_adult');
            $child_count[$facility_name] = Ticket::where('facility_id',$facility->id)->where('show_date',$date_sel)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($organisation_id) { $fac->where('organisation_id',$organisation_id); })->sum('noof_child');
            $tickets_count[$facility_name] = $adult_count[$facility_name] + $child_count[$facility_name];
        }
        
        //dd($tickets_count);
        $tickets_count = json_encode($tickets_count);
        return $tickets_count;
    }

    public function get_weekly_tickets($organisation_id)
    {
        ///////////facility wise ticket count -- simple line graph/./////////////////




            /////ticket faiclity//////////////////
            $ticket_facility_org = 0;
            $org_facility_tickets_count ="";
            $current_date = date("Y-m-d");
            $ts = strtotime($current_date);
            $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
            $start_date = date('Y-m-d', $start);
            $end_date = date('Y-m-d', strtotime('next saturday', $start));
            $end_date_plus_onday = date( "Y-m-d", strtotime( $end_date ."+1 day" ) );
            $weekly_dates = new DatePeriod(
                            new DateTime($start_date),
                            new DateInterval('P1D'),
                            new DateTime($end_date_plus_onday)
                         );
            $i=0;
            $date_show =[];
            foreach ($weekly_dates as $weekly_dates_value) 
            {
                $date_show[$i]= $weekly_dates_value->format('Y-m-d');
                $i++;      
            }
            $k=0;
            $org_facility_tickets = [];
            $facilities_org = Facility::where('organisation_id',$organisation_id)->where('active_flag',1)->get();
            foreach($facilities_org as $facility_org)
            {
                $facility_org_id = $facility_org->id;                    
                $fac_name_linegraph = $facility_org->facility_name;
                $org_facility_tickets[$k]['name'] = $fac_name_linegraph;
                $org_facility_tickets[$k]['data'] = [];
                foreach($date_show as $date_shows)
                {  
                    $adult_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_adult');
                        $child_count_week = Ticket::where('facility_id',$facility_org_id)->where('show_date',$date_shows)->where('status',1)->sum('noof_child');            
                        $org_facility_tickets[$k]['data'][] = $adult_count_week + $child_count_week; 
                 
                }
                $k++;
            }
        //////////////////////////////////////////////////////////////
        $org_facility_tickets_new = json_encode($org_facility_tickets);
        return $org_facility_tickets;
    }

    public function get_organisation_tickets($date_sel)
    {
        $organisation_tickets_count =[];
        $organisations_bar = Organisation::all();
        foreach($organisations_bar as $org_bar)
        {
            $orgn_id = $org_bar->id;
            $currentdate = date("Y-m-d");
            $adult_count[$orgn_id] = Ticket::where('show_date',$date_sel)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_adult');
            $child_count[$orgn_id] = Ticket::where('show_date',$date_sel)->where('status',1)->with('facility')->whereHas('facility',function($fac) use($orgn_id) { $fac->where('organisation_id',$orgn_id); })->sum('noof_child');
            $organisation_tickets_count[$orgn_id] = $adult_count[$orgn_id] + $child_count[$orgn_id];
        }
        //dd($organisation_tickets_count);
        return $organisation_tickets_count;
    }

    public function myprofile()
    {
        $page_title = 'My Profile';
        $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;     
        $roles = Roles::where('status',1)->get();
        $users = User::where('id',$id)->with('userrole','organisation','department','section')->first();
        if(isset($users))
        {
            $organisation_id = $users->organisation_id;
            $department_id = $users->department_id;
            $section_id = $users->section_id;
        }
        $organisations = Organisation::all();
        $departments = Department::where('organisation_id',$organisation_id)->get();
        $sections = Section::where('organisation_id',$organisation_id)->where('department_id',$department_id)->get();
        return view('myprofile', compact('page_title', 'page_description','action','logo','logoText','active','event_class','button_class','roles','users','departments','sections','organisations'));
    }

    public function myprofile_post(Request $request)
    {
        $insert_id="";
        $name=$request->name;
        $email=$request->email;
        $user_id = $request->user_id;
        $organisation_id = $request->organisation_id;
        $department_id = $request->department_id;
        $section_id = $request->section_id;
        $phone_number =$request->phone_number;
        //dd($request);
        $updflg = 0;
        $id = Auth::user()->id;
        $users = User::where('id',$user_id)->first();
        if(isset($users))
        {
            $updflg = 1;
            $users->name=$name;
            $users->email=$email;
            $users->organisation_id=$organisation_id;
            $users->department_id=$department_id;
            $users->section_id=$section_id;
            $users->phone_number = $phone_number;
            $users->save();
        }
        $message = 'Profile has been updated succeesfully';

        return redirect('myprofile');
    }

    public function myprofilepwd_post(Request $request)
    {
        $insert_id="";
        $password=$request->password;
        $cpassword=$request->confirm_password;
        $user_id = $request->user_id;
        $updflg = 0;
        $id = Auth::user()->id;
        $users = User::where('id',$user_id)->first();
        if(isset($users))
        {
            $updflg = 1;
            if($password && $cpassword)
            {
                if(!(strcmp($password, $cpassword)) == 0)
                {
                    return redirect()->back()->with('status',"Password and confirm should be same.");
                }
                else
                {
                    if($cpassword)
                    {
                        $newpassword = Hash::make($cpassword);
                        $user_pwd = User::where('id',$user_id)->first();
                        $user_pwd->password = $newpassword;
                        $user_pwd->save();
                    }
                }
            }
        }
        $message = 'Profile has been updated succeesfully';

        return redirect('myprofile');
    }

    public function myprofilephoto_post(Request $request)
    {
        $insert_id="";
        $updflg = 0;
        $id = Auth::user()->id;
        $user_id = $request->user_id;
        $users = User::where('id',$user_id)->first();
        if(isset($users))
        {
            $updflg = 1;
            if($request->hasFile("photo")) 
            {
                $fileobj=$request->file("photo")->getClientOriginalName();
                $destpath="uploads/users";
                $custom_file_name =$user_id.'-'.$fileobj;
                if($custom_file_name!="")
                {
                    $path = $request->file("photo")->move(public_path().'/uploads/users/', $custom_file_name);
                    $uploadphoto = User::where('id',$user_id)->update(['photo' => $custom_file_name]);
                }
            }
        }
        $message = 'Profile has been updated succeesfully';

        return redirect('myprofile');
    }


}
