<?php
declare(strict_types=1);

namespace App\Controllers;

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

/**
 * Staff-side "book a new appointment" flow.
 * - Lookup existing customer OR create new one.
 * - Select artist, date, time, add notes.
 * - Requires PIN confirmation.
 */
class HubNewAppointmentController
{
    public function start(): void
    {
        $matches  = [];
        $q        = '';
        $artists  = Container::artists()->all(true);
        render('hub', 'hub.new-appointment', compact('matches', 'q', 'artists'), t('hub.new_appt.title'));
    }

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

    public function create(): void
    {
        Csrf::requireValid();
        $staff = Pin::authenticate((string)($_POST['username'] ?? ''), (string)($_POST['pin'] ?? ''));
        if (!$staff) {
            $_SESSION['_flash']['error'] = t('hub.pin.invalid');
            redirect('/hub/new-appointment');
        }

        $users  = Container::users();
        $appts  = Container::appointments();
        $forms  = Container::intakeForms();

        // Resolve or create customer
        $customerId = trim((string)($_POST['customer_id'] ?? ''));
        if ($customerId) {
            $customer = $users->find($customerId);
        } else {
            $firstName = trim((string)($_POST['first_name'] ?? ''));
            $lastName  = trim((string)($_POST['last_name']  ?? ''));
            if (!$firstName || !$lastName) {
                $_SESSION['_flash']['error'] = t('hub.new_appt.name_required');
                redirect('/hub/new-appointment');
            }
            $customer = $users->save([
                'role'       => 'CUSTOMER',
                'first_name' => $firstName,
                'last_name'  => $lastName,
                'email'      => trim((string)($_POST['email'] ?? '')),
                'phone'      => trim((string)($_POST['phone'] ?? '')),
                'is_active'  => true,
            ]);
        }

        // Build start_at / end_at from date + time (default 2-hour slot)
        $dateStr  = trim((string)($_POST['appt_date'] ?? ''));
        $timeStr  = trim((string)($_POST['appt_time'] ?? ''));
        $startAt  = $dateStr && $timeStr
            ? date('Y-m-d\TH:i:s', strtotime($dateStr . ' ' . $timeStr))
            : now_iso();
        $endAt = date('Y-m-d\TH:i:s', strtotime($startAt) + 7200);

        $artistId = trim((string)($_POST['artist_id'] ?? '')) ?: null;
        $notes    = trim((string)($_POST['notes'] ?? ''));

        // Conflict guard
        if ($artistId) {
            $conflict = \App\Services\Availability::findConflict($artistId, $startAt, $endAt);
            if ($conflict) {
                $_SESSION['_flash']['error'] = t('booking.errors.slot_taken');
                redirect('/hub/new-appointment');
            }
        }

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

        $appt = $appts->save([
            'customer_id'    => $customer['id'],
            'artist_id'      => $artistId,
            'start_at'       => $startAt,
            'end_at'         => $endAt,
            'status'         => 'PENDING',
            'source'         => 'STAFF',
            'notes'          => $notes,
            'intake_form_id' => $intake['id'],
        ]);

        Container::audit()->log($staff['id'], 'CREATE_APPT', 'appointment', $appt['id']);
        $_SESSION['_flash']['success'] = t('hub.new_appt.created');
        redirect('/hub/appointments/' . $appt['id']);
    }
}
