<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Csrf;
use App\Repositories\Container;

class HubWalkinController
{
    public function start(): void
    {
        $matches = [];
        $q = '';
        render('hub', 'hub.walkin', compact('matches', 'q'), t('hub.walkin.title'));
    }

    public function lookup(): void
    {
        Csrf::requireValid();
        $q = trim((string)($_POST['q'] ?? ''));
        $matches = $q ? Container::users()->search($q, 'CUSTOMER', 15) : [];
        render('hub', 'hub.walkin', compact('matches', 'q'), t('hub.walkin.title'));
    }

    public function create(): void
    {
        Csrf::requireValid();
        // Staff must re-verify username + PIN (or password for admins) to start a form.
        $staff = \App\Pin::authenticate((string)($_POST['username'] ?? ''), (string)($_POST['pin'] ?? ''));
        if (!$staff) {
            $_SESSION['_flash']['error'] = t('hub.pin.invalid');
            redirect('/hub/walkin');
        }

        $customerId = $_POST['customer_id'] ?? null;
        $users = Container::users();
        $form = Container::intakeForms();
        $appts = Container::appointments();

        if (!$customerId) {
            $customer = $users->save([
                'role' => 'CUSTOMER',
                'first_name' => trim((string)($_POST['first_name'] ?? '')),
                'last_name'  => trim((string)($_POST['last_name'] ?? '')),
                'email'      => trim((string)($_POST['email'] ?? '')),
                'phone'      => trim((string)($_POST['phone'] ?? '')),
                'is_active'  => true,
            ]);
        } else {
            $customer = $users->find($customerId);
        }

        $intake = $form->save([
            'customer_id' => $customer['id'],
            'status' => 'DRAFT',
            'general_info' => array_filter([
                'first_name' => $customer['first_name'] ?? '',
                'last_name'  => $customer['last_name']  ?? '',
                'email'      => $customer['email']      ?? '',
                'phone'      => $customer['phone']      ?? '',
            ]),
        ]);

        $appt = $appts->save([
            'customer_id' => $customer['id'],
            'start_at' => now_iso(),
            'end_at'   => now_iso(),
            'status' => 'APPROVED',
            'source' => 'WALKIN',
            'intake_form_id' => $intake['id'],
            'approved_by_id' => $staff['id'],
            'approved_at' => now_iso(),
        ]);
        Container::audit()->log($staff['id'], 'CREATE_WALKIN', 'appointment', $appt['id']);

        redirect('/hub/forms/' . $intake['id']);
    }
}
