<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../../dripend/includes/db.php';
try {
    if (!isset($conn)) throw new Exception("Database connection variable '\$conn' not found in db.php.");
    $db = $conn;

    // The Universal Upsert Query
    $sql = "INSERT INTO system_integrations (module_type, provider_name, is_enabled, config_data) 
            VALUES (?, ?, ?, ?) 
            ON DUPLICATE KEY UPDATE provider_name=VALUES(provider_name), is_enabled=VALUES(is_enabled), config_data=VALUES(config_data)";
    $stmt = $db->prepare($sql);

    // --- 1. PROCESS SMS ---
    $mod = 'sms';
    $sms_enabled = isset($_POST['sms_toggle']) ? 1 : 0;
    $sms_provider = $_POST['sms_provider'] ?? 'Arkesel';
    $sms_config = [];
    if ($sms_provider === 'Arkesel') {
        $sms_config = ['api_key' => $_POST['arkesel_api_key'] ?? '', 'sender_id' => $_POST['arkesel_sender_id'] ?? ''];
    } elseif ($sms_provider === 'Hubtel') {
        $sms_config = ['client_id' => $_POST['hubtel_client_id'] ?? '', 'client_secret' => $_POST['hubtel_client_secret'] ?? '', 'sender_id' => $_POST['hubtel_sender_id'] ?? ''];
    } elseif ($sms_provider === 'SMSOnlineGH') {
        $sms_config = ['username' => $_POST['smsonline_username'] ?? '', 'api_key' => $_POST['smsonline_api_key'] ?? '', 'sender_id' => $_POST['smsonline_sender_id'] ?? ''];
    }
    $sms_json = json_encode($sms_config);
    $stmt->bind_param("ssis", $mod, $sms_provider, $sms_enabled, $sms_json);
    $stmt->execute();

    // --- 2. PROCESS PAYMENT ---
    $mod = 'payment';
    $pay_enabled = isset($_POST['payment_toggle']) ? 1 : 0;
    $pay_provider = $_POST['payment_provider'] ?? 'Paystack';
    $pay_config = [
        'public_key' => $_POST['paystack_public'] ?? '',
        'secret_key' => $_POST['paystack_secret'] ?? '',
        'environment' => $_POST['paystack_env'] ?? 'test'
    ];
    $pay_json = json_encode($pay_config);
    $stmt->bind_param("ssis", $mod, $pay_provider, $pay_enabled, $pay_json);
    $stmt->execute();

    // --- 3. PROCESS EMAIL ---
    $mod = 'email';
    $email_enabled = isset($_POST['email_toggle']) ? 1 : 0;
    $email_provider = $_POST['email_provider'] ?? 'SMTP';
    $email_config = [
        'from_email' => $_POST['from_email'] ?? '',
        'from_name' => $_POST['from_name'] ?? ''
    ];
    if ($email_provider === 'SMTP') {
        $email_config['smtp_host'] = $_POST['smtp_host'] ?? '';
        $email_config['smtp_port'] = $_POST['smtp_port'] ?? '';
        $email_config['smtp_user'] = $_POST['smtp_user'] ?? '';
        $email_config['smtp_pass'] = $_POST['smtp_pass'] ?? '';
    } elseif ($email_provider === 'SendGrid') {
        $email_config['sendgrid_api'] = $_POST['sendgrid_api'] ?? '';
    }
    $email_json = json_encode($email_config);
    $stmt->bind_param("ssis", $mod, $email_provider, $email_enabled, $email_json);
    $stmt->execute();

    // --- 4. PROCESS HL7 (LIS) ---
    $mod = 'hl7';
    $hl7_enabled = isset($_POST['hl7_toggle']) ? 1 : 0;
    $hl7_mode = $_POST['hl7_mode'] ?? 'Direct TCP Socket';
    $hl7_config = ['ip_address' => $_POST['hl7_ip'] ?? '', 'port' => $_POST['hl7_port'] ?? ''];
    $hl7_json = json_encode($hl7_config);
    $stmt->bind_param("ssis", $mod, $hl7_mode, $hl7_enabled, $hl7_json);
    $stmt->execute();

    // --- 5. PROCESS PACS ---
    $mod = 'pacs';
    $pacs_enabled = isset($_POST['pacs_toggle']) ? 1 : 0;
    $pacs_title = $_POST['pacs_title'] ?? 'CENTRAL_PACS';
    $pacs_config = ['ip_address' => $_POST['pacs_ip'] ?? '', 'port' => $_POST['pacs_port'] ?? ''];
    $pacs_json = json_encode($pacs_config);
    $stmt->bind_param("ssis", $mod, $pacs_title, $pacs_enabled, $pacs_json);
    $stmt->execute();

    // --- 6. PROCESS LOCAL HARDWARE (Biometrics & Printers) ---
    $mod = 'biometrics';
    $bio_enabled = isset($_POST['bio_toggle']) ? 1 : 0;
    $bio_driver = $_POST['bio_driver'] ?? 'DigitalPersona (WebAPI)';
    // Capturing the Print Routing Mode so it remembers next time
    $bio_config = ['print_mode' => $_POST['print_mode'] ?? 'Standard Browser Print (PDF)']; 
    $bio_json = json_encode($bio_config);
    $stmt->bind_param("ssis", $mod, $bio_driver, $bio_enabled, $bio_json);
    $stmt->execute();

    echo json_encode(['status' => 'success', 'message' => 'Integrations and Hardware settings securely updated!']);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'System Error: ' . $e->getMessage()]);
}
?>