<?php
/**
 * ajax/get_patient_billing_info.php
 * Returns a patient's registration type, insurance details, and preferred
 * payment method so the dispense form can auto-populate the payment section.
 */
session_start();
header('Content-Type: application/json');

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

include '../layouts/dbconn.php';

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

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

$stmt = $conn->prepare(
    "SELECT
        p.patient_id,
        p.patient_number,
        p.registration_type,
        p.insurance_provider_id,
        p.insurance_number,
        p.policy_number,
        p.employer,
        ip.provider_name,
        ip.provider_code,
        ip.coverage_percentage,
        ip.copay_percentage,
        ip.co_payment_percentage,
        ip.coverage_limit,
        ip.contact_person      AS ins_contact_person,
        ip.phone               AS ins_phone,
        ip.email               AS ins_email,
        ip.claim_processing_days,
        u.full_name,
        u.phone_primary,
        u.email                AS patient_email
     FROM patients p
     INNER JOIN users u ON p.user_id = u.user_id
     LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
     WHERE p.patient_id = ?
       AND p.is_active = 1"
);
$stmt->bind_param('i', $patient_id);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();
$stmt->close();
$conn->close();

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

// Derive the default payment method from registration_type
$payment_map = [
    'INSURANCE' => 'INSURANCE',
    'PRO_BONO'  => 'PRO_BONO',
    'WALK_IN'   => 'CASH',   // default cash for walk-ins
];
$default_payment = $payment_map[$patient['registration_type']] ?? 'CASH';

// Effective copay percentage (use copay_percentage first, fall back to co_payment_percentage)
$copay = (float)($patient['copay_percentage'] ?? $patient['co_payment_percentage'] ?? 0);
$coverage = (float)($patient['coverage_percentage'] ?? 80);

echo json_encode([
    'success'              => true,
    'patient_id'           => $patient['patient_id'],
    'patient_number'       => $patient['patient_number'],
    'full_name'            => $patient['full_name'],
    'registration_type'    => $patient['registration_type'],
    'default_payment'      => $default_payment,
    // Insurance details (null if not an insurance patient)
    'insurance_provider_id'=> $patient['insurance_provider_id'],
    'provider_name'        => $patient['provider_name'],
    'provider_code'        => $patient['provider_code'],
    'insurance_number'     => $patient['insurance_number'],
    'policy_number'        => $patient['policy_number'],
    'employer'             => $patient['employer'],
    'coverage_percentage'  => $coverage,
    'copay_percentage'     => $copay,
    'coverage_limit'       => $patient['coverage_limit'],
    'ins_contact_person'   => $patient['ins_contact_person'],
    'ins_phone'            => $patient['ins_phone'],
    'claim_processing_days'=> $patient['claim_processing_days'],
]);