<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();

require_once '../../includes/db.php';
header('Content-Type: application/json');

$staff_id = (int)($_SESSION['staff_id'] ?? 1);
$action = $_POST['action'] ?? '';

try {
    // ==========================================
    // AUTO-HEALING: UPGRADE SYSTEM WORKFLOW RULES
    // ==========================================
    $chkCol = $conn->query("SHOW COLUMNS FROM system_workflow_rules LIKE 'block_new_ipd_on_discharge'");
    if ($chkCol && $chkCol->num_rows == 0) {
        $conn->query("ALTER TABLE `system_workflow_rules` 
            ADD COLUMN `block_new_ipd_on_discharge` TINYINT(1) DEFAULT 1,
            ADD COLUMN `block_edit_ipd_on_discharge` TINYINT(1) DEFAULT 1,
            ADD COLUMN `block_new_ipd_on_theatre_req` TINYINT(1) DEFAULT 1,
            ADD COLUMN `block_edit_ipd_on_theatre_req` TINYINT(1) DEFAULT 1,
            ADD COLUMN `block_new_ipd_on_theatre_revert` TINYINT(1) DEFAULT 0,
            ADD COLUMN `block_edit_theatre_post_surgery` TINYINT(1) DEFAULT 1,
            ADD COLUMN `block_new_theatre_post_surgery` TINYINT(1) DEFAULT 1
        ");
    }

    // Ensure at least one configuration row exists
    $chkRow = $conn->query("SELECT id FROM system_workflow_rules LIMIT 1");
    if ($chkRow && $chkRow->num_rows == 0) {
        $conn->query("INSERT INTO system_workflow_rules (id) VALUES (1)");
    }

    // ==========================================
    // FETCH ACCESS & WORKFLOW RULES
    // ==========================================
    if ($action === 'fetch_access_rules') {
        $q = $conn->query("SELECT 
            block_new_ipd_on_discharge, 
            block_edit_ipd_on_discharge, 
            block_new_ipd_on_theatre_req, 
            block_edit_ipd_on_theatre_req, 
            block_new_ipd_on_theatre_revert, 
            block_edit_theatre_post_surgery, 
            block_new_theatre_post_surgery 
            FROM system_workflow_rules LIMIT 1");
        
        $rules = $q->fetch_assoc();
        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $rules]); exit;
    }

    // ==========================================
    // SAVE / UPDATE ACCESS RULES
    // ==========================================
    if ($action === 'save_access_rules') {
        // Capture toggle states (If checkbox is checked, it posts '1', else we default to '0')
        $b_new_ipd_dis = isset($_POST['block_new_ipd_on_discharge']) ? 1 : 0;
        $b_edit_ipd_dis = isset($_POST['block_edit_ipd_on_discharge']) ? 1 : 0;
        
        $b_new_ipd_th = isset($_POST['block_new_ipd_on_theatre_req']) ? 1 : 0;
        $b_edit_ipd_th = isset($_POST['block_edit_ipd_on_theatre_req']) ? 1 : 0;
        
        $b_new_ipd_rev = isset($_POST['block_new_ipd_on_theatre_revert']) ? 1 : 0;
        
        $b_edit_th_post = isset($_POST['block_edit_theatre_post_surgery']) ? 1 : 0;
        $b_new_th_post = isset($_POST['block_new_theatre_post_surgery']) ? 1 : 0;

        $stmt = $conn->prepare("UPDATE system_workflow_rules SET 
            block_new_ipd_on_discharge = ?,
            block_edit_ipd_on_discharge = ?,
            block_new_ipd_on_theatre_req = ?,
            block_edit_ipd_on_theatre_req = ?,
            block_new_ipd_on_theatre_revert = ?,
            block_edit_theatre_post_surgery = ?,
            block_new_theatre_post_surgery = ?
        ");

        $stmt->bind_param("iiiiiii", 
            $b_new_ipd_dis, $b_edit_ipd_dis, 
            $b_new_ipd_th, $b_edit_ipd_th, 
            $b_new_ipd_rev, 
            $b_edit_th_post, $b_new_th_post
        );

        if ($stmt->execute()) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Clinical access rules applied globally.']);
        } else {
            throw new Exception("Database error while applying rules.");
        }
        exit;
    }

} catch (Exception $e) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>