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

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

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

    // Extract and cleanly cast input variables
    $mandatory_triage = isset($_POST['mandatory_triage']) ? (int)$_POST['mandatory_triage'] : 0;
    $strict_discharge = isset($_POST['strict_discharge']) ? (int)$_POST['strict_discharge'] : 0;
    $auto_expire_labs = isset($_POST['auto_expire_labs']) ? (int)$_POST['auto_expire_labs'] : 0;
    $opd_consult_validity_days = isset($_POST['opd_consult_validity_days']) ? (int)$_POST['opd_consult_validity_days'] : 30;
    $strict_prepay = isset($_POST['strict_prepay']) ? (int)$_POST['strict_prepay'] : 0;
    $max_unsecured_debt = isset($_POST['max_unsecured_debt']) ? (float)$_POST['max_unsecured_debt'] : 0.00;
    $hmo_auto_approve = isset($_POST['hmo_auto_approve']) ? (int)$_POST['hmo_auto_approve'] : 0;
    $hmo_auto_approve_threshold = isset($_POST['hmo_auto_approve_threshold']) ? (float)$_POST['hmo_auto_approve_threshold'] : 0.00;
    $enforce_fefo = isset($_POST['enforce_fefo']) ? (int)$_POST['enforce_fefo'] : 0;
    $block_zero_stock = isset($_POST['block_zero_stock']) ? (int)$_POST['block_zero_stock'] : 0;
    
    $inventory_display_expiry_days = isset($_POST['inventory_display_expiry_days']) ? (int)$_POST['inventory_display_expiry_days'] : 90;
    $expiry_action_threshold_days = isset($_POST['expiry_action_threshold_days']) ? (int)$_POST['expiry_action_threshold_days'] : 30;
    $expiry_action = isset($_POST['expiry_action']) ? $conn->real_escape_string($_POST['expiry_action']) : 'Warn';
    
    $system_currency = isset($_POST['system_currency']) ? $conn->real_escape_string($_POST['system_currency']) : 'GHS';
    $date_format = isset($_POST['date_format']) ? $conn->real_escape_string($_POST['date_format']) : 'd-M-Y';
    $time_format = isset($_POST['time_format']) ? $conn->real_escape_string($_POST['time_format']) : '12';

    $conn->begin_transaction();

    try {
        // 1. Fetch Old Data & check for base existence
        $old_query = $conn->query("SELECT * FROM system_workflow_rules WHERE id = 1");
        $old_data = $old_query->fetch_assoc();
        
        $new_data = [
            'mandatory_triage' => $mandatory_triage,
            'strict_discharge' => $strict_discharge,
            'auto_expire_labs' => $auto_expire_labs,
            'opd_consult_validity_days' => $opd_consult_validity_days,
            'strict_prepay' => $strict_prepay,
            'max_unsecured_debt' => $max_unsecured_debt,
            'hmo_auto_approve' => $hmo_auto_approve,
            'hmo_auto_approve_threshold' => $hmo_auto_approve_threshold,
            'enforce_fefo' => $enforce_fefo,
            'block_zero_stock' => $block_zero_stock,
            'inventory_display_expiry_days' => $inventory_display_expiry_days,
            'expiry_action_threshold_days' => $expiry_action_threshold_days,
            'expiry_action' => $expiry_action,
            'system_currency' => $system_currency,
            'date_format' => $date_format,
            'time_format' => $time_format
        ];

        if (!$old_data) {
            $old_json = json_encode([]);
            
            // 2. Perform INSERT instead if row 1 is completely absent
            $insert_sql = "INSERT INTO system_workflow_rules (
                id, mandatory_triage, strict_discharge, auto_expire_labs, opd_consult_validity_days,
                strict_prepay, max_unsecured_debt, hmo_auto_approve, hmo_auto_approve_threshold,
                enforce_fefo, block_zero_stock, inventory_display_expiry_days, expiry_action_threshold_days,
                expiry_action, system_currency, date_format, time_format, updated_by
            ) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param(
                "iiiiididiiiissssi",
                $mandatory_triage, $strict_discharge, $auto_expire_labs, $opd_consult_validity_days,
                $strict_prepay, $max_unsecured_debt, $hmo_auto_approve, $hmo_auto_approve_threshold,
                $enforce_fefo, $block_zero_stock, $inventory_display_expiry_days, $expiry_action_threshold_days, 
                $expiry_action, $system_currency, $date_format, $time_format, $staff_id
            );
        } else {
            $old_json = json_encode($old_data);

            // Perform predictable standard UPDATE
            $update_sql = "UPDATE system_workflow_rules SET 
                mandatory_triage = ?, strict_discharge = ?, auto_expire_labs = ?, opd_consult_validity_days = ?,
                strict_prepay = ?, max_unsecured_debt = ?, hmo_auto_approve = ?, hmo_auto_approve_threshold = ?,
                enforce_fefo = ?, block_zero_stock = ?, inventory_display_expiry_days = ?, expiry_action_threshold_days = ?, 
                expiry_action = ?, system_currency = ?, date_format = ?, time_format = ?, updated_by = ? 
                WHERE id = 1";

            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param(
                "iiiiididiiiissssi",
                $mandatory_triage, $strict_discharge, $auto_expire_labs, $opd_consult_validity_days,
                $strict_prepay, $max_unsecured_debt, $hmo_auto_approve, $hmo_auto_approve_threshold,
                $enforce_fefo, $block_zero_stock, $inventory_display_expiry_days, $expiry_action_threshold_days, 
                $expiry_action, $system_currency, $date_format, $time_format, $staff_id
            );
        }

        if (!$stmt->execute()) {
            throw new Exception("Database Modification Failed: " . $stmt->error);
        }

        // 3. Write securely to the Audit Trail Table
        $new_json = json_encode($new_data);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

        $audit_sql = "INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, old_values, new_values, ip_address) 
                      VALUES (?, 'UPDATE', 'system_workflow_rules', '1', ?, ?, ?)";
        
        $audit_stmt = $conn->prepare($audit_sql);
        $audit_stmt->bind_param("isss", $staff_id, $old_json, $new_json, $ip_address);
        
        if (!$audit_stmt->execute()) {
            throw new Exception("Audit Log Failed: " . $audit_stmt->error);
        }

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

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