<?php
/**
 * ajax/get_insurance_provider.php
 * Returns details for a single insurance provider (used by the override dropdown
 * in the dispense form when a pharmacist manually switches provider).
 */
session_start();
header('Content-Type: application/json');

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

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

$provider_id = isset($_POST['provider_id']) ? (int)$_POST['provider_id'] : 0;
if ($provider_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid provider ID']);
    exit();
}

$stmt = $conn->prepare(
    "SELECT provider_id, provider_name, provider_code,
            coverage_percentage, copay_percentage, co_payment_percentage,
            coverage_limit, contact_person, phone, email, claim_processing_days
     FROM insurance_providers
     WHERE provider_id = ? AND is_active = 1"
);
$stmt->bind_param('i', $provider_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
$conn->close();

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

echo json_encode([
    'success'              => true,
    'provider_id'          => $row['provider_id'],
    'provider_name'        => $row['provider_name'],
    'provider_code'        => $row['provider_code'],
    'coverage_percentage'  => (float)($row['coverage_percentage'] ?? 80),
    'copay_percentage'     => (float)($row['copay_percentage'] ?? $row['co_payment_percentage'] ?? 0),
    'coverage_limit'       => (int)($row['coverage_limit'] ?? 0),
    'contact_person'       => $row['contact_person'],
    'phone'                => $row['phone'],
    'email'                => $row['email'],
    'claim_processing_days'=> (int)($row['claim_processing_days'] ?? 14),
]);