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

// SAFELY FETCH DYNAMIC DATA
$departments = [];
$dept_query = "SELECT id, department_name FROM departments WHERE is_active = 1 AND LOWER(department_name) NOT LIKE '%pharmacy%' ORDER BY department_name ASC";
$d_res = $conn->query($dept_query);
if($d_res) {
    while($row = $d_res->fetch_assoc()) {
        $departments[] = $row;
    }
}

$insurances = [];
$ins_query = "SELECT id, insurance_name FROM insurance_type WHERE is_active = 1 ORDER BY insurance_name ASC";
$i_res = $conn->query($ins_query);
if($i_res) {
    while($row = $i_res->fetch_assoc()) {
        $insurances[] = $row;
    }
}

$is_success = isset($_GET['status']) && $_GET['status'] == 'success';
$error_msg = isset($_GET['status']) && $_GET['status'] == 'error' ? "Error saving: " . htmlspecialchars($_GET['msg'] ?? 'Unknown Error') : "";
?>

<style>
/* Embedded Styles to guarantee SPA rendering */
.gdrg-add-module { width: 100%; animation: fadeIn 0.3s ease-in-out; font-family: "Segoe UI", system-ui, sans-serif; }
.header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
.header-bar h2 { color: #1e3a8a; margin: 0; font-size: 24px; font-weight: 800; display: flex; align-items: center; gap: 10px; }
.btn-back { background: #fff; color: #334155; padding: 10px 18px; text-decoration: none; border-radius: 8px; font-weight: bold; border: 1px solid #e2e8f0; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; }
.btn-outline { background: #fff; color: #1e3a8a; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; border: 1px solid #1e3a8a; cursor: pointer; transition: 0.2s; }
.btn-outline:hover { background: #eff6ff; }

/* Clean Card Layout */
.form-card { background: #ffffff; border-radius: 12px; margin-bottom: 24px; border: 1px solid #e2e8f0; box-shadow: 0 2px 5px rgba(0,0,0,0.02); overflow: hidden; }
.form-card-header { padding: 18px 24px; color: #1e3a8a; font-weight: 800; font-size: 15px; text-transform: uppercase; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #f1f5f9; background: #fafaf9; }
.form-card-body { padding: 24px; }

.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
.grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 24px; }

.form-group { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
.form-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
.form-control { padding: 12px 16px; border-radius: 8px; border: 1px solid #cbd5e1; outline: none; font-size: 14px; width: 100%; box-sizing: border-box; color: #334155; }
.form-control:focus { border-color: #1e3a8a; box-shadow: 0 0 0 3px #eff6ff; }

.input-group { display: flex; align-items: center; }
.input-group-text { background: #f1f5f9; border: 1px solid #cbd5e1; border-right: none; padding: 12px 16px; border-radius: 8px 0 0 8px; font-weight: 700; color: #475569; font-size: 14px;}
.input-group .form-control { border-radius: 0 8px 8px 0; }

/* Toggles */
.toggle-row { display: flex; align-items: center; justify-content: space-between; background: #f8fafc; padding: 16px 20px; border-radius: 8px; border: 1px solid #e2e8f0; margin-bottom: 20px; }
.toggle-label { font-size: 14px; font-weight: 700; color: #1e293b; }
.switch { position: relative; display: inline-block; width: 50px; height: 26px; margin: 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: 18px; width: 18px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
input:checked + .slider { background-color: #10b981; }
input:checked + .slider:before { transform: translateX(24px); }

/* Inner Tariff Cards */
.tariff-box { border: 1px dashed #cbd5e1; padding: 20px; border-radius: 8px; background: #fff; }
.tariff-box h4 { margin: 0 0 16px 0; font-size: 13px; color: #334155; text-transform: uppercase; font-weight: 800; }

.btn-submit { background: #0f172a; color: #fff; border: none; padding: 16px; border-radius: 8px; font-weight: 800; font-size: 15px; cursor: pointer; width: 100%; transition: 0.2s; text-transform: uppercase; }
.btn-submit:hover { background: #1e293b; }

/* SUCCESS MODAL STYLES */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.7); display: flex; align-items: center; justify-content: center; z-index: 9999; animation: fadeIn 0.2s ease; }
.modal-content { background: #fff; width: 450px; padding: 40px 30px; border-radius: 16px; text-align: center; box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
.modal-icon { font-size: 60px; color: #10b981; margin-bottom: 20px; animation: scaleIn 0.4s ease-out; }
.modal-content h3 { color: #1e293b; font-size: 22px; font-weight: 800; margin-bottom: 10px; }
.modal-content p { color: #64748b; font-size: 15px; margin-bottom: 30px; line-height: 1.5; }
.modal-actions { display: flex; gap: 15px; justify-content: center; }
@keyframes scaleIn { from { transform: scale(0); } to { transform: scale(1); } }
</style>

<div class="gdrg-add-module">
    
    <?php if ($is_success): ?>
    <div id="successModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-icon"><i class="fa-solid fa-circle-check"></i></div>
            <h3>Procedure Saved!</h3>
            <p>The new procedure and all associated insurance pricing matrices have been successfully added to the catalog.</p>
            <div class="modal-actions">
                <button type="button" class="btn-outline" onclick="if(typeof loadContent === 'function') { loadContent('Add New Procedure', 'gdrg/addNewGdrg.php', 'Catalog', 'system_setup', null, true); }">
                    <i class="fa-solid fa-plus"></i> Add Another
                </button>
                <button type="button" class="btn-submit" style="width: auto; padding: 12px 24px;" onclick="if(typeof loadContent === 'function') { loadContent('Procedures / Services', 'gdrg/nhis_tariffs.php', 'Catalog', 'system_setup', null, true); }">
                    Return to Catalog
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="header-bar">
        <h2>Add New Procedure</h2>
        <button onclick="if(typeof loadContent === 'function') { loadContent('Procedures / Services', 'gdrg/nhis_tariffs.php', 'Catalog', 'system_setup', null, true); }" class="btn-back">
            <i class="fa-solid fa-arrow-left"></i> Back to Catalog
        </button>
    </div>

    <?php if ($error_msg): ?>
        <div style="background: #fee2e2; color: #991b1b; padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: 600;"><i class="fa-solid fa-triangle-exclamation"></i> <?php echo $error_msg; ?></div>
    <?php endif; ?>

    <form method="POST" action="../../dripend/systemSetup/gdrg/processAddNewGdrg.php">
        
        <!-- SECTION 1: Basic Details -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fa-solid fa-circle-info"></i> Basic Procedure Details
            </div>
            <div class="form-card-body">
                <div class="grid-2">
                    <div class="form-group">
                        <label>Procedure / Service Name</label>
                        <input type="text" name="service_name" class="form-control" placeholder="e.g., Forceps Extraction, General Consult..." required>
                    </div>
                    <div class="form-group">
                        <label>Assigned Department</label>
                        <select name="department_id" class="form-control" required>
                            <option value="">-- Select Department --</option>
                            <?php foreach($departments as $dept): ?>
                                <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['department_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="grid-2" style="margin-top: 16px;">
                    <div class="form-group">
                        <label>Adult Base Price (Cash)</label>
                        <div class="input-group">
                            <span class="input-group-text">GHS</span>
                            <input type="number" step="0.01" name="cash_price_adult" class="form-control" placeholder="0.00" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Child Base Price (Cash)</label>
                        <div class="input-group">
                            <span class="input-group-text">GHS</span>
                            <input type="number" step="0.01" name="cash_price_child" class="form-control" placeholder="0.00" required>
                        </div>
                    </div>
                </div>

                <div class="grid-2" style="margin-top: 16px;">
                    <div class="form-group">
                        <label>Target Age Group</label>
                        <select name="target_age_group" class="form-control">
                            <option value="All Ages">All Ages</option>
                            <option value="Adult Only">Adult Only (e.g. Hypertension)</option>
                            <option value="Child Only">Child Only (e.g. Neonatal)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Applicable Gender</label>
                        <select name="applicable_gender" class="form-control">
                            <option value="Both">Both Genders</option>
                            <option value="Male">Male Only</option>
                            <option value="Female">Female Only (e.g. Maternity)</option>
                        </select>
                    </div>
                </div>
                
                <div style="margin-top: 16px; border-top: 1px dashed #cbd5e1; padding-top: 20px;">
                    <div class="form-group" style="margin: 0;">
                        <div class="form-control" style="display:flex; justify-content:space-between; align-items:center; background:#f8fafc; border: 1px solid #e2e8f0; width: 100%; max-width: 500px;">
                            <div>
                                <span style="font-size:14px; font-weight:700; color:#334155; display:block;">Is this a Consultation?</span>
                                <span style="font-size:11px; color:#64748b;">(Check for Consultation, uncheck for Procedure/Lab)</span>
                            </div>
                            <label class="switch">
                                <input type="checkbox" name="is_consultation" value="1">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- SECTION 2: NHIS Config -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fa-solid fa-building-columns"></i> NHIA (National Health Insurance) Setup
            </div>
            <div class="form-card-body">
                <div class="toggle-row">
                    <span class="toggle-label">Is this procedure NHIA Insured?</span>
                    <label class="switch">
                        <input type="checkbox" name="nhis_covered" value="1" onchange="document.getElementById('nhis_section').style.display = this.checked ? 'block' : 'none';">
                        <span class="slider"></span>
                    </label>
                </div>

                <div id="nhis_section" style="display:none; padding: 20px; background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 8px; margin-bottom: 20px;">
                    <div class="grid-2">
                        <div class="tariff-box">
                            <h4>Adult Tariff Config</h4>
                            <div class="form-group">
                                <label>GDRG Code (Adult)</label>
                                <input type="text" name="gdrg_adult_code" class="form-control" placeholder="e.g., DENTO1A">
                            </div>
                            <div class="form-group">
                                <label>NHIS Price (Adult)</label>
                                <div class="input-group">
                                    <span class="input-group-text">GHS</span>
                                    <input type="number" step="0.01" name="tariff_adult" class="form-control" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                        
                        <div class="tariff-box">
                            <h4>Child Tariff Config</h4>
                            <div class="form-group">
                                <label>GDRG Code (Child)</label>
                                <input type="text" name="gdrg_child_code" class="form-control" placeholder="e.g., DENTO1C">
                            </div>
                            <div class="form-group">
                                <label>NHIS Price (Child)</label>
                                <div class="input-group">
                                    <span class="input-group-text">GHS</span>
                                    <input type="number" step="0.01" name="tariff_child" class="form-control" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="toggle-row" style="margin-top: 20px; background: #fff; border-color:#fed7aa;">
                        <span class="toggle-label" style="color: #ea580c;"><i class="fa-solid fa-coins"></i> Does NHIA require Co-payment?</span>
                        <label class="switch">
                            <input type="checkbox" name="is_copay_required" value="1" onchange="document.getElementById('nhis_copay_section').style.display = this.checked ? 'flex' : 'none';">
                            <span class="slider"></span>
                        </label>
                    </div>

                    <div id="nhis_copay_section" class="grid-2" style="display:none; margin-top: 16px;">
                        <div class="form-group">
                            <label>Adult Co-payment Amount</label>
                            <div class="input-group">
                                <span class="input-group-text">GHS</span>
                                <input type="number" step="0.01" name="nhis_copay_adult" class="form-control" placeholder="0.00">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>Child Co-payment Amount</label>
                            <div class="input-group">
                                <span class="input-group-text">GHS</span>
                                <input type="number" step="0.01" name="nhis_copay_child" class="form-control" placeholder="0.00">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- SECTION 3: Corporate Insurance -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fa-solid fa-building-shield"></i> Corporate / Private Insurance Mapping
            </div>
            <div class="form-card-body">
                <p style="font-size: 13px; color: #64748b; margin-top: -10px; margin-bottom: 24px;">Enable and configure pricing for private insurers that cover this procedure. Leave disabled if not covered.</p>

                <?php foreach($insurances as $ins): $ins_id = $ins['id']; ?>
                    <div style="border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 16px; overflow:hidden;">
                        
                        <div style="background: #f8fafc; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center;">
                            <div style="font-weight: 800; font-size: 14px; color: #1e3a8a;">
                                <?php echo htmlspecialchars($ins['insurance_name']); ?> Policy
                            </div>
                            <label class="switch">
                                <input type="checkbox" name="corp_covered[<?php echo $ins_id; ?>]" value="1" onchange="document.getElementById('corp_body_<?php echo $ins_id; ?>').style.display = this.checked ? 'block' : 'none';">
                                <span class="slider"></span>
                            </label>
                        </div>

                        <div id="corp_body_<?php echo $ins_id; ?>" style="display:none; padding: 20px; border-top: 1px solid #e2e8f0;">
                            <div class="grid-3">
                                <div class="form-group">
                                    <label>Provider Tariff</label>
                                    <div class="input-group">
                                        <span class="input-group-text">GHS</span>
                                        <input type="number" step="0.01" name="corp_tariff[<?php echo $ins_id; ?>]" class="form-control" placeholder="0.00">
                                    </div>
                                </div>
                                <div class="form-group" style="grid-column: span 2;">
                                    <label>Require Co-Payment?</label>
                                    <div class="toggle-row" style="margin-bottom:0; padding: 9px 16px;">
                                        <span style="font-size: 13px; font-weight:600; color:#475569;">Enable Copay for <?php echo htmlspecialchars($ins['insurance_name']); ?></span>
                                        <label class="switch" style="transform: scale(0.9);">
                                            <input type="checkbox" name="corp_copay_req[<?php echo $ins_id; ?>]" value="1" onchange="document.getElementById('ccopay_inputs_<?php echo $ins_id; ?>').style.display = this.checked ? 'flex' : 'none';">
                                            <span class="slider"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <div id="ccopay_inputs_<?php echo $ins_id; ?>" class="grid-2" style="display:none; margin-top: 16px; padding-top: 16px; border-top: 1px dashed #cbd5e1;">
                                <div class="form-group">
                                    <label>Adult Co-payment</label>
                                    <div class="input-group">
                                        <span class="input-group-text">GHS</span>
                                        <input type="number" step="0.01" name="corp_copay_adult[<?php echo $ins_id; ?>]" class="form-control" placeholder="0.00">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>Child Co-payment</label>
                                    <div class="input-group">
                                        <span class="input-group-text">GHS</span>
                                        <input type="number" step="0.01" name="corp_copay_child[<?php echo $ins_id; ?>]" class="form-control" placeholder="0.00">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>

            </div>
        </div>

        <button type="submit" class="btn-submit">
            <i class="fa-solid fa-floppy-disk"></i> Save Procedure Configuration
        </button>
        <div style="height: 50px;"></div>
    </form>
</div>