<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Floorplan;
use App\Models\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Reservation;

class FloorplanController extends Controller
{
    public function assignWaiter(\Illuminate\Http\Request $request, \App\Models\Floorplan $floorplan)
{
    $user = auth()->user();
    if (!$user) abort(401);

    // Only SuperAdmin/Manager can assign waiter groups (Hostess optional)
    if (!$user->hasAnyRole(['SuperAdmin','Upravitel'])) {
        abort(403);
    }

    $data = $request->validate([
        'table_ids' => ['required','string'], // comma-separated
        'waiter_team' => ['nullable','string','max:50'],
        'waiter_color' => ['nullable','string','max:20'],
    ]);

    $ids = array_values(array_filter(array_map('intval', explode(',', $data['table_ids']))));
    if (count($ids) === 0) {
        return back()->with('status', 'No tables selected.');
    }

    \App\Models\Table::query()
        ->where('floorplan_id', $floorplan->id)
        ->whereIn('id', $ids)
        ->update([
            'waiter_team' => $data['waiter_team'] ?: null,
            'waiter_color' => $data['waiter_color'] ?: null,
        ]);

    return back()->with('status', 'Waiter group assigned.');
}

    public function syncReservationTables(Request $request, Reservation $reservation)
{
    $user = auth()->user();
    if (!$user) abort(401);

    // Who may assign/move tables at all:
    if (!$user->hasAnyRole(['SuperAdmin', 'Upravitel', 'Hostess'])) {
        abort(403);
    }

    // Enforce DO NOT MOVE lock:
    // If locked_move = true, only SuperAdmin or the creator can change table assignment
    if ($reservation->locked_move) {
        if (!$user->hasRole('SuperAdmin') && (int)$reservation->created_by_user_id !== (int)$user->id) {
            abort(403, 'Reservation is locked (DO NOT MOVE).');
        }
    }

    $data = $request->validate([
        'table_ids' => ['required','string'], // comma-separated
        'floorplan_id' => ['required','integer','exists:floorplans,id'],
    ]);

    $ids = array_values(array_filter(array_map('intval', explode(',', $data['table_ids']))));
    if (count($ids) === 0) {
        return back()->with('status', 'No tables selected.');
    }

    $allowed = Table::query()
        ->where('floorplan_id', (int)$data['floorplan_id'])
        ->whereIn('id', $ids)
        ->pluck('id')
        ->all();

    $reservation->tables()->sync($allowed);

    return back()->with('status', 'Reservation tables updated.');
}


    private function superAdminOnly(): void
    {
        abort_unless(auth()->user()?->hasRole('SuperAdmin'), 403);
    }

    public function index()
    {
        $this->superAdminOnly();

        return view('admin.floorplans.index', [
            'floorplans' => Floorplan::query()->orderByDesc('id')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $this->superAdminOnly();

        $data = $request->validate([
            'name' => ['required','string','max:190'],
            'image' => ['required','image','mimes:png,jpg,jpeg','max:8192'],
        ]);

        $path = $request->file('image')->store('floorplans', 'public');

        $fullPath = Storage::disk('public')->path($path);
        $w = null; $h = null;
        $size = @getimagesize($fullPath);
        if (is_array($size)) {
            $w = (int)($size[0] ?? 0) ?: null;
            $h = (int)($size[1] ?? 0) ?: null;
        }

        $fp = Floorplan::create([
            'name' => $data['name'],
            'image_path' => $path,
            'width' => $w,
            'height' => $h,
        ]);

        return redirect()->route('admin.floorplans.show', $fp);
    }

    public function show(Floorplan $floorplan)
{
    $this->superAdminOnly();

    $floorplan->load('tables');

    $today = now()->toDateString();

    // Pull today's reservations with their tables, but only keep tables that belong to THIS floorplan
    $reservations = \App\Models\Reservation::query()
        ->whereDate('date', $today)
        ->with(['tables:id,floorplan_id,label,x,y,w,h,rotation'])
        ->orderBy('expected_arrival_time')
        ->orderBy('id')
        ->get();

    $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,
            '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),
            'table_ids' => $tableIds,
        ];
    })->values();

    return view('admin.floorplans.show', [
        'floorplan' => $floorplan,
        'tables' => $floorplan->tables()->orderBy('label')->get(),
        'reservationGroups' => $reservationGroups,
        'today' => $today,
    ]);
}


    public function createTable(Request $request, Floorplan $floorplan)
    {
        $this->superAdminOnly();

        $data = $request->validate([
            'label' => ['required','string','max:50'],
            'shape' => ['required','in:rect_lg,rect_sm,sq_lg,sq_sm,circle_lg,circle_sm'],
            'seats' => ['required','integer','min:1','max:30'],
        ]);

        $table = Table::create([
            'floorplan_id' => $floorplan->id,
            'label' => $data['label'],
            'shape' => $data['shape'],
            'seats' => $data['seats'],
            'x' => 20,
            'y' => 20,
            'w' => in_array($data['shape'], ['rect_lg','rect_sm']) ? 90 : 60,
            'h' => in_array($data['shape'], ['rect_lg','rect_sm']) ? 60 : 60,
            'rotation' => 0,
            'is_active' => true,
            'live_status' => 'free',
        ]);

        return redirect()->route('admin.floorplans.show', $floorplan)->with('status', 'Table created.');
    }

    public function updateTable(Request $request, Table $table)
    {
        $this->superAdminOnly();

        $data = $request->validate([
            'x' => ['required','integer','min:-5000','max:5000'],
            'y' => ['required','integer','min:-5000','max:5000'],
            'w' => ['nullable','integer','min:20','max:500'],
            'h' => ['nullable','integer','min:20','max:500'],
            'rotation' => ['nullable','integer','min:0','max:359'],
        ]);

        $table->update([
            'x' => $data['x'],
            'y' => $data['y'],
            'w' => $data['w'] ?? $table->w,
            'h' => $data['h'] ?? $table->h,
            'rotation' => $data['rotation'] ?? $table->rotation,
        ]);

        return response()->json(['ok' => true]);
    }
}
