<?php
declare(strict_types=1);

namespace App\Controllers;

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

class HubCustomersController
{
    public function index(): void
    {
        $q = trim((string)($_GET['q'] ?? ''));
        $list = Container::users()->search($q, 'CUSTOMER', 50);
        render('hub', 'hub.customers', compact('list', 'q'), t('hub.customers.title'));
    }

    public function search(): void
    {
        $q = trim((string)($_GET['q'] ?? ''));
        $list = Container::users()->search($q, 'CUSTOMER', 20);
        echo view('hub.customers-results', compact('list'));
    }

    public function show(array $params): void
    {
        $customer = Container::users()->find($params['id'] ?? '');
        if (!$customer) { http_response_code(404); require MAT_ROOT . '/src/Views/errors/404.php'; return; }
        $appointments = Container::appointments()->forCustomer($customer['id']);
        $forms = Container::intakeForms()->forCustomer($customer['id']);
        render('hub', 'hub.customer-detail', compact('customer', 'appointments', 'forms'), ($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''));
    }

    /**
     * Soft-delete a customer — requires staff PIN.
     * Record is preserved in data/users.json with deleted_at set; visible to admin only.
     */
    public function delete(array $params): void
    {
        Csrf::requireValid();
        $customer = Container::users()->find($params['id'] ?? '');
        if (!$customer || ($customer['role'] ?? '') !== 'CUSTOMER') {
            redirect('/hub/customers');
        }
        $staff = Pin::authenticate((string)($_POST['username'] ?? ''), (string)($_POST['pin'] ?? ''));
        if (!$staff) {
            $_SESSION['_flash']['error'] = t('hub.pin.invalid');
            redirect('/hub/customers/' . $customer['id']);
        }
        Container::users()->softDelete($customer['id'], $staff['id']);
        Container::audit()->log($staff['id'], 'DELETE_CUSTOMER', 'user', $customer['id']);
        $_SESSION['_flash']['success'] = t('hub.customers.deleted');
        redirect('/hub/customers');
    }
}
