<?php
/**
 * AJAX Endpoint: Get Insurer-Specific Pre-Authorization Form
 *
 * Receives provider_id via POST and returns the appropriate
 * form HTML based on the provider's code.
 */

session_start();
include __DIR__ . '/../layouts/dbconn.php';
include __DIR__ . '/../preauth_forms/form_config.php';

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

// Check allowed roles
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FINANCE_MANAGER', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit();
}

// Get provider_id from request
$provider_id = isset($_POST['provider_id']) ? (int) $_POST['provider_id'] : 0;
$patient_id = isset($_POST['patient_id']) ? (int) $_POST['patient_id'] : 0;

if ($provider_id <= 0) {
    // Return empty form or default
    http_response_code(200);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'html' => '',
        'provider_code' => '',
        'provider_name' => '',
        'form_type' => 'none'
    ]);
    exit();
}

// Fetch provider details
$provider_sql = "SELECT provider_id, provider_name, provider_code FROM insurance_providers WHERE provider_id = ?";
$stmt = $conn->prepare($provider_sql);
$stmt->bind_param('i', $provider_id);
$stmt->execute();
$result = $stmt->get_result();
$provider = $result->fetch_assoc();

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

$provider_code = strtoupper(trim($provider['provider_code']));
$form_config = getFormConfig($provider_code);

// Fetch patient data if provided (for pre-filling)
$patient_data = null;
if ($patient_id > 0) {
    $patient_sql = "SELECT p.*, u.full_name, u.phone_primary, u.email, u.national_id
                    FROM patients p
                    INNER JOIN users u ON p.user_id = u.user_id
                    WHERE p.patient_id = ?";
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param('i', $patient_id);
    $stmt->execute();
    $patient_result = $stmt->get_result();
    $patient_data = $patient_result->fetch_assoc();
}

// Define constant to allow form includes
define('PREAUTH_FORM_INCLUDE', true);

// Start output buffering to capture form HTML
ob_start();

// Include the appropriate form template
$template_path = __DIR__ . '/../preauth_forms/' . $form_config['template'];

if (file_exists($template_path)) {
    include $template_path;
} else {
    // Fallback to default form
    include __DIR__ . '/../preauth_forms/form_default.php';
}

$form_html = ob_get_clean();

// Return JSON response
header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'html' => $form_html,
    'provider_code' => $provider_code,
    'provider_name' => $provider['provider_name'],
    'form_type' => hasCustomForm($provider_code) ? 'custom' : 'default',
    'form_description' => $form_config['description']
]);
