<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Queue;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Carbon\Carbon;



class QueueController extends Controller
{

    public function index()
    {
        $user = Auth::user();

        $query = Queue::where('tenant_id', $user->tenant_id)
            ->with(['dailyMetrics' => function ($q) {
                $q->whereDate('date', Carbon::today());
            }, 'waitingList']);

        if (!empty($user->allowed_sector)) {
            $query->where('sector', $user->allowed_sector);
        }

        return Inertia::render('Queues/Index', [
            'queues' => $query->get()
        ]);
    }
    public function setQueueName(Request $request)
    {
        if (Auth::user()->role !== "supervisor" && Auth::user()->role !== "admin") {
            abort(403, 'Apenas administradores podem gerenciar setores.');
        }

        $validated = $request->validate([
            'queue_number'  => 'required|numeric',
            'friendly_name' => 'required|string|max:255'
        ]);

        Queue::updateOrCreate(
            [
                'tenant_id' => Auth::user()->tenant_id,
                'source_id' => $validated['queue_number'],
            ],
            [
                'name' => $validated['friendly_name']
            ]
        );

        return back()->with('message', 'Nome da fila atualizado com sucesso!');
    }

    public function updateSectors(Request $request)
    {
        if (Auth::user()->role !== "supervisor" && Auth::user()->role !== "admin") {
            abort(403, 'Apenas administradores podem gerenciar setores.');
        }

        $data = $request->validate([
            'queues' => 'required|array',
            'queues.*.id' => 'required|exists:queues,id', // Garante que a fila existe
            'queues.*.sector' => 'nullable|string|max:50', // Valida o nome do setor
        ]);

        foreach ($data['queues'] as $item) {
            // Encontra a fila pelo ID e atualiza apenas a coluna 'sector'
            // Sugestão: Se usar multi-tenancy, adicione ->where('tenant_id', ...) aqui
            $queue = Queue::find($item['id']);

            if ($queue) {
                $queue->sector = $item['sector'];
                $queue->save();
            }
        }

        return back()->with('message', 'Setores organizados com sucesso!');
    }
}
