<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Reservation;
use App\Models\Customer;
use App\Models\Table;
use App\Models\Outlet;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Http\RedirectResponse;

class ReservationController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();
        $outletFilter = $request->input('outlet_id');
        $outletId = $user->outlet_id ? (int)$user->outlet_id : ($outletFilter ? (int)$outletFilter : null);

        $reservations = Reservation::with(['customer', 'table', 'outlet'])
            ->when($outletId, fn($q) => $q->where('outlet_id', $outletId))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        $outlets = Outlet::select('id', 'name')->get();
        $customers = Customer::select('id', 'name')->get();
        $tables = Table::when($outletId, fn($q) => $q->where('outlet_id', $outletId))
            ->select('id', 'number', 'outlet_id')
            ->get();

        return Inertia::render('CafePOS/Reservations/Index', [
            'reservations' => $reservations,
            'outlets' => $outlets,
            'customers' => $customers,
            'tables' => $tables,
            'filters' => [
                'outlet_id' => $outletFilter,
            ]
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'customer_id' => ['required', 'integer', 'exists:customers,id'],
            'table_id' => ['required', 'integer', 'exists:tables,id'],
            'outlet_id' => ['required', 'integer', 'exists:outlets,id'],
            'reservation_date' => ['required', 'date'],
            'reservation_time' => ['required', 'string'],
            'status' => ['required', 'string', 'in:pending,confirmed,cancelled'],
        ]);

        $table = Table::findOrFail($request->table_id);
        if ($table->outlet_id !== (int)$request->outlet_id) {
            return redirect()->back()->with('error', 'Table must belong to the selected outlet.');
        }

        Reservation::create($request->only(['customer_id', 'table_id', 'outlet_id', 'reservation_date', 'reservation_time', 'status']));

        // If confirmed, update table status to reserved
        if ($request->status === 'confirmed') {
            $table->update(['status' => 'reserved']);
        }

        return redirect()->back()->with('success', 'Reservation created successfully.');
    }

    public function update(Request $request, Reservation $reservation): RedirectResponse
    {
        $request->validate([
            'customer_id' => ['required', 'integer', 'exists:customers,id'],
            'table_id' => ['required', 'integer', 'exists:tables,id'],
            'outlet_id' => ['required', 'integer', 'exists:outlets,id'],
            'reservation_date' => ['required', 'date'],
            'reservation_time' => ['required', 'string'],
            'status' => ['required', 'string', 'in:pending,confirmed,cancelled'],
        ]);

        $table = Table::findOrFail($request->table_id);
        if ($table->outlet_id !== (int)$request->outlet_id) {
            return redirect()->back()->with('error', 'Table must belong to the selected outlet.');
        }

        $oldStatus = $reservation->status;
        $reservation->update($request->only(['customer_id', 'table_id', 'outlet_id', 'reservation_date', 'reservation_time', 'status']));

        // Handle table status logic
        if ($request->status === 'confirmed') {
            $table->update(['status' => 'reserved']);
        } elseif ($oldStatus === 'confirmed' && $request->status !== 'confirmed') {
            $table->update(['status' => 'available']);
        }

        return redirect()->back()->with('success', 'Reservation updated successfully.');
    }

    public function destroy(Reservation $reservation): RedirectResponse
    {
        $table = Table::find($reservation->table_id);
        if ($table && $reservation->status === 'confirmed') {
            $table->update(['status' => 'available']);
        }
        $reservation->delete();
        return redirect()->back()->with('success', 'Reservation deleted successfully.');
    }
}
