<?php
// Connect to the database safely
require_once __DIR__ . '/../../../dripend/includes/db.php';

// Fetch ALL integrations and group them by Module -> Provider
$db_data = [];
$active_providers = []; 

$res = $conn->query("SELECT * FROM system_integrations");
if ($res) {
    while($row = $res->fetch_assoc()) {
        $mod = $row['module_type'];
        $prov = $row['provider_name'];
        $db_data[$mod][$prov] = json_decode($row['config_data'], true) ?: [];
        if ($row['is_enabled'] == 1) {
            $active_providers[$mod] = $prov;
        }
    }
}

function getActiveProv($active_arr, $module, $default) {
    return isset($active_arr[$module]) ? $active_arr[$module] : $default;
}
function getVal($arr, $module, $key, $default = '') {
    return isset($arr[$module]['config'][$key]) ? htmlspecialchars($arr[$module]['config'][$key]) : $default;
}
function getProv($arr, $module, $default = '') {
    return isset($arr[$module]['provider_name']) ? htmlspecialchars($arr[$module]['provider_name']) : $default;
}
function getStatus($arr, $module) {
    return isset($arr[$module]) ? 'checked' : '';
}
?>

<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: #0ea5e9; }
.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: #0ea5e9; background: #fff; box-shadow: 0 0 0 3px #e0f2fe; }
.fac-toggle-container { display: flex; align-items: center; justify-content: space-between; background: #ffffff; border: 1px solid #e2e8f0; padding: 16px; border-radius: 8px; margin-bottom: 12px; transition: 0.2s;}
.fac-toggle-container:hover { border-color: #cbd5e1; background: #f8fafc; }
.fac-toggle-text { font-size: 13px; font-weight: 800; color: #1e293b; display: block; margin-bottom: 4px;}
.fac-toggle-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;}
.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 { background-color: #0ea5e9; }
input:checked + .slider.cyan { background-color: #06b6d4; }
input:checked + .slider.indigo { background-color: #6366f1; }
input:checked + .slider.emerald { background-color: #10b981; }
input:checked + .slider.rose { background-color: #f43f5e; }
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: 16px; border-top: none; border-top-left-radius: 0; border-top-right-radius: 0; display: none; }
.fac-btn-primary { background: #0ea5e9; 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: #0284c7; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(14, 165, 233, 0.2); }
.fac-btn-primary:disabled { background: #94a3b8; cursor: not-allowed; }
#uiNotificationBanner { display: none; padding: 16px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 700; font-size: 14px; align-items: center; gap: 10px; }
</style>

<script id="db-integration-data" type="application/json">
<?php echo json_encode($db_data); ?>
</script>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    (function() {
        // 1. Manually bind toggles
        const binds = [
            {t:'smsToggle', b:'smsBlock'},
            {t:'emailToggle', b:'emailBlock'},
            {t:'paymentToggle', b:'paymentBlock'},
            {t:'hl7Toggle', b:'hl7Block'},
            {t:'pacsToggle', b:'pacsBlock'}
        ];
        binds.forEach(item => {
            const t = document.getElementById(item.t);
            const b = document.getElementById(item.b);
            if(t && b) {
                b.style.display = t.checked ? 'block' : 'none';
                t.onchange = function() { b.style.display = this.checked ? 'block' : 'none'; };
            }
        });

        // 2. Parse DB configs safely
        let rawData = document.getElementById('db-integration-data');
        window.dbIntConfig = rawData ? JSON.parse(rawData.textContent || '{}') : {};

        window.getConfigVal = function(mod, prov, key, def) {
            if (window.dbIntConfig[mod] && window.dbIntConfig[mod][prov] && window.dbIntConfig[mod][prov][key]) {
                return window.dbIntConfig[mod][prov][key];
            }
            return def || '';
        };

        // 3. Bind Hot-Swapping Dropsdowns
        const sSel = document.getElementById('smsProviderSelect');
        if(sSel) {
            sSel.onchange = function() {
                document.getElementById('smsSenderId').value = window.getConfigVal('sms', this.value, 'sender_id');
                document.getElementById('smsUrl').value = window.getConfigVal('sms', this.value, 'destination_url');
                document.getElementById('smsApiKey').value = window.getConfigVal('sms', this.value, 'api_key');
            };
            sSel.onchange(); // trigger load
        }

        const pSel = document.getElementById('paymentProviderSelect');
        if(pSel) {
            pSel.onchange = function() {
                document.getElementById('paymentEnv').value = window.getConfigVal('payment', this.value, 'environment', 'test');
                document.getElementById('paymentUrl').value = window.getConfigVal('payment', this.value, 'destination_url');
                document.getElementById('paymentPubKey').value = window.getConfigVal('payment', this.value, 'public_key');
                document.getElementById('paymentSecKey').value = window.getConfigVal('payment', this.value, 'secret_key');
            };
            pSel.onchange();
        }

        const hSel = document.getElementById('hl7ProviderSelect');
        if(hSel) {
            hSel.onchange = function() {
                document.getElementById('hl7Ip').value = window.getConfigVal('hl7', this.value, 'ip_address');
                document.getElementById('hl7Port').value = window.getConfigVal('hl7', this.value, 'port');
            };
            hSel.onchange();
        }

        if(document.getElementById('emailHost')) {
            document.getElementById('emailHost').value = window.getConfigVal('email', 'SMTP', 'smtp_host');
            document.getElementById('emailPort').value = window.getConfigVal('email', 'SMTP', 'smtp_port');
            document.getElementById('emailUser').value = window.getConfigVal('email', 'SMTP', 'smtp_user');
            document.getElementById('emailPass').value = window.getConfigVal('email', 'SMTP', 'smtp_pass');
            document.getElementById('emailFromName').value = window.getConfigVal('email', 'SMTP', 'from_name');
        }

        // 4. Bind Global Save Function
        window.saveIntegrationsData = function(btn) {
            const form = document.getElementById('integrationsForm');
            const fd = new FormData(form);
            
            ['sms_enabled','email_enabled','payment_enabled','hl7_enabled','pacs_enabled','biometrics_enabled'].forEach(n => {
                fd.set(n, form.elements[n] && form.elements[n].checked ? '1' : '0');
            });

            const orig = btn.innerHTML;
            btn.innerHTML = '<i class=\'fa-solid fa-spinner fa-spin\'></i> Saving...';
            btn.disabled = true;

            fetch('../../dripend/systemSetup/facility/process_integrations.php', {
                method: 'POST',
                body: fd
            })
            .then(res => res.json())
            .then(data => {
                const banner = document.getElementById('uiNotificationBanner');
                banner.style.display = 'flex';
                if(data.status === '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> Integrations saved successfully!';
                    btn.innerHTML = '<i class=\'fa-solid fa-check\'></i> Secured';
                    btn.style.backgroundColor = '#16a34a';
                    setTimeout(() => { btn.innerHTML = orig; btn.disabled = false; btn.style.backgroundColor = ''; banner.style.display='none'; }, 3000);
                } else {
                    banner.style.backgroundColor = '#fef2f2';
                    banner.style.color = '#991b1b';
                    banner.style.border = '1px solid #fecaca';
                    banner.innerHTML = '<strong>Error:</strong> ' + data.message;
                    btn.innerHTML = orig; btn.disabled = false;
                }
                window.scrollTo({top:0, behavior:'smooth'});
            })
            .catch(err => {
                alert('Network Fetch Error');
                btn.innerHTML = orig; btn.disabled = false;
            });
        };
    })();
    this.remove();
" style="display:none;">

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

    <div class="fac-header-area">
        <div class="fac-page-title"><i class="fa-solid fa-plug-circle-bolt"></i> Hardware & Integrations</div>
        <div class="fac-page-subtitle">Configure 3rd-party API keys, Laboratory HL7 interfaces, Radiology PACS, and email servers.</div>
    </div>

    <form id="integrationsForm">
        <div class="fac-split-layout">
            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #0284c7;"><i class="fa-solid fa-message"></i> SMS Text Messaging</div>
                
                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable SMS Engine</span>
                        <span class="fac-toggle-desc">Send appointment reminders and lab alerts.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="smsToggle" name="sms_enabled" <?php echo getStatus($active_providers, 'sms'); ?>>
                        <span class="slider"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="smsBlock">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>SMS Provider</label>
                            <?php $active_sms = getActiveProv($active_providers, 'sms', 'Arkesel'); ?>
                            <select class="fac-input" name="sms_provider" id="smsProviderSelect">
                                <option <?php echo $active_sms == 'Arkesel' ? 'selected' : ''; ?>>Arkesel</option>
                                <option <?php echo $active_sms == 'Hubtel' ? 'selected' : ''; ?>>Hubtel</option>
                                <option <?php echo $active_sms == 'Twilio' ? 'selected' : ''; ?>>Twilio</option>
                                <option <?php echo $active_sms == 'SMSOnlineGH' ? 'selected' : ''; ?>>SMSOnlineGH</option>
                            </select>
                        </div>
                        <div class="fac-form-col">
                            <label>Sender ID (Max 11 Chars)</label>
                            <input type="text" class="fac-input" name="sms_sender_id" id="smsSenderId" maxlength="11">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Destination API URL / Endpoint</label>
                            <input type="text" class="fac-input" name="sms_url" id="smsUrl" placeholder="https://sms.provider.com/v1/send">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>API Key / Bearer Token</label>
                            <input type="password" class="fac-input" name="sms_api_key" id="smsApiKey">
                        </div>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #f43f5e;"><i class="fa-solid fa-envelope"></i> Email Notifications (SMTP)</div>
                
                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable Email Engine</span>
                        <span class="fac-toggle-desc">Send invoices, reports, and system alerts via email.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="emailToggle" name="email_enabled" <?php echo getStatus($active_providers, 'email'); ?>>
                        <span class="slider rose"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="emailBlock">
                    <input type="hidden" name="email_provider" value="SMTP">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>SMTP Host Server (URL)</label>
                            <input type="text" class="fac-input" name="email_smtp_host" id="emailHost" placeholder="smtp.gmail.com">
                        </div>
                        <div class="fac-form-col" style="max-width: 100px;">
                            <label>Port</label>
                            <input type="text" class="fac-input" name="email_smtp_port" id="emailPort" placeholder="465">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>SMTP Username / Email</label>
                            <input type="text" class="fac-input" name="email_smtp_user" id="emailUser">
                        </div>
                        <div class="fac-form-col">
                            <label>SMTP Password / App Password</label>
                            <input type="password" class="fac-input" name="email_smtp_pass" id="emailPass">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>From Name (Hospital Name)</label>
                            <input type="text" class="fac-input" name="email_from_name" id="emailFromName">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="fac-split-layout">
            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #10b981;"><i class="fa-solid fa-credit-card"></i> Digital Payments Gateway</div>
                
                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable Digital Payments</span>
                        <span class="fac-toggle-desc">Process MoMo and Card transactions automatically.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="paymentToggle" name="payment_enabled" <?php echo getStatus($active_providers, 'payment'); ?>>
                        <span class="slider emerald"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="paymentBlock">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Payment Processor</label>
                            <?php $active_pay = getActiveProv($active_providers, 'payment', 'Paystack'); ?>
                            <select class="fac-input" name="payment_provider" id="paymentProviderSelect">
                                <option <?php echo $active_pay == 'Paystack' ? 'selected' : ''; ?>>Paystack</option>
                                <option <?php echo $active_pay == 'Flutterwave' ? 'selected' : ''; ?>>Flutterwave</option>
                                <option <?php echo $active_pay == 'Hubtel Merchant' ? 'selected' : ''; ?>>Hubtel Merchant</option>
                            </select>
                        </div>
                        <div class="fac-form-col">
                            <label>Environment</label>
                            <select class="fac-input" name="payment_env" id="paymentEnv">
                                <option value="test">Test Mode (Sandbox)</option>
                                <option value="live">Live Mode (Production)</option>
                            </select>
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Processor API URL</label>
                            <input type="text" class="fac-input" name="payment_url" id="paymentUrl" placeholder="https://api.paystack.co">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Public Key</label>
                            <input type="text" class="fac-input" name="payment_public_key" id="paymentPubKey">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Secret Key</label>
                            <input type="password" class="fac-input" name="payment_secret_key" id="paymentSecKey">
                        </div>
                    </div>
                </div>
            </div>

            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #6366f1;"><i class="fa-solid fa-microscope"></i> LIS Machine Interfacing (HL7)</div>

                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable Automated Analyzers</span>
                        <span class="fac-toggle-desc">Pull lab results directly from Sysmex, Mindray, Roche.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="hl7Toggle" name="hl7_enabled" <?php echo getStatus($active_providers, 'hl7'); ?>>
                        <span class="slider indigo"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="hl7Block">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Middleware Mode / Type</label>
                            <?php $active_hl7 = getActiveProv($active_providers, 'hl7', 'Direct TCP Socket'); ?>
                            <select class="fac-input" name="hl7_provider" id="hl7ProviderSelect">
                                <option <?php echo $active_hl7 == 'Direct TCP Socket' ? 'selected' : ''; ?>>Direct TCP Socket</option>
                                <option <?php echo $active_hl7 == 'Mirth Connect' ? 'selected' : ''; ?>>Mirth Connect</option>
                            </select>
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>HL7 Receiver IP / Endpoint URL</label>
                            <input type="text" class="fac-input" name="hl7_ip" id="hl7Ip">
                        </div>
                        <div class="fac-form-col">
                            <label>TCP/IP Port</label>
                            <input type="number" class="fac-input" name="hl7_port" id="hl7Port">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="fac-split-layout">
            <div class="fac-panel fac-panel-half">
                <div class="fac-panel-title" style="color: #06b6d4;"><i class="fa-solid fa-x-ray"></i> Radiology PACS (DICOM)</div>

                <div class="fac-toggle-container">
                    <div>
                        <span class="fac-toggle-text">Enable PACS Integration</span>
                        <span class="fac-toggle-desc">Send Worklists to X-Ray/MRI modalities.</span>
                    </div>
                    <label class="switch">
                        <input type="checkbox" id="pacsToggle" name="pacs_enabled" <?php echo getStatus($active_providers, 'pacs'); ?>>
                        <span class="slider cyan"></span>
                    </label>
                </div>

                <div class="fac-dependent-setting" id="pacsBlock">
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>PACS Server AE Title (Provider Name)</label>
                            <input type="text" class="fac-input" name="pacs_provider" value="<?php echo getActiveProv($active_providers, 'pacs', 'CENTRAL_PACS'); ?>">
                        </div>
                    </div>
                    <div class="fac-form-row">
                        <div class="fac-form-col">
                            <label>Server IP Address</label>
                            <input type="text" class="fac-input" name="pacs_ip" value="<?php echo getVal($db_data, 'pacs', 'ip_address'); ?>">
                        </div>
                        <div class="fac-form-col">
                            <label>DICOM Port</label>
                            <input type="number" class="fac-input" name="pacs_port" value="<?php echo getVal($db_data, 'pacs', 'port'); ?>">
                        </div>
                    </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-desktop"></i> Local Hardware Configurations</div>

                <div class="fac-form-row">
                    <div class="fac-form-col">
                        <div class="fac-toggle-container" style="background:#fff; border-color:#e2e8f0; margin-bottom: 0;">
                            <div>
                                <span class="fac-toggle-text"><i class="fa-solid fa-fingerprint"></i> Biometric Auth</span>
                            </div>
                            <label class="switch">
                                <input type="checkbox" name="biometrics_enabled" <?php echo getStatus($active_providers, 'biometrics'); ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>

                    <div class="fac-form-col">
                        <label>Biometric Hardware Driver</label>
                        <?php $bio_prov = getActiveProv($active_providers, 'biometrics', 'DigitalPersona (WebAPI)'); ?>
                        <select class="fac-input" name="biometrics_provider">
                            <option <?php echo $bio_prov == 'DigitalPersona (WebAPI)' ? 'selected' : ''; ?>>DigitalPersona (WebAPI)</option>
                            <option <?php echo $bio_prov == 'SecuGen Hamster' ? 'selected' : ''; ?>>SecuGen Hamster</option>
                            <option <?php echo $bio_prov == 'ZKTeco' ? 'selected' : ''; ?>>ZKTeco</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.saveIntegrationsData === 'function') window.saveIntegrationsData(this);"><i class="fa-solid fa-key"></i> Encrypt & Save Integrations</button>
        </div>

    </form>
</div>