<?php
session_start();
ini_set('display_errors', 0);
header('Content-Type: application/json');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $staff_id = isset($_SESSION['staff_id']) ? (int)$_SESSION['staff_id'] : 1; 

    try {
        // 1. Sanitize Inputs
        $insurance_name = isset($_POST['insurance_name']) ? trim($conn->real_escape_string($_POST['insurance_name'])) : '';
        $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 0;

        // Validation
        if (empty($insurance_name)) {
            throw new Exception("The Insurance Provider Name is required.");
        }

        $conn->begin_transaction();

        // 2. Check for Duplicates
        $check_sql = "SELECT id FROM insurance_type WHERE LOWER(insurance_name) = LOWER(?)";
        $stmt_check = $conn->prepare($check_sql);
        $stmt_check->bind_param("s", $insurance_name);
        $stmt_check->execute();
        if ($stmt_check->get_result()->num_rows > 0) {
            throw new Exception("An Insurance Provider named '{$insurance_name}' already exists in the system.");
        }

        // 3. Insert New Provider
        $insert_sql = "INSERT INTO insurance_type (insurance_name, is_active) VALUES (?, ?)";
        $stmt_ins = $conn->prepare($insert_sql);
        $stmt_ins->bind_param("si", $insurance_name, $is_active);
        
        if (!$stmt_ins->execute()) {
            throw new Exception("Failed to save provider: " . $stmt_ins->error);
        }
        
        $new_provider_id = $stmt_ins->insert_id;

        // 4. Audit Trail
        $new_data = json_encode([
            'insurance_name' => $insurance_name,
            'is_active' => $is_active
        ]);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';

        $audit_sql = "INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, new_values, ip_address) 
                      VALUES (?, 'INSERT', 'insurance_type', ?, ?, ?)";
        
        $audit_stmt = $conn->prepare($audit_sql);
        $audit_stmt->bind_param("iiss", $staff_id, $new_provider_id, $new_data, $ip_address);
        $audit_stmt->execute(); 

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => "{$insurance_name} has been successfully added to the system."]);

    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request Method']);
}
?>