<?php
/**
 * ajax/get_patient_visits.php
 *
 * Returns active + recently-completed visits for a patient so billing
 * can create an invoice against any of them.
 *
 * KEY FIX: COMPLETED visits MUST be included — after a consultation is
 * finished and the patient is routed to billing, patient_visits.status
 * becomes 'COMPLETED'. The old filter (status NOT IN ('COMPLETED','CANCELLED'))
 * was hiding exactly the visits that billing needs to invoice.
 *
 * Inclusion rules:
 *   ✅  REGISTERED, WAITING, IN_CONSULTATION  — always show
 *   ✅  COMPLETED  — show when created today OR has no invoice yet
 *   ❌  CANCELLED  — never show
 *
 * Response shape:
 *   { success: true, visits: [ { visit_id, visit_number, visit_type,
 *                                 status, formatted_date, consultation_fee,
 *                                 has_invoice } ] }
 */

session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php'; // provides $conn (MySQLi)

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

$patient_id = isset($_POST['patient_id']) ? (int)$_POST['patient_id'] : 0;

if (!$patient_id) {
    echo json_encode(['success' => false, 'message' => 'Missing patient_id.']);
    exit;
}

/*
 * Fetch visits that billing should see:
 *
 *  1. All non-cancelled visits from today (covers REGISTERED → COMPLETED same day)
 *  2. Any non-cancelled visit from the past 30 days that has no invoice yet
 *     (catches edge cases where billing was delayed)
 *
 * has_invoice = 1 means an active (non-cancelled) invoice already exists.
 * The JS can use this to warn the clerk rather than hard-blocking.
 */
$sql = "
    SELECT
        pv.visit_id,
        pv.visit_number,
        pv.visit_type,
        pv.status,
        pv.consultation_fee,
        DATE_FORMAT(
            COALESCE(pv.registration_date, pv.created_at),
            '%d %b %Y %H:%i'
        ) AS formatted_date,
        COALESCE(pv.registration_date, pv.created_at) AS sort_date,
        EXISTS (
            SELECT 1 FROM invoices i
            WHERE  i.visit_id = pv.visit_id
              AND  i.status  != 'CANCELLED'
        ) AS has_invoice
    FROM patient_visits pv
    WHERE pv.patient_id = ?
      AND pv.status     != 'CANCELLED'
      AND (
            /* Always show today's visits regardless of status */
            DATE(COALESCE(pv.registration_date, pv.created_at)) = CURDATE()

            OR

            /* Show older visits only if they still have no invoice */
            (
                COALESCE(pv.registration_date, pv.created_at) >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                AND NOT EXISTS (
                    SELECT 1 FROM invoices i2
                    WHERE  i2.visit_id = pv.visit_id
                      AND  i2.status  != 'CANCELLED'
                )
            )
      )
    ORDER BY sort_date DESC
    LIMIT 50
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Query prepare error: ' . $conn->error]);
    exit;
}

$stmt->bind_param('i', $patient_id);
if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Query execute error: ' . $stmt->error]);
    exit;
}

$result = $stmt->get_result();
$visits = [];

while ($row = $result->fetch_assoc()) {
    /*
     * Build a human-readable status label for the <option> text in create_invoice.php.
     * The JS uses: ${v.visit_number} — ${v.formatted_date} — ${vType} ${status}
     */
    $status_label = match($row['status']) {
        'REGISTERED'      => '[Registered]',
        'WAITING'         => '[Waiting]',
        'IN_CONSULTATION' => '[In Consultation]',
        'COMPLETED'       => '[Seen ✓ — Ready to Invoice]',
        default           => '[' . $row['status'] . ']',
    };

    $visits[] = [
        'visit_id'         => (int)$row['visit_id'],
        'visit_number'     => $row['visit_number'],
        'visit_type'       => $row['visit_type'],
        'status'           => $row['status'],
        'status_label'     => $status_label,
        'formatted_date'   => $row['formatted_date'],
        'consultation_fee' => (float)$row['consultation_fee'],
        'has_invoice'      => (bool)$row['has_invoice'],
    ];
}

$stmt->close();

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