<?php

namespace App\Http\Controllers\Restaurant;

use App\BusinessLocation;
use App\CustomerGroup;
use App\Restaurant\Booking;
use App\User;
use App\Utils\Util;
use App\Utils\RestaurantUtil;
use App\GuestCheckin;
use DB;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Yajra\DataTables\Facades\DataTables;

class BookingController extends Controller
{
    protected $commonUtil;
    protected $restUtil;

    public function __construct(Util $commonUtil, RestaurantUtil $restUtil)
    {
        $this->commonUtil = $commonUtil;
        $this->restUtil = $restUtil;
    }

    public function index()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');

        $user_id = request()->has('user_id') ? request()->user_id : null;
        if (!auth()->user()->hasPermissionTo('crud_all_bookings') && !$this->restUtil->is_admin(auth()->user(), $business_id)) {
            $user_id = request()->session()->get('user.id');
        }
        if (request()->ajax()) {
            $filters = [
                'start_date' => request()->start,
                'end_date' => request()->end,
                'user_id' => $user_id,
                'location_id' => !empty(request()->location_id) ? request()->location_id : null,
                'business_id' => $business_id
            ];

            $events = $this->restUtil->getBookingsForCalendar($filters);

            return $events;
        }

        $business_locations = BusinessLocation::forDropdown($business_id);
        $correspondents = User::forDropdown($business_id, false);
        $customer_groups = CustomerGroup::forDropdown($business_id);

        return view('restaurant.booking.index', compact('business_locations', 'correspondents', 'customer_groups'));
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            if ($request->ajax()) {
                $business_id = request()->session()->get('user.business_id');
                $user_id = request()->session()->get('user.id');

                $input = $request->input();
                $booking_start = $this->commonUtil->uf_date($input['booking_start'], true);
                $booking_end = $this->commonUtil->uf_date($input['booking_end'], true);
                $date_range = [$booking_start, $booking_end];

                // Handle guest check-in
                $guest_id = $input['guest_id'];
                if (empty($guest_id)) {
                    // Create new guest check-in
                    $guest_data = [
                        'surname' => $input['surname'],
                        'name' => $input['name'],
                        'email' => $input['email'],
                        'phone' => $input['phone'],
                        'gender' => $input['gender'],
                        'nationality' => $input['nationality'],
                        'id_type' => $input['id_type'],
                        'id_number' => $input['id_number'],
                        'passport_no' => $input['passport_no'],
                        'stay_purpose' => $input['stay_purpose'],
                        'payment_method' => $input['payment_method'],
                        'company' => $input['company'],
                        'remarks' => $input['remarks'],
                        'staff_acknowledged' => !empty($input['staff_acknowledged']) ? 1 : 0,
                        'guest_acknowledged' => !empty($input['guest_acknowledged']) ? 1 : 0,
                        'location_id' => $input['location_id'],
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                    $guest = GuestCheckin::create($guest_data);
                    $guest_id = $guest->id;
                }

                // Check if booking is available
                $query = Booking::where('business_id', $business_id)
                                ->where('location_id', $input['location_id'])
                                ->where('guest_id', $guest_id)
                                ->where(function ($q) use ($date_range) {
                                    $q->whereBetween('booking_start', $date_range)
                                      ->orWhereBetween('booking_end', $date_range);
                                });

                if (isset($input['res_table_id'])) {
                    $query->where('table_id', $input['res_table_id']);
                }

                $existing_booking = $query->first();
                if (empty($existing_booking)) {
                    $booking_data = [
                        'guest_id' => $guest_id,
                        'res_waiter_id' => isset($input['res_waiter_id']) ? $input['res_waiter_id'] : null,
                        'res_table_id' => isset($input['res_table_id']) ? $input['res_table_id'] : null,
                        'business_id' => $business_id,
                        'location_id' => $input['location_id'],
                        'correspondent' => isset($input['correspondent']) ? $input['correspondent'] : null,
                        'booking_start' => $booking_start,
                        'booking_end' => $booking_end,
                        'created_by' => $user_id,
                        'booking_status' => isset($input['booking_status']) ? $input['booking_status'] : 'booked',
                        'booking_note' => $input['booking_note']
                    ];
                    $booking = Booking::createBooking($booking_data);

                    $output = [
                        'success' => 1,
                        'msg' => trans("lang_v1.added_success"),
                    ];

                    if (isset($input['send_notification']) && $input['send_notification'] == 1) {
                        $output['send_notification'] = 1;
                        $output['notification_url'] = action('NotificationController@getTemplate', ["transaction_id" => $booking->id, "template_for" => "new_booking"]);
                    }
                } else {
                    $time_range = $this->commonUtil->format_date($existing_booking->booking_start, true) . ' ~ ' .
                                  $this->commonUtil->format_date($existing_booking->booking_end, true);

                    $guest = GuestCheckin::find($guest_id);
                    $output = [
                        'success' => 0,
                        'msg' => trans(
                            "restaurant.booking_not_available",
                            ['customer_name' => $guest->surname . ' ' . $guest->name,
                             'booking_time_range' => $time_range]
                        )
                    ];
                }
            } else {
                throw new \Exception(__("messages.something_went_wrong"));
            }
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());
            $output = [
                'success' => 0,
                'msg' => __("messages.something_went_wrong")
            ];
        }
        return $output;
    }

    public function show($id)
    {
        if (request()->ajax()) {
            $business_id = request()->session()->get('user.business_id');
            $booking = Booking::where('business_id', $business_id)
                             ->where('id', $id)
                             ->with(['table', 'guest', 'correspondent', 'waiter', 'location'])
                             ->first();
            if (!empty($booking)) {
                $booking_start = $this->commonUtil->format_date($booking->booking_start, true);
                $booking_end = $this->commonUtil->format_date($booking->booking_end, true);

                $booking_statuses = [
                    'waiting' => __('lang_v1.waiting'),
                    'booked' => __('restaurant.booked'),
                    'completed' => __('restaurant.completed'),
                    'cancelled' => __('restaurant.cancelled'),
                ];
                return view('restaurant.booking.show', compact('booking', 'booking_start', 'booking_end', 'booking_statuses'));
            }
        }
    }

    public function update(Request $request, $id)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            $business_id = $request->session()->get('user.business_id');
            $booking = Booking::where('business_id', $business_id)
                             ->find($id);
            if (!empty($booking)) {
                $booking->booking_status = $request->booking_status;
                $booking->save();
            }

            $output = [
                'success' => 1,
                'msg' => trans("lang_v1.updated_success")
            ];
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());
            $output = [
                'success' => 0,
                'msg' => __("messages.something_went_wrong")
            ];
        }
        return $output;
    }

    public function destroy($id)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            $business_id = request()->session()->get('user.business_id');
            Booking::where('business_id', $business_id)
                   ->where('id', $id)
                   ->delete();
            $output = [
                'success' => 1,
                'msg' => trans("lang_v1.deleted_success")
            ];
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());
            $output = [
                'success' => 0,
                'msg' => __("messages.something_went_wrong")
            ];
        }
        return $output;
    }

    public function getTodaysBookings()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }

        if (request()->ajax()) {
            $business_id = request()->session()->get('user.business_id');
            $user_id = request()->session()->get('user.id');
            $today = \Carbon::now()->format('Y-m-d');
            $query = Booking::where('business_id', $business_id)
                           ->where('booking_status', 'booked')
                           ->whereDate('booking_start', $today)
                           ->with(['table', 'correspondent', 'waiter', 'location', 'guest']);

            if (!empty(request()->location_id)) {
                $query->where('location_id', request()->location_id);
            }

            if (!auth()->user()->hasPermissionTo('crud_all_bookings') && !$this->commonUtil->is_admin(auth()->user(), $business_id)) {
                $query->where(function ($query) use ($user_id) {
                    $query->where('created_by', $user_id)
                          ->orWhere('correspondent_id', $user_id)
                          ->orWhere('waiter_id', $user_id);
                });
            }

            return Datatables::of($query)
                ->editColumn('table', function ($row) {
                    return !empty($row->table->name) ? $row->table->name : '--';
                })
                ->editColumn('customer', function ($row) {
                    return !empty($row->guest) ? $row->guest->surname . ' ' . $row->guest->name : '--';
                })
                ->editColumn('correspondent', function ($row) {
                    return !empty($row->correspondent->user_full_name) ? $row->correspondent->user_full_name : '--';
                })
                ->editColumn('waiter', function ($row) {
                    return !empty($row->waiter->user_full_name) ? $row->waiter->user_full_name : '--';
                })
                ->editColumn('location', function ($row) {
                    return !empty($row->location->name) ? $row->location->name : '--';
                })
                ->editColumn('booking_start', function ($row) {
                    return $this->commonUtil->format_date($row->booking_start, true);
                })
                ->editColumn('booking_end', function ($row) {
                    return $this->commonUtil->format_date($row->booking_end, true);
                })
                ->removeColumn('id')
                ->make(true);
        }
    }

    public function getGuestCheckins()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }

        if (request()->ajax()) {
            try {
                $query = GuestCheckin::orderBy('created_at', 'desc');

                if (!empty(request()->location_id)) {
                    $query->where('location_id', request()->location_id);
                }

                return Datatables::of($query)
                    ->editColumn('surname', function ($row) {
                        return $row->surname ?? '--';
                    })
                    ->editColumn('name', function ($row) {
                        return $row->name ?? '--';
                    })
                    ->editColumn('email', function ($row) {
                        return $row->email ?? '--';
                    })
                    ->editColumn('phone', function ($row) {
                        return $row->phone ?? '--';
                    })
                    ->editColumn('gender', function ($row) {
                        return $row->gender ?? '--';
                    })
                    ->editColumn('nationality', function ($row) {
                        return $row->nationality ?? '--';
                    })
                    ->editColumn('id_type', function ($row) {
                        return $row->id_type ?? '--';
                    })
                    ->editColumn('id_number', function ($row) {
                        return $row->id_number ?? '--';
                    })
                    ->editColumn('passport_no', function ($row) {
                        return $row->passport_no ?? '--';
                    })
                    ->editColumn('stay_purpose', function ($row) {
                        return $row->stay_purpose ?? '--';
                    })
                    ->editColumn('payment_method', function ($row) {
                        return $row->payment_method ?? '--';
                    })
                    ->editColumn('company', function ($row) {
                        return $row->company ?? '--';
                    })
                    ->editColumn('remarks', function ($row) {
                        return $row->remarks ?? '--';
                    })
                    ->editColumn('staff_acknowledged', function ($row) {
                        return $row->staff_acknowledged ? __('lang_v1.yes') : __('lang_v1.no');
                    })
                    ->editColumn('guest_acknowledged', function ($row) {
                        return $row->guest_acknowledged ? __('lang_v1.yes') : __('lang_v1.no');
                    })
                    ->editColumn('created_at', function ($row) {
                        return \Carbon\Carbon::parse($row->created_at)->format('Y-m-d H:i:s');
                    })
                    ->addColumn('action', function ($row) {
                        $action = '<button type="button" class="btn btn-xs btn-info btn-modal" 
                                   data-href="' . url('/bookings/guest-checkin/' . $row->id) . '" 
                                   data-container=".view_modal">
                                   <i class="fa fa-eye"></i> ' . __('messages.view') . '
                           </button>';
                        return $action;
                    })
                    ->rawColumns(['action'])
                    ->removeColumn('id')
                    ->make(true);
            } catch (\Exception $e) {
                \Log::error("Guest checkins DataTable error: " . $e->getMessage());
                return response()->json(['error' => 'Something went wrong: ' . $e->getMessage()], 500);
            }
        }
    }

    public function showGuestCheckin($id)
    {
        if (request()->ajax()) {
            try {
                $guest_checkin = GuestCheckin::where('id', $id)->first();
                
                if (!empty($guest_checkin)) {
                    return view('restaurant.guest_checkin.show', compact('guest_checkin'));
                } else {
                    return response()->json(['error' => 'Guest checkin not found'], 404);
                }
            } catch (\Exception $e) {
                \Log::error("Guest checkin show error: " . $e->getMessage());
                return response()->json(['error' => 'Something went wrong'], 500);
            }
        }
    }

    public function getGuestCheckinsDropdown()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            $query = GuestCheckin::select('id', DB::raw("CONCAT(surname, ' ', name) as name"))
                                ->orderBy('surname', 'asc');

            if (!empty(request()->location_id)) {
                $query->where('location_id', request()->location_id);
            }

            $guests = $query->pluck('name', 'id')->toArray();

            \Log::info("Guests retrieved for dropdown: ", ['guests' => $guests, 'location_id' => request()->location_id]);

            return response()->json($guests);
        } catch (\Exception $e) {
            \Log::error("Guest checkins dropdown error: " . $e->getMessage());
            return response()->json(['error' => 'Failed to load guests'], 500);
        }
    }
}