<?php
/**
 * ajax/search_patients_dispense.php
 * Select2-compatible patient search for the pharmacy dispensing form.
 * Returns: { results: [{id, text, ...}, ...] }
 */
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['results' => []]);
    exit();
}

$search = trim($_GET['q'] ?? $_POST['q'] ?? '');
if (strlen($search) < 2) {
    echo json_encode(['results' => []]);
    exit();
}

try {
    $like  = '%' . $search . '%';
    $start = $search . '%';

    /*
     * FIX 1: `p.is_active = 1` silently excludes patients whose column is NULL
     *         (MySQL evaluates NULL = 1 as NULL, not TRUE).
     *         Use COALESCE so unset rows are treated as active.
     *
     * FIX 2: Added insurance_number and email to the search columns so
     *         pharmacy staff can look up patients by those identifiers too.
     */
    $stmt = $conn->prepare(
        "SELECT p.patient_id, p.patient_number, p.registration_type,
                p.insurance_number,
                u.full_name, u.phone_primary, u.email, u.date_of_birth, u.gender
         FROM patients p
         INNER JOIN users u ON p.user_id = u.user_id
         WHERE COALESCE(p.is_active, 1) = 1
           AND (
               u.full_name         LIKE ?
            OR p.patient_number    LIKE ?
            OR u.phone_primary     LIKE ?
            OR p.insurance_number  LIKE ?
            OR u.email             LIKE ?
           )
         ORDER BY
             CASE
                 WHEN p.patient_number   LIKE ? THEN 1
                 WHEN u.full_name        LIKE ? THEN 2
                 ELSE 3
             END,
             u.full_name ASC
         LIMIT 30"
    );

    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }

    // 5 search params + 2 ORDER BY params = 7 total
    $stmt->bind_param('sssssss', $like, $like, $like, $like, $like, $start, $start);

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $pm = [
        'INSURANCE' => 'INSURANCE',
        'PRO_BONO'  => 'PRO_BONO',
        'WALK_IN'   => 'CASH',
        'CORPORATE' => 'CORPORATE',
        'REFERRAL'  => 'CASH',
    ];

    $results = [];
    foreach ($rows as $row) {
        $regType = $row['registration_type'] ?? 'WALK_IN';
        $results[] = [
            // Select2 required fields
            'id'               => (int)$row['patient_id'],
            'text'             => $row['patient_number'] . ' — ' . $row['full_name'] .
                                  ($row['phone_primary'] ? ' — ' . $row['phone_primary'] : ''),
            // Extra fields for the patient info panel
            'patient_number'   => $row['patient_number']   ?? '',
            'full_name'        => $row['full_name']         ?? '',
            'phone_primary'    => $row['phone_primary']     ?? '',
            'email'            => $row['email']             ?? '',
            'date_of_birth'    => $row['date_of_birth']     ?? '',
            'gender'           => $row['gender']            ?? '',
            'insurance_number' => $row['insurance_number']  ?? '',
            'registration_type'=> $regType,
            'default_payment'  => $pm[$regType] ?? 'CASH',
        ];
    }

    echo json_encode(['results' => $results]);

} catch (Exception $e) {
    error_log('search_patients_dispense error: ' . $e->getMessage());
    echo json_encode(['results' => [], 'error' => $e->getMessage()]);
}