<?php
session_start();

// Connect to the database using reliable absolute directory context
require_once __DIR__ . '/../../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // 1. Clean and Sanitize Standard Text & Select Inputs
    $facility_code = mysqli_real_escape_string($conn, $_POST['facility_code'] ?? '');
    $scheme_code = mysqli_real_escape_string($conn, $_POST['scheme_code'] ?? '');
    $provider_category = mysqli_real_escape_string($conn, $_POST['provider_category'] ?? '');
    $prescribing_level = mysqli_real_escape_string($conn, $_POST['prescribing_level'] ?? '');

    // Billing & Export Data
    $tariff_version = mysqli_real_escape_string($conn, $_POST['tariff_version'] ?? '');
    $default_attendance = mysqli_real_escape_string($conn, $_POST['default_attendance'] ?? '');
    $xml_export_path = mysqli_real_escape_string($conn, $_POST['xml_export_path'] ?? '');

    // Referral Data
    $default_referring_facility = mysqli_real_escape_string($conn, $_POST['default_referring_facility'] ?? '');

    // 2. Handle Checkbox Toggles (If checked = 1, else = 0)
    $enable_api_sync = isset($_POST['enable_api_sync']) ? 1 : 0;
    $auto_bundle_claims = isset($_POST['auto_bundle_claims']) ? 1 : 0;
    $accept_referrals = isset($_POST['accept_referrals']) ? 1 : 0;

    // 3. Update the Database Record safely
    $update_sql = "UPDATE nhis_setup SET
        facility_code = '$facility_code',
        scheme_code = '$scheme_code',
        provider_category = '$provider_category',
        prescribing_level = '$prescribing_level',
        enable_api_sync = $enable_api_sync,
        tariff_version = '$tariff_version',
        default_attendance = '$default_attendance',
        auto_bundle_claims = $auto_bundle_claims,
        xml_export_path = '$xml_export_path',
        accept_referrals = $accept_referrals,
        default_referring_facility = '$default_referring_facility'
        WHERE id = 1";

    if (mysqli_query($conn, $update_sql)) {
        // Build environment-safe redirect back to the system dashboard container
        $redirect_url = "../../../views/system_setup/systemSetup.php?cat=facility&page=facility/nhis_config.php&status=success";
        header("Location: " . $redirect_url);
        exit();
    } else {
        echo "Error updating general NHIS configuration: " . mysqli_error($conn);
    }
} else {
    echo "Direct access denied. Please submit the form via POST.";
}
?>