<?php
/**
 * ccc_nhis.php
 * Fetch 5-digit CCC for a patient using NHIS API
 * Conditional logic:
 *   - Active NHIS: return CCC
 *   - Inactive NHIS: fail, patient treated as private cash
 *   - API fetch failure: allow manual CCC input
 */

header('Content-Type: application/json');
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

if (empty($_GET['patient_no'])) {
    echo json_encode(['status' => 'fail', 'message' => 'Missing patient_no']);
    exit;
}

$patient_no = $_GET['patient_no'];

// Fetch patient NHIS number
$stmt = $conn->prepare("SELECT nhis_no FROM patient WHERE patient_no = ? LIMIT 1");
$stmt->bind_param("s", $patient_no);
$stmt->execute();
$result = $stmt->get_result();
$patient = $result->fetch_assoc();

if (!$patient || empty($patient['nhis_no'])) {
    echo json_encode([
        'status' => 'fail',
        'message' => 'No NHIS number found',
        'manual_input_allowed' => false // No NHIS number → cannot manually input
    ]);
    exit;
}

$nhis_no = $patient['nhis_no'];

// --- Simulate NHIS API call ---
$api_active = rand(0, 1); // Simulated API response: 1 = active, 0 = inactive

if ($api_active) {
    // NHIS number active → return 5-digit CCC
    $ccc_code = str_pad(rand(10000, 99999), 5, '0', STR_PAD_LEFT);
    echo json_encode([
        'status' => 'success',
        'ccc_code' => $ccc_code
    ]);
    exit;
} else {
    // NHIS number inactive → patient treated as private cash
    echo json_encode([
        'status' => 'fail',
        'message' => 'NHIS number inactive. Treat patient as private cash.',
        'manual_input_allowed' => false // Cannot manually input
    ]);
    exit;
}

// Optionally, you could add another branch for temporary API failure and allow manual input
// Example:
// echo json_encode([
//     'status' => 'fail',
//     'message' => 'Temporary API error. Please enter CCC manually.',
//     'manual_input_allowed' => true
// ]);
