<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Repositories\QueueRepository;

final class PublicController extends Controller {
    public function queuePublic(): void {
        $repo = new QueueRepository();
        $token = trim((string)($_GET['token'] ?? ''));
        $ticket = $repo->findByToken($token);
        if (!$ticket) {
            http_response_code(404);
            $this->view('errors/404');
            return;
        }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf();
            $phone = normalize_phone((string)($_POST['customer_phone'] ?? ''));
            if ($phone !== '') {
                $repo->savePhoneIfEmpty((int)$ticket['id'], $phone);
                flash('success', 'تم حفظ رقم الهاتف بنجاح، وستصلك التحديثات عند اقتراب الدور.');
            }
            redirect(base_url('?page=queue_public&token=' . urlencode($token)));
        }
        $ticket = $repo->findByToken($token);
        $remaining = $repo->countBefore((int)$ticket['queue_session_id'], (int)$ticket['seq_no']);
        $snap = $repo->snapshot();
        $this->view('queue/public', compact('ticket', 'remaining', 'snap'));
    }
}
