<?php
/**
 * ajax/search_procedures.php
 * Searches procedures, tests, medications, and services for invoice line items
 * and the audiology edit page.
 *
 * GET params:
 *   query  — search string (min 2 chars)
 *   type   — PROCEDURE | TEST | MEDICATION | ACCOMMODATION | OTHER | '' (defaults to ALL)
 */
session_start();
require_once dirname(__DIR__) . '/layouts/dbconn.php';
require_once dirname(__DIR__) . '/layouts/session.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$query = trim($_GET['query'] ?? '');
$type  = strtoupper(trim($_GET['type'] ?? ''));

if (mb_strlen($query) < 2) {
    echo json_encode(['success' => false, 'results' => [], 'message' => 'Query too short']);
    exit();
}

$like    = '%' . mysqli_real_escape_string($conn, $query) . '%';
$results = [];

// ════════════════════════════════════════════════════════════════════════
// 1. ent_procedure_types  →  PROCEDURE / CONSULTATION / OTHER
//    Columns: procedure_type_id, procedure_name, standard_cost, category
// ════════════════════════════════════════════════════════════════════════
if (in_array($type, ['', 'PROCEDURE', 'CONSULTATION', 'ACCOMMODATION', 'OTHER'])) {
    $sql = "SELECT procedure_type_id AS id,
                   procedure_name    AS name,
                   COALESCE(standard_cost, 0) AS price,
                   CONCAT(category, ' — ', COALESCE(subcategory,'')) AS category
            FROM ent_procedure_types
            WHERE is_active = 1
              AND (procedure_name LIKE '$like'
                OR procedure_code LIKE '$like'
                OR COALESCE(subcategory,'') LIKE '$like')
            ORDER BY procedure_name
            LIMIT 20";

    $res = mysqli_query($conn, $sql);
    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $results[] = [
                'procedure_id' => (int)$row['id'],
                'name'         => $row['name'],
                'price'        => (float)$row['price'],
                'category'     => rtrim($row['category'], ' —'),
            ];
        }
    }
}

// ════════════════════════════════════════════════════════════════════════
// 2. ent_test_types  →  TEST
//    Columns: test_type_id, test_name, cost, category
// ════════════════════════════════════════════════════════════════════════
if (in_array($type, ['', 'TEST'])) {
    $sql = "SELECT test_type_id AS id,
                   test_name    AS name,
                   COALESCE(cost, 0) AS price,
                   CONCAT(category, COALESCE(CONCAT(' — ', subcategory),'')) AS category
            FROM ent_test_types
            WHERE is_active = 1
              AND (test_name LIKE '$like'
                OR test_code LIKE '$like'
                OR COALESCE(subcategory,'') LIKE '$like')
            ORDER BY test_name
            LIMIT 20";

    $res = mysqli_query($conn, $sql);
    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $results[] = [
                'procedure_id' => (int)$row['id'],
                'name'         => $row['name'],
                'price'        => (float)$row['price'],
                'category'     => $row['category'],
            ];
        }
    }
}

// ════════════════════════════════════════════════════════════════════════
// 3. pharmacy_inventory  →  MEDICATION
//    Columns: inventory_id, item_name, selling_price, dosage_form
// ════════════════════════════════════════════════════════════════════════
if (in_array($type, ['', 'MEDICATION'])) {
    $sql = "SELECT inventory_id AS id,
                   CONCAT(item_name, IF(strength IS NOT NULL AND strength != '', CONCAT(' ', strength), '')) AS name,
                   COALESCE(selling_price, 0) AS price,
                   COALESCE(dosage_form, 'Medication') AS category
            FROM pharmacy_inventory
            WHERE is_active = 1
              AND current_stock > 0
              AND (item_name   LIKE '$like'
                OR generic_name LIKE '$like'
                OR brand_name   LIKE '$like'
                OR item_code    LIKE '$like')
            ORDER BY item_name
            LIMIT 20";

    $res = mysqli_query($conn, $sql);
    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $results[] = [
                'procedure_id' => (int)$row['id'],
                'name'         => $row['name'],
                'price'        => (float)$row['price'],
                'category'     => $row['category'],
            ];
        }
    }
}

// ════════════════════════════════════════════════════════════════════════
// 4. service_pricing  →  fallback / ALL types
//    This table has the definitive pricing for all service types.
//    Join avoids duplicating results already found above.
//    Only pull rows whose service_type matches the requested type.
// ════════════════════════════════════════════════════════════════════════
$sp_type_filter = '';
if ($type !== '') {
    $safe_type = mysqli_real_escape_string($conn, $type);
    $sp_type_filter = "AND service_type = '$safe_type'";
}

// Only run the service_pricing query when we haven't found enough yet,
// OR when the type is exactly matching a service_pricing service_type.
// This prevents doubling up results from ent_procedure_types.
$run_sp = (count($results) < 5) || in_array($type, ['CONSULTATION','PROCEDURE','TEST','MEDICATION','HEARING_AID_ACCESSORIES']);

if ($run_sp) {
    $sql = "SELECT sp.pricing_id AS id,
                   sp.service_name AS name,
                   COALESCE(sp.base_price, 0) AS price,
                   sp.service_type AS category
            FROM service_pricing sp
            WHERE sp.is_active = 1
              AND sp.service_name LIKE '$like'
              $sp_type_filter
              AND (sp.effective_until IS NULL OR sp.effective_until >= CURDATE())
            ORDER BY sp.service_name
            LIMIT 20";

    $res = mysqli_query($conn, $sql);
    if ($res) {
        // Deduplicate by name (case-insensitive) against what we already have
        $existing_names = array_map(fn($r) => strtolower($r['name']), $results);
        while ($row = mysqli_fetch_assoc($res)) {
            if (!in_array(strtolower($row['name']), $existing_names)) {
                $results[] = [
                    'procedure_id' => (int)$row['id'],
                    'name'         => $row['name'],
                    'price'        => (float)$row['price'],
                    'category'     => $row['category'],
                ];
                $existing_names[] = strtolower($row['name']);
            }
        }
    }
}

// Sort all combined results alphabetically
usort($results, fn($a, $b) => strcmp($a['name'], $b['name']));

// Cap at 25 total
$results = array_slice($results, 0, 25);

echo json_encode([
    'success' => true,
    'results' => $results,
    'count'   => count($results),
]);