<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\Customer;
use App\Models\TimeSlot;
use App\Models\Users;
use Illuminate\Support\Facades\DB;
// use pdf;

class BookingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $bookings = db::select(db::raw("SELECT bookings.*, c.fname as user1,c.lname as user2,c.contact_number as contact FROM `bookings`
join users as c on bookings.customer_id= c.id
"));
        $users = users::all();
        return view('dashboard.bookings.index', compact('bookings', 'users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $users = Users::all();
        $timeSlot = TimeSlot::all();
        /*for header global */
        $gl = db::select(db::raw("select seat_price from global_options"));
        $globl = "";
        foreach ($gl as $gls) {
            $globl .= "$gls->seat_price";
        }
        $data['globl'] = $globl;
        return view('dashboard.admin.addBooking', compact('users', 'timeSlot'), $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $rules = [
            'customer_id' => ['required'],
            'booking_date' => ['required'],
            'timeslot' => ['required'],
            'seats' => ['required'],
            // 'status' => ['required'],
            'payment_status' => ['required'],

        ];

        $customMessages = [
            'required' => 'The :attribute field is required.'
        ];
        $this->validate($request, $rules, $customMessages);

        $booked_seats = Booking::where('booking_date', $request->input('booking_date'))->where('timeslot', $request->input('timeslot'))->where('status', 'reserved')->sum('seats');
        if (($booked_seats + $request->input('seats')) > 25) {
            $remaining_seats = 25 - $booked_seats;

            if ($request->input('web')) {
                $errors = ["errors" => [
                    "booking" => ["Oops! booking failed, only ".$remaining_seats." are available."]
                ]];
                return response()->json($errors, 404);
            }
        }

        $booking = Booking::create($request->all());

        if ($request->input('web')) {
                return response()->json($booking->id);
        }

        $request->session()->flash('message', 'Add Booking Successfully');
        return redirect()->route('bookings.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $users = users::all();
        $booking = Booking::where('id', '=', $id)->first();
        return view('dashboard.bookings.show', compact('booking', 'users'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $users = Users::all();
        $timeSlot = TimeSlot::all();
        $booking = Booking::where('id', '=', $id)->first();
        return view('dashboard.bookings.edit', compact('booking', 'users', 'timeSlot'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            'customer_id' => ['required'],
            'booking_date' => ['required'],
            'timeslot' => ['required'],
            'seats' => ['required'],
            // 'status' => ['required'],
            'payment_status' => ['required'],
        ];
        $this->validate($request, $rules);
        $booking = Booking::where('id', '=', $id)->first();
        $booking->update($request->all());
        $request->session()->flash('message', 'Successfully updated Booking');
        $request->session()->flash('back', 'bookings.index');
        return view('dashboard.shared.universal-info');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Booking  $booking
     * @return \Illuminate\Http\Response
     */
    public function destroy($id, Request $request)
    {
        $booking = Booking::where('id', '=', $id)->first();
        $booking->delete();
        $request->session()->flash('message', "Successfully deleted Booking");
        $request->session()->flash('back', 'bookings.index');
        return view('dashboard.shared.universal-info');
    }



    public function getseats(Request $request)
    {
        $res = DB::table("bookings")
            ->select('seats')
            ->where('timeslot', "=", $request->timeslot_id)
            ->where('booking_date', "=", $request->booking_date)
            ->where('status', "=", 'reserved')
            ->get()->sum('seats');

        $t_seats = db::table('global_options')
            ->select('total_seats')->get()->sum('total_seats');
        $response = $t_seats - $res;

        return response()->json($response);
    }
    public function getamount(Request $request)
    {

        $gl = db::table('global_options')
            ->select('seat_price')->get();
        $globl = '';
        foreach ($gl as $gls) {
            $globl .= "$gls->seat_price" * $request->seats_id;
        }
        $data['globl'] = $globl;
        //  dd($data);
        return response()->json($globl);
    }


    public function booking_canceled($id, Request $request)
    {
        $booking = booking::find($id);
        $booking->status = "cancelled";
        $booking->save();
        $request->session()->flash('message', "Successfully Canceled Booking");
        $request->session()->flash('back', 'bookings.index');
        return view('dashboard.shared.universal-info');
    }
    public function homepage(Request $request)

    {


        /*3D Chart */

        $result = db::select(db::raw("SELECT status, count(*) as total_status from
bookings  group by status"));
        $chardata = "";
        foreach ($result as $list) {
            $chardata .= "['" . $list->status . "', " . $list->total_status . "],";
        }
        $data['chardata'] = rtrim($chardata, ",");
        // dd($data);
        /*Bar chart */

        $query = db::select(db::raw("select sum(seats) as total_seats , c.fname as customers from bookings
 join users as c on bookings.customer_id = c.id
 group by c.fname"));
        $barchart = "";
        foreach ($query as $line) {
            $barchart .= "['" . $line->customers . "', " . $line->total_seats . ",'#891446'],";
        }

        $data['barchart'] = rtrim($barchart, ",");
        //dd($data);
        /*$donutchart chart */
        $sql = db::select(db::raw("select sum(seats) as seats ,c.fname as name from bookings
join users as c on bookings.customer_id= c.id
group by name having seats > 25"));
        $donutchart = "";
        foreach ($sql as $val) {
            $donutchart .= "['" . $val->name . "', " . $val->seats . "],";
        }

        $data['donutchart'] = rtrim($donutchart, ",");
        /*Pie Chart */
        $s = db::select(db::raw("SELECT timeslot,sum(seats) as seats FROM `bookings`
group by timeslot"));
        $piechart = "";

        foreach ($s as $row) {

            $piechart .= "['" . $row->timeslot . "', " . $row->seats . ", '#40E0D0'],";
        }
        $data['piechart'] = rtrim($piechart, ",");
        // dd($data);
        $book = db::select(db::raw("SELECT count(customer_id) as customers FROM `bookings` "));

        // dd($t_cust);
        $booking = "";

        foreach ($book as $cust) {
            $booking .= "$cust->customers";
        }
        $data['booking'] = $booking;
        // dd($data);
        $user = db::select(db::raw("select count(fname) as users from users"));
        $users = "";
        foreach ($user as $use) {
            $users .= "$use->users";
        }
        $data['users'] = $users;
        $t_seats = db::select(db::raw("select sum(seats) as seats from bookings "));
        $seats = "";
        foreach ($t_seats as $seat) {
            $seats .= "$seat->seats";
        }
        $data['seats'] = $seats;
        return view('dashboard.homepage', $data);
    }
    
    public function get_homepage(Request $req)
{
    /*3D Chart */

    $result = db::select(db::raw("SELECT status, count(*) as total_status from 
    bookings where bookings.booking_date between  '$req->date_from' and '$req->date_to'
     group by status "));
        $chardata = "";
        foreach ($result as $list) {
            $chardata .= "['" . $list->status . "', " . $list->total_status . "],";
        }
        $data['chardata'] = rtrim($chardata, ",");
        // dd($data);
        /*Bar chart */

        $query = db::select(db::raw("select sum(seats) as total_seats , c.fname as customers from bookings
          join users as c on bookings.customer_id = c.id 
          where bookings.booking_date between  '$req->date_from' and '$req->date_to'
           group by c.fname"));
        $barchart = "";
        foreach ($query as $line) {
            $barchart .= "['" . $line->customers . "', " . $line->total_seats . ",'#891446'],";
        }

        $data['barchart'] = rtrim($barchart, ",");
        //dd($data);
        /*$donutchart chart */
        $sql = db::select(db::raw("select sum(seats) as seats ,c.fname as name from bookings 
      join users as c on bookings.customer_id= c.id
      where bookings.booking_date between  '$req->date_from' and '$req->date_to'
      group by name having seats > 25"));
        $donutchart = "";
        foreach ($sql as $val) {
            $donutchart .= "['" . $val->name . "', " . $val->seats . "],";
        }

        $data['donutchart'] = rtrim($donutchart, ",");
        
        /*Pie Chart */
        $s = db::select(db::raw("SELECT timeslot,sum(seats) as seats FROM `bookings` where bookings.booking_date between  '$req->date_from' and '$req->date_to'
        group by timeslot"));
        $piechart = "";

        foreach ($s as $row) {

            $piechart .= "['" . $row->timeslot . "', " . $row->seats . ", '#40E0D0'],";
        }
        $data['piechart'] = rtrim($piechart, ",");
        // dd($data);
        $book = db::select(db::raw("SELECT count(customer_id) as customers FROM `bookings` where bookings.booking_date between  '$req->date_from' and '$req->date_to' "));

        // dd($t_cust);
        $booking = "";

        foreach ($book as $cust) {
            $booking .= "$cust->customers";
        }
        $data['booking'] = $booking;
        // dd($data);
        $user = db::select(db::raw("select count(fname) as users from users where users.created_at between  '$req->date_from' and '$req->date_to'"));
        $users = "";
        foreach ($user as $use) {
            $users .= "$use->users";
        }
        $data['users'] = $users;
        $t_seats = db::select(db::raw("select sum(seats) as seats from bookings where bookings.booking_date between  '$req->date_from' and '$req->date_to'"));
        $seats = "";
        foreach ($t_seats as $seat) {
            $seats .= "$seat->seats";
        }
        $data['seats'] = $seats;
    // $booking= booking::whereBetween('created_at',[$req->date_from.' 00:00:00',$req->date_to.' 23:59:59'])->get();
    return view('dashboard.homepage', $data);
}
    
    public function getbook(Request $req)
    {
        $booking = booking::whereBetween('booking_date', [$req->date_from . ' 00:00:00', $req->date_to . ' 23:59:59'])->get();

        return view('dashboard.homepage', $booking);
    }
    // public function generatePDF()
    // {
    //     $bookings= db::select(db::raw("select c.fname as customer1,c.lname as customer2,c.contact_number as contact,
    //      booking_date,seats,status,payment_status,timeslot
    //     from bookings join users as c on bookings.customer_id= c.id"));
    // //    dd($booking);
    //     $data = [
    //         'title' => 'Bookings Record',
    //         'date' => date('m/d/Y')
    //     ];

    //     $pdf = pdf::loadView('dashboard.bookings.booking_pdf', $data,compact('bookings'));

    //     return $pdf->download('booking.pdf');
    //     }
    public function single_record_pdf($id)
    {
        $booking = db::select(db::raw("select bookings.id as id, c.fname as customer1,c.lname as customer2,c.contact_number as contact,
        booking_date,seats,status,payment_status,timeslot
       from bookings join users as c on bookings.customer_id= c.id  where bookings.id =  $id"));
        /*Total amount */
        $total_amount = db::select(db::raw("select total_amount from bookings where id = $id"));
        $amount = "";
        foreach ($total_amount as $t_amount) {
            $amount .= "$t_amount->total_amount";
        }
        $d['amount'] = $amount;
        // dd($amount);
        $data = [
            'title' => 'Bookings Record',
            'date' => date('m/d/Y')
        ];
        return view('dashboard.bookings.single_record_pdf', $d, compact('booking'));
    }
}
