<?php

namespace App\Http\Controllers\Portal;

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

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

        $areas = TableArea::forBranch($branchId)
            ->withCount('tables')
            ->get();

        return view('portal.table-areas.index', compact('areas'));
    }

    public function create(): View
    {
        return view('portal.table-areas.create');
    }

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'is_active' => 'boolean',
        ]);

        $validated['branch_id'] = $branchId;

        TableArea::create($validated);

        return redirect()->route('portal.table-areas.index')->with('success', 'Area created successfully.');
    }

    public function edit(TableArea $tableArea): View
    {
        $this->authorizeAccess($tableArea);

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

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'is_active' => 'boolean',
        ]);

        $tableArea->update($validated);

        return redirect()->route('portal.table-areas.index')->with('success', 'Area updated successfully.');
    }

    public function destroy(TableArea $tableArea): RedirectResponse
    {
        $this->authorizeAccess($tableArea);

        $tableArea->delete();

        return redirect()->route('portal.table-areas.index')->with('success', 'Area deleted successfully.');
    }

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