<?php
require_once __DIR__ . '/../../../dripend/includes/db.php';

$query = $conn->query("SELECT * FROM system_workflow_rules WHERE id = 1");
$rules = $query->fetch_assoc();

if (!$rules) {
    $rules = [
        'mandatory_triage' => 1, 'strict_discharge' => 1, 'auto_expire_labs' => 0, 'opd_consult_validity_days' => 30,
        'strict_prepay' => 1, 'max_unsecured_debt' => 500.00, 'hmo_auto_approve' => 1, 'hmo_auto_approve_threshold' => 200.00,
        'enforce_fefo' => 1, 'block_zero_stock' => 1, 'inventory_display_expiry_days' => 90, 'expiry_action_threshold_days' => 30, 
        'expiry_action' => 'Warn', 'system_currency' => 'GHS', 'date_format' => 'd-M-Y', 'time_format' => '12'
    ];
}

// BULLETPROOF SYSTEM DIRECTION: Calculate web-accessible endpoint path completely dynamically
$docRoot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
$targetBackendFile = str_replace('\\', '/', realpath(__DIR__ . '/../../../dripend/systemSetup/facility/process_workflow_rules.php'));
$dynamicEndpointUrl = '/' . ltrim(str_replace($docRoot, '', $targetBackendFile), '/');
?>

<style>
.fac-module { width: 100%; animation: fadeIn 0.3s ease-in-out; font-family: "Segoe UI", system-ui, sans-serif;}
.fac-header-area { margin-bottom: 24px; border-bottom: 1px solid #e2e8f0; padding-bottom: 16px; }
.fac-page-title { font-size: 22px; font-weight: 800; color: #0f172a; display: flex; align-items: center; gap: 10px; margin-bottom: 6px; text-transform: uppercase;}
.fac-page-title i { color: #f59e0b; }
.fac-page-subtitle { font-size: 14px; color: #64748b; }

.fac-split-layout { display: flex; gap: 24px; flex-wrap: wrap; align-items: stretch; margin-bottom: 24px; }
.fac-panel { background: #fff; border-radius: 12px; padding: 24px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); }
.fac-panel-half { flex: 1; min-width: 400px; display: flex; flex-direction: column; }

.fac-panel-title { font-size: 15px; font-weight: 800; text-transform: uppercase; color: #1e293b; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid #e2e8f0; display:flex; align-items:center; gap:8px;}

.fac-form-row { display: flex; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
.fac-form-col { flex: 1; display: flex; flex-direction: column; gap: 6px; min-width: 150px; }
.fac-form-col label { font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }

.fac-input { padding: 12px 14px; border-radius: 8px; border: 1px solid #cbd5e1; font-size: 13px; outline: none; width: 100%; background: #f8fafc; color: #1e293b; transition: 0.2s; font-weight: 600; box-sizing: border-box;}
.fac-input:focus { border-color: #f59e0b; background: #fff; box-shadow: 0 0 0 3px #fef3c7; }

.fac-input-group { display: flex; align-items: center; border: 1px solid #cbd5e1; border-radius: 8px; background: #f8fafc; overflow: hidden; transition: 0.2s; box-sizing: border-box;}
.fac-input-group:focus-within { border-color: #f59e0b; box-shadow: 0 0 0 3px #fef3c7; background: #fff;}
.fac-input-addon { padding: 12px 14px; background: #f1f5f9; color: #475569; font-weight: 800; font-size: 13px; border-right: 1px solid #cbd5e1; }
.fac-input-group input { flex: 1; border: none; padding: 12px 14px; background: transparent; outline: none; font-size: 14px; font-weight: 700; color: #1e293b; width: 100%; box-sizing: border-box;}

.fac-rule-row { display: flex; align-items: flex-start; justify-content: space-between; background: #ffffff; border: 1px solid #e2e8f0; padding: 16px; border-radius: 8px; margin-bottom: 12px; transition: 0.2s;}
.fac-rule-row:hover { border-color: #cbd5e1; background: #f8fafc; }
.fac-rule-text { flex: 1; padding-right: 20px;}
.fac-rule-title { font-size: 13px; font-weight: 800; color: #1e293b; display: block; margin-bottom: 4px;}
.fac-rule-desc { font-size: 11px; font-weight: 500; color: #64748b; line-height: 1.4;}

.switch { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; margin-top: 2px;}
.switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e1; transition: .4s; border-radius: 34px; }
.slider:before { position: absolute; content: ""; height: 16px; width: 16px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
input:checked + .slider.blue { background-color: #3b82f6; }
input:checked + .slider.green { background-color: #10b981; }
input:checked + .slider.purple { background-color: #8b5cf6; }
input:checked + .slider:before { transform: translateX(20px); }

.fac-dependent-setting { background: #f8fafc; border: 1px dashed #cbd5e1; padding: 16px; border-radius: 8px; margin-top: -8px; margin-bottom: 12px; border-top: none; border-top-left-radius: 0; border-top-right-radius: 0; display: none; }
.fac-dependent-setting.active { display: block; animation: slideDown 0.3s ease-out; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }

.fac-btn-primary { background: #f59e0b; color: #fff; border: none; padding: 14px 28px; border-radius: 8px; font-weight: 800; font-size: 14px; text-transform: uppercase; cursor: pointer; transition: 0.2s; display: inline-flex; justify-content: center; align-items: center; gap: 8px; }
.fac-btn-primary:hover { background: #d97706; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2); }
.fac-btn-primary:disabled { background: #94a3b8; cursor: not-allowed; transform: none; box-shadow: none; }

.fac-notice { background: #fffbeb; border: 1px solid #fde68a; padding: 16px; border-radius: 8px; margin-bottom: 20px; font-size: 13px; color: #b45309; line-height: 1.5; display: flex; gap: 12px; align-items: flex-start;}
.fac-notice i { font-size: 18px; color: #d97706; margin-top: 2px;}
.fac-notice strong { color: #92400e; display: block; font-size: 13px; margin-bottom: 4px; font-weight: 800;}

#uiNotificationBanner { display: none; padding: 16px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 700; font-size: 14px; display: flex; align-items: center; gap: 10px; animation: slideDown 0.3s ease-out; }
</style>

<div class="fac-module">
    <div id="uiNotificationBanner"></div>

    <div class="fac-header-area">
        <div class="fac-page-title"><i class="fa-solid fa-code-branch"></i> Workflow & Financial Rules</div>
        <div class="fac-page-subtitle">Configure operational constraints, billing triggers, and mandatory clinical pathways for the hospital.</div>
    </div>

    <form id="workflowRulesForm">
        <div class="fac-split-layout">
            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #3b82f6;"><i class="fa-solid fa-user-doctor"></i> Clinical & Patient Flow Rules</div>
                
                <div class="fac-notice" style="background:#eff6ff; border-color:#bfdbfe; color:#1e3a8a;">
                    <i class="fa-solid fa-sitemap" style="color:#3b82f6;"></i>
                    <div>
                        <strong>Tertiary Hospital Pathway Enforced</strong>
                        Activating these constraints prevents users from skipping operational steps (e.g. Doctors are locked out if Vitals are missing).
                    </div>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Mandatory Triage / Vitals Sign-off</span>
                        <span class="fac-rule-desc">Doctors cannot open a patient's consultation file until a nurse has recorded and saved the baseline vitals.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="mandatory_triage" <?php echo $rules['mandatory_triage'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider blue"></span>
                    </label>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Strict Discharge Clearance</span>
                        <span class="fac-rule-desc">Inpatients require both Medical clearance (Doctor) AND Financial clearance (Billing) before the bed is released.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="strict_discharge" <?php echo $rules['strict_discharge'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider blue"></span>
                    </label>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Auto-Expire Unused Lab Orders</span>
                        <span class="fac-rule-desc">Automatically cancel laboratory requests if the patient does not visit the lab within 48 hours.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="auto_expire_labs" <?php echo $rules['auto_expire_labs'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider blue"></span>
                    </label>
                </div>

                <div class="fac-form-row" style="margin-top: 15px;">
                    <div class="fac-form-col">
                        <label>Default Outpatient Consultation Validity</label>
                        <select class="fac-input" name="opd_consult_validity_days">
                            <option value="1" <?php echo $rules['opd_consult_validity_days'] == 1 ? 'selected' : ''; ?>>Valid for 24 Hours (1 Day)</option>
                            <option value="7" <?php echo $rules['opd_consult_validity_days'] == 7 ? 'selected' : ''; ?>>Valid for 7 Days (1 Week)</option>
                            <option value="30" <?php echo $rules['opd_consult_validity_days'] == 30 ? 'selected' : ''; ?>>Valid for 30 Days (1 Month)</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #10b981;"><i class="fa-solid fa-file-invoice-dollar"></i> Financial & Billing Constraints</div>
                
                <div class="fac-notice" style="background:#f0fdf4; border-color:#bbf7d0; color:#166534;">
                    <i class="fa-solid fa-vault" style="color:#10b981;"></i>
                    <div>
                        <strong>Revenue Leakage Prevention</strong>
                        Strict Pre-pay blocks service delivery until a cashier has processed the receipt in the system.
                    </div>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Strict Pre-Pay for Services (Cash Patients)</span>
                        <span class="fac-rule-desc">Blocks lab technicians and pharmacists from fulfilling orders until the item is fully paid for.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="strictPrePayToggle" name="strict_prepay" <?php echo $rules['strict_prepay'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider green"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="creditLimitBlock">
                    <div class="fac-form-row" style="margin-bottom:0;">
                        <div class="fac-form-col">
                            <label>Max Unsecured Debt Threshold (ER Override)</label>
                            <div class="fac-input-group">
                                <span class="fac-input-addon"><?php echo htmlspecialchars($rules['system_currency']); ?></span>
                                <input type="number" step="0.01" name="max_unsecured_debt" value="<?php echo number_format($rules['max_unsecured_debt'], 2, '.', ''); ?>">
                            </div>
                            <span style="font-size:10px; font-weight:600; color:#64748b; margin-top:4px;">Allows Emergency ER patients to incur debt up to this threshold before system hard-blocks them.</span>
                        </div>
                    </div>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Corporate/HMO Auto-Approval</span>
                        <span class="fac-rule-desc">Automatically approve prescriptions and labs for insured patients without sending them to the manual vetting queue.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="hmoAutoApproveToggle" name="hmo_auto_approve" <?php echo $rules['hmo_auto_approve'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider green"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="hmoThresholdBlock">
                    <div class="fac-form-row" style="margin-bottom:0;">
                        <div class="fac-form-col">
                            <label>Auto-Approval Upper Limit</label>
                            <div class="fac-input-group">
                                <span class="fac-input-addon"><?php echo htmlspecialchars($rules['system_currency']); ?></span>
                                <input type="number" step="0.01" name="hmo_auto_approve_threshold" value="<?php echo number_format($rules['hmo_auto_approve_threshold'], 2, '.', ''); ?>">
                            </div>
                            <span style="font-size:10px; font-weight:600; color:#64748b; margin-top:4px;">Invoices over this amount will always require manual vetting by a claims officer.</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="fac-split-layout">
            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #8b5cf6;"><i class="fa-solid fa-pills"></i> Pharmacy & Inventory Rules</div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Enforce FEFO Dispensing (Expiry)</span>
                        <span class="fac-rule-desc">Forces pharmacists to dispense the First-Expire-First-Out batch automatically.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="enforce_fefo" <?php echo $rules['enforce_fefo'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider purple"></span>
                    </label>
                </div>

                <div class="fac-rule-row">
                    <div class="fac-rule-text">
                        <span class="fac-rule-title">Block Dispensing on Zero Stock</span>
                        <span class="fac-rule-desc">Prevents negative inventory. The pharmacist cannot dispense if the system stock is 0.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" name="block_zero_stock" <?php echo $rules['block_zero_stock'] == 1 ? 'checked' : ''; ?>>
                        <span class="slider purple"></span>
                    </label>
                </div>

                <div class="fac-form-row" style="margin-top: 20px;">
                    <div class="fac-form-col">
                        <label>Show Expiring Products within (Days)</label>
                        <div class="fac-input-group">
                            <input type="number" min="1" name="inventory_display_expiry_days" value="<?php echo (int)$rules['inventory_display_expiry_days']; ?>" required>
                            <span class="fac-input-addon" style="border-right:none; border-left:1px solid #cbd5e1;">Days</span>
                        </div>
                        <span style="font-size:10px; font-weight:600; color:#64748b; margin-top:4px;">Products expiring in this timeframe will show up on the dashboard radar.</span>
                    </div>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col" style="flex:1;">
                        <label>Action When Product Reaches...</label>
                        <div class="fac-input-group">
                            <input type="number" min="0" name="expiry_action_threshold_days" value="<?php echo (int)$rules['expiry_action_threshold_days']; ?>" required>
                            <span class="fac-input-addon" style="border-right:none; border-left:1px solid #cbd5e1;">Days</span>
                        </div>
                    </div>
                    <div class="fac-form-col" style="flex:1.5;">
                        <label>Execute Action</label>
                        <select class="fac-input" name="expiry_action" style="border-color:#8b5cf6;">
                            <option value="Warn" <?php echo $rules['expiry_action'] === 'Warn' ? 'selected' : ''; ?>>Keep Selling (Warning Only)</option>
                            <option value="Block" <?php echo $rules['expiry_action'] === 'Block' ? 'selected' : ''; ?>>Stop Selling (Hard Block at POS)</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-half" style="border-style: dashed; background: #f8fafc;">
                <div class="fac-panel-title"><i class="fa-solid fa-globe"></i> Global Data Formats</div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>System Currency Symbol</label>
                        <input type="text" class="fac-input" name="system_currency" value="<?php echo htmlspecialchars($rules['system_currency']); ?>" style="max-width: 150px; font-weight:800;">
                    </div>
                    <div class="fac-form-col">
                        <label>Date Format Display</label>
                        <select class="fac-input" name="date_format">
                            <option value="d-M-Y" <?php echo $rules['date_format'] === 'd-M-Y' ? 'selected' : ''; ?>>DD-MMM-YYYY (e.g. 15-Jun-2026)</option>
                            <option value="d/m/Y" <?php echo $rules['date_format'] === 'd/m/Y' ? 'selected' : ''; ?>>DD/MM/YYYY (e.g. 15/06/2026)</option>
                            <option value="Y-m-d" <?php echo $rules['date_format'] === 'Y-m-d' ? 'selected' : ''; ?>>YYYY-MM-DD (Database Standard)</option>
                        </select>
                    </div>
                </div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <label>Time Format Display</label>
                        <select class="fac-input" name="time_format">
                            <option value="12" <?php echo $rules['time_format'] === '12' ? 'selected' : ''; ?>>12-Hour (02:30 PM)</option>
                            <option value="24" <?php echo $rules['time_format'] === '24' ? 'selected' : ''; ?>>24-Hour (14:30)</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div style="background:#fff; border:1px solid #e2e8f0; border-radius:12px; padding: 20px; text-align: right; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);">
            <button type="button" class="fac-btn-primary" onclick="if(typeof window.saveWorkflowRules === 'function') window.saveWorkflowRules(this);"><i class="fa-solid fa-shield-halved"></i> Apply & Audit Operational Rules</button>
        </div>
    </form>
</div>

<textarea id="workflow-js-core" style="display:none;">
    function setupDependentToggle(toggleId, blockId) {
        const toggle = document.getElementById(toggleId);
        const block = document.getElementById(blockId);
        if(toggle && block) {
            block.classList.toggle('active', toggle.checked);
            toggle.addEventListener('change', function() {
                block.classList.toggle('active', this.checked);
            });
        }
    }

    setupDependentToggle('strictPrePayToggle', 'creditLimitBlock');
    setupDependentToggle('hmoAutoApproveToggle', 'hmoThresholdBlock');

    function showNotification(type, message) {
        const banner = document.getElementById('uiNotificationBanner');
        if(!banner) return;
        banner.style.display = 'flex';
        if (type === 'success') {
            banner.style.backgroundColor = '#f0fdf4';
            banner.style.color = '#166534';
            banner.style.border = '1px solid #bbf7d0';
            banner.innerHTML = '<i class="fa-solid fa-circle-check"></i> ' + message;
        } else {
            banner.style.backgroundColor = '#fef2f2';
            banner.style.color = '#991b1b';
            banner.style.border = '1px solid #fecaca';
            banner.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> ' + message;
        }
        window.scrollTo({ top: 0, behavior: 'smooth' });
        setTimeout(() => { banner.style.display = 'none'; }, 5000);
    }

    window.saveWorkflowRules = function(btnElement) {
        const form = document.getElementById('workflowRulesForm');
        if(!form) return;
        const formData = new FormData(form);

        const checkboxes = ['mandatory_triage', 'strict_discharge', 'auto_expire_labs', 'strict_prepay', 'hmo_auto_approve', 'enforce_fefo', 'block_zero_stock'];
        checkboxes.forEach(name => {
            if(form.elements[name]) {
                formData.set(name, form.elements[name].checked ? '1' : '0');
            }
        });

        const originalHTML = btnElement.innerHTML;
        btnElement.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving Rules...';
        btnElement.disabled = true;

        // Injected Dynamic Endpoint Context URL
        const endpointContext = '<?php echo $dynamicEndpointUrl; ?>';

        fetch(endpointContext, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if(data.status === 'success') {
                showNotification('success', 'Operational Rules & Policies have been updated successfully.');
                btnElement.innerHTML = '<i class="fa-solid fa-check-double"></i> Rules Applied & Audited';
                btnElement.style.backgroundColor = '#16a34a';
                setTimeout(() => {
                    btnElement.innerHTML = originalHTML;
                    btnElement.disabled = false;
                    btnElement.style.backgroundColor = ''; 
                }, 3000);
            } else {
                showNotification('error', data.message || 'Failed to save rules to the database.');
                btnElement.innerHTML = originalHTML;
                btnElement.disabled = false;
            }
        })
        .catch(err => {
            console.error('Fetch error:', err);
            showNotification('error', 'Network Error. Could not connect to the backend server.');
            btnElement.innerHTML = originalHTML;
            btnElement.disabled = false;
        });
    };
</textarea>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    var rawCode = document.getElementById('workflow-js-core').value;
    var cleanCode = rawCode.replace(/\u00a0/g, ' '); 
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.text = cleanCode;
    document.head.appendChild(s);
    this.remove();
" style="position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none;">