<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\RestaurantTable;
use App\Models\TableArea;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class TableController extends Controller
{
    public function index(Request $request): View
    {
        $branchId = auth()->user()->active_branch_id;

        $areas = TableArea::forBranch($branchId)
            ->with(['tables' => function ($query) {
                $query->orderBy('name');
            }])
            ->get();

        // Tables without areas
        $unassignedTables = RestaurantTable::forBranch($branchId)
            ->whereNull('area_id')
            ->orderBy('name')
            ->get();

        return view('portal.tables.index', compact('areas', 'unassignedTables'));
    }

    public function create(): View
    {
        $branchId = auth()->user()->active_branch_id;
        $areas = TableArea::forBranch($branchId)->get();

        return view('portal.tables.create', compact('areas'));
    }

    public function store(Request $request): RedirectResponse
    {
        $branchId = auth()->user()->active_branch_id;

        $request->validate([
            'area_id' => 'nullable|exists:table_areas,id',
            'name' => 'required|string|max:255',
            'capacity' => 'required|integer|min:1',
            'status' => 'required|in:available,occupied,reserved,cleaning',
            'is_active' => 'boolean',
        ]);

        $data = $request->all();
        $data['branch_id'] = $branchId;

        RestaurantTable::create($data);

        return redirect()->route('portal.tables.index')->with('success', 'Table created successfully.');
    }

    public function edit(RestaurantTable $table): View
    {
        $this->authorizeAccess($table);

        $branchId = auth()->user()->active_branch_id;
        $areas = TableArea::forBranch($branchId)->get();

        return view('portal.tables.edit', compact('table', 'areas'));
    }

    public function update(Request $request, RestaurantTable $table): RedirectResponse
    {
        $this->authorizeAccess($table);

        $request->validate([
            'area_id' => 'nullable|exists:table_areas,id',
            'name' => 'required|string|max:255',
            'capacity' => 'required|integer|min:1',
            'status' => 'required|in:available,occupied,reserved,cleaning',
            'is_active' => 'boolean',
        ]);

        $table->update($request->all());

        return redirect()->route('portal.tables.index')->with('success', 'Table updated successfully.');
    }

    public function destroy(RestaurantTable $table): RedirectResponse
    {
        $this->authorizeAccess($table);

        $table->delete();

        return redirect()->route('portal.tables.index')->with('success', 'Table deleted successfully.');
    }

    /**
     * Ensure the user has access to the table.
     */
    protected function authorizeAccess(RestaurantTable $table): void
    {
        if ($table->branch_id !== auth()->user()->active_branch_id) {
            abort(403, 'Unauthorized access to this table.');
        }
    }
}
