<?php

namespace App\Http\Controllers;

use App\Models\Floorplan;
use App\Models\Reservation;
use Illuminate\Http\Request;

class OperationsController extends Controller
{
    public function index(Request $request)
    {
        $date = $request->get('date', now()->toDateString());

        // For now: use latest floorplan as the active one
        // Later we can add a "default_floorplan_id" setting or per-day assignment.
        $floorplan = Floorplan::query()->orderByDesc('id')->firstOrFail();
        $floorplan->load('tables');

        $reservations = Reservation::query()
            ->whereDate('date', $date)
            ->with(['tables:id,floorplan_id,label,x,y,w,h,rotation'])
            ->orderBy('expected_arrival_time')
            ->orderBy('id')
            ->get();

        // Build "groups" used by the frontend to draw links + label tables
        $reservationGroups = $reservations->map(function ($r) use ($floorplan) {
            $tableIds = $r->tables
                ->where('floorplan_id', $floorplan->id)
                ->pluck('id')
                ->values()
                ->all();

            return [
                'id' => $r->id,
                'guest_name' => $r->guest_name,
                'phone' => $r->phone,
                'expected_arrival_time' => $r->expected_arrival_time,
                'people_count' => $r->people_count,
                'advance_amount' => (float)($r->advance_amount ?? 0),
                'locked_move' => (bool)($r->locked_move ?? false),
                'is_seated' => (bool)($r->seated_at ?? false),
                'table_ids' => $tableIds,
            ];
        })->values();

        return view('ops.floorplan', [
            'date' => $date,
            'floorplan' => $floorplan,
            'tables' => $floorplan->tables()->orderBy('label')->get(),
            'reservations' => $reservations,
            'reservationGroups' => $reservationGroups,
        ]);
    }
}
