<?php

namespace App\Http\Controllers\Api\Biller;

use App\Http\Controllers\Controller;
use App\Models\RestaurantTable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TableController extends Controller
{
    /**
     * Get the restaurant tables and floor plan layout with active orders.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(): JsonResponse
    {
        $branchId = auth()->user()->active_branch_id;

        $tables = RestaurantTable::where('branch_id', $branchId)
            ->with(['activeOrder.items.kotItems'])
            ->get()
            ->map(function (RestaurantTable $table): array {
                $hasReadyItems = false;
                $activeOrderData = null;

                if ($table->activeOrder) {
                    foreach ($table->activeOrder->items as $item) {
                        if ($item->kotItems->where('status', 'ready')->count() > 0) {
                            $hasReadyItems = true;
                            break;
                        }
                    }

                    $activeOrderData = [
                        'id' => $table->activeOrder->id,
                        'grand_total' => number_format((float) $table->activeOrder->grand_total, 2, '.', ''),
                        'items' => $table->activeOrder->items->map(function ($item): array {
                            return [
                                'id' => $item->id,
                                'name' => $item->name,
                                'price' => number_format((float) $item->price, 2, '.', ''),
                                'quantity' => $item->quantity,
                            ];
                        })->values()->toArray(),
                    ];
                }

                return [
                    'id' => $table->id,
                    'area_id' => $table->area_id,
                    'name' => $table->name,
                    'capacity' => $table->capacity,
                    'status' => $table->status,
                    'pos_x' => $table->pos_x,
                    'pos_y' => $table->pos_y,
                    'width' => $table->width,
                    'height' => $table->height,
                    'shape' => $table->shape,
                    'has_ready_items' => $hasReadyItems,
                    'active_order' => $activeOrderData,
                ];
            });

        return response()->json($tables);
    }

    /**
     * Update the coordinates for the floor map layout.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateLayout(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'tables' => ['required', 'array'],
            'tables.*.id' => ['required', 'exists:restaurant_tables,id'],
            'tables.*.pos_x' => ['required', 'integer'],
            'tables.*.pos_y' => ['required', 'integer'],
        ]);

        foreach ($validated['tables'] as $tableData) {
            RestaurantTable::where('id', $tableData['id'])
                ->update([
                    'pos_x' => $tableData['pos_x'],
                    'pos_y' => $tableData['pos_y'],
                ]);
        }

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