<?php
/**
 * ajax/get_consultation_rate.php
 *
 * Returns the correct consultation fee for a patient/visit.
 * Priority:  visit.consultation_fee (set at registration)
 *         → insurance_providers.consultation_rate (live fallback)
 *         → 4000 (cash default)
 *
 * POST params: patient_id (required), visit_id (optional)
 */

session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';
header('Content-Type: application/json');

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

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

if ($patient_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'patient_id required']);
    exit();
}

// ── 1. Try to read fee stored on the visit ─────────────────────────────────
if ($visit_id > 0) {
    $sql  = "SELECT consultation_fee, registration_type
             FROM patient_visits
             WHERE visit_id = ? AND patient_id = ?
             LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $visit_id, $patient_id);
    $stmt->execute();
    $row  = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($row && floatval($row['consultation_fee']) > 0) {
        echo json_encode([
            'success'          => true,
            'source'           => 'visit',
            'consultation_fee' => floatval($row['consultation_fee']),
            'registration_type'=> $row['registration_type'],
        ]);
        exit();
    }
}

// ── 2. Fallback: derive from patient's insurance provider or type ───────────
$sql  = "SELECT p.registration_type,
                p.insurance_provider_id,
                COALESCE(ip.consultation_rate, 0) AS provider_rate
         FROM   patients p
         LEFT   JOIN insurance_providers ip
                ON   ip.provider_id = p.insurance_provider_id
                AND  ip.is_active   = 1
         WHERE  p.patient_id = ?
         LIMIT  1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$row  = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row) {
    echo json_encode(['success' => false, 'message' => 'Patient not found']);
    exit();
}

$type         = $row['registration_type'];
$provider_rate = floatval($row['provider_rate']);

if ($type === 'PRO_BONO') {
    $fee    = 0.0;
    $source = 'pro_bono';
} elseif ($type === 'INSURANCE' && $provider_rate > 0) {
    $fee    = $provider_rate;
    $source = 'insurance_provider';
} else {
    // WALK_IN or insurance without a stored rate → cash default
    $fee    = 4000.0;
    $source = 'cash_default';
}

echo json_encode([
    'success'          => true,
    'source'           => $source,
    'consultation_fee' => $fee,
    'registration_type'=> $type,
    'provider_rate'    => $provider_rate,
]);