<?php
use App\Core\View;
$initial = '';
if (!empty($user['full_name'])) {
    $initial = mb_substr(trim($user['full_name']), 0, 1);
}
$avatarUrl = (!empty($user['avatar'])) ? '/public/uploads/avatars/' . htmlspecialchars($user['avatar']) : '';

$notifCount = 0;
$notifItems = [];
if (!empty($user['id'])) {
    try {
        $pdo = \App\Core\Database::pdo();
        $stmt = $pdo->prepare("SELECT id, type, title, message, link, is_read, created_at FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
        $stmt->execute([(int)$user['id']]);
        $notifItems = $stmt->fetchAll();
        $cntStmt = $pdo->prepare("SELECT COUNT(*) AS c FROM notifications WHERE user_id = ? AND is_read = 0");
        $cntStmt->execute([(int)$user['id']]);
        $notifCount = (int)($cntStmt->fetch()['c'] ?? 0);
    } catch (\Throwable $e) {}
}
?>

<?php if (!empty($pageHelp)): ?>
<style>
.page-help-pill {
    display: inline-flex; align-items: center; gap: 5px;
    background: linear-gradient(135deg,#4f46e5,#7c3aed); color:#fff !important;
    border: none; border-radius: 20px; padding: 4px 12px 4px 10px;
    font-size: 12.5px; font-weight: 700; font-family: inherit;
    cursor: pointer; box-shadow: 0 2px 8px rgba(79,70,229,.35);
    transition: opacity .15s, transform .15s; white-space: nowrap; line-height: 1;
}
.page-help-pill:hover { opacity: .88; transform: translateY(-1px); }
.page-help-pill i { font-size: 13px; }

/* ════ HELP MODAL — LIGHT MODE ════ */
#pageHelpModal .modal-content { background:#fff; border:none; border-radius:16px; overflow:hidden; }
#pageHelpModal .modal-body    { background:#fff; }
#pageHelpModal .modal-footer  { background:#fff; border-top:1px solid #e9ecef; }
#pageHelpModal .phm-section {
    background:#fff; border:1.5px solid #e2e8f0; border-radius:12px; height:100%; padding:16px;
}
#pageHelpModal .phm-section-title { font-size:14px; font-weight:700; color:#0f172a; }
#pageHelpModal .phm-section ul { font-size:13.5px; color:#475569; line-height:1.9; margin:0; padding-right:18px; padding-left:0; }
#pageHelpModal .phm-section p  { font-size:13.5px; color:#475569; line-height:1.85; margin:0; }
#pageHelpModal .phm-icon-badge {
    width:32px; height:32px; border-radius:8px;
    display:inline-flex; align-items:center; justify-content:center; flex-shrink:0; font-size:14px;
}
#pageHelpModal .phm-intro {
    background:#eef2ff; color:#3730a3; border:1px solid #c7d2fe;
    border-radius:10px; padding:12px 16px; font-size:13.5px; margin-bottom:16px;
}
#pageHelpModal .phm-tips {
    background:#fffbeb; border:1px solid #fde68a; border-radius:10px; padding:14px 16px; margin-top:12px;
}
#pageHelpModal .phm-tips-title { color:#92400e; font-weight:700; margin-bottom:8px; }
#pageHelpModal .phm-tips ul { font-size:13.5px; color:#78350f; line-height:1.9; margin:0; padding-right:18px; padding-left:0; }
#pageHelpModal .btn-phm-close { background:#e2e8f0; color:#334155; border:none; border-radius:10px; font-weight:600; padding:8px 20px; }
#pageHelpModal .btn-phm-close:hover { background:#cbd5e1; }

/* ════ HELP MODAL — DARK MODE ════ */
[data-theme="dark"] #pageHelpModal .modal-content { background:#16213e; }
[data-theme="dark"] #pageHelpModal .modal-body    { background:#16213e; }
[data-theme="dark"] #pageHelpModal .modal-footer  { background:#16213e; border-top-color:#1e3a5f; }
[data-theme="dark"] #pageHelpModal .phm-section   { background:#1e2d4a; border-color:#2d4a72; }
[data-theme="dark"] #pageHelpModal .phm-section-title { color:#e2e8f0; }
[data-theme="dark"] #pageHelpModal .phm-section ul    { color:#94a3b8; }
[data-theme="dark"] #pageHelpModal .phm-section p     { color:#94a3b8; }
[data-theme="dark"] #pageHelpModal .phm-intro   { background:#1e3459; color:#93c5fd; border-color:#2563eb; }
[data-theme="dark"] #pageHelpModal .phm-tips    { background:#2d1f04; border-color:#78350f; }
[data-theme="dark"] #pageHelpModal .phm-tips-title { color:#fbbf24; }
[data-theme="dark"] #pageHelpModal .phm-tips ul    { color:#fcd34d; }
[data-theme="dark"] #pageHelpModal .btn-phm-close  { background:#1e3a5f; color:#cbd5e1; }
[data-theme="dark"] #pageHelpModal .btn-phm-close:hover { background:#254d80; }
</style>
<?php endif; ?>

<header class="app-topbar">
    <div class="d-flex align-items-center gap-2">
        <button type="button" class="menu-toggle" aria-label="منو"><i class="bi bi-list"></i></button>
        <h1 class="topbar-title"><?= View::e($title ?? '') ?></h1>
        <?php if (!empty($pageHelp)): ?>
        <button type="button" class="page-help-pill" data-bs-toggle="modal" data-bs-target="#pageHelpModal" title="راهنمای این صفحه">
            <i class="bi bi-question-circle-fill"></i> راهنما
        </button>
        <?php endif; ?>
    </div>
    <div class="d-flex align-items-center gap-3">
        <button type="button" class="btn theme-toggle-btn" id="themeToggleBtn" aria-label="تغییر تم" title="تغییر تم">
            <i class="bi bi-moon-stars-fill theme-toggle-icon"></i>
        </button>
        <?php if (!empty($user)): ?>
        <div class="dropdown notif-dropdown">
            <button class="btn notif-bell p-0" type="button" data-bs-toggle="dropdown" aria-expanded="false" id="notifBtn" title="اعلان‌ها">
                <i class="bi bi-bell-fill"></i>
                <?php if ($notifCount > 0): ?>
                <span class="notif-badge"><?= $notifCount > 9 ? '9+' : $notifCount ?></span>
                <?php endif; ?>
            </button>
            <div class="dropdown-menu dropdown-menu-start notif-menu" style="min-width:320px;max-height:420px;overflow-y:auto;">
                <div class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom">
                    <span class="fw-bold small notif-menu-title"><i class="bi bi-bell-fill me-2"></i>اعلان‌ها</span>
                    <?php if ($notifItems): ?>
                    <a href="/notifications/mark-all-read" class="small text-muted text-decoration-none notif-mark-all">همه را خوانده‌ام</a>
                    <?php endif; ?>
                </div>
                <?php if (!$notifItems): ?>
                    <div class="text-center text-muted py-4 small notif-empty-state"><i class="bi bi-bell-slash d-block fs-3 mb-2"></i>اعلانی وجود ندارد</div>
                <?php else: ?>
                    <div id="notifList">
                    <?php foreach ($notifItems as $n): ?>
                    <a href="<?= $n['link'] ?: '#' ?>" class="notif-item <?= $n['is_read'] ? '' : 'unread' ?>" data-id="<?= (int)$n['id'] ?>">
                        <div class="notif-icon <?= htmlspecialchars($n['type']) ?>">
                            <i class="bi bi-<?= $n['type'] === 'ticket' ? 'chat-left-text-fill' : ($n['type'] === 'payment' ? 'credit-card-fill' : 'info-circle-fill') ?>"></i>
                        </div>
                        <div class="notif-body">
                            <div class="notif-title"><?= View::e($n['title']) ?></div>
                            <div class="notif-msg"><?= View::e(mb_substr($n['message'] ?? '', 0, 60)) ?><?= mb_strlen($n['message'] ?? '') > 60 ? '...' : '' ?></div>
                            <div class="notif-time"><?= \App\Helpers\JalaliDate::fromDb($n['created_at'], 'Y/m/d') ?></div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                    </div>
                    <div class="text-center text-muted py-4 small notif-empty-state d-none"><i class="bi bi-bell-slash d-block fs-3 mb-2"></i>اعلانی وجود ندارد</div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
        <div class="topbar-user dropdown">
            <?php if (!empty($user)): ?>
                <button class="btn p-0 d-flex align-items-center gap-2" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <?php if ($avatarUrl): ?>
                        <img src="<?= $avatarUrl ?>" class="topbar-avatar-img" alt="avatar">
                    <?php else: ?>
                        <span class="topbar-avatar"><?= View::e($initial) ?></span>
                    <?php endif; ?>
                    <div class="text-end d-none d-sm-block">
                        <div class="topbar-name"><?= View::e($user['full_name']) ?></div>
                        <span class="topbar-role badge bg-<?= ($user['role'] ?? '') === 'admin' ? 'primary' : 'secondary' ?>">
                            <?= ($user['role'] ?? '') === 'admin' ? 'مدیر' : 'کاربر' ?>
                        </span>
                    </div>
                    <i class="bi bi-chevron-down text-muted small"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-start">
                    <?php if (($user['role'] ?? '') === 'admin'): ?>
                        <li><a class="dropdown-item" href="/admin/account"><i class="bi bi-person-circle"></i> پروفایل و رمز عبور</a></li>
                        <li><a class="dropdown-item" href="/admin"><i class="bi bi-shield-lock"></i> پنل مدیریت</a></li>
                    <?php else: ?>
                        <li><a class="dropdown-item" href="/account"><i class="bi bi-person-circle"></i> پروفایل و رمز عبور</a></li>
                    <?php endif; ?>
                    <li><a class="dropdown-item" href="/dashboard"><i class="bi bi-house"></i> پنل کاربری</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li>
                        <form action="/logout" method="post" class="px-2">
                            <input type="hidden" name="_csrf" value="<?= View::e($csrf) ?>">
                            <button type="submit" class="dropdown-item text-danger"><i class="bi bi-box-arrow-right"></i> خروج از حساب</button>
                        </form>
                    </li>
                </ul>
            <?php endif; ?>
        </div>
    </div>
</header>

<script>
(function () {
    function post(url) {
        var csrf = document.querySelector('meta[name="csrf-token"]');
        return fetch(url, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest','X-CSRF-Token': csrf ? csrf.getAttribute('content') : ''}});
    }
    function refreshBadge() {
        var unread = document.querySelectorAll('.notif-item.unread').length;
        var badge = document.querySelector('.notif-badge');
        if (unread > 0) {
            if (!badge) { var btn = document.getElementById('notifBtn'); if (btn) { badge = document.createElement('span'); badge.className = 'notif-badge'; btn.appendChild(badge); } }
            if (badge) badge.textContent = unread > 9 ? '9+' : unread;
        } else if (badge) { badge.remove(); }
    }
    document.querySelectorAll('.notif-mark-all').forEach(function (el) {
        el.addEventListener('click', function (e) {
            e.preventDefault();
            post('/notifications/mark-all-read').then(function () {
                var notifList = document.getElementById('notifList');
                if (notifList) notifList.remove();
                document.querySelectorAll('.notif-empty-state').forEach(function (s) { s.classList.remove('d-none'); });
                el.style.display = 'none';
                var badge = document.querySelector('.notif-badge');
                if (badge) badge.remove();
            });
        });
    });
    document.querySelectorAll('.notif-item').forEach(function (el) {
        el.addEventListener('click', function (e) {
            var id = el.getAttribute('data-id');
            var href = el.getAttribute('href');
            if (!id) return;
            if (el.classList.contains('unread')) {
                e.preventDefault(); el.classList.remove('unread'); refreshBadge();
                post('/notifications/read/' + id).finally(function () { if (href && href !== '#') window.location.href = href; });
            }
        });
    });
    var pd = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    document.querySelectorAll('.notif-msg').forEach(function (el) { el.textContent = el.textContent.replace(/[0-9]/g, function (d) { return pd[d]; }); });
})();
</script>

<?php if (!empty($pageHelp)): ?>
<div class="modal fade" id="pageHelpModal" tabindex="-1" aria-labelledby="pageHelpModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
    <div class="modal-content">
      <div class="modal-header border-0 p-0">
        <div class="w-100 d-flex align-items-center justify-content-between px-4 py-3" style="background:linear-gradient(135deg,#4338ca,#6d28d9)">
          <div class="d-flex align-items-center gap-3">
            <div style="width:40px;height:40px;background:rgba(255,255,255,.18);border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
              <i class="bi bi-question-circle-fill text-white" style="font-size:18px"></i>
            </div>
            <div>
              <h5 class="mb-0 fw-bold text-white" id="pageHelpModalLabel"><?= View::e($pageHelp['title'] ?? 'راهنمای صفحه') ?></h5>
              <?php if (!empty($pageHelp['subtitle'])): ?>
              <div class="small text-white mt-1" style="opacity:.8"><?= View::e($pageHelp['subtitle']) ?></div>
              <?php endif; ?>
            </div>
          </div>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="بستن"></button>
        </div>
      </div>
      <div class="modal-body p-4">
        <?php if (!empty($pageHelp['intro'])): ?>
        <div class="phm-intro"><i class="bi bi-info-circle-fill me-2"></i><?= $pageHelp['intro'] ?></div>
        <?php endif; ?>
        <?php if (!empty($pageHelp['sections'])): ?>
        <div class="row g-3">
          <?php foreach ($pageHelp['sections'] as $sec): ?>
          <div class="col-md-<?= $sec['cols'] ?? 6 ?>">
            <div class="phm-section">
              <div class="d-flex align-items-center gap-2 mb-2">
                <span class="phm-icon-badge" style="background:<?= $sec['iconBg'] ?? '#e0e7ff' ?>">
                  <i class="bi bi-<?= $sec['icon'] ?? 'info-circle' ?>" style="color:<?= $sec['iconColor'] ?? '#4f46e5' ?>"></i>
                </span>
                <span class="phm-section-title"><?= View::e($sec['title']) ?></span>
              </div>
              <?php if (!empty($sec['items'])): ?>
              <ul><?php foreach ($sec['items'] as $item): ?><li><?= $item ?></li><?php endforeach; ?></ul>
              <?php elseif (!empty($sec['text'])): ?>
              <p><?= $sec['text'] ?></p>
              <?php endif; ?>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <?php if (!empty($pageHelp['tips'])): ?>
        <div class="phm-tips">
          <div class="phm-tips-title"><i class="bi bi-lightbulb-fill me-2" style="color:#f59e0b"></i>نکات مفید</div>
          <ul><?php foreach ($pageHelp['tips'] as $tip): ?><li><?= $tip ?></li><?php endforeach; ?></ul>
        </div>
        <?php endif; ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-phm-close" data-bs-dismiss="modal">بستن</button>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>
