<?php
session_start();
// Turn off HTML errors so we don't break the JSON response!
ini_set('display_errors', 0);
header('Content-Type: application/json');

// From dripend/systemSetup/facility/ to dripend/includes/
require_once __DIR__ . '/../../includes/db.php';

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

    try {
        $conn->begin_transaction();

        // Fetch old data for audit
        $old_query = $conn->query("SELECT * FROM system_integrations");
        $old_data = [];
        if ($old_query) {
            while($row = $old_query->fetch_assoc()) {
                $old_data[$row['module_type']][$row['provider_name']] = $row;
            }
        }

        $new_data_audit = [];

        // Reusable function to Upsert Integration rows WITH STRICT ERROR CATCHING
        function updateIntegrationProvider($conn, $module, $provider, $is_enabled, $config_array) {
            $enabled_int = (int)$is_enabled;
            $config_json = json_encode($config_array);

            // 1. Disable ALL providers in this module group
            if (!$conn->query("UPDATE system_integrations SET is_enabled = 0 WHERE module_type = '$module'")) {
                throw new Exception("Reset $module Failed: " . $conn->error);
            }

            // 2. Check if this specific provider already exists
            $stmt_check = $conn->prepare("SELECT id FROM system_integrations WHERE module_type = ? AND provider_name = ?");
            if (!$stmt_check) throw new Exception("Prepare Select Failed ($module): " . $conn->error);
            
            $stmt_check->bind_param("ss", $module, $provider);
            if (!$stmt_check->execute()) throw new Exception("Execute Select Failed ($module): " . $stmt_check->error);
            
            $res = $stmt_check->get_result();

            if ($res && $res->num_rows > 0) {
                // Exists: Update
                $stmt_upd = $conn->prepare("UPDATE system_integrations SET is_enabled = ?, config_data = ? WHERE module_type = ? AND provider_name = ?");
                if (!$stmt_upd) throw new Exception("Prepare Update Failed ($module): " . $conn->error);
                
                $stmt_upd->bind_param("isss", $enabled_int, $config_json, $module, $provider);
                if (!$stmt_upd->execute()) throw new Exception("Execute Update Failed ($module): " . $stmt_upd->error);
            } else {
                // New Provider: Insert
                $stmt_ins = $conn->prepare("INSERT INTO system_integrations (module_type, provider_name, is_enabled, config_data) VALUES (?, ?, ?, ?)");
                if (!$stmt_ins) throw new Exception("Prepare Insert Failed ($module): " . $conn->error);
                
                $stmt_ins->bind_param("ssis", $module, $provider, $enabled_int, $config_json);
                if (!$stmt_ins->execute()) throw new Exception("Execute Insert Failed ($module): " . $stmt_ins->error);
            }
        }

        // 1. Process SMS
        $sms_config = [
            'sender_id' => $_POST['sms_sender_id'] ?? '',
            'destination_url' => $_POST['sms_url'] ?? '',
            'api_key' => $_POST['sms_api_key'] ?? ''
        ];
        updateIntegrationProvider($conn, 'sms', $_POST['sms_provider'] ?? 'Unknown', $_POST['sms_enabled'] ?? '0', $sms_config);
        $new_data_audit['sms'] = $sms_config;

        // 2. Process Email
        $email_config = [
            'smtp_host' => $_POST['email_smtp_host'] ?? '',
            'smtp_port' => $_POST['email_smtp_port'] ?? '',
            'smtp_user' => $_POST['email_smtp_user'] ?? '',
            'smtp_pass' => $_POST['email_smtp_pass'] ?? '',
            'from_name' => $_POST['email_from_name'] ?? ''
        ];
        updateIntegrationProvider($conn, 'email', 'SMTP', $_POST['email_enabled'] ?? '0', $email_config);
        $new_data_audit['email'] = $email_config;

        // 3. Process Payments
        $pay_config = [
            'environment' => $_POST['payment_env'] ?? 'test',
            'destination_url' => $_POST['payment_url'] ?? '',
            'public_key' => $_POST['payment_public_key'] ?? '',
            'secret_key' => $_POST['payment_secret_key'] ?? ''
        ];
        updateIntegrationProvider($conn, 'payment', $_POST['payment_provider'] ?? 'Unknown', $_POST['payment_enabled'] ?? '0', $pay_config);
        $new_data_audit['payment'] = $pay_config;

        // 4. Process HL7
        $hl7_config = [
            'ip_address' => $_POST['hl7_ip'] ?? '',
            'port' => $_POST['hl7_port'] ?? ''
        ];
        updateIntegrationProvider($conn, 'hl7', $_POST['hl7_provider'] ?? 'Unknown', $_POST['hl7_enabled'] ?? '0', $hl7_config);
        $new_data_audit['hl7'] = $hl7_config;

        // 5. Process PACS
        $pacs_config = [
            'ip_address' => $_POST['pacs_ip'] ?? '',
            'port' => $_POST['pacs_port'] ?? ''
        ];
        updateIntegrationProvider($conn, 'pacs', $_POST['pacs_provider'] ?? 'CENTRAL_PACS', $_POST['pacs_enabled'] ?? '0', $pacs_config);
        $new_data_audit['pacs'] = $pacs_config;

        // 6. Process Biometrics
        $bio_config = ['print_mode' => 'Standard'];
        updateIntegrationProvider($conn, 'biometrics', $_POST['biometrics_provider'] ?? 'Unknown', $_POST['biometrics_enabled'] ?? '0', $bio_config);
        $new_data_audit['biometrics'] = $bio_config;

        // Write to Audit Trail
        $old_json = json_encode($old_data);
        $new_json = json_encode($new_data_audit);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';

        $audit_sql = "INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, old_values, new_values, ip_address) 
                      VALUES (?, 'UPDATE_INTEGRATIONS', 'system_integrations', 'ALL', ?, ?, ?)";
        
        $audit_stmt = $conn->prepare($audit_sql);
        if (!$audit_stmt) throw new Exception("Audit Prepare Failed: " . $conn->error);
        
        $audit_stmt->bind_param("isss", $staff_id, $old_json, $new_json, $ip_address);
        if (!$audit_stmt->execute()) throw new Exception("Audit Execute Failed: " . $audit_stmt->error);

        $conn->commit();
        echo json_encode(['status' => 'success']);

    // Notice we use Throwable to catch everything, including PHP Fatal Errors!
    } catch (Throwable $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid Request Method']);
}
?>