<?php
require_once __DIR__ . '/db.php';
require_login(); // Wymaga bycia zalogowanym (dowolna rola)

$user = current_user();
$db = get_db();

$profileMsg = '';
$profileError = '';

// Obsługa aktualizacji profilu (Discord Tag / Hasło)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_profile') {
        $newDiscord = trim($_POST['discord_tag'] ?? '');
        $oldPass    = $_POST['old_password'] ?? '';
        $newPass    = $_POST['new_password'] ?? '';

        try {
            // Aktualizacja tagu discord
            $stmt = $db->prepare("UPDATE users SET discord_tag = ? WHERE id = ?");
            $stmt->execute([$newDiscord, $user['id']]);
            $_SESSION['discord_tag'] = $newDiscord;
            $user['discord_tag'] = $newDiscord;
            $profileMsg = 'Dane profilu zostały zaktualizowane.';

            // Jeśli użytkownik chce zmienić hasło
            if (!empty($newPass)) {
                if (strlen($newPass) < 6) {
                    $profileError = 'Nowe hasło musi mieć co najmniej 6 znaków.';
                } else {
                    // Sprawdzamy stare hasło
                    $stmtUser = $db->prepare("SELECT password FROM users WHERE id = ?");
                    $stmtUser->execute([$user['id']]);
                    $currHash = $stmtUser->fetchColumn();

                    if (password_verify($oldPass, $currHash) || $currHash === $oldPass) {
                        $newHash = password_hash($newPass, PASSWORD_BCRYPT);
                        $stmtUpd = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                        $stmtUpd->execute([$newHash, $user['id']]);
                        $profileMsg = 'Profil oraz hasło zostały pomyślnie zaktualizowane!';
                    } else {
                        $profileError = 'Podane dotychczasowe hasło jest nieprawidłowe.';
                    }
                }
            }
        } catch (Exception $e) {
            $profileError = 'Błąd aktualizacji: ' . $e->getMessage();
        }
    }
    // 2. Akceptacja wyceny i złożenie zamówienia na projekt custom
    elseif ($_POST['action'] === 'order_custom_quote') {
        $quoteId = (int)($_POST['quote_id'] ?? 0);
        $paymentMethod = trim($_POST['payment_method'] ?? 'BLIK');
        $customerNotes = trim($_POST['customer_notes'] ?? '');

        if ($quoteId <= 0) {
            $profileError = 'Nieprawidłowy identyfikator wyceny.';
        } else {
            try {
                // Sprawdzamy czy wycena należy do klienta (lub admina/właściciela)
                if (is_admin() || is_owner()) {
                    $stmtQ = $db->prepare("SELECT * FROM quotes WHERE id = ?");
                    $stmtQ->execute([$quoteId]);
                } else {
                    $uDiscord = trim($user['discord_tag'] ?? '');
                    if ($uDiscord !== '') {
                        $stmtQ = $db->prepare("SELECT * FROM quotes WHERE id = ? AND (user_id = ? OR LOWER(TRIM(discord_tag)) = LOWER(TRIM(?)))");
                        $stmtQ->execute([$quoteId, $user['id'], $uDiscord]);
                    } else {
                        $stmtQ = $db->prepare("SELECT * FROM quotes WHERE id = ? AND user_id = ?");
                        $stmtQ->execute([$quoteId, $user['id']]);
                    }
                }
                $qData = $stmtQ->fetch();

                if (!$qData) {
                    $profileError = 'Nie znaleziono takiego zapytania o wycenę.';
                } elseif (!isset($qData['quoted_price']) || (float)$qData['quoted_price'] <= 0) {
                    $profileError = 'To zgłoszenie nie zostało jeszcze oficjalnie wycenione przez Administratora.';
                } else {
                    $price = (float)$qData['quoted_price'];
                    $orderNum = 'HS-CUST-' . mt_rand(1000, 9999);
                    $discord = !empty($user['discord_tag']) ? $user['discord_tag'] : $qData['discord_tag'];
                    $email = !empty($user['email']) ? $user['email'] : '';

                    $items = [
                        [
                            'id'    => 'custom-' . $qData['id'],
                            'title' => 'Projekt Custom: ' . $qData['project_type'],
                            'price' => $price,
                            'qty'   => 1,
                            'tag'   => 'Zlecenie Custom'
                        ]
                    ];
                    $itemsJson = json_encode($items, JSON_UNESCAPED_UNICODE);
                    $fullNotes = "Zlecenie wyceny #" . $qData['id'] . " (" . $qData['project_type'] . ")." . (!empty($customerNotes) ? " Uwaga klienta: " . $customerNotes : "");

                    // Wstawienie do bazy zamówień
                    $stmtIns = $db->prepare("
                        INSERT INTO orders (order_number, user_id, customer_discord, customer_email, payment_method, promo_code, items_json, total_amount, status, is_paid, notes, created_at)
                        VALUES (?, ?, ?, ?, ?, '', ?, ?, 'Oczekujące', 0, ?, NOW())
                    ");
                    $stmtIns->execute([
                        $orderNum,
                        $user['id'],
                        $discord,
                        $email,
                        $paymentMethod,
                        $itemsJson,
                        $price,
                        $fullNotes
                    ]);
                    $newOrderId = (int)$db->lastInsertId();

                    // Usuwamy wycenę z tabeli quotes - zostaje w 100% przeniesiona do zamówień
                    $stmtDel = $db->prepare("DELETE FROM quotes WHERE id = ?");
                    $stmtDel->execute([$quoteId]);

                    $profileMsg = "🎉 Gratulacje! Wycena została zaakceptowana i pomyślnie zakupiona. Utworzono zamówienie <strong>#{$orderNum}</strong> (kwota: " . number_format($price, 2) . " PLN). Wycena zniknęła z listy wycen i trafiła bezpośrednio do Twoich zamówień!";
                    $activeTabOnLoad = 'orders';
                    $autoPayOrderNum = $orderNum;
                    $autoPayTotal = $price;
                    $autoPayMethod = $paymentMethod;
                }
            } catch (Exception $e) {
                $profileError = 'Błąd składania zamówienia: ' . $e->getMessage();
            }
        }
    }
}

// Pobieranie zamówień użytkownika
$orders = [];
$quotes = [];
$totalSpent = 0.00;
$inProgressCount = 0;

if ($db) {
    try {
        $userEmail = trim($user['email'] ?? '');
        $userDiscord = trim($user['discord_tag'] ?? '');
        $userId = (int)$user['id'];

        // 1. Pobieranie zamówień powiązanych z user_id, e-mailem lub Discordem
        $orderWhere = ["user_id = ?"];
        $orderParams = [$userId];

        if ($userEmail !== '') {
            $orderWhere[] = "customer_email = ?";
            $orderParams[] = $userEmail;
        }
        if ($userDiscord !== '') {
            $orderWhere[] = "customer_discord = ?";
            $orderParams[] = $userDiscord;
        }

        $orderSql = "SELECT * FROM orders WHERE (" . implode(" OR ", $orderWhere) . ") ORDER BY id DESC";
        $orderStmt = $db->prepare($orderSql);
        $orderStmt->execute($orderParams);
        $orders = $orderStmt->fetchAll();

        foreach ($orders as $ord) {
            $totalSpent += (float)$ord['total_amount'];
            if ($ord['status'] === 'W realizacji' || $ord['status'] === 'Oczekujące') {
                $inProgressCount++;
            }
        }

        // 2. Pobieranie wycen indywidualnych (user_id lub Discord)
        $quoteWhere = ["user_id = ?"];
        $quoteParams = [$userId];

        if ($userDiscord !== '') {
            $quoteWhere[] = "LOWER(TRIM(discord_tag)) = LOWER(TRIM(?))";
            $quoteParams[] = $userDiscord;
        }

        $quoteSql = "SELECT * FROM quotes WHERE (" . implode(" OR ", $quoteWhere) . ") AND (status != 'Zamówione') ORDER BY id DESC";
        $quoteStmt = $db->prepare($quoteSql);
        $quoteStmt->execute($quoteParams);
        $quotes = $quoteStmt->fetchAll();
    } catch (Exception $e) {
        $profileError = "Błąd pobierania danych z bazy: " . $e->getMessage();
    }
}

// Pobranie aktualnych danych do płatności z bazy MySQL (konfigurowalnych w panelu admina)
$appBlikPhone = get_setting('payment_blik_phone', '500 123 456');
$appBlikName  = get_setting('payment_blik_name', 'HerbScripts Studio');
$appBankAcc   = get_setting('payment_bank_account', '12 1020 0000 0000 0000 0000 0000');
$appBankName  = get_setting('payment_bank_name', 'PKO Bank Polski');
$appPscEmail  = get_setting('payment_psc_email', 'herbscripts@gmail.com');
$appTransferTitlePrefix = get_setting('payment_transfer_title', 'Za jedzenie');
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel Klienta | HerbScripts</title>
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <style>
        .panel-container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px 60px;
        }
        .user-welcome-bar {
            background: linear-gradient(135deg, rgba(113, 39, 245, 0.18), rgba(168, 85, 247, 0.08));
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 30px;
            backdrop-filter: blur(14px);
            box-shadow: 0 10px 35px rgba(0,0,0,0.35);
        }
        .user-welcome-bar h1 {
            font-size: 1.6rem;
            color: #fff;
            margin-bottom: 4px;
        }
        .user-meta {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
            font-size: 0.85rem;
            color: var(--text-muted);
        }
        .user-badge {
            background: rgba(168, 85, 247, 0.2);
            color: var(--accent-cyan);
            padding: 3px 10px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 0.75rem;
            border: 1px solid rgba(168, 85, 247, 0.3);
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }
        .panel-stat-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 6px;
            backdrop-filter: blur(10px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        .panel-stat-card .val {
            font-size: 1.8rem;
            font-weight: 800;
            color: #fff;
        }
        .panel-stat-card .lbl {
            font-size: 0.8rem;
            color: var(--text-muted);
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 0.5px;
        }
        .tabs-header {
            display: flex;
            gap: 10px;
            border-bottom: 1px solid var(--border);
            margin-bottom: 24px;
            overflow-x: auto;
        }
        .tab-btn {
            background: none;
            border: none;
            color: var(--text-muted);
            padding: 12px 18px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
            white-space: nowrap;
        }
        .tab-btn.active {
            color: var(--accent-cyan);
            border-bottom-color: var(--accent-cyan);
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .order-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
            transition: border-color 0.25s, transform 0.25s, box-shadow 0.25s;
        }
        .order-card:hover {
            border-color: rgba(168, 85, 247, 0.45);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(113, 39, 245, 0.18);
        }
        .order-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--border);
            padding-bottom: 12px;
            margin-bottom: 14px;
            flex-wrap: wrap;
            gap: 10px;
        }
        .order-number {
            font-size: 1.1rem;
            font-weight: 800;
            color: #fff;
        }
        .order-badges {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        .badge-paid {
            background: rgba(16, 185, 129, 0.15);
            color: #34d399;
            border: 1px solid rgba(16, 185, 129, 0.3);
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 700;
        }
        .badge-unpaid {
            background: rgba(239, 68, 68, 0.15);
            color: #f87171;
            border: 1px solid rgba(239, 68, 68, 0.3);
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 700;
        }
        .badge-status {
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 700;
        }
        .badge-oczekujace { background: rgba(245, 158, 11, 0.15); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.3); }
        .badge-w-realizacji { background: rgba(168, 85, 247, 0.15); color: #c084fc; border: 1px solid rgba(168, 85, 247, 0.3); }
        .badge-zrealizowane { background: rgba(16, 185, 129, 0.15); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.3); }
        .badge-anulowane { background: rgba(239, 68, 68, 0.15); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
        
        .items-list {
            margin: 12px 0;
            padding-left: 18px;
            color: var(--text-muted);
            font-size: 0.88rem;
        }
        .items-list li {
            margin-bottom: 4px;
        }
        .items-list strong {
            color: #fff;
        }
        .order-card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top: 1px solid var(--border);
            padding-top: 12px;
            margin-top: 14px;
            font-size: 0.85rem;
            color: var(--text-muted);
            flex-wrap: wrap;
            gap: 10px;
        }
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 14px;
            color: var(--text-muted);
        }
        .empty-state h3 {
            color: #fff;
            margin-bottom: 8px;
            font-size: 1.2rem;
        }

        /* Responsywność na telefony */
        @media (max-width: 768px) {
            .panel-container {
                padding: 0 14px 40px;
                margin: 15px auto;
            }
            .user-welcome-bar {
                padding: 18px 16px;
                border-radius: 12px;
                flex-direction: column;
                align-items: stretch;
                gap: 14px;
            }
            .user-welcome-bar h1 {
                font-size: 1.25rem;
                line-height: 1.3;
            }
            .user-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 6px;
                font-size: 0.8rem;
            }
            .user-welcome-bar .btn {
                width: 100%;
                justify-content: center;
            }
            .stats-grid {
                grid-template-columns: 1fr;
                gap: 10px;
                margin-bottom: 20px;
            }
            .panel-stat-card {
                padding: 14px 16px;
            }
            .panel-stat-card .val {
                font-size: 1.5rem;
            }
            .tabs-header {
                gap: 6px;
                padding-bottom: 6px;
                -webkit-overflow-scrolling: touch;
            }
            .tab-btn {
                padding: 10px 14px;
                font-size: 0.84rem;
            }
            .order-card {
                padding: 16px 14px;
            }
            .order-card-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
            .order-card-footer {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
            .form-control {
                font-size: 16px; /* Zapobiega zoomowaniu na iOS */
            }
        }

        @media (max-width: 520px) {
            header {
                padding: 10px 14px;
            }
            .logo {
                font-size: 1.15rem;
            }
            .nav-actions {
                gap: 6px;
            }
            .nav-actions .btn {
                padding: 6px 9px;
                font-size: 0.76rem;
            }
            .nav-actions .nav-btn-text {
                display: none;
            }
            .order-number {
                font-size: 0.95rem;
                word-break: break-all;
            }
            .order-badges {
                flex-wrap: wrap;
                gap: 6px;
            }
            .order-card-footer {
                font-size: 0.8rem;
            }
        }

        /* Modal zakupu wyceny custom w panelu klienta */
        .modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(6px);
            z-index: 99999;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 16px;
        }
        .modal-overlay.active {
            display: flex !important;
        }
        .modal-box {
            background: #0d081f;
            border: 1px solid rgba(168, 85, 247, 0.4);
            border-radius: 14px;
            width: 100%;
            max-width: 520px;
            max-height: 90vh;
            overflow-y: auto;
            padding: 24px;
            position: relative;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.95), 0 0 35px rgba(113, 39, 245, 0.35);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border);
        }
        .modal-header h3 {
            font-size: 1.15rem;
            color: #fff;
            font-weight: 700;
        }
        .btn-close {
            background: none;
            border: none;
            color: var(--text-muted);
            font-size: 1.5rem;
            cursor: pointer;
            line-height: 1;
        }
        .btn-close:hover {
            color: #fff;
        }
    </style>
</head>
<body>
    <header>
        <a href="index.html" class="logo">Herb<span>Scripts.</span></a>
        <div class="nav-actions">
            <!-- Mała kompaktowa ikonka sklepu -->
            <a href="index.html#katalog" class="cart-icon-btn" title="Przejdź do oferty sklepu" aria-label="Sklep" style="display:inline-flex; align-items:center; justify-content:center; gap:7px; background:linear-gradient(135deg, #7127f5, #a855f7); color:#fff; border:1px solid rgba(168,85,247,0.4); border-radius:9px; padding:6px 12px; height:38px; cursor:pointer; text-decoration:none;">
                <span class="cart-icon-emoji" style="font-size:1.12rem; line-height:1;">🛒</span>
                <span class="cart-badge-pill" style="background:rgba(13,8,30,0.85); border:1px solid rgba(255,255,255,0.3); color:#fff; font-size:0.78rem; font-weight:800; padding:1px 6px; border-radius:999px; min-width:18px; text-align:center; line-height:1.3;">Sklep</span>
            </a>

            <!-- Trzy poziome kreski (hamburger menu) -->
            <button class="mobile-menu-btn" id="mobileMenuBtn" aria-label="Menu nawigacji" onclick="toggleMobileMenu()" title="Menu i panele" style="display:flex !important; flex-direction:column; justify-content:center; align-items:center; gap:5px; width:38px; height:38px; background:rgba(168,85,247,0.18); border:1px solid rgba(168,85,247,0.4); border-radius:9px; cursor:pointer; padding:8px; flex-shrink:0;">
                <span style="display:block; width:20px; height:2px; background:#fff; border-radius:2px;"></span>
                <span style="display:block; width:20px; height:2px; background:#fff; border-radius:2px;"></span>
                <span style="display:block; width:20px; height:2px; background:#fff; border-radius:2px;"></span>
            </button>
        </div>
    </header>

    <!-- Wysuwane Menu Nawigacji (3 poziome kreski ☰) -->
    <div class="mobile-menu-overlay" id="mobileMenuOverlay" onclick="closeMobileMenu()"></div>
    <div class="mobile-menu" id="mobileMenu">
        <div class="mobile-menu-header">
            <a href="index.html" class="logo" onclick="closeMobileMenu()">Herb<span>Scripts.</span></a>
            <button class="btn-close" onclick="closeMobileMenu()">✕</button>
        </div>
        <ul class="mobile-menu-links">
            <li><a href="index.html">🛒 Sklep & Gotowe Produkty</a></li>
            <li><a href="index.html#custom">💬 Zamówienie Custom</a></li>
            <li><a href="index.html#opinie">⭐ Opinie Klientów</a></li>
            <li><a href="index.html#faq">❓ FAQ</a></li>
        </ul>
        <div class="mobile-menu-footer">
            <div style="font-size:0.75rem; text-transform:uppercase; color:var(--text-muted); font-weight:700; margin-bottom:8px; letter-spacing:0.5px;">
                👤 Twoje Panele & Konto
            </div>
            <a href="panel-klienta.php" class="btn btn-outline full-width" style="border-color: #a855f7; color: #a855f7; margin-bottom: 8px;">
                👤 Panel Klienta (Twoje Konto)
            </a>
            <?php if (is_media()): ?>
                <a href="panel-media.php" class="btn btn-outline full-width" style="border-color: #ec4899; color: #f472b6; margin-bottom: 8px;">
                    🎬 Panel Twórcy (Media)
                </a>
            <?php endif; ?>
            <?php if (is_owner()): ?>
                <a href="panel-wlasciciela.php" class="btn btn-outline full-width" style="border-color: #fbbf24; color: #fbbf24; margin-bottom: 8px;">
                    👑 Panel Właściciela
                </a>
            <?php endif; ?>
            <?php if (is_admin()): ?>
                <a href="panel-admina.php" class="btn btn-outline full-width" style="border-color: #34d399; color: #34d399; margin-bottom: 8px;">
                    🛡️ Panel Administratora
                </a>
            <?php endif; ?>
            <a href="logout.php" class="btn btn-outline full-width" style="border-color: #ef4444; color: #f87171;">
                🚪 Wyloguj się
            </a>
        </div>
    </div>

    <div class="panel-container">
        <!-- Pasek powitalny użytkownika -->
        <div class="user-welcome-bar">
            <div>
                <h1>Witaj w Panelu, <?= htmlspecialchars($user['username']) ?>! 👋</h1>
                <div class="user-info-row">
                    <?php if (is_owner()): ?>
                        <span class="user-badge" style="background:linear-gradient(135deg, rgba(245, 158, 11, 0.25), rgba(234, 179, 8, 0.15)); color:#fbbf24; border-color:rgba(245, 158, 11, 0.5); font-weight:800;">👑 Właściciel</span>
                    <?php elseif (strtolower($user['role']) === 'admin'): ?>
                        <span class="user-badge" style="background:rgba(16, 185, 129, 0.2); color:#34d399; border-color:rgba(16, 185, 129, 0.4); font-weight:700;">🛡️ Administrator</span>
                    <?php elseif (is_media()): ?>
                        <span class="user-badge" style="background:rgba(236, 72, 153, 0.2); color:#f472b6; border-color:rgba(236, 72, 153, 0.4); font-weight:700;">🎬 Twórca Media</span>
                    <?php else: ?>
                        <span class="user-badge">👤 Klient VIP</span>
                    <?php endif; ?>
                    <span>✉️ <?= htmlspecialchars($user['email']) ?></span>
                    <?php if (!empty($user['discord_tag'])): ?>
                        <span>💬 Discord: <strong><?= htmlspecialchars($user['discord_tag']) ?></strong></span>
                    <?php else: ?>
                        <span style="color:#fbbf24;">⚠️ Brak przypisanego Discord Taga</span>
                    <?php endif; ?>
                </div>
            </div>
            <div>
                <a href="index.html#katalog" class="btn btn-gradient">🛒 Złóż nowe zamówienie</a>
            </div>
        </div>

        <?php if (!empty($profileMsg)): ?>
            <div class="alert-box alert-success" style="margin-bottom: 20px;">
                ✅ <?= $profileMsg ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($profileError)): ?>
            <div class="alert-box alert-error" style="margin-bottom: 20px;">
                ⚠️ <?= $profileError ?>
            </div>
        <?php endif; ?>

        <?php if (is_media()): ?>
            <!-- Baner partnerski dla twórcy Media -->
            <div style="background: linear-gradient(135deg, rgba(236, 72, 153, 0.12), rgba(168, 85, 247, 0.12)); border: 1px solid rgba(236, 72, 153, 0.35); border-radius: 12px; padding: 16px 20px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
                <div>
                    <strong style="color: #f472b6; font-size: 1rem; display: flex; align-items: center; gap: 6px;">
                        <span>🎬 Twój Program Partnerski (Media) jest aktywny!</span>
                    </strong>
                    <p style="color: var(--text-muted); font-size: 0.85rem; margin: 4px 0 0;">
                        Twój kod daje widzom 5% rabatu, a Ty zarabiasz 10% prowizji z każdego zamówienia.
                    </p>
                </div>
                <a href="panel-media.php" class="btn btn-gradient" style="background: linear-gradient(135deg, #ec4899, #a855f7); font-weight: 700; font-size: 0.88rem;">
                    🚀 Otwórz Panel Twórcy (Zarobki) ➔
                </a>
            </div>
        <?php endif; ?>

        <!-- Statystyki klienta -->
        <div class="stats-grid">
            <div class="panel-stat-card">
                <span class="lbl">Twoje Zamówienia</span>
                <span class="val" style="color:var(--accent-cyan);"><?= count($orders) ?></span>
            </div>
            <div class="panel-stat-card">
                <span class="lbl">W realizacji / Oczekujące</span>
                <span class="val" style="color:#fbbf24;"><?= $inProgressCount ?></span>
            </div>
            <div class="panel-stat-card">
                <span class="lbl">Zapytania o wycenę</span>
                <span class="val" style="color:#c084fc;"><?= count($quotes) ?></span>
            </div>
        </div>

        <!-- Zakładki -->
        <div class="tabs-header">
            <button class="tab-btn active" onclick="switchTab('orders', this)">📦 Moje Zamówienia (<?= count($orders) ?>)</button>
            <button class="tab-btn" onclick="switchTab('quotes', this)">💬 Moje Wyceny Custom (<?= count($quotes) ?>)</button>
            <button class="tab-btn" onclick="switchTab('settings', this)">⚙️ Ustawienia Profilu</button>
            <?php if (is_media()): ?>
                <a href="panel-media.php" class="tab-btn" style="color: #f472b6; text-decoration: none;">
                    🎬 Panel Twórcy (10% Prowizji) ➔
                </a>
            <?php endif; ?>
        </div>

        <!-- TAB: ZAMÓWIENIA -->
        <div id="tab-orders" class="tab-content active">
            <?php if (empty($orders)): ?>
                <div class="empty-state">
                    <div style="font-size: 3rem; margin-bottom: 12px;">📦</div>
                    <h3>Brak zamówień na Twoim koncie</h3>
                    <p>Nie złożyłeś jeszcze żadnego zamówienia lub złożyłeś je z innym Discord Tagiem.</p>
                    <div style="margin-top: 20px;">
                        <a href="index.html#katalog" class="btn btn-gradient">Przeglądaj katalog produktów</a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($orders as $order): 
                    $items = json_decode($order['items_json'], true) ?: [];
                    $statusClass = 'badge-' . strtolower(str_replace([' ', 'ą', 'ę'], ['-', 'a', 'e'], $order['status']));
                ?>
                    <div class="order-card">
                        <div class="order-card-header">
                            <div>
                                <span class="order-number"><?= htmlspecialchars($order['order_number']) ?></span>
                                <span style="font-size:0.8rem; color:var(--text-muted); margin-left:8px;">
                                    (ID: #<?= $order['id'] ?> &bull; Data: <?= date('d.m.Y H:i', strtotime($order['created_at'])) ?>)
                                </span>
                            </div>
                            <div class="order-badges">
                                <?php if ($order['is_paid']): ?>
                                    <span class="badge-paid">✅ Opłacone</span>
                                <?php else: ?>
                                    <span class="badge-unpaid">⏳ Oczekuje na płatność</span>
                                    <button type="button" class="btn btn-sm btn-gradient"
                                            data-order-num="<?= htmlspecialchars($order['order_number']) ?>"
                                            data-total="<?= number_format((float)$order['total_amount'], 2, '.', '') ?>"
                                            data-method="<?= htmlspecialchars($order['payment_method']) ?>"
                                            data-notes="<?= htmlspecialchars($order['notes'] ?? '') ?>"
                                            onclick="handlePayOrderClick(this)"
                                            style="padding: 3px 10px; font-size: 0.76rem; font-weight: 800; box-shadow: 0 2px 10px rgba(168, 85, 247, 0.35);">
                                        💳 Opłać / Dane
                                    </button>
                                <?php endif; ?>
                                <span class="badge-status <?= $statusClass ?>">
                                    <?= htmlspecialchars($order['status']) ?>
                                </span>
                            </div>
                        </div>

                        <div>
                            <strong style="color:#fff; font-size:0.85rem;">Zamówione pozycje:</strong>
                            <ul class="items-list">
                                <?php if (empty($items)): ?>
                                    <li>Brak szczegółów pozycji</li>
                                <?php else: ?>
                                    <?php foreach ($items as $item): ?>
                                        <li>
                                            <strong><?= htmlspecialchars($item['title'] ?? 'Produkt') ?></strong> 
                                            &times; <?= (int)($item['qty'] ?? 1) ?> 
                                            &mdash; <span style="color:var(--accent-cyan);"><?= number_format((float)($item['price'] ?? 0) * (int)($item['qty'] ?? 1), 2) ?> PLN</span>
                                        </li>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                        </div>

                        <div class="order-card-footer">
                            <div>
                                Metoda płatności: <strong style="color:#fff;"><?= htmlspecialchars($order['payment_method']) ?></strong>
                                <?php if (!empty($order['customer_discord'])): ?>
                                    &bull; Discord kontaktowy: <strong style="color:var(--accent-cyan);"><?= htmlspecialchars($order['customer_discord']) ?></strong>
                                <?php endif; ?>

                                <?php if (!empty($order['notes'])): ?>
                                    <div style="margin-top:8px; font-size:0.78rem; background:rgba(168,85,247,0.1); border:1px dashed rgba(168,85,247,0.3); border-radius:6px; padding:6px 10px; color:#c084fc; line-height:1.4;">
                                        📝 <strong>Uwagi / Kupon:</strong> <?= nl2br(htmlspecialchars($order['notes'])) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div style="font-size:1.1rem; color:#fff; display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                                <span>Suma do zapłaty: <strong style="color:var(--accent-cyan); font-weight:800;"><?= number_format((float)$order['total_amount'], 2) ?> PLN</strong></span>
                                <?php if (!$order['is_paid']): ?>
                                    <button type="button" class="btn btn-sm btn-gradient"
                                            data-order-num="<?= htmlspecialchars($order['order_number']) ?>"
                                            data-total="<?= number_format((float)$order['total_amount'], 2, '.', '') ?>"
                                            data-method="<?= htmlspecialchars($order['payment_method']) ?>"
                                            data-notes="<?= htmlspecialchars($order['notes'] ?? '') ?>"
                                            onclick="handlePayOrderClick(this)"
                                            style="padding: 6px 14px; font-size: 0.82rem; font-weight: 800;">
                                        💳 Dane do opłacenia
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- TAB: WYCENY CUSTOM -->
        <div id="tab-quotes" class="tab-content">
            <?php if (empty($quotes)): ?>
                <div class="empty-state">
                    <div style="font-size: 3rem; margin-bottom: 12px;">💬</div>
                    <h3>Brak zapytań o wycenę indywidualną</h3>
                    <p>Potrzebujesz unikalnego bota Discord lub strony internetowej? Złóż darmowe zapytanie!</p>
                    <div style="margin-top: 20px;">
                        <a href="index.html#custom" class="btn btn-gradient">Wyceń swój projekt</a>
                    </div>
                </div>
            <?php else: ?>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 12px;">
                    <div>
                        <h3 style="color:#fff; font-size:1.15rem; margin-bottom:2px;">Wyceny i zlecenia przypisane do Twojego konta</h3>
                        <p style="color:var(--text-muted); font-size:0.83rem;">Oficjalne ceny i statusy aktualizowane na bieżąco przez Administratora.</p>
                    </div>
                    <a href="index.html#custom" class="btn btn-gradient btn-sm">➕ Nowe zapytanie o wycenę</a>
                </div>
                <?php foreach ($quotes as $q): ?>
                    <div class="order-card">
                        <div class="order-card-header">
                            <div>
                                <span class="order-number">Zgłoszenie: <?= htmlspecialchars($q['project_type']) ?></span>
                                <span style="font-size:0.8rem; color:var(--text-muted); margin-left:8px;">
                                    (Data: <?= date('d.m.Y H:i', strtotime($q['created_at'])) ?>)
                                </span>
                            </div>
                            <div>
                                <?php
                                    $quoteStatusClass = 'badge-oczekujace';
                                    if ($q['status'] === 'Wycenione') $quoteStatusClass = 'badge-zrealizowane';
                                    elseif ($q['status'] === 'Zamówione') $quoteStatusClass = 'badge-w-realizacji';
                                    elseif ($q['status'] === 'W kontakcie') $quoteStatusClass = 'badge-w-realizacji';
                                    elseif ($q['status'] === 'Odrzucone') $quoteStatusClass = 'badge-anulowane';
                                ?>
                                <span class="badge-status <?= $quoteStatusClass ?>">
                                    Status: <?= htmlspecialchars($q['status']) ?>
                                </span>
                            </div>
                        </div>

                        <p style="color:#cbd5e1; font-size:0.9rem; line-height:1.5; margin-bottom:12px; white-space:pre-wrap;"><?= htmlspecialchars($q['description']) ?></p>

                        <!-- Wyświetlanie ustalonej ceny przez administratora i opcja zakupu -->
                        <?php if (isset($q['quoted_price']) && $q['quoted_price'] !== null && (float)$q['quoted_price'] > 0): ?>
                            <?php if ($q['status'] !== 'Zamówione'): ?>
                                <div style="background: linear-gradient(135deg, rgba(168, 85, 247, 0.16), rgba(113, 39, 245, 0.14)); border: 1px solid rgba(168, 85, 247, 0.45); border-radius: 12px; padding: 18px 20px; margin: 14px 0; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
                                    <div>
                                        <div style="font-size: 0.8rem; color: #c084fc; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px;">💰 Oficjalna wycena od Administratora:</div>
                                        <div style="font-size: 1.75rem; font-weight: 900; color: #fff; margin-top: 2px;">
                                            <?= number_format((float)$q['quoted_price'], 2) ?> PLN
                                        </div>
                                        <small style="color: #cbd5e1; font-size: 0.84rem; display:block; margin-top:2px;">
                                            🎉 Administrator wycenił Twój projekt. Dodaj go do koszyka i sfinalizuj zakup – w koszyku możesz wpisać <strong>kod rabatowy (-5%)</strong>!
                                        </small>
                                    </div>
                                    <div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
                                        <button type="button" class="btn btn-gradient"
                                                onclick="addQuoteToCart(<?= (int)$q['id'] ?>, <?= htmlspecialchars(json_encode($q['project_type']), ENT_QUOTES, 'UTF-8') ?>, <?= (float)$q['quoted_price'] ?>)"
                                                style="padding: 12px 22px; font-size: 0.95rem; font-weight: 800; box-shadow: 0 4px 20px rgba(168, 85, 247, 0.45); cursor: pointer;">
                                            🛒 Dodaj do koszyka & Kup (<?= number_format((float)$q['quoted_price'], 2) ?> PLN)
                                        </button>
                                        <button type="button" class="btn btn-outline btn-sm"
                                                data-quote-id="<?= (int)$q['id'] ?>"
                                                data-project-type="<?= htmlspecialchars($q['project_type'], ENT_QUOTES, 'UTF-8') ?>"
                                                data-price="<?= number_format((float)$q['quoted_price'], 2, '.', '') ?>"
                                                onclick="handleBuyQuoteClick(this)"
                                                title="Szybkie zamówienie bezpośrednio w panelu"
                                                style="padding: 11px 16px; font-size: 0.85rem;">
                                            ⚡ Szybki zakup
                                        </button>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.35); border-radius: 10px; padding: 14px 18px; margin: 12px 0; color: #34d399; font-size: 0.9rem; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
                                    <div>
                                        <strong>✅ Wycena została zamówiona i jest w trakcie realizacji!</strong>
                                        <div style="font-size: 0.8rem; color: #94a3b8; margin-top: 2px;">Szczegóły realizacji oraz status znajdziesz w zakładce „Moje Zamówienia”.</div>
                                    </div>
                                    <button class="btn btn-outline btn-sm" onclick="switchTab('orders')" style="border-color:#34d399; color:#34d399;">📦 Przejdź do zamówień</button>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div style="background: rgba(245, 158, 11, 0.08); border: 1px dashed rgba(245, 158, 11, 0.3); border-radius: 8px; padding: 10px 14px; margin: 12px 0; font-size: 0.83rem; color: #fbbf24;">
                                ⏳ Oczekiwanie na wycenę od administratora. Gdy administrator sprawdzi Twoje zgłoszenie i poda cenę, kwota oraz przycisk zakupu pojawią się w tym miejscu.
                            </div>
                        <?php endif; ?>

                        <div class="order-card-footer">
                            <div>
                                Szacowany budżet: <strong style="color:var(--accent-cyan);"><?= htmlspecialchars($q['budget']) ?> PLN</strong>
                            </div>
                            <div>
                                Discord do kontaktu: <strong><?= htmlspecialchars($q['discord_tag']) ?></strong>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- TAB: USTAWIENIA PROFILU -->
        <div id="tab-settings" class="tab-content">
            <div style="max-width: 600px; margin: 0 auto; background:var(--card-bg); border:1px solid var(--border); border-radius:12px; padding:24px;">
                <h3 style="color:#fff; margin-bottom:16px;">Edycja Twoich Danych</h3>
                <form method="POST" action="panel-klienta.php">
                    <input type="hidden" name="action" value="update_profile">

                    <div class="form-group">
                        <label>Login:</label>
                        <input type="text" class="form-control" value="<?= htmlspecialchars($user['username']) ?>" disabled style="opacity:0.6;">
                        <small style="color:var(--text-muted);">Loginu nie można zmienić.</small>
                    </div>

                    <div class="form-group">
                        <label>Adres E-mail:</label>
                        <input type="email" class="form-control" value="<?= htmlspecialchars($user['email']) ?>" disabled style="opacity:0.6;">
                    </div>

                    <div class="form-group">
                        <label for="discord_tag">Twój Discord Tag:</label>
                        <input type="text" id="discord_tag" name="discord_tag" class="form-control" value="<?= htmlspecialchars($user['discord_tag']) ?>" placeholder="np. devforge#1234">
                        <small style="color:var(--text-muted);">Użyj tego samego taga przy zakupach, aby zamówienia natychmiast trafiały do tego panelu.</small>
                    </div>

                    <hr style="border:0; border-top:1px solid var(--border); margin:20px 0;">
                    <h4 style="color:#fff; font-size:0.95rem; margin-bottom:12px;">Zmiana Hasła (opcjonalnie)</h4>

                    <div class="form-group">
                        <label for="old_password">Dotychczasowe hasło:</label>
                        <input type="password" id="old_password" name="old_password" class="form-control" placeholder="Wpisz obecne hasło, jeśli chcesz je zmienić">
                    </div>

                    <div class="form-group">
                        <label for="new_password">Nowe hasło:</label>
                        <input type="password" id="new_password" name="new_password" class="form-control" placeholder="Min. 6 znaków">
                    </div>

                    <button type="submit" class="btn btn-gradient" style="margin-top:10px;">
                        💾 Zapisz zmiany
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal potwierdzenia zakupu i zamówienia wyceny custom -->
    <div class="modal-overlay" id="orderQuoteModal" onclick="if(event.target==this) closeQuoteModal()">
        <div class="modal-box" style="max-width: 520px;">
            <div class="modal-header">
                <h3 style="color:#fff; font-size:1.2rem;">🛒 Zamówienie Projektu Custom</h3>
                <button class="btn-close" onclick="closeQuoteModal()">✕</button>
            </div>
            
            <form method="POST" action="panel-klienta.php" style="padding: 10px 0;">
                <input type="hidden" name="action" value="order_custom_quote">
                <input type="hidden" name="quote_id" id="modalQuoteId" value="">

                <div style="background: rgba(168, 85, 247, 0.1); border: 1px solid rgba(168, 85, 247, 0.3); border-radius: 10px; padding: 14px; margin-bottom: 18px;">
                    <div style="font-size: 0.78rem; color: var(--text-muted); text-transform: uppercase;">Zlecenie:</div>
                    <strong id="modalProjectType" style="color: #fff; font-size: 1.05rem; display:block; margin: 2px 0 6px;"></strong>
                    <div style="display:flex; justify-content: space-between; align-items: center; border-top: 1px dashed rgba(255,255,255,0.15); padding-top: 8px; margin-top: 8px;">
                        <span style="color: var(--text-muted); font-size: 0.88rem;">Ustalona kwota do zapłaty:</span>
                        <strong id="modalQuotedPrice" style="color: #34d399; font-size: 1.35rem;"></strong>
                    </div>
                </div>

                <div style="margin-bottom: 18px;">
                    <button type="button" class="btn btn-gradient full-width" onclick="addQuoteFromModalToCart()" style="width:100%; padding: 12px; font-weight:800; justify-content:center; box-shadow:0 4px 18px rgba(168,85,247,0.4);">
                        🛒 Kup przez Koszyk (Użyj Kodu Rabatowego -5%)
                    </button>
                    <div style="text-align: center; color: var(--text-muted); font-size: 0.78rem; margin-top: 6px;">
                        W koszyku możesz wpisać kod twórcy (np. <strong>MLODY5</strong>) i obniżyć cenę!
                    </div>
                </div>

                <div style="text-align: center; color: var(--text-muted); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; margin: 12px 0; position: relative;">
                    <span style="background: #120d24; padding: 0 10px; position: relative; z-index: 1;">lub zamów bezpośrednio tutaj</span>
                    <div style="position: absolute; top: 50%; left: 0; right: 0; height: 1px; background: rgba(255,255,255,0.1); z-index: 0;"></div>
                </div>

                <div class="form-group" style="margin-bottom: 16px;">
                    <label for="modalPaymentMethod" style="display:block; margin-bottom: 6px; font-weight: 600; color: #fff;">Wybierz preferowaną metodę płatności:</label>
                    <select name="payment_method" id="modalPaymentMethod" class="form-control" style="width: 100%;">
                        <option value="BLIK (Szybka płatność)">⚡ BLIK (Przelew na telefon / kod)</option>
                        <option value="Paysafecard">💳 Paysafecard (PIN / myPaysafecard)</option>
                        <option value="Przelew Bankowy">🏦 Tradycyjny przelew bankowy</option>
                        <option value="PayPal">💳 PayPal / Karta płatnicza</option>
                        <option value="PayPo / Odroczona">⏳ PayPo (Kup teraz, zapłać za 30 dni)</option>
                    </select>
                </div>

                <div class="form-group" style="margin-bottom: 20px;">
                    <label for="modalCustomerNotes" style="display:block; margin-bottom: 6px; font-weight: 600; color: #fff;">Dodatkowa uwaga (opcjonalnie):</label>
                    <textarea name="customer_notes" id="modalCustomerNotes" class="form-control" rows="2" placeholder="np. preferowane godziny kontaktu, dodatkowe wytyczne..."></textarea>
                </div>

                <button type="submit" class="btn btn-gradient full-width" style="width: 100%; padding: 14px; font-size: 1rem; font-weight: 800; justify-content: center;">
                    🚀 Potwierdzam zakup i zamawiam projekt
                </button>
            </form>
        </div>
    </div>

    <!-- Modal opłacenia zamówienia (BLIK / Przelew) -->
    <div class="modal-overlay" id="orderPaymentModal" onclick="if(event.target==this) closePaymentModal()">
        <div class="modal-box" style="max-width: 520px;">
            <div class="modal-header">
                <h3 id="payModalTitle" style="color:#fff; font-size:1.15rem; display:flex; align-items:center; gap:8px;">
                    💳 <span>Opłać zamówienie</span>
                </h3>
                <button class="btn-close" onclick="closePaymentModal()">✕</button>
            </div>
            <div id="payModalBody">
                <!-- Wypełniane dynamicznie przez JS -->
            </div>
        </div>
    </div>

    <div id="toastBox" class="toast"></div>

    <script>
        const PAYMENT_CONFIG = {
            blik_phone: <?= json_encode($appBlikPhone) ?>,
            blik_name: <?= json_encode($appBlikName) ?>,
            bank_account: <?= json_encode($appBankAcc) ?>,
            bank_name: <?= json_encode($appBankName) ?>,
            psc_email: <?= json_encode($appPscEmail) ?>,
            transfer_prefix: <?= json_encode($appTransferTitlePrefix) ?>
        };

        function showToast(msg) {
            const box = document.getElementById('toastBox');
            if (!box) return;
            box.innerText = msg;
            box.classList.add('show');
            setTimeout(() => {
                box.classList.remove('show');
            }, 3000);
        }

        function copyToClipboard(text, successMsg = 'Skopiowano do schowka!') {
            if (!text) return;
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showToast(successMsg);
                }).catch(() => fallbackCopy(text, successMsg));
            } else {
                fallbackCopy(text, successMsg);
            }
        }

        function fallbackCopy(text, successMsg) {
            const ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.left = '-9999px';
            document.body.appendChild(ta);
            ta.select();
            try {
                document.execCommand('copy');
                showToast(successMsg);
            } catch (err) {
                showToast('Nie udało się skopiować.');
            }
            document.body.removeChild(ta);
        }

        function copyPaymentField(elementId, msg) {
            const el = document.getElementById(elementId);
            if (!el) return;
            let val = el.value || el.innerText || '';
            if (val.endsWith(' PLN')) val = val.replace(' PLN', '');
            copyToClipboard(val, msg);
        }

        function handlePayOrderClick(btn) {
            if (!btn) return;
            const orderNum = btn.getAttribute('data-order-num') || '';
            const total = btn.getAttribute('data-total') || '0.00';
            const method = btn.getAttribute('data-method') || 'BLIK';
            const notes = btn.getAttribute('data-notes') || '';
            openOrderPaymentModal(orderNum, total, method, notes);
        }

        function openOrderPaymentModal(orderNum, total, method = 'BLIK', existingNotes = '') {
            const modal = document.getElementById('orderPaymentModal');
            const body = document.getElementById('payModalBody');
            if (!modal || !body) return;

            const phone = PAYMENT_CONFIG.blik_phone || '500 123 456';
            const name = PAYMENT_CONFIG.blik_name || 'HerbScripts Studio';
            const cleanNum = (orderNum && orderNum.toString().startsWith('#')) ? orderNum : '#' + orderNum;
            const prefix = PAYMENT_CONFIG.transfer_prefix || 'Za jedzenie';
            const title = prefix + ' ' + cleanNum;
            const amount = parseFloat(total || 0).toFixed(2);
            const bankAcc = PAYMENT_CONFIG.bank_account || '12 1020 0000 0000 0000 0000 0000';
            const bankName = PAYMENT_CONFIG.bank_name || 'PKO Bank Polski';
            const pscEmail = PAYMENT_CONFIG.psc_email || 'herbscripts@gmail.com';

            const initialCodes = [];
            if (existingNotes) {
                const lines = existingNotes.split('\n');
                lines.forEach(l => {
                    const m = l.match(/💳 Kod Paysafecard:\s*([^\(\n\r]+)/);
                    if (m && m[1]) initialCodes.push(m[1].trim());
                });
            }

            const lowerMethod = (method || '').toLowerCase();
            let initialTab = 'blik';
            if (lowerMethod.includes('paysafecard') || lowerMethod.includes('psc')) {
                initialTab = 'psc';
            } else if (lowerMethod.includes('przelew') || lowerMethod.includes('bank')) {
                initialTab = 'bank';
            }

            body.innerHTML = `
                <div style="background: rgba(168, 85, 247, 0.1); border: 1px solid rgba(168, 85, 247, 0.3); border-radius: 12px; padding: 14px 16px; margin-bottom: 16px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
                        <span style="font-size:0.78rem; color:var(--text-muted); text-transform:uppercase; font-weight:700;">Numer zamówienia:</span>
                        <strong style="color:var(--accent-cyan); font-size:1.15rem; letter-spacing:0.5px;">#${orderNum}</strong>
                    </div>
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <span style="font-size:0.85rem; color:var(--text-muted);">Kwota do zapłaty:</span>
                        <strong style="color:#34d399; font-size:1.45rem; font-weight:900;">${amount} PLN</strong>
                    </div>
                </div>

                <!-- Wybór metody płatności -->
                <div style="display:flex; gap:8px; margin-bottom:14px; flex-wrap:wrap;">
                    <button type="button" id="payTabBtnBlik" class="btn btn-sm ${initialTab === 'blik' ? 'btn-gradient' : 'btn-outline'}" onclick="switchPayModalTab('blik')" style="flex:1; justify-content:center; padding:9px 10px; font-weight:700; min-width:110px;">
                        ⚡ BLIK
                    </button>
                    <button type="button" id="payTabBtnPsc" class="btn btn-sm ${initialTab === 'psc' ? 'btn-gradient' : 'btn-outline'}" onclick="switchPayModalTab('psc')" style="flex:1; justify-content:center; padding:9px 10px; font-weight:700; min-width:110px;">
                        💳 Paysafecard
                    </button>
                    <button type="button" id="payTabBtnBank" class="btn btn-sm ${initialTab === 'bank' ? 'btn-gradient' : 'btn-outline'}" onclick="switchPayModalTab('bank')" style="flex:1; justify-content:center; padding:9px 10px; font-weight:700; min-width:110px;">
                        🏦 Przelew bankowy
                    </button>
                </div>

                <!-- 1. BLIK -->
                <div id="paySectionBlik" style="display: ${initialTab === 'blik' ? 'block' : 'none'};">
                    <div style="background:#0c081d; border:1px solid rgba(16, 185, 129, 0.4); border-radius:12px; padding:16px; margin-bottom:14px;">
                        <div style="color:#34d399; font-weight:800; font-size:0.92rem; margin-bottom:12px; display:flex; align-items:center; gap:6px;">
                            <span>📱 Przelew na telefon BLIK (Odbiorca zarejestrowany w BLIK)</span>
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Numer telefonu do BLIK:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${phone}" id="copyPayPhone" class="form-control" style="font-size:1.15rem; font-weight:900; color:#34d399; letter-spacing:1px; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPayPhone', 'Skopiowano numer telefonu BLIK!')" style="border-color:#34d399; color:#34d399; font-weight:700; flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Odbiorca (Imię / Nazwa):</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${name}" id="copyPayName" class="form-control" style="font-size:0.92rem; font-weight:700; color:#fff; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPayName', 'Skopiowano odbiorcę!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Tytuł / Opis przelewu (BARDZO WAŻNE):</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${title}" id="copyPayTitle" class="form-control" style="font-size:0.95rem; font-weight:800; color:#c084fc; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPayTitle', 'Skopiowano tytuł przelewu!')" style="border-color:#a855f7; color:#c084fc; font-weight:700; flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div>
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Dokładna kwota:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${amount} PLN" id="copyPayAmount" class="form-control" style="font-size:1.1rem; font-weight:900; color:#fff; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPayAmount', 'Skopiowano kwotę!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>
                    </div>

                    <div style="background:rgba(245, 158, 11, 0.08); border:1px dashed rgba(245, 158, 11, 0.35); border-radius:8px; padding:10px 12px; margin-bottom:14px; font-size:0.8rem; color:#fbbf24; line-height:1.4;">
                        💡 <strong>Jak opłacić:</strong> W aplikacji swojego banku wybierz <strong>Przelew na telefon BLIK</strong>, wklej powyższe dane i wyślij. Realizacja rusza od razu po odnotowaniu wpłaty!
                    </div>
                </div>

                <!-- 2. PAYSAFECARD -->
                <div id="paySectionPsc" style="display: ${initialTab === 'psc' ? 'block' : 'none'};">
                    <!-- Opcja 1: Kod(y) PIN kuponu fizycznego -->
                    <div style="background:#0c081d; border:1px solid rgba(168, 85, 247, 0.4); border-radius:12px; padding:16px; margin-bottom:14px;">
                        <div style="color:#c084fc; font-weight:800; font-size:0.92rem; margin-bottom:10px; display:flex; align-items:center; gap:6px;">
                            <span>🎟️ Opcja 1: Kod(y) PIN Paysafecard (Kupon fizyczny / Możesz dodać kilka kodów)</span>
                        </div>

                        <div style="background:rgba(239, 68, 68, 0.12); border:1px solid rgba(239, 68, 68, 0.35); border-radius:8px; padding:10px 12px; margin-bottom:12px; font-size:0.82rem; color:#fca5a5; line-height:1.45;">
                            ⚠️ <strong>Ważna informacja:</strong> Przy płatności kodem pobierana jest <strong>pełna kwota z kuponu</strong> (np. 20, 30, 50, 100 PLN). Możesz dodać <strong>dowolną liczbę kodów</strong> (np. dwa kupony po 20 zł), aby pokryć kwotę zamówienia (${amount} PLN). Kliknij poniżej <em>"➕ Dodaj kolejny kod"</em>, aby dodać kolejne pole.
                        </div>

                        <!-- Blok dotychczas przesłanych kodów -->
                        <div id="pscSubmittedBox" style="display: ${initialCodes.length > 0 ? 'block' : 'none'}; background:rgba(16, 185, 129, 0.1); border:1px solid rgba(16, 185, 129, 0.35); border-radius:8px; padding:10px 12px; margin-bottom:14px; font-size:0.82rem;">
                            <div style="color:#34d399; font-weight:800; margin-bottom:6px; display:flex; align-items:center; gap:6px;">
                                <span>✅ Dotychczas przesłane kody do zamówienia #${orderNum}:</span>
                            </div>
                            <ul id="pscSubmittedList" style="margin:0; padding-left:18px; color:#fff; font-family:monospace; font-size:0.88rem; line-height:1.5;">
                                ${initialCodes.map(c => `<li>${c}</li>`).join('')}
                            </ul>
                        </div>

                        <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:6px;">
                            Wprowadź 16-cyfrowy kod PIN kuponu Paysafecard:
                        </label>
                        
                        <div id="pscInputsContainer">
                            <div class="psc-input-row" style="display:flex; gap:6px; margin-bottom:8px;">
                                <input type="text" class="form-control psc-code-input" placeholder="Kupon 1 (16 cyfr): np. 0123-4567-8901-2345" maxlength="32" style="font-family:monospace; font-weight:700; font-size:0.95rem; letter-spacing:1px; background:#080514; color:#34d399;">
                            </div>
                        </div>

                        <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; flex-wrap:wrap; margin-top:8px;">
                            <button type="button" class="btn btn-outline btn-sm" onclick="addPscInputRow()" style="border-color:#a855f7; color:#c084fc; font-weight:700; font-size:0.8rem; padding:6px 12px;">
                                ➕ Dodaj kolejny kod
                            </button>
                            <button type="button" id="pscSubmitBtn" class="btn btn-gradient btn-sm" onclick="submitPscCodes('${orderNum}')" style="white-space:nowrap; font-weight:700; padding:7px 16px;">
                                🚀 Wyślij kod(y) kuponu
                            </button>
                        </div>

                        <div id="pscSubmitFeedback" style="display:none; font-size:0.82rem; margin-top:10px;"></div>
                    </div>

                    <!-- Opcja 2: Przelew myPaysafecard na e-mail -->
                    <div style="background:#0c081d; border:1px solid rgba(52, 211, 153, 0.4); border-radius:12px; padding:16px; margin-bottom:14px;">
                        <div style="color:#34d399; font-weight:800; font-size:0.92rem; margin-bottom:8px; display:flex; align-items:center; gap:6px;">
                            <span>✉️ Opcja 2: Przelew kontem myPaysafecard na e-mail (Dokładna kwota ze sklepu)</span>
                        </div>
                        <p style="color:var(--text-muted); font-size:0.82rem; line-height:1.45; margin-bottom:10px;">
                            Posiadasz zarejestrowane konto w <strong>myPaysafecard</strong>? Możesz przelać <strong>dokładną kwotę zamówienia (${amount} PLN)</strong> bez przepłacania bezpośrednio na nasz e-mail:
                        </p>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Adres e-mail konta myPaysafecard:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${pscEmail}" id="copyPscEmail" class="form-control" style="font-size:0.95rem; font-weight:800; color:#34d399; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPscEmail', 'Skopiowano e-mail Paysafecard!')" style="border-color:#34d399; color:#34d399; font-weight:700; flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div>
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Tytuł / Opis przelewu (Numer zamówienia):</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${cleanNum}" id="copyPscTitle" class="form-control" style="font-size:0.95rem; font-weight:800; color:#c084fc; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyPscTitle', 'Skopiowano numer zamówienia!')" style="border-color:#a855f7; color:#c084fc; font-weight:700; flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 3. Przelew Bankowy -->
                <div id="paySectionBank" style="display: ${initialTab === 'bank' ? 'block' : 'none'};">
                    <div style="background:#0c081d; border:1px solid rgba(168, 85, 247, 0.4); border-radius:12px; padding:16px; margin-bottom:14px;">
                        <div style="color:var(--accent-cyan); font-weight:800; font-size:0.92rem; margin-bottom:12px;">
                            🏦 Tradycyjny przelew bankowy (${bankName})
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Numer konta bankowego:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${bankAcc}" id="copyBankAcc" class="form-control" style="font-size:0.95rem; font-weight:800; color:#34d399; letter-spacing:0.5px; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyBankAcc', 'Skopiowano numer konta!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Odbiorca:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${name}" id="copyBankName" class="form-control" style="font-size:0.92rem; font-weight:700; color:#fff; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyBankName', 'Skopiowano odbiorcę!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div style="margin-bottom:10px;">
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Tytuł przelewu:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${title}" id="copyBankTitle" class="form-control" style="font-size:0.95rem; font-weight:800; color:#c084fc; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyBankTitle', 'Skopiowano tytuł przelewu!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>

                        <div>
                            <label style="display:block; font-size:0.75rem; color:var(--text-muted); text-transform:uppercase; font-weight:700; margin-bottom:3px;">Kwota:</label>
                            <div style="display:flex; gap:8px;">
                                <input type="text" readonly value="${amount} PLN" id="copyBankAmount" class="form-control" style="font-size:1.1rem; font-weight:900; color:#fff; background:#080514;">
                                <button type="button" class="btn btn-outline btn-sm" onclick="copyPaymentField('copyBankAmount', 'Skopiowano kwotę!')" style="flex-shrink:0;">📋 Kopiuj</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div style="margin-top:10px;">
                    <button type="button" class="btn btn-gradient full-width" onclick="closePaymentModal()" style="justify-content:center; padding:12px; font-weight:800; font-size:0.95rem;">
                        ✅ Rozumiem, zamknij to okno
                    </button>
                </div>
            `;

            modal.classList.add('active');
        }

        function switchPayModalTab(tab) {
            const blikSec = document.getElementById('paySectionBlik');
            const bankSec = document.getElementById('paySectionBank');
            const pscSec  = document.getElementById('paySectionPsc');
            const btnBlik = document.getElementById('payTabBtnBlik');
            const btnBank = document.getElementById('payTabBtnBank');
            const btnPsc  = document.getElementById('payTabBtnPsc');

            if (blikSec) blikSec.style.display = (tab === 'blik') ? 'block' : 'none';
            if (bankSec) bankSec.style.display = (tab === 'bank') ? 'block' : 'none';
            if (pscSec)  pscSec.style.display  = (tab === 'psc')  ? 'block' : 'none';

            if (btnBlik) btnBlik.className = 'btn btn-sm ' + (tab === 'blik' ? 'btn-gradient' : 'btn-outline');
            if (btnPsc)  btnPsc.className  = 'btn btn-sm ' + (tab === 'psc'  ? 'btn-gradient' : 'btn-outline');
            if (btnBank) btnBank.className = 'btn btn-sm ' + (tab === 'bank' ? 'btn-gradient' : 'btn-outline');
        }

        function addPscInputRow() {
            const container = document.getElementById('pscInputsContainer');
            if (!container) return;
            const count = container.querySelectorAll('.psc-code-input').length + 1;
            const row = document.createElement('div');
            row.className = 'psc-input-row';
            row.style.cssText = 'display:flex; gap:6px; margin-bottom:8px; align-items:center;';
            row.innerHTML = `
                <input type="text" class="form-control psc-code-input" placeholder="Kupon ${count} (16 cyfr): np. 0123-4567-8901-2345" maxlength="32" style="font-family:monospace; font-weight:700; font-size:0.95rem; letter-spacing:1px; background:#080514; color:#34d399;">
                <button type="button" class="btn btn-outline btn-sm" onclick="this.parentElement.remove()" style="border-color:rgba(239,68,68,0.4); color:#f87171; padding:6px 10px; font-weight:700; flex-shrink:0;" title="Usuń ten kod">✕</button>
            `;
            container.appendChild(row);
            const input = row.querySelector('input');
            if (input) input.focus();
        }

        function submitPscCodes(orderNum) {
            const inputs = document.querySelectorAll('.psc-code-input');
            const btn = document.getElementById('pscSubmitBtn');
            const feedback = document.getElementById('pscSubmitFeedback');
            const submittedBox = document.getElementById('pscSubmittedBox');
            const submittedList = document.getElementById('pscSubmittedList');

            const codes = [];
            inputs.forEach(inp => {
                const val = inp.value.trim();
                if (val.length >= 6) codes.push(val);
            });

            if (codes.length === 0) {
                showToast('Wpisz co najmniej jeden kod kuponu Paysafecard (16 cyfr)!');
                return;
            }

            if (btn) {
                btn.disabled = true;
                btn.innerText = 'Przesyłanie...';
            }

            fetch('api.php?action=submit_psc_code', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order_number: orderNum, psc_codes: codes })
            })
            .then(res => res.json())
            .then(data => {
                if (btn) {
                    btn.disabled = false;
                    btn.innerText = '🚀 Wyślij kod(y) kuponu';
                }
                if (data.status === 'success') {
                    showToast(data.message || '✅ Kod(y) Paysafecard zostały pomyślnie przesłane!');
                    if (feedback) {
                        feedback.style.display = 'block';
                        feedback.innerHTML = '<span style="color:#34d399; font-weight:700;">✅ Pomyślnie dodano ' + (data.added_count || codes.length) + ' kupon(y) do zamówienia #' + orderNum + '! Możesz w każdej chwili dopisać kolejny kod poniżej.</span>';
                    }

                    if (submittedBox && submittedList && data.all_codes) {
                        submittedList.innerHTML = '';
                        data.all_codes.forEach(c => {
                            const li = document.createElement('li');
                            li.textContent = c;
                            submittedList.appendChild(li);
                        });
                        submittedBox.style.display = 'block';
                    }

                    const container = document.getElementById('pscInputsContainer');
                    if (container) {
                        container.innerHTML = `
                            <div class="psc-input-row" style="display:flex; gap:6px; margin-bottom:8px;">
                                <input type="text" class="form-control psc-code-input" placeholder="Wpisz kolejny kupon (jeśli masz więcej)..." maxlength="32" style="font-family:monospace; font-weight:700; font-size:0.95rem; letter-spacing:1px; background:#080514; color:#34d399;">
                            </div>
                        `;
                    }
                } else {
                    showToast(data.message || 'Wystąpił błąd podczas zapisywania kodów.');
                }
            })
            .catch(err => {
                if (btn) {
                    btn.disabled = false;
                    btn.innerText = '🚀 Wyślij kod(y) kuponu';
                }
                showToast('Błąd połączenia z serwerem.');
            });
        }

        function submitPscCode(orderNum) {
            submitPscCodes(orderNum);
        }

        function closePaymentModal() {
            const m = document.getElementById('orderPaymentModal');
            if (m) m.classList.remove('active');
        }

        // Dodawanie wyceny do koszyka i przejście do sklepu (z możliwością użycia kodu rabatowego)
        function addQuoteToCart(quoteId, projectType, price) {
            let cart = [];
            try {
                cart = JSON.parse(localStorage.getItem('devforge_cart') || '[]');
            } catch(e) {
                cart = [];
            }

            const quoteItemId = 'custom-quote-' + quoteId;
            cart = cart.filter(item => item.id !== quoteItemId);

            cart.push({
                id: quoteItemId,
                quote_id: parseInt(quoteId),
                title: 'Projekt Custom: ' + projectType,
                price: parseFloat(price),
                qty: 1,
                tag: 'Wycena Custom',
                is_quote: true
            });

            localStorage.setItem('devforge_cart', JSON.stringify(cart));
            window.location.href = 'index.html?open_cart=1#katalog';
        }

        function addQuoteFromModalToCart() {
            const id = document.getElementById('modalQuoteId').value;
            const type = document.getElementById('modalProjectType').innerText;
            const priceText = document.getElementById('modalQuotedPrice').innerText.replace(' PLN', '').trim();
            if (id) {
                addQuoteToCart(id, type, priceText);
            }
        }

        function handleBuyQuoteClick(btn) {
            if (!btn) return;
            const quoteId = btn.getAttribute('data-quote-id');
            const projectType = btn.getAttribute('data-project-type') || 'Zlecenie Custom';
            const price = btn.getAttribute('data-price') || '0.00';
            openOrderQuoteModal(quoteId, projectType, price);
        }

        function openOrderQuoteModal(quoteId, projectType, price) {
            const idEl = document.getElementById('modalQuoteId');
            const typeEl = document.getElementById('modalProjectType');
            const priceEl = document.getElementById('modalQuotedPrice');
            const modalEl = document.getElementById('orderQuoteModal');

            if (idEl) idEl.value = quoteId;
            if (typeEl) typeEl.textContent = projectType;
            if (priceEl) priceEl.textContent = parseFloat(price || 0).toFixed(2) + ' PLN';
            if (modalEl) modalEl.classList.add('active');
        }

        function closeQuoteModal() {
            const m = document.getElementById('orderQuoteModal');
            if (m) m.classList.remove('active');
        }

        function switchTab(tabId, btn) {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            let targetBtn = btn;
            if (!targetBtn) {
                document.querySelectorAll('.tab-btn').forEach(b => {
                    const oc = b.getAttribute('onclick') || '';
                    if (oc.includes("'" + tabId + "'") || oc.includes('"' + tabId + '"')) {
                        targetBtn = b;
                    }
                });
            }
            if (targetBtn) targetBtn.classList.add('active');
            
            const targetContent = document.getElementById('tab-' + tabId);
            if (targetContent) targetContent.classList.add('active');
        }

        <?php if (isset($activeTabOnLoad) && $activeTabOnLoad === 'orders'): ?>
            document.addEventListener('DOMContentLoaded', function() {
                switchTab('orders');
                <?php if (!empty($autoPayOrderNum)): ?>
                    setTimeout(function() {
                        openOrderPaymentModal(<?= json_encode($autoPayOrderNum) ?>, <?= json_encode((float)$autoPayTotal) ?>, <?= json_encode($autoPayMethod) ?>);
                    }, 400);
                <?php endif; ?>
            });
        <?php endif; ?>

        function toggleMobileMenu() {
            const menu = document.getElementById('mobileMenu');
            const overlay = document.getElementById('mobileMenuOverlay');
            const btn = document.getElementById('mobileMenuBtn');
            if (menu && overlay) {
                const isOpen = menu.classList.toggle('active');
                overlay.classList.toggle('active', isOpen);
                if (btn) btn.classList.toggle('active', isOpen);
                document.body.style.overflow = isOpen ? 'hidden' : '';
            }
        }
        function closeMobileMenu() {
            const menu = document.getElementById('mobileMenu');
            const overlay = document.getElementById('mobileMenuOverlay');
            const btn = document.getElementById('mobileMenuBtn');
            if (menu) menu.classList.remove('active');
            if (overlay) overlay.classList.remove('active');
            if (btn) btn.classList.remove('active');
            document.body.style.overflow = '';
        }
    </script>
</body>
</html>

