<?php
if(session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once dirname(__DIR__, 3) . '/dripend/includes/db.php';
if (!isset($conn) && isset($db)) { $conn = $db; }

$departments = [];
$depRes = $conn->query("SELECT id, department_name FROM departments WHERE is_active = 1 ORDER BY department_name ASC");
if ($depRes) {
    while ($r = $depRes->fetch_assoc()) $departments[] = $r;
}

$unique_sections = [];
$secRes = $conn->query("SELECT DISTINCT section_name FROM consultation_form_setup WHERE is_active = 1");
if ($secRes) {
    while ($r = $secRes->fetch_assoc()) {
        $unique_sections[] = $r['section_name'];
    }
}
?>

<style>
.consult-builder-wrapper { font-family: 'Inter', sans-serif; color: #0f172a; margin-top: 5px;}
.consult-builder-wrapper .alert { padding: 15px; border-radius: 8px; font-weight: 700; margin-bottom: 20px; display: none; }
.consult-builder-wrapper .alert-error { background: #fee2e2; color: #991b1b; border-left: 5px solid #ef4444; }
.consult-builder-wrapper .alert-success { background: #dcfce7; color: #166534; border-left: 5px solid #10b981; }

.consult-builder-wrapper .layout-grid { display: grid; grid-template-columns: 420px 1fr; gap: 25px; align-items: start; }
@media (max-width: 1200px) { .consult-builder-wrapper .layout-grid { grid-template-columns: 1fr; } }

.consult-builder-wrapper .card { background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px rgba(0,0,0,0.02); padding: 25px; margin-bottom: 25px;}
.consult-builder-wrapper .card-header { font-size: 16px; font-weight: 800; color: #075985; margin-bottom: 20px; display: flex; align-items: center; gap: 8px; border-bottom: 1px dashed #e2e8f0; padding-bottom: 10px;}

.consult-builder-wrapper .form-group { margin-bottom: 15px; }
.consult-builder-wrapper .form-group label { display: block; font-size: 11px; font-weight: 800; color: #475569; text-transform: uppercase; margin-bottom: 6px; letter-spacing: 0.5px;}
.consult-builder-wrapper .input-control { width: 100%; padding: 10px 14px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 13px; font-weight: 600; outline: none; background: #f8fafc; transition: 0.2s;}
.consult-builder-wrapper .input-control:focus { border-color: #0284c7; background: #fff; box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.1); }

.consult-builder-wrapper .checkbox-group { display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; font-weight: 700; color: #0f172a; margin-top: 10px;}
.consult-builder-wrapper .checkbox-group input { width: 16px; height: 16px; cursor: pointer;}

.consult-builder-wrapper .btn { padding: 12px 20px; border-radius: 8px; font-size: 13px; font-weight: 800; cursor: pointer; border: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px; transition: 0.2s;}
.consult-builder-wrapper .btn-primary { background: linear-gradient(135deg, #0284c7, #075985); color: #fff; width: 100%; }
.consult-builder-wrapper .btn-outline { background: #f1f5f9; color: #0f172a; border: 1px solid #cbd5e1; width: 100%; margin-top: 10px;}

.consult-builder-wrapper .setup-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.consult-builder-wrapper .setup-table th { background: #f8fafc; padding: 12px; text-align: left; font-weight: 800; color: #475569; text-transform: uppercase; font-size: 10px; border-bottom: 2px solid #e2e8f0; }
.consult-builder-wrapper .setup-table td { padding: 12px; border-bottom: 1px solid #e2e8f0; vertical-align: middle; font-weight: 600; color: #0f172a; }

.consult-builder-wrapper .badge { padding: 4px 8px; border-radius: 6px; font-size: 10px; font-weight: 800; text-transform: uppercase; background: #e0f2fe; color: #0284c7;}
.consult-builder-wrapper .badge-dept { background: #fef3c7; color: #b45309; }
.consult-builder-wrapper .hint-text { display: block; font-size: 11px; font-weight: 500; color: #94a3b8; margin-top: 4px; line-height: 1.4; }
.consult-builder-wrapper .panel-section { background: #ffffff; padding: 15px; border-radius: 8px; border: 1px solid #e2e8f0; margin-bottom: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);}
</style>

<div class="consult-builder-wrapper">
    <div id="alertError" class="alert alert-error"></div>
    <div id="alertSuccess" class="alert alert-success"></div>

    <div class="layout-grid">
        <div class="card" style="border-top: 4px solid #0284c7; background: #f8fafc;">
            <div class="card-header" id="formHeader"><i class="fa-solid fa-wand-magic-sparkles"></i> Field Builder & Mapper</div>
            
            <form id="setupConsultForm">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="field_id" id="field_id" value="">

                <div class="panel-section" style="border-left: 4px solid #0284c7;">
                    <div style="font-size:12px; font-weight:800; color:#0284c7; margin-bottom:15px; text-transform:uppercase;">Step 1: Define the Field</div>
                    
                    <div class="form-group">
                        <label>What is the question/label? <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="field_label" id="field_label" class="input-control" placeholder="e.g., Blood Pressure" required>
                    </div>

                    <div class="form-group">
                        <label>How should the user answer? <span style="color:#dc2626;">*</span></label>
                        <select name="field_type" id="field_type" class="input-control">
                            <option value="textarea" selected>Long Text (Paragraphs / Notes)</option>
                            <option value="text">Short Text (Single Line)</option>
                            <option value="number">Numeric Value Only (e.g. Vitals)</option>
                            <option value="date">Date Picker</option>
                            <option value="select">Dropdown Menu (Select Options)</option>
                            <option value="checkbox">Checkboxes (Multiple Select)</option>
                            <option value="radio">Radio Buttons (Single Select)</option>
                        </select>
                    </div>

                    <div class="form-group" id="optionsBox" style="display: none; background: #fdf8ea; padding: 12px; border-radius: 6px; border: 1px dashed #f59e0b;">
                        <label style="color:#b45309;">List the Custom Options</label>
                        <textarea name="field_options" id="field_options" class="input-control" placeholder="e.g. Mild, Moderate, Severe" rows="2"></textarea>
                        <span class="hint-text">Separate each option with a comma.</span>
                    </div>

                    <div class="form-group mb-0">
                        <label>Database Key (Auto-Generated) <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="field_name" id="field_name" class="input-control" placeholder="e.g. blood_pressure" style="font-family: monospace; background: #f1f5f9; color:#64748b;" readonly>
                    </div>
                </div>

                <div class="panel-section" style="border-left: 4px solid #f59e0b;">
                    <div style="font-size:12px; font-weight:800; color:#b45309; margin-bottom:15px; text-transform:uppercase;">Step 2: Assign its Location</div>

                    <div class="form-group">
                        <label>Which Department sees this? <span style="color:#dc2626;">*</span></label>
                        <select name="department_id" id="department_id" class="input-control">
                            <option value="">-- Apply to ALL Departments --</option>
                            <?php foreach($departments as $d): ?>
                                <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['department_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Clinical Phase / Form Tab <span style="color:#dc2626;">*</span></label>
                        <input type="text" name="section_name" id="section_name" class="input-control" list="section_list" placeholder="e.g., Triage, Doctor Notes" required>
                        <datalist id="section_list">
                            <?php foreach($unique_sections as $sec): ?>
                                <option value="<?= htmlspecialchars($sec) ?>"></option>
                            <?php endforeach; ?>
                        </datalist>
                    </div>

                    <div class="form-group mb-0">
                        <label>Display Order (Sorting)</label>
                        <input type="number" name="display_order" id="display_order" class="input-control" value="0">
                    </div>
                </div>

                <div class="form-group" style="padding-top: 5px;">
                    <label class="checkbox-group">
                        <input type="checkbox" name="is_required" id="is_required"> Make this field Mandatory
                    </label>
                    <label class="checkbox-group">
                        <input type="checkbox" name="is_active" id="is_active" checked> Field is Active
                    </label>
                </div>

                <button type="button" class="btn btn-primary" id="btnSubmitConsultForm">
                    <i class="fa-solid fa-link"></i> Save & Map to Form
                </button>
                <button type="button" class="btn btn-outline" id="btnCancelConsultEdit" style="display:none;">
                    <i class="fa-solid fa-xmark"></i> Cancel Edit
                </button>
            </form>
        </div>

        <div class="card">
            <div class="card-header"><i class="fa-solid fa-server"></i> Dynamic Form Architecture Registry</div>
            <div style="overflow-x: auto;">
                <table id="registryTable" class="setup-table display nowrap" style="width:100%">
                    <thead>
                        <tr>
                            <th>Mapped Dept</th>
                            <th>Clinical Phase (Tab)</th>
                            <th>Field Question / Label</th>
                            <th>Answer Type</th>
                            <th>Req.</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Populated by DataTables AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>