<?php
$cur = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$isActive = function($s) use ($cur) {
    return (strpos($cur, '/admin/'.$s) !== false) ? 'active' : '';
};
$adminUser = (new \App\Core\Session())->get('admin_user');
$adminName = htmlspecialchars($adminUser['name'] ?? 'Admin');
?>
<!DOCTYPE html>
<html lang="tr" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title><?php echo htmlspecialchars(isset($title) ? $title : 'Yönetim Paneli'); ?></title>
    <meta name="robots" content="noindex,nofollow">
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚙️</text></svg>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="<?php echo $baseUrl; ?>/assets/css/admin.css?v=20260709">

    <!-- Inline theme apply BEFORE render to prevent flash -->
    <script>
    (function(){
        var t = localStorage.getItem('admin_theme') || 'dark';
        document.documentElement.setAttribute('data-theme', t);
    })();

    /* ══════════════════════════════════════════
       AUTO SEARCH (AJAX Live Search)
    ══════════════════════════════════════════ */
    function initAutoSearch(inputId, formId, delay) {
        delay = delay || 450;
        
        // Wait for DOM if it's called before elements exist
        document.addEventListener('DOMContentLoaded', function() {
            var input = document.getElementById(inputId);
            var form  = document.getElementById(formId);
            if (!input || !form) return;
            var timer;
            var icon = form.querySelector('.search-icon');
            
            input.addEventListener('input', function() {
                clearTimeout(timer);
                timer = setTimeout(function() { 
                    if(icon) icon.className = 'fa fa-spinner fa-spin search-icon';
                    
                    var url = new URL(form.action || window.location.href, window.location.origin);
                    var params = new URLSearchParams(new FormData(form));
                    for(var pair of Array.from(params.entries())) {
                        if(pair[1] === '') params.delete(pair[0]);
                    }
                    url.search = params.toString();
                    
                    window.history.replaceState({}, '', url);

                    fetch(url)
                    .then(res => res.text())
                    .then(html => {
                        var doc = new DOMParser().parseFromString(html, 'text/html');
                        var newCard = doc.querySelector('.admin-card');
                        var oldCard = document.querySelector('.admin-card');
                        if(newCard && oldCard) {
                            oldCard.innerHTML = newCard.innerHTML;
                        }
                        
                        var newPag = doc.querySelector('.pagination');
                        var oldPag = document.querySelector('.pagination');
                        if(newPag && oldPag && newPag.parentNode !== newCard) {
                            oldPag.parentNode.replaceChild(newPag, oldPag);
                        }
                        
                        if(icon) icon.className = 'fa fa-search search-icon';
                    })
                    .catch(() => {
                        if(icon) icon.className = 'fa fa-search search-icon';
                    });
                }, delay);
            });
            
            form.addEventListener('submit', function(e) { e.preventDefault(); });
        });
    }

    /* ══════════════════════════════════════════
       PROFILE DROPDOWN TOGGLE
    ══════════════════════════════════════════ */
    function toggleAdminMenu(e) {
        if (e) e.stopPropagation();
        var menu = document.getElementById('adminDropdownMenu');
        if (!menu) return;
        menu.classList.toggle('show');
    }
    document.addEventListener('DOMContentLoaded', function() {
        document.addEventListener('click', function(e) {
            var wrap = document.querySelector('.admin-profile-wrap');
            var menu = document.getElementById('adminDropdownMenu');
            if (wrap && menu && !wrap.contains(e.target)) {
                menu.classList.remove('show');
            }
        });
    });
    </script>
</head>
<body class="admin-body">

<!-- ─── Sidebar Overlay (mobile) ─── -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<!-- ─── Toast Container ─── -->
<div id="toast-container"></div>

<div class="admin-layout">

    <!-- ─── SIDEBAR ─── -->
    <aside class="admin-sidebar" id="adminSidebar">

        <div class="sidebar-brand">
            <div class="sidebar-logo">
                <i class="fa fa-cogs"></i>
            </div>
            <span class="sidebar-brand-text">Everest</span>
            <span class="sidebar-brand-badge">admin</span>
        </div>

        <div class="sidebar-scroll">

            <div class="nav-label">Ana Menü</div>
            <nav class="admin-nav">
                <a href="<?php echo $baseUrl; ?>/admin/dashboard"
                   class="admin-nav-item <?php echo $isActive('dashboard'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-dashboard"></i> Panel
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/products"
                   class="admin-nav-item <?php echo $isActive('products'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-print"></i> Ürünler
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/categories"
                   class="admin-nav-item <?php echo $isActive('categories'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-tags"></i> Kategoriler
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/brands"
                   class="admin-nav-item <?php echo $isActive('brands'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-bookmark"></i> Markalar
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/orders"
                   class="admin-nav-item <?php echo $isActive('orders'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-shopping-cart"></i> Siparişler
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/users"
                   class="admin-nav-item <?php echo $isActive('users'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-users"></i> Kullanıcılar
                </a>
            </nav>

             <div class="nav-label">Sistem</div>
            <nav class="admin-nav">
                <a href="<?php echo $baseUrl; ?>/admin/settings"
                   class="admin-nav-item <?php echo $isActive('settings'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-sliders"></i> Ayarlar
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/theme"
                   class="admin-nav-item <?php echo $isActive('theme'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-paint-brush"></i> Tema
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/pages"
                   class="admin-nav-item <?php echo $isActive('pages'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-file-text"></i> Sayfalar
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/database"
                   class="admin-nav-item <?php echo $isActive('database'); ?>"
                   onclick="closeSidebar()">
                    <i class="fa fa-database"></i> Veritabanı
                </a>
                <a href="<?php echo $baseUrl; ?>/cozummerkezi/admin/dashboard"
                   class="admin-nav-item"
                   onclick="closeSidebar()">
                    <i class="fa fa-wrench"></i> Çözüm Merkezi
                </a>
            </nav>

        </div><!-- /.sidebar-scroll -->

        <div class="sidebar-footer">
            <nav class="admin-nav">
                <a href="<?php echo $baseUrl; ?>/" target="_blank"
                   class="admin-nav-item">
                    <i class="fa fa-external-link"></i> Siteyi Görüntüle
                </a>
                <a href="<?php echo $baseUrl; ?>/admin/logout"
                   class="admin-nav-item danger">
                    <i class="fa fa-sign-out"></i> Çıkış Yap
                </a>
            </nav>
        </div>

    </aside><!-- /.admin-sidebar -->

    <!-- ─── MAIN ─── -->
    <main class="admin-main">

        <!-- ─── TOP HEADER ─── -->
        <header class="admin-header" id="adminHeader">

            <!-- Hamburger (mobile only, shown via CSS) -->
            <button class="sidebar-toggle-btn" id="sidebarToggle" aria-label="Menüyü Aç/Kapat">
                <i class="fa fa-bars"></i>
            </button>

            <!-- Page title -->
            <span class="admin-page-title">
                <?php echo htmlspecialchars(isset($title) ? $title : 'Yönetim Paneli'); ?>
            </span>

            <!-- Spacer -->
            <div class="header-spacer"></div>

            <!-- Actions -->
            <div class="admin-header-actions">
                <!-- Theme Toggle -->
                <button class="h-btn" id="themeToggleBtn" aria-label="Temayı Değiştir" title="Temayı Değiştir">
                    <i class="fa fa-moon-o" id="themeIcon"></i>
                </button>

                <!-- Profile Dropdown -->
                <div class="admin-profile-wrap">
                    <div class="admin-profile" onclick="toggleAdminMenu(event)">
                        <div class="admin-profile-avatar" style="border-radius:50%; width:32px; height:32px; overflow:hidden;">
                            <?php if (!empty($adminUser['avatar'])): ?>
                                <img src="<?php echo htmlspecialchars($adminUser['avatar']); ?>" alt="" referrerpolicy="no-referrer" style="width:100%;height:100%;object-fit:cover;border-radius:50%;display:block;">
                            <?php else: ?>
                                <i class="fa fa-user" style="font-size: 14px; color: #fff;"></i>
                            <?php endif; ?>
                        </div>
                        <span><?php echo $adminName; ?></span>
                        <i class="fa fa-caret-down" style="font-size:10px;color:var(--text-3);margin-left:2px;"></i>
                    </div>
                    <div class="admin-dropdown-menu" id="adminDropdownMenu">
                        <a href="<?php echo $baseUrl; ?>/" target="_blank" class="admin-dropdown-item"><i class="fa fa-external-link"></i> Siteyi Görüntüle</a>
                        <a href="<?php echo $baseUrl; ?>/profile" class="admin-dropdown-item"><i class="fa fa-user-circle"></i> Profilim</a>
                        <div class="admin-dropdown-divider"></div>
                        <a href="<?php echo $baseUrl; ?>/admin/logout" class="admin-dropdown-item" style="color:var(--danger);"><i class="fa fa-sign-out"></i> Çıkış Yap</a>
                    </div>
                </div>
            </div>

        </header><!-- /.admin-header -->

        <!-- ─── PAGE CONTENT ─── -->
        <div class="admin-content">