<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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

class TableController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();
        $outlets = Outlet::select('id', 'name')->get();
        
        $outletFilter = $request->input('outlet_id');
        $outletId = $user->outlet_id 
            ? (int)$user->outlet_id 
            : ($outletFilter 
                ? (int)$outletFilter 
                : ($outlets->first() ? $outlets->first()->id : null));

        $tables = Table::with(['outlet', 'mergedTo'])
            ->when($outletId, fn($q) => $q->where('outlet_id', $outletId))
            ->orderBy('number')
            ->get();

        return Inertia::render('CafePOS/Tables/Index', [
            'tables' => $tables,
            'outlets' => $outlets,
            'filters' => [
                'outlet_id' => $outletId ? (string)$outletId : null,
            ]
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'outlet_id' => ['required', 'integer', 'exists:outlets,id'],
            'number' => ['required', 'string', 'max:255'],
            'capacity' => ['required', 'integer', 'min:1'],
            'status' => ['required', 'string', 'in:available,occupied,reserved'],
        ]);

        Table::create($request->only(['outlet_id', 'number', 'capacity', 'status']));

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

    public function update(Request $request, Table $table): RedirectResponse
    {
        $request->validate([
            'number' => ['required', 'string', 'max:255'],
            'capacity' => ['required', 'integer', 'min:1'],
            'status' => ['required', 'string', 'in:available,occupied,reserved'],
        ]);

        $table->update($request->only(['number', 'capacity', 'status']));

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

    public function destroy(Table $table): RedirectResponse
    {
        $table->delete();
        return redirect()->back()->with('success', 'Table deleted successfully.');
    }

    public function mergeTables(Request $request): RedirectResponse
    {
        $request->validate([
            'source_table_id' => ['required', 'integer', 'exists:tables,id'],
            'target_table_id' => ['required', 'integer', 'exists:tables,id', 'different:source_table_id'],
        ]);

        $source = Table::findOrFail($request->source_table_id);
        $target = Table::findOrFail($request->target_table_id);

        if ($source->outlet_id !== $target->outlet_id) {
            return redirect()->back()->with('error', 'Tables must belong to the same outlet.');
        }

        // Merge source to target
        $source->update([
            'merged_to_id' => $target->id,
            'status' => 'occupied',
        ]);

        $target->update(['status' => 'occupied']);

        return redirect()->back()->with('success', "Table {$source->number} merged into Table {$target->number} successfully.");
    }

    public function splitTable(Request $request): RedirectResponse
    {
        $request->validate([
            'table_id' => ['required', 'integer', 'exists:tables,id'],
        ]);

        $table = Table::findOrFail($request->table_id);
        $table->update([
            'merged_to_id' => null,
            'status' => 'available',
        ]);

        return redirect()->back()->with('success', "Table {$table->number} split successfully.");
    }
}
