<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap.min.css') ?>?v=<?= av() ?>">
    <link rel="stylesheet" href="<?= base_url('assets/template/css/bootstrap-icons.css') ?>?v=<?= av() ?>">
    <link rel="stylesheet" href="<?= base_url('assets/template/css/admin-dashboard-custom.css') ?>?v=<?= av() ?>">
    
    <title><?= __('admin.developer_tools') ?></title>
</head>
<body class="debug-page">
<div style="min-height:100vh; background:#0d1117;">
    <!-- Navbar -->
    <div class="devnav">
        <div style="display:flex;align-items:center;gap:24px;">
            <a class="devnav-brand" href="<?= base_url('admincontrol/dashboard') ?>">
                <i class="bi bi-code-slash" style="color:#388bfd;"></i><?= __('admin.developer_tools') ?>
            </a>
            <nav class="devnav-tabs">
                <a class="devnav-tab <?= $dtype=='logs' ? 'active' : '' ?>" href="<?= base_url('debug/logs') ?>">
                    <i class="bi bi-file-text"></i><?= __('admin.logs') ?>
                </a>
                <a class="devnav-tab <?= $dtype=='dbstructure' ? 'active' : '' ?>" href="<?= base_url('debug/dbstructure') ?>">
                    <i class="bi bi-database"></i><?= __('admin.database_structure') ?>
                </a>
                <a class="devnav-tab <?= $dtype=='sysupdatereport' ? 'active' : '' ?>" href="<?= base_url('debug/sysupdatereport') ?>">
                    <i class="bi bi-arrow-up-circle"></i><?= __('admin.system_update_report') ?>
                </a>
            </nav>
        </div>
        <span class="devnav-version">Version <?= SCRIPT_VERSION ?></span>
    </div>
    <div style="padding:24px;">
    <div class="row">
        <div class="col-12">
            <?php if(isset($error)) { ?>
                <div class="alert alert-danger d-flex align-items-center" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <div><?= $error ?></div>
                </div>
            <?php } else { ?>
                <?php
                    switch ($dtype) {
                        case 'logs':
                            ?>
        <!-- LOGS HERO -->
        <div class="dt-hero" style="background:linear-gradient(135deg,#0c1526 0%,#1a1f3c 60%,#0c1526 100%);border:1px solid #21262d;">
            <div style="position:absolute;inset:0;border-radius:14px;overflow:hidden;pointer-events:none;">
                <div style="position:absolute;top:-30px;right:-20px;width:160px;height:160px;background:rgba(56,139,253,.06);border-radius:50%;"></div>
            </div>
            <div style="position:relative;z-index:1;">
                <div class="d-flex align-items-center gap-2 mb-2">
                    <span style="background:#388bfd;color:#fff;border-radius:20px;padding:3px 12px;font-size:.78rem;font-weight:600;">
                        <i class="bi bi-file-text me-1"></i>Error Log
                    </span>
                    <span style="background:rgba(255,255,255,.07);color:rgba(255,255,255,.6);border-radius:20px;padding:3px 12px;font-size:.78rem;border:1px solid rgba(255,255,255,.1);">
                        <?= date('d M Y') ?>
                    </span>
                </div>
                <h4 class="fw-bold text-white mb-1">Log Viewer</h4>
                <div style="color:rgba(255,255,255,.4);font-size:.82rem;"><i class="bi bi-clock me-1"></i>Last loaded: <?= date('H:i:s') ?></div>
            </div>
        </div>

        <!-- STATS -->
        <div class="row g-3 mb-4">
            <?php foreach ([
                ['0','Total Lines',   'bi-file-earmark-text','#58a6ff','rgba(88,166,255,.1)','rgba(88,166,255,.25)','total-lines'],
                ['0','Errors',        'bi-x-circle-fill',    '#f85149','rgba(248,81,73,.1)', 'rgba(248,81,73,.25)', 'error-lines'],
                ['0','Warnings',      'bi-exclamation-triangle-fill','#e3b341','rgba(227,179,65,.1)','rgba(227,179,65,.25)','warn-lines'],
                ['0 KB','File Size',  'bi-hdd-fill',         '#3fb950','rgba(63,185,80,.1)', 'rgba(63,185,80,.25)', 'file-size'],
            ] as [$val,$lbl,$ico,$clr,$bg,$bdr,$id]): ?>
            <div class="col-6 col-md-3">
                <div class="dt-stat" style="background:<?= $bg ?>;border:1px solid <?= $bdr ?>;">
                    <div class="dt-stat-icon" style="background:<?= $bdr ?>;"><i class="bi <?= $ico ?>" style="color:<?= $clr ?>;"></i></div>
                    <div><div class="dt-stat-val" id="<?= $id ?>" style="color:<?= $clr ?>;"><?= $val ?></div><div class="dt-stat-lbl"><?= $lbl ?></div></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- FILTER + SEARCH BAR -->
        <div class="d-flex flex-wrap align-items-center gap-3 mb-3">
            <div class="dt-filter-bar mb-0">
                <button class="dt-filter-btn active" onclick="filterLogs('all',this)"><?= __('admin.all_logs') ?></button>
                <button class="dt-filter-btn" onclick="filterLogs('error',this)" style="--ac:#f85149;"><?= __('admin.errors_only') ?></button>
                <button class="dt-filter-btn" onclick="filterLogs('warning',this)" style="--ac:#e3b341;"><?= __('admin.warnings_only') ?></button>
                <button class="dt-filter-btn" onclick="filterLogs('info',this)"><?= __('admin.info_only') ?></button>
            </div>
            <div style="flex:1;min-width:200px;">
                <input type="text" id="log-search" class="dt-search" placeholder="Search logs..." oninput="searchLogs(this.value)">
            </div>
        </div>

        <!-- TERMINAL -->
        <div class="dt-term">
            <div class="dt-term-bar">
                <div style="display:flex;align-items:center;">
                    <div class="dt-term-dots">
                        <span class="dt-term-dot" style="background:#ff5f57;"></span>
                        <span class="dt-term-dot" style="background:#febc2e;"></span>
                        <span class="dt-term-dot" style="background:#28c840;"></span>
                    </div>
                    <span class="dt-term-title">affiliatepro ~ error-log ~ <?= date('d M Y') ?></span>
                </div>
                <div style="display:flex;gap:6px;">
                    <button class="dt-btn" onclick="location.reload()"><i class="bi bi-arrow-clockwise"></i></button>
                    <button class="dt-btn" onclick="scrollLogBottom()"><i class="bi bi-arrow-down-circle"></i></button>
                </div>
            </div>
            <div id="log-container" class="dt-term-body" style="padding:12px 0;">
                <?php
                if (empty(trim($log))) {
                    echo '<div style="text-align:center;padding:60px 20px;color:#484860;">';
                    echo '<i class="bi bi-inbox" style="font-size:2.5rem;display:block;margin-bottom:12px;"></i>';
                    echo '<div style="font-size:.9rem;">No log entries found.</div>';
                    echo '</div>';
                } else {
                    $lines = explode("\n", $log);
                    $ln = 1;
                    foreach ($lines as $line) {
                        if (!trim($line)) continue;
                        $line = htmlspecialchars($line);
                        $type = 'info'; $ico = 'bi-info-circle-fill'; $clr = '#58a6ff';
                        if (stripos($line,'error')!==false || stripos($line,'fatal')!==false) {
                            $type='error';   $ico='bi-x-circle-fill';            $clr='#f85149';
                        } elseif (stripos($line,'warning')!==false || stripos($line,'warn')!==false) {
                            $type='warning'; $ico='bi-exclamation-circle-fill';  $clr='#e3b341';
                        } elseif (stripos($line,'success')!==false) {
                            $type='success'; $ico='bi-check-circle-fill';        $clr='#3fb950';
                        }
                        echo '<div class="dt-log-row '.$type.'" data-type="'.$type.'" data-raw="'.htmlspecialchars($line).'">';
                        echo '<span class="dt-ln">'.str_pad($ln,4,'0',STR_PAD_LEFT).'</span>';
                        echo '<i class="bi '.$ico.' flex-shrink-0" style="color:'.$clr.';font-size:.68rem;margin-top:4px;"></i>';
                        echo '<span style="color:'.$clr.';flex:1;word-break:break-word;">'.$line.'</span>';
                        echo '</div>';
                        $ln++;
                    }
                }
                ?>
            </div>
            <div class="dt-footer">
                <div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
                    <span style="color:#484860;font-size:.78rem;"><i class="bi bi-clock me-1"></i><?= date('H:i:s') ?></span>
                    <label style="display:flex;align-items:center;gap:6px;font-size:.78rem;color:#8b949e;cursor:pointer;">
                        <input type="checkbox" id="auto-scroll-toggle" checked onchange="toggleAutoScroll(this.checked)" style="accent-color:#388bfd;">
                        <?= __('admin.auto_scroll') ?>
                    </label>
                </div>
                <div style="display:flex;gap:8px;">
                    <button class="dt-btn danger" onclick="clearLogs()"><i class="bi bi-trash"></i><?= __('admin.clear') ?></button>
                    <button class="dt-btn" onclick="downloadLogs()"><i class="bi bi-download"></i><?= __('admin.download') ?></button>
                </div>
            </div>
        </div>

                        <script>
                        let autoScrollEnabled = true;

                        document.addEventListener('DOMContentLoaded', function() {
                            const rows = document.querySelectorAll('.dt-log-row');
                            let errors = 0, warns = 0;
                            rows.forEach(r => {
                                if (r.dataset.type === 'error')   errors++;
                                if (r.dataset.type === 'warning') warns++;
                            });
                            document.getElementById('total-lines').textContent  = rows.length;
                            document.getElementById('error-lines').textContent  = errors;
                            document.getElementById('warn-lines').textContent   = warns;
                            // file size from raw log length
                            const raw = <?= json_encode(strlen($log ?? '')) ?>;
                            document.getElementById('file-size').textContent = raw >= 1024 ? (raw/1024).toFixed(1)+' KB' : raw+' B';

                            const savedScroll = localStorage.getItem('logsAutoScroll');
                            if (savedScroll !== null) {
                                autoScrollEnabled = savedScroll === 'true';
                                document.getElementById('auto-scroll-toggle').checked = autoScrollEnabled;
                            }
                            if (autoScrollEnabled) scrollLogBottom();
                        });

                        function scrollLogBottom() {
                            const c = document.getElementById('log-container');
                            if (c) c.scrollTop = c.scrollHeight;
                        }
                        function toggleAutoScroll(on) {
                            autoScrollEnabled = on;
                            localStorage.setItem('logsAutoScroll', on);
                            if (on) scrollLogBottom();
                        }
                        function filterLogs(type, btn) {
                            document.querySelectorAll('.dt-filter-btn').forEach(b => b.classList.remove('active'));
                            if (btn) btn.classList.add('active');
                            document.querySelectorAll('.dt-log-row').forEach(r => {
                                r.style.display = (type === 'all' || r.dataset.type === type) ? '' : 'none';
                            });
                            if (autoScrollEnabled) setTimeout(scrollLogBottom, 50);
                        }
                        function searchLogs(q) {
                            const lc = q.toLowerCase();
                            document.querySelectorAll('.dt-log-row').forEach(r => {
                                const raw = (r.dataset.raw || '').toLowerCase();
                                r.style.display = raw.includes(lc) ? '' : 'none';
                            });
                        }
                        function showToast(msg, type) {
                            const t = document.createElement('div');
                            t.style.cssText = 'position:fixed;top:16px;right:16px;background:#161b22;border:1px solid #30363d;color:#c9d1d9;padding:10px 18px;border-radius:8px;z-index:9999;font-size:.82rem;box-shadow:0 4px 20px rgba(0,0,0,.5);';
                            const clr = type==='error'?'#f85149':type==='success'?'#3fb950':'#58a6ff';
                            t.innerHTML = '<span style="color:'+clr+';margin-right:6px;">&#9679;</span>'+msg;
                            document.body.appendChild(t);
                            setTimeout(()=>t.remove(), 3500);
                        }
                        function clearLogs() {
                            const clearBtn = event.target.closest('button');
                            window.confirmDelete('Are you sure you want to permanently clear all log files? This action cannot be undone!', function() {
                                const orig = clearBtn.innerHTML;
                                clearBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Clearing...';
                                clearBtn.disabled = true;
                                fetch('<?= base_url("admincontrol/clear_logs") ?>', {
                                    method: 'POST',
                                    headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
                                    body: JSON.stringify({action:'clear_logs'})
                                }).then(r=>r.json()).then(data => {
                                    clearBtn.innerHTML = orig; clearBtn.disabled = false;
                                    if (data.success) {
                                        document.getElementById('log-container').innerHTML = '<div style="text-align:center;padding:60px;color:#3fb950;"><i class="bi bi-check-circle" style="font-size:2.5rem;display:block;margin-bottom:10px;"></i>Log files cleared successfully.</div>';
                                        document.getElementById('total-lines').textContent='0';
                                        document.getElementById('error-lines').textContent='0';
                                        document.getElementById('warn-lines').textContent='0';
                                        showToast('Log files cleared.','success');
                                    } else { showToast(data.message||'Failed','error'); }
                                }).catch(()=>{ clearBtn.innerHTML=orig; clearBtn.disabled=false; showToast('Request failed','error'); });
                            });
                        }
                        function downloadLogs() {
                            let c='';
                            document.querySelectorAll('.dt-log-row').forEach((r,i)=>{
                                if(r.style.display!=='none') c+=(i+1)+': '+(r.dataset.raw||'')+'\n';
                            });
                            const b=new Blob([c||'No logs available'],{type:'text/plain'});
                            const u=URL.createObjectURL(b),a=document.createElement('a');
                            a.href=u; a.download='logs-'+new Date().toISOString().slice(0,10)+'.txt';
                            document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(u);
                        }
                        </script>
                        <?php
                        break;
                    case 'dbstructure':
                        ?>
        <!-- DB STRUCTURE HERO -->
        <?php
        $totalColumns = 0;
        foreach ($dbstructure as $s) $totalColumns += count($s);
        ?>
        <div class="dt-hero" style="background:linear-gradient(135deg,#051c10 0%,#0d2b1a 60%,#051c10 100%);border:1px solid #21262d;">
            <div style="position:absolute;inset:0;border-radius:14px;overflow:hidden;pointer-events:none;">
                <div style="position:absolute;top:-30px;right:-20px;width:160px;height:160px;background:rgba(63,185,80,.05);border-radius:50%;"></div>
            </div>
            <div style="position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
                <div>
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <span style="background:#3fb950;color:#0d1117;border-radius:20px;padding:3px 12px;font-size:.78rem;font-weight:700;">
                            <i class="bi bi-database-fill me-1"></i>Database
                        </span>
                        <span style="background:rgba(255,255,255,.07);color:rgba(255,255,255,.6);border-radius:20px;padding:3px 12px;font-size:.78rem;border:1px solid rgba(255,255,255,.1);">
                            <?= date('d M Y') ?>
                        </span>
                    </div>
                    <h4 class="fw-bold text-white mb-1"><?= __('admin.database_structure') ?></h4>
                    <div style="color:rgba(255,255,255,.4);font-size:.82rem;">
                        <i class="bi bi-table me-1"></i><?= count($dbstructure) ?> tables &nbsp;&bull;&nbsp;
                        <i class="bi bi-list-columns me-1"></i><?= $totalColumns ?> total columns
                    </div>
                </div>
                <div style="flex:1;max-width:320px;">
                    <input type="text" id="dbt-search" class="dt-search" placeholder="Search tables..." oninput="filterTables(this.value)" style="width:100%;">
                </div>
            </div>
        </div>

        <!-- STATS ROW -->
        <div class="row g-3 mb-4">
            <div class="col-6 col-md-3">
                <div class="dt-stat" style="background:rgba(63,185,80,.08);border:1px solid rgba(63,185,80,.2);">
                    <div class="dt-stat-icon" style="background:rgba(63,185,80,.2);"><i class="bi bi-table" style="color:#3fb950;"></i></div>
                    <div><div class="dt-stat-val" style="color:#3fb950;"><?= count($dbstructure) ?></div><div class="dt-stat-lbl">Tables</div></div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="dt-stat" style="background:rgba(88,166,255,.08);border:1px solid rgba(88,166,255,.2);">
                    <div class="dt-stat-icon" style="background:rgba(88,166,255,.2);"><i class="bi bi-list-columns" style="color:#58a6ff;"></i></div>
                    <div><div class="dt-stat-val" style="color:#58a6ff;"><?= $totalColumns ?></div><div class="dt-stat-lbl">Total Columns</div></div>
                </div>
            </div>
            <?php
            $pkCount = 0; $noNullCount = 0;
            foreach ($dbstructure as $s) { foreach ($s as $col) { if ($col->primary_key) $pkCount++; if ($col->default === null && !$col->primary_key) $noNullCount++; } }
            ?>
            <div class="col-6 col-md-3">
                <div class="dt-stat" style="background:rgba(227,179,65,.08);border:1px solid rgba(227,179,65,.2);">
                    <div class="dt-stat-icon" style="background:rgba(227,179,65,.2);"><i class="bi bi-key-fill" style="color:#e3b341;"></i></div>
                    <div><div class="dt-stat-val" style="color:#e3b341;"><?= $pkCount ?></div><div class="dt-stat-lbl">Primary Keys</div></div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="dt-stat" style="background:rgba(188,140,255,.08);border:1px solid rgba(188,140,255,.2);">
                    <div class="dt-stat-icon" style="background:rgba(188,140,255,.2);"><i class="bi bi-ban" style="color:#bc8cff;"></i></div>
                    <div><div class="dt-stat-val" style="color:#bc8cff;"><?= $noNullCount ?></div><div class="dt-stat-lbl">NOT NULL cols</div></div>
                </div>
            </div>
        </div>

        <!-- TABLES LIST -->
        <div id="dbt-list">
        <?php
        foreach ($dbstructure as $table => $structure) {
            $has_pk = false;
            foreach ($structure as $str) { if ($str->primary_key) { $has_pk = true; break; } }
            $colCount = count($structure);
        ?>
        <div class="dbt-item" data-table="<?= strtolower($table) ?>">
            <div class="dbt-header" data-bs-toggle="collapse" data-bs-target="#dbt-<?= $table ?>" aria-expanded="false">
                <i class="bi bi-table" style="color:#3fb950;font-size:.85rem;flex-shrink:0;"></i>
                <span class="dbt-tname"><?= $table ?></span>
                <div style="display:flex;gap:6px;margin-left:auto;flex-shrink:0;">
                    <?php if ($has_pk): ?>
                    <span style="background:rgba(227,179,65,.15);color:#e3b341;border:1px solid rgba(227,179,65,.3);border-radius:4px;padding:1px 8px;font-size:.7rem;">
                        <i class="bi bi-key-fill me-1"></i>PK
                    </span>
                    <?php endif; ?>
                    <span style="background:#21262d;color:#8b949e;border:1px solid #30363d;border-radius:4px;padding:1px 8px;font-size:.7rem;">
                        <?= $colCount ?> col<?= $colCount!=1?'s':'' ?>
                    </span>
                    <i class="bi bi-chevron-down" style="color:#484860;font-size:.7rem;margin-left:4px;"></i>
                </div>
            </div>
            <div id="dbt-<?= $table ?>" class="collapse dbt-body">
                <div style="overflow-x:auto;">
                    <table>
                        <thead>
                            <tr>
                                <th style="width:30px;">#</th>
                                <th><i class="bi bi-tag me-1"></i><?= __('admin.name') ?></th>
                                <th><i class="bi bi-gear me-1"></i><?= __('admin.type') ?></th>
                                <th><i class="bi bi-rulers me-1"></i><?= __('admin.max_length') ?></th>
                                <th><i class="bi bi-file-text me-1"></i><?= __('admin.default') ?></th>
                                <th style="text-align:center;width:70px;"><i class="bi bi-key me-1"></i>PK</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php $ci = 1; foreach ($structure as $str):
                            $typeBase = strtolower(preg_replace('/\(.+/','',$str->type));
                            $isPk = $str->primary_key;
                        ?>
                            <tr style="<?= $isPk ? 'background:rgba(227,179,65,.04);' : '' ?>">
                                <td style="color:#484860;"><?= $ci++ ?></td>
                                <td style="<?= $isPk ? 'color:#e3b341;' : '' ?>">
                                    <?= $isPk ? '<i class="bi bi-key-fill me-1" style="color:#e3b341;font-size:.7rem;"></i>' : '' ?>
                                    <?= htmlspecialchars($str->name) ?>
                                </td>
                                <td><span class="type-badge type-<?= $typeBase ?>"><?= htmlspecialchars($str->type) ?></span></td>
                                <td style="color:#8b949e;"><?= $str->max_length ?: '&mdash;' ?></td>
                                <td><?= $str->default !== null ? '<code style="color:#3fb950;background:rgba(63,185,80,.08);padding:1px 6px;border-radius:3px;">'.htmlspecialchars($str->default).'</code>' : '<span style="color:#30363d;">NULL</span>' ?></td>
                                <td style="text-align:center;"><?= $isPk ? '<i class="bi bi-check-circle-fill" style="color:#3fb950;"></i>' : '<i class="bi bi-dash" style="color:#30363d;"></i>' ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php } ?>
        </div>
        <script>
        function filterTables(q) {
            const lc = q.toLowerCase();
            document.querySelectorAll('#dbt-list .dbt-item').forEach(el => {
                el.style.display = el.dataset.table.includes(lc) ? '' : 'none';
            });
        }
        </script>
            </div>
        </div>
    </div>
</div>
                        <?php
                        break;
                    case 'sysupdatereport':
                        // ── Data prep ────────────────────────────────────────
                        $upd_attempted = isset($result) && is_array($result) && !empty($result);
                        $upd_success   = true;
                        $upd_latest    = false;
                        $cnt_ok = $cnt_err = $cnt_warn = $cnt_info = 0;
                        $log_lines = [];
                        if ($upd_attempted) {
                            foreach ($result as $entry) {
                                foreach ($entry as $k => $v) {
                                    switch ($k) {
                                        case 'success': $cnt_ok++;   break;
                                        case 'error':
                                            $cnt_err++;
                                            if ($upd_success && str_contains($v, 'already a latest version')) $upd_latest = true;
                                            $upd_success = false;
                                            break;
                                        case 'warning': $cnt_warn++; break;
                                        case 'info':    $cnt_info++; break;
                                    }
                                    $log_lines[] = ['type' => $k, 'msg' => $v];
                                }
                            }
                        }
                        $total_ops  = $cnt_ok + $cnt_err + $cnt_warn + $cnt_info;
                        $log_date_str = '';
                        if (!empty($selected_file)) {
                            $p = explode('-', str_replace('.json', '', $selected_file));
                            if (is_numeric($p[0])) $log_date_str = date('d M Y, H:i', (int)$p[0]);
                        }
                        if ($upd_success) {
                            $st_lbl = 'Success';    $st_clr = '#28c840'; $st_ico = 'bi-check-circle-fill';
                        } elseif ($upd_latest) {
                            $st_lbl = 'Up to Date'; $st_clr = '#0dcaf0'; $st_ico = 'bi-info-circle-fill';
                        } else {
                            $st_lbl = 'Has Errors'; $st_clr = '#f85149'; $st_ico = 'bi-exclamation-triangle-fill';
                        }
                        ?>

        <!-- ── HERO ──────────────────────────────────────────────── -->
        <div class="mb-4 px-4 py-4" style="background:linear-gradient(135deg,#0f0c29 0%,#302b63 55%,#24243e 100%);border-radius:14px;position:relative;">
            <div style="position:absolute;inset:0;border-radius:14px;overflow:hidden;pointer-events:none;z-index:0;">
                <div style="position:absolute;top:-40px;right:-20px;width:200px;height:200px;background:rgba(255,255,255,.04);border-radius:50%;"></div>
                <div style="position:absolute;bottom:-50px;right:100px;width:130px;height:130px;background:rgba(255,255,255,.04);border-radius:50%;"></div>
            </div>
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3" style="position:relative;z-index:1;">
                <div>
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <?php if ($upd_attempted): ?>
                        <span class="fw-semibold px-3 py-1" style="background:<?= $st_clr ?>;color:#000;border-radius:20px;font-size:.8rem;">
                            <i class="bi <?= $st_ico ?> me-1"></i><?= $st_lbl ?>
                        </span>
                        <?php endif; ?>
                        <span class="fw-medium px-3 py-1" style="background:rgba(255,255,255,.1);color:rgba(255,255,255,.8);border-radius:20px;font-size:.8rem;border:1px solid rgba(255,255,255,.15);">
                            v<?= SCRIPT_VERSION ?>
                        </span>
                    </div>
                    <h4 class="fw-bold text-white mb-1" style="letter-spacing:-.3px;">System Update Console</h4>
                    <div style="color:rgba(255,255,255,.45);font-size:.82rem;">
                        <?php if ($log_date_str): ?>
                        <i class="bi bi-calendar3 me-1"></i><?= $log_date_str ?>
                        <?php endif; ?>
                        <?php if ($total_ops > 0): ?>
                        &nbsp;&middot;&nbsp;<i class="bi bi-activity me-1"></i><?= $total_ops ?> operations
                        <?php endif; ?>
                    </div>
                </div>
                <div class="dropdown">
                    <button id="log-dropdown-btn" class="btn btn-sm dropdown-toggle fw-medium" data-bs-toggle="dropdown" style="background:rgba(255,255,255,.1);color:#fff;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:8px 18px;backdrop-filter:blur(8px);">
                        <i class="bi bi-folder2-open me-2"></i><?= __('admin.log_files') ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0" style="min-width:270px;border-radius:12px;overflow:hidden;">
                        <?php if (empty($log_files)): ?>
                            <li><span class="dropdown-item text-muted small py-3 text-center"><i class="bi bi-inbox d-block mb-1" style="font-size:1.4rem;"></i>No log files</span></li>
                        <?php else: foreach ($log_files as $lf):
                            $lp    = explode('-', str_replace('.json', '', $lf));
                            $ldate = is_numeric($lp[0]) ? date('d M Y  H:i', (int)$lp[0]) : $lf;
                            $lver  = isset($lp[1]) ? str_replace('_', '.', $lp[1]) : '?';
                            $isel  = isset($selected_file) && $selected_file === $lf;
                        ?>
                        <li>
                            <a class="dropdown-item d-flex align-items-center gap-2 py-2 <?= $isel ? 'active' : '' ?>"
                               href="<?= base_url('/debug/sysupdatereport/') . str_replace('.json', '', $lf) ?>">
                                <i class="bi <?= $isel ? 'bi-record-circle-fill' : 'bi-clock-history text-muted' ?>" style="font-size:.75rem;flex-shrink:0;<?= $isel ? 'color:var(--bs-primary)' : '' ?>"></i>
                                <span class="flex-grow-1" style="font-size:.83rem;"><?= $ldate ?></span>
                                <span class="badge rounded-pill" style="background:rgba(0,0,0,.08);color:#666;font-size:.7rem;">v<?= $lver ?></span>
                            </a>
                        </li>
                        <?php endforeach; endif; ?>
                    </ul>
                </div>
            </div>
        </div>

        <?php if ($upd_attempted): ?>
        <!-- ── STATS ─────────────────────────────────────────────── -->
        <div class="row g-3 mb-4">
            <?php
            $stats = [
                [$cnt_ok,   'Completed', 'bi-check-circle-fill',        '#3fb950', 'rgba(63,185,80,.1)',   'rgba(63,185,80,.25)'],
                [$cnt_err,  'Errors',    'bi-x-circle-fill',             '#f85149', 'rgba(248,81,73,.1)',   'rgba(248,81,73,.25)'],
                [$cnt_warn, 'Warnings',  'bi-exclamation-triangle-fill', '#e3b341', 'rgba(227,179,65,.1)',  'rgba(227,179,65,.25)'],
                [$cnt_info, 'Info',      'bi-info-circle-fill',          '#58a6ff', 'rgba(88,166,255,.1)',  'rgba(88,166,255,.25)'],
            ];
            foreach ($stats as [$val, $lbl, $ico, $clr, $bg, $bdr]): ?>
            <div class="col-6 col-md-3">
                <div class="rounded-3 p-3 d-flex align-items-center gap-3 h-100" style="background:<?= $bg ?>;border:1px solid <?= $bdr ?>;">
                    <div style="width:40px;height:40px;border-radius:10px;background:<?= $bdr ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i class="bi <?= $ico ?>" style="color:<?= $clr ?>;font-size:1.1rem;"></i>
                    </div>
                    <div>
                        <div class="fw-bold lh-1 mb-1" style="font-size:1.5rem;color:<?= $clr ?>;"><?= $val ?></div>
                        <div class="text-muted" style="font-size:.78rem;"><?= $lbl ?></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- ── TERMINAL ──────────────────────────────────────────── -->
        <div class="mb-4" style="border-radius:14px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.4);border:1px solid #1e1e2e;">
            <!-- Title bar -->
            <div class="d-flex align-items-center justify-content-between px-4" style="background:#1e1e2e;height:42px;border-bottom:1px solid #2d2d3f;">
                <div class="d-flex align-items-center gap-2">
                    <span style="width:12px;height:12px;border-radius:50%;background:#ff5f57;display:inline-block;cursor:default;" title="Close"></span>
                    <span style="width:12px;height:12px;border-radius:50%;background:#febc2e;display:inline-block;cursor:default;" title="Minimize"></span>
                    <span style="width:12px;height:12px;border-radius:50%;background:#28c840;display:inline-block;cursor:default;" title="Maximize"></span>
                    <span class="ms-3" style="color:#4e4e6a;font-size:.75rem;font-family:monospace;">
                        affiliatepro — update-log<?= $log_date_str ? ' · ' . $log_date_str : '' ?>
                    </span>
                </div>
                <button onclick="scrollUpdConsole()" title="Jump to bottom" style="background:transparent;border:none;color:#4e4e6a;cursor:pointer;padding:2px 6px;border-radius:5px;font-size:.9rem;transition:color .15s;" onmouseover="this.style.color='#aaa'" onmouseout="this.style.color='#4e4e6a'">
                    <i class="bi bi-arrow-down-circle"></i>
                </button>
            </div>
            <!-- Console output -->
            <div id="upd-console" style="background:#0d1117;font-family:'Cascadia Code','Fira Code','JetBrains Mono',Consolas,monospace;font-size:.81rem;line-height:1.75;max-height:580px;overflow-y:auto;padding:16px 0;">
                <?php if (!$upd_attempted): ?>
                <div class="text-center py-5" style="color:#484860;">
                    <i class="bi bi-terminal" style="font-size:2.8rem;"></i>
                    <p class="mt-3 mb-1" style="font-size:.9rem;">No update log loaded.</p>
                    <p style="font-size:.78rem;">Select a file from the Log Files dropdown.</p>
                </div>
                <?php else:
                $ln = 1;
                foreach ($log_lines as $ll):
                    $t   = $ll['type'];
                    $msg = htmlspecialchars($ll['msg']);
                    switch ($t) {
                        case 'success': $clr='#3fb950'; $ico='bi-check-circle-fill';        $lbdr='#3fb950'; break;
                        case 'error':   $clr='#f85149'; $ico='bi-x-circle-fill';            $lbdr='#f85149'; break;
                        case 'warning': $clr='#e3b341'; $ico='bi-exclamation-circle-fill';  $lbdr='#e3b341'; break;
                        default:        $clr='#58a6ff'; $ico='bi-info-circle-fill';         $lbdr='#30363d'; break;
                    }
                    $is_sql = strlen($msg) > 90 && preg_match('/\b(CREATE|ALTER|INSERT|UPDATE|DROP|SET)\b/i', $msg);
                    $row_bg = $ln % 2 === 0 ? 'rgba(255,255,255,.014)' : 'transparent';
                ?>
                <div class="upd-line d-flex align-items-start gap-2 px-3 py-1" style="background:<?= $row_bg ?>;border-left:2px solid <?= $lbdr ?>44;">
                    <span style="color:#30363d;font-size:.7rem;min-width:30px;text-align:right;padding-top:3px;user-select:none;flex-shrink:0;"><?= str_pad($ln, 3, '0', STR_PAD_LEFT) ?></span>
                    <i class="bi <?= $ico ?> mt-1 flex-shrink-0" style="color:<?= $clr ?>;font-size:.68rem;"></i>
                    <?php if ($is_sql): ?>
                    <details class="flex-grow-1" style="color:#c9d1d9;">
                        <summary style="cursor:pointer;list-style:none;outline:none;color:<?= $clr ?>;">
                            <span style="color:#484860;font-size:.72rem;">[SQL]&nbsp;</span><?= mb_substr($msg, 0, 90) ?>…
                        </summary>
                        <div style="margin-top:6px;padding:10px 12px;background:rgba(255,255,255,.04);border-radius:6px;word-break:break-all;color:#8b949e;"><?= $msg ?></div>
                    </details>
                    <?php else: ?>
                    <span class="flex-grow-1" style="color:<?= $clr ?>;word-break:break-word;"><?= $msg ?></span>
                    <?php endif; ?>
                </div>
                <?php $ln++; endforeach; endif; ?>
            </div>
        </div>

        <!-- ── STATUS FOOTER ─────────────────────────────────────── -->
        <?php if ($upd_attempted):
            $ft_bg = $upd_success ? 'linear-gradient(135deg,#0d2818,#122b1e)' : ($upd_latest ? 'linear-gradient(135deg,#0d1f33,#112840)' : 'linear-gradient(135deg,#2d0a0a,#3a1010)');
        ?>
        <div class="rounded-3 p-4 mb-4 d-flex flex-wrap align-items-center justify-content-between gap-3" style="background:<?= $ft_bg ?>;border:1px solid <?= $st_clr ?>33;">
            <div class="d-flex align-items-center gap-3">
                <div style="width:44px;height:44px;border-radius:50%;background:<?= $st_clr ?>1a;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:1px solid <?= $st_clr ?>44;">
                    <i class="bi <?= $st_ico ?>" style="color:<?= $st_clr ?>;font-size:1.3rem;"></i>
                </div>
                <div>
                    <div class="fw-semibold text-white" style="font-size:.95rem;">
                        <?= $upd_success ? 'Update Completed Successfully' : ($upd_latest ? 'System Already Up-to-Date' : 'Update Completed with Issues') ?>
                    </div>
                    <div style="color:rgba(255,255,255,.4);font-size:.78rem;">Running version <?= SCRIPT_VERSION ?></div>
                </div>
            </div>
            <div class="d-flex gap-2">
                <button onclick="downloadUpdLog()" class="btn btn-sm fw-medium" style="background:rgba(255,255,255,.08);color:rgba(255,255,255,.8);border:1px solid rgba(255,255,255,.18);border-radius:8px;">
                    <i class="bi bi-download me-1"></i>Download Log
                </button>
                <a href="<?= base_url('admincontrol/dashboard') ?>" class="btn btn-sm fw-medium" style="background:rgba(255,255,255,.13);color:#fff;border:1px solid rgba(255,255,255,.25);border-radius:8px;">
                    <i class="bi bi-grid me-1"></i>Dashboard
                </a>
            </div>
        </div>
        <?php endif; ?>

        </div></div>

                        <?php
                        break;
                    default:
                        ?>
<span class="badge bg-warning w-100 fs-4 d-block mt-3">
Something went wrong, please try again!
</span>
                        <?php
                        break;
                }
            ?>
            <?php } ?>
        </div>
    </div>
</div>

    <!--bootstrap 5 js files-->
     <script src="<?= base_url('assets/template/js/jquery-3.6.0.min.js'); ?>"></script>
     <script src="<?= base_url('assets/template/js/bootstrap.bundle.min.js'); ?>"></script>
    <!--bootstrap 5 js files-->

    <!-- Global Delete Confirmation Modal (standalone debug page - no admin footer) -->
    <div class="modal fade" id="globalDeleteConfirm" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-danger text-white border-0">
                    <h6 class="modal-title"><i class="bi bi-exclamation-triangle me-2"></i><?= __('admin.confirm_delete') ?? 'Confirm Delete' ?></h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center py-4">
                    <p class="mb-0" id="globalDeleteMessage"><?= __('admin.are_you_sure_delete') ?? 'Are you sure you want to delete this item?' ?></p>
                </div>
                <div class="modal-footer border-0 justify-content-center">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal"><?= __('admin.cancel') ?? 'Cancel' ?></button>
                    <button type="button" class="btn btn-danger btn-sm" id="globalDeleteConfirmBtn"><i class="bi bi-trash me-1"></i><?= __('admin.delete') ?? 'Delete' ?></button>
                </div>
            </div>
        </div>
    </div>
    <script>
    window.confirmDelete = function(message, callback) {
        if (message) $('#globalDeleteMessage').text(message);
        var modal = new bootstrap.Modal(document.getElementById('globalDeleteConfirm'));
        $('#globalDeleteConfirmBtn').off('click').on('click', function() {
            modal.hide();
            if (typeof callback === 'function') callback();
        });
        modal.show();
    };
    </script>

    <?php if($dtype=="sysupdatereport") { ?>
<script>
function scrollUpdConsole() {
    var c = document.getElementById('upd-console');
    if (c) c.scrollTop = c.scrollHeight;
}

function downloadUpdLog() {
    var lines = document.querySelectorAll('#upd-console .upd-line');
    var text  = 'AffiliatePro Update Log  v<?= SCRIPT_VERSION ?>\n';
    text += '='.repeat(60) + '\n';
    lines.forEach(function(row, i) {
        var span = row.querySelector('span.flex-grow-1');
        var det  = row.querySelector('details');
        var msg  = span ? span.textContent.trim() : (det ? det.textContent.replace(/\s+/g,' ').trim() : '');
        var type = row.className.match(/\b(success|error|warning|info)\b/);
        text += (i+1) + '  [' + (type ? type[1].toUpperCase() : 'INFO').padEnd(7) + ']  ' + msg + '\n';
    });
    var a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([text], {type:'text/plain'}));
    a.download = 'update-log-v<?= SCRIPT_VERSION ?>-' + Date.now() + '.txt';
    a.click();
}

document.addEventListener('DOMContentLoaded', function() {
    // Scroll terminal to bottom on load
    scrollUpdConsole();

    // Auto-navigate to the first (latest) log file on first visit
    if (sessionStorage.getItem('autoSelectedLastItem') !== 'true') {
        var menu = document.querySelector('#log-dropdown-btn + .dropdown-menu');
        if (menu) {
            var first = menu.querySelector('a.dropdown-item:not([class*="text-muted"])');
            if (first) {
                var url = first.getAttribute('href');
                var btn = document.getElementById('log-dropdown-btn');
                var dateSpan = first.querySelector('span.flex-grow-1');
                if (btn && dateSpan) {
                    btn.innerHTML = '<i class="bi bi-folder2-open me-2"></i>' + dateSpan.textContent.trim();
                }
                sessionStorage.setItem('autoSelectedLastItem', 'true');
                if (url) { window.location.href = url; }
            }
        }
    } else {
        // Highlight the active dropdown item label on the button
        var activeItem = document.querySelector('#log-dropdown-btn + .dropdown-menu a.active');
        if (activeItem) {
            var btn = document.getElementById('log-dropdown-btn');
            var dateSpan = activeItem.querySelector('span.flex-grow-1');
            if (btn && dateSpan) {
                btn.innerHTML = '<i class="bi bi-folder2-open me-2"></i>' + dateSpan.textContent.trim();
            }
        }
        sessionStorage.setItem('autoSelectedLastItem', 'false');
    }
});
</script>
    <?php } ?>
        </div><!-- col-12 -->
    </div><!-- row -->
    </div><!-- padding wrapper -->
</div><!-- min-height wrapper -->
  </body>
</html>