<?php

/** GET /api/catalogs — everything the ticket form needs, in one call. */
route('GET', ['catalogs'], function () {
    Auth::require();
    Response::json([
        'manufacturers' => DB::all('SELECT id, name FROM manufacturers WHERE is_active = 1 ORDER BY name'),
        'products'      => DB::all('SELECT id, manufacturer_id, name, model FROM products WHERE is_active = 1 ORDER BY name'),
    ]);
});

/**
 * GET /api/catalogs/units?product_id=..
 * Serials are fetched per product so the customer never scrolls a list of thousands.
 */
route('GET', ['catalogs', 'units'], function () {
    $u = Auth::require();
    $productId = (int) ($_GET['product_id'] ?? 0);
    if ($productId <= 0) {
        Response::json([]);
    }
    $sql    = 'SELECT id, serial_number, warranty_until FROM product_units
               WHERE is_active = 1 AND product_id = ?';
    $params = [$productId];

    // A customer only sees serials belonging to their organisation, plus unassigned ones.
    if ($u['role'] === 'customer') {
        $sql .= ' AND (customer_id = ? OR customer_id IS NULL)';
        $params[] = $u['customer_id'];
    }
    Response::json(DB::all($sql . ' ORDER BY serial_number', $params));
});

/** GET /api/handlers — staff who can be assigned a ticket. */
route('GET', ['handlers'], function () {
    Auth::require('support', 'admin');
    Response::json(DB::all(
        'SELECT u.id, u.full_name, r.code AS role FROM users u
         JOIN roles r ON r.id = u.role_id
         WHERE u.is_active = 1 AND r.code IN ("technician", "instructor")
         ORDER BY r.code, u.full_name'
    ));
});

/** GET /api/templates — active procedure templates, for the assignment dialog. */
route('GET', ['templates'], function () {
    Auth::require('support', 'admin');
    Response::json(DB::all(
        'SELECT id, name, applies_to, is_default FROM procedure_templates WHERE is_active = 1 ORDER BY name'
    ));
});
