<?php
// Use absolute path for bulletproof connection
require_once $_SERVER['DOCUMENT_ROOT'] . '/rimax/application/dripend/includes/db.php';

// 1. Fetch from SERVICE CATALOG (Procedures) instead of the dictionary
$gdrgs = [];
$gdrg_query = "
    SELECT 
        gdrg_adult_code as code, 
        GROUP_CONCAT(service_name SEPARATOR ' | ') as description 
    FROM service_catalog 
    WHERE gdrg_adult_code IS NOT NULL AND gdrg_adult_code != ''
    GROUP BY gdrg_adult_code
    ORDER BY gdrg_adult_code ASC
";
$g_res = $conn->query($gdrg_query);
if($g_res) { while($row = $g_res->fetch_assoc()) { $gdrgs[] = $row; } }

// 2. Fetch ALL ICD-10 Codes
$icds = [];
$icd_query = "SELECT code, description FROM icd10_dictionary ORDER BY code ASC";
$i_res = $conn->query($icd_query);
if($i_res) { while($row = $i_res->fetch_assoc()) { $icds[] = $row; } }

// 3. Fetch Existing Mappings
$existing_mappings = [];
$mapping_query = "SELECT gdrg_code, icd10_code FROM gdrg_icd_mapping";
$m_res = $conn->query($mapping_query);
if($m_res) { while($row = $m_res->fetch_assoc()) { $existing_mappings[] = $row; } }

$is_success = isset($_GET['status']) && $_GET['status'] == 'success';
$error_msg = isset($_GET['status']) && $_GET['status'] == 'error' ? "Error saving mapping. Please check inputs or database constraints." : "";
?>

<style>
.gdrg-add-module { width: 100%; animation: fadeIn 0.3s ease; font-family: "Segoe UI", system-ui, sans-serif; position: relative; }
.header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.header-bar h2 { color: #1e3a8a; margin: 0; font-size: 24px; font-weight: 800; display: flex; align-items: center; gap: 10px; text-transform: uppercase; }
.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; transition: 0.2s; }
.btn-back:hover { background: #f1f5f9; }

.mapping-grid { display: grid; grid-template-columns: 1fr 1.5fr; gap: 24px; margin-bottom: 100px; }
.pane-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; display: flex; flex-direction: column; height: 600px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); overflow: hidden; }
.pane-header { padding: 16px 20px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; font-weight: 800; color: #1e3a8a; font-size: 15px; text-transform: uppercase; display: flex; justify-content: space-between; align-items: center; }
.pane-search { padding: 12px 20px; border-bottom: 1px solid #e2e8f0; background: #fff; }
.search-input { width: 100%; padding: 10px 14px 10px 36px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; outline: none; background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="14" fill="%2394a3b8"><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352a144 144 0 1 0 0-288 144 144 0 1 0 0 288z"/></svg>') no-repeat 12px center; }
.search-input:focus { border-color: #1e3a8a; box-shadow: 0 0 0 3px #eff6ff; }

.pane-list { flex: 1; overflow-y: auto; padding: 10px; background: #fafaf9; }
.list-item { padding: 12px 16px; margin-bottom: 6px; background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; transition: 0.2s; display: flex; align-items: flex-start; gap: 12px; }
.list-item:hover { border-color: #cbd5e1; transform: translateY(-1px); box-shadow: 0 2px 4px rgba(0,0,0,0.02); }

.gdrg-item.selected { background: #eff6ff; border-color: #3b82f6; box-shadow: 0 0 0 1px #3b82f6; }
.gdrg-code { font-weight: 800; color: #1e40af; font-size: 14px; margin-bottom: 4px; display: block; }

.icd-item { align-items: center; }
.icd-item.selected { background: #f0fdf4; border-color: #10b981; }
.icd-code { background: #e2e8f0; color: #334155; padding: 2px 6px; border-radius: 4px; font-size: 12px; font-weight: 800; min-width: 55px; text-align: center; }
.icd-desc { font-size: 13px; color: #334155; font-weight: 600; flex: 1; }
.custom-checkbox { width: 20px; height: 20px; accent-color: #10b981; cursor: pointer; }
.badge-mapped { background: #10b981; color: #fff; padding: 3px 8px; border-radius: 6px; font-size: 11px; font-weight: 800; text-transform: uppercase; }

.staging-bar { position: sticky; bottom: 0; left: 0; width: 100%; background: #0f172a; padding: 20px 30px; border-radius: 12px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 -10px 30px rgba(0,0,0,0.1); box-sizing: border-box; z-index: 10; margin-top: -60px; }
.staging-info { color: #fff; }
.staging-title { font-size: 13px; color: #94a3b8; text-transform: uppercase; font-weight: 700; margin-bottom: 4px; }
.staging-target { font-size: 18px; font-weight: 800; color: #38bdf8; display: flex; align-items: center; gap: 10px; }
.badge-count { background: #f59e0b; color: #78350f; padding: 2px 8px; border-radius: 20px; font-size: 12px; font-weight: 800; }
.btn-submit { background: #10b981; color: #fff; border: none; padding: 14px 28px; border-radius: 8px; font-weight: 800; font-size: 15px; cursor: pointer; transition: 0.2s; text-transform: uppercase; display: flex; align-items: center; gap: 10px; }
.btn-submit:disabled { background: #475569; color: #94a3b8; cursor: not-allowed; }

.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; }
.modal-content { background: #fff; width: 450px; padding: 40px 30px; border-radius: 16px; text-align: center; }
.modal-icon { font-size: 60px; color: #10b981; margin-bottom: 20px; }
.btn-outline { background: #fff; color: #1e3a8a; padding: 12px 24px; border-radius: 8px; font-weight: bold; border: 1px solid #1e3a8a; cursor: pointer; }
</style>

<div id="rawGdrgData" style="display:none;"><?php echo htmlspecialchars(json_encode($gdrgs)); ?></div>
<div id="rawIcdData" style="display:none;"><?php echo htmlspecialchars(json_encode($icds)); ?></div>
<div id="rawMappingData" style="display:none;"><?php echo htmlspecialchars(json_encode($existing_mappings)); ?></div>

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" onload="
    if (typeof window.initMappingBuilder !== 'function') {
        const script = document.createElement('script');
        script.src = '../../assets/js/add-mapping.js?v=' + new Date().getTime();
        script.onload = () => window.initMappingBuilder();
        document.head.appendChild(script);
    } else {
        window.initMappingBuilder();
    }
    this.remove();
" style="display:none;">

<div class="gdrg-add-module">
    
    <?php if ($is_success): ?>
    <div class="modal-overlay">
        <div class="modal-content">
            <div class="modal-icon"><i class="fa-solid fa-circle-check"></i></div>
            <h3 style="margin-bottom: 10px; color: #1e293b;">Mapping Successful!</h3>
            <p style="color: #64748b;">The ICD-10 codes have been successfully linked to the selected procedures.</p>
            <div style="display: flex; gap: 15px; justify-content: center; margin-top: 20px;">
                <button type="button" class="btn-outline" onclick="if(typeof loadContent === 'function') { loadContent('Add Mapping', 'gdrg/addMapping.php', 'Mapping', 'facility', null, true); }">Map Another</button>
                <button type="button" class="btn-submit" onclick="if(typeof loadContent === 'function') { loadContent('GDRG Mappings', 'gdrg/gdrg_icd_mapping.php', 'Mapping', 'facility', null, true); }" style="width: auto; padding: 12px 24px; margin:0;">View Directory</button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="header-bar">
        <h2><i class="fa-solid fa-link"></i> Map Procedures (Catalog) to ICD-10</h2>
        <button onclick="if(typeof loadContent === 'function') { loadContent('GDRG Mappings', 'gdrg/gdrg_icd_mapping.php', 'Mapping', 'facility', null, true); }" class="btn-back">
            <i class="fa-solid fa-arrow-left"></i> Back to Directory
        </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/processAddMapping.php" id="mappingForm">
        
        <input type="hidden" name="target_gdrg" id="targetGdrgInput" value="">
        <div id="hiddenIcdInputsContainer"></div>

        <div class="mapping-grid">
            
            <div class="pane-card">
                <div class="pane-header">
                    <span>1. Select Catalog Procedure</span>
                    <span id="gdrgCountBadge" class="badge-count">0</span>
                </div>
                <div class="pane-search">
                    <input type="text" id="gdrgSearch" class="search-input" placeholder="Search procedure name or code...">
                </div>
                <div class="pane-list" id="gdrgListContainer"></div>
            </div>

            <div class="pane-card">
                <div class="pane-header">
                    <span>2. Map Multiple ICD-10 Codes</span>
                    <span id="icdCountBadge" class="badge-count">0</span>
                </div>
                <div class="pane-search">
                    <input type="text" id="icdSearch" class="search-input" placeholder="Search ICD-10 code or diagnosis...">
                </div>
                <div class="pane-list" id="icdListContainer" style="pointer-events: none; opacity: 0.5;">
                    <div style="text-align:center; padding: 40px; color:#64748b;">
                        <i class="fa-solid fa-arrow-left" style="font-size: 24px; margin-bottom:10px;"></i><br>
                        Please select a Procedure from the left first.
                    </div>
                </div>
            </div>

        </div>

        <div class="staging-bar">
            <div class="staging-info">
                <div class="staging-title">Current Mapping Configuration</div>
                <div class="staging-target" id="stagingTargetText">
                    <i class="fa-solid fa-circle-exclamation" style="color:#ef4444;"></i> No Procedure Selected
                </div>
            </div>
            
            <button type="submit" class="btn-submit" id="btnSubmitMapping" disabled>
                <i class="fa-solid fa-floppy-disk"></i> Execute Batch Mapping
            </button>
        </div>

    </form>
</div>