<?php
/**
 * Update Patient Insurance - Used from patient list and other contexts (same approach as Add to Queue)
 */
session_start();
require_once __DIR__ . '/../layouts/dbconn.php';

header('Content-Type: application/json');

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FRONT_OFFICE'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

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

if (!$patient_id || !$insurance_provider_id || $member_number === '') {
    echo json_encode(['success' => false, 'message' => 'Patient ID, insurance provider and member number are required']);
    exit();
}

try {
    $update_sql = "UPDATE patients
                   SET insurance_provider_id = ?,
                       insurance_number = ?,
                       registration_type = 'INSURANCE'
                   WHERE patient_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("isi", $insurance_provider_id, $member_number, $patient_id);
    
    if ($stmt->execute()) {
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Patient insurance updated successfully']);
    } else {
        $stmt->close();
        echo json_encode(['success' => false, 'message' => 'Failed to update patient insurance']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
