<?php
require_once __DIR__ . '/db.php';
require_login('owner'); // Wymaga najwyższych uprawnień Właściciela sklepu

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

$msg = '';
$msgType = 'success';
$activeTab = $_POST['active_tab'] ?? $_GET['tab'] ?? 'orders';

// Obsługa akcji POST administratora
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_action'])) {
    $action = $_POST['admin_action'];

    try {
        // 1. Zmiana statusu zamówienia
        if ($action === 'update_order_status') {
            $orderId = (int)$_POST['order_id'];
            $newStatus = trim($_POST['status']);
            $allowed = ['Oczekujące', 'W realizacji', 'Zrealizowane', 'Anulowane'];
            if (in_array($newStatus, $allowed)) {
                $stmt = $db->prepare("UPDATE orders SET status = ? WHERE id = ?");
                $stmt->execute([$newStatus, $orderId]);
                $msg = "Zaktualizowano status zamówienia #{$orderId} na: {$newStatus}";
            }
        }
        // 2. Zmiana statusu płatności
        elseif ($action === 'update_order_paid') {
            $orderId = (int)$_POST['order_id'];
            $isPaid = (int)$_POST['is_paid'];
            $stmt = $db->prepare("UPDATE orders SET is_paid = ? WHERE id = ?");
            $stmt->execute([$isPaid, $orderId]);
            $msg = "Zaktualizowano status płatności dla zamówienia #{$orderId}.";
        }
        // 3. Usunięcie zamówienia
        elseif ($action === 'delete_order') {
            $orderId = (int)$_POST['order_id'];
            $stmt = $db->prepare("DELETE FROM orders WHERE id = ?");
            $stmt->execute([$orderId]);
            $msg = "Usunięto zamówienie #{$orderId}.";
        }
        // 4. Zmiana statusu i wyceny ceny dla projektu
        elseif ($action === 'update_quote_status' || $action === 'update_quote') {
            $quoteId = (int)$_POST['quote_id'];
            $newStatus = trim($_POST['status'] ?? 'Nowe');
            $quotedPrice = (isset($_POST['quoted_price']) && $_POST['quoted_price'] !== '') ? (float)$_POST['quoted_price'] : null;

            // Jeśli administrator podał cenę, a status był 'Nowe', automatycznie zmieniamy na 'Wycenione'
            if ($quotedPrice !== null && $quotedPrice > 0 && $newStatus === 'Nowe') {
                $newStatus = 'Wycenione';
            }

            $stmt = $db->prepare("UPDATE quotes SET status = ?, quoted_price = ? WHERE id = ?");
            $stmt->execute([$newStatus, $quotedPrice, $quoteId]);
            $msg = "Zapisano wycenę dla zlecenia #{$quoteId}" . ($quotedPrice !== null ? " (Ustalona kwota: " . number_format($quotedPrice, 2) . " PLN | Status: {$newStatus})" : " (Status: {$newStatus})");
        }
        // 5. Usunięcie wyceny
        elseif ($action === 'delete_quote') {
            $quoteId = (int)$_POST['quote_id'];
            $stmt = $db->prepare("DELETE FROM quotes WHERE id = ?");
            $stmt->execute([$quoteId]);
            $msg = "Usunięto zapytanie o wycenę #{$quoteId}.";
        }
        // 6. Zmiana roli użytkownika (WYŁĄCZNIE DLA WŁAŚCICIELA)
        elseif ($action === 'update_user_role') {
            $targetUserId = (int)$_POST['user_id'];
            $reqRole = $_POST['role'] ?? 'client';
            $newRole = in_array($reqRole, ['owner', 'admin', 'media', 'client', 'user']) ? $reqRole : 'client';
            if ($newRole === 'user') $newRole = 'client';
            
            $checkTarget = $db->prepare("SELECT role, username FROM users WHERE id = ?");
            $checkTarget->execute([$targetUserId]);
            $targetUser = $checkTarget->fetch();

            if (!$targetUser) {
                $msg = "Nie znaleziono takiego użytkownika.";
                $msgType = 'error';
            } elseif ($targetUser['role'] === 'owner' && (int)$admin['id'] !== $targetUserId) {
                $msg = "Rola innego Właściciela jest chroniona!";
                $msgType = 'error';
            } elseif (!is_owner()) {
                $msg = "Tylko Właściciel ma uprawnienia do nadawania i odbierania ról!";
                $msgType = 'error';
            } else {
                $stmt = $db->prepare("UPDATE users SET role = ? WHERE id = ?");
                $stmt->execute([$newRole, $targetUserId]);
                $msg = "Zmieniono rolę użytkownika {$targetUser['username']} na: {$newRole}";
            }
        }
        // 7. Usunięcie użytkownika (Z OCHRONĄ WŁAŚCICIELA)
        elseif ($action === 'delete_user') {
            $targetUserId = (int)$_POST['user_id'];
            
            $checkTarget = $db->prepare("SELECT role, username FROM users WHERE id = ?");
            $checkTarget->execute([$targetUserId]);
            $targetUser = $checkTarget->fetch();

            if (!$targetUser) {
                $msg = "Nie znaleziono użytkownika.";
                $msgType = 'error';
            } elseif ($targetUser['role'] === 'owner') {
                $msg = "Konto Właściciela jest nietykalne i nie może zostać usunięte!";
                $msgType = 'error';
            } elseif ($targetUserId === (int)$admin['id']) {
                $msg = "Nie możesz usunąć swojego własnego konta!";
                $msgType = 'error';
            } elseif (!is_owner() && $targetUser['role'] === 'admin') {
                $msg = "Tylko Właściciel może usuwać konta administratorów!";
                $msgType = 'error';
            } else {
                $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$targetUserId]);
                $msg = "Usunięto użytkownika {$targetUser['username']}.";
            }
        }
        // 8. Dodanie nowego użytkownika / administratora z poziomu panelu
        elseif ($action === 'create_user') {
            $username = trim($_POST['username'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $discord = trim($_POST['discord_tag'] ?? '');
            $pass = $_POST['password'] ?? '';
            $roleReq = $_POST['role'] ?? 'client';
            $role = in_array($roleReq, ['owner', 'admin', 'media', 'client']) ? $roleReq : 'client';

            if (empty($username) || empty($email) || empty($pass)) {
                $msg = "Wypełnij wszystkie wymagane pola (Login, Email, Hasło).";
                $msgType = 'error';
            } else {
                $hash = password_hash($pass, PASSWORD_BCRYPT);
                $stmt = $db->prepare("INSERT INTO users (username, email, password, discord_tag, role) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$username, $email, $hash, $discord, $role]);
                $msg = "Pomyślnie dodano użytkownika: {$username} ({$role})";
            }
        }
        // 9. Dodawanie nowego produktu do sklepu
        elseif ($action === 'add_product') {
            $title       = trim($_POST['title'] ?? '');
            $category    = trim($_POST['category'] ?? 'discord');
            $tag         = trim($_POST['tag'] ?? 'Bot Discord');
            $price       = (float)str_replace(',', '.', $_POST['price'] ?? 0);
            $techs       = trim($_POST['techs'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $details     = trim($_POST['details'] ?? '');

            if (empty($title) || $price <= 0) {
                $msg = "Podaj poprawną nazwę produktu i cenę (większą od 0).";
                $msgType = 'error';
            } else {
                $maxId = (int)$db->query("SELECT MAX(id) FROM products")->fetchColumn();
                $code = 'prod-' . ($maxId + 1);

                $stmt = $db->prepare("
                    INSERT INTO products (product_code, category, tag, title, description, price, techs, details, is_active)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
                ");
                $stmt->execute([$code, $category, $tag, $title, $description, $price, $techs, $details]);
                $msg = "Pomyślnie dodano nowy produkt do sklepu: {$title} ({$code}) za " . number_format($price, 2) . " PLN!";
            }
        }
        // 10. Aktualizacja istniejącego produktu
        elseif ($action === 'update_product') {
            $productId   = (int)$_POST['product_id'];
            $title       = trim($_POST['title'] ?? '');
            $category    = trim($_POST['category'] ?? 'discord');
            $tag         = trim($_POST['tag'] ?? 'Bot Discord');
            $price       = (float)str_replace(',', '.', $_POST['price'] ?? 0);
            $techs       = trim($_POST['techs'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $details     = trim($_POST['details'] ?? '');
            $isActive    = (int)($_POST['is_active'] ?? 1);

            if (empty($title) || $price <= 0) {
                $msg = "Podaj poprawną nazwę i cenę produktu.";
                $msgType = 'error';
            } else {
                $stmt = $db->prepare("
                    UPDATE products 
                    SET title = ?, category = ?, tag = ?, price = ?, techs = ?, description = ?, details = ?, is_active = ?
                    WHERE id = ?
                ");
                $stmt->execute([$title, $category, $tag, $price, $techs, $description, $details, $isActive, $productId]);
                $msg = "Zaktualizowano produkt #{$productId} ({$title})!";
            }
        }
        // 11. Włączanie / wyłączanie widoczności produktu
        elseif ($action === 'toggle_product_status') {
            $productId = (int)$_POST['product_id'];
            $newStatus = (int)$_POST['is_active'];
            $stmt = $db->prepare("UPDATE products SET is_active = ? WHERE id = ?");
            $stmt->execute([$newStatus, $productId]);
            $msg = $newStatus ? "Produkt jest teraz widoczny w sklepie." : "Produkt został ukryty w sklepie.";
        }
        // 12. Usuwanie produktu
        elseif ($action === 'delete_product') {
            $productId = (int)$_POST['product_id'];
            $stmt = $db->prepare("DELETE FROM products WHERE id = ?");
            $stmt->execute([$productId]);
            $msg = "Produkt został bezpowrotnie usunięty ze sklepu i bazy MySQL.";
        }
        // 13. Usuwanie opinii (moderacja spamu)
        elseif ($action === 'delete_review') {
            $reviewId = (int)$_POST['review_id'];
            $stmt = $db->prepare("DELETE FROM reviews WHERE id = ?");
            $stmt->execute([$reviewId]);
            $msg = "Opinia #{$reviewId} została usunięta z bazy danych.";
        }
        // 14. Aktualizacja danych do płatności (BLIK i Przelew)
        elseif ($action === 'update_payment_settings') {
            $blikPhone     = trim($_POST['payment_blik_phone'] ?? '');
            $blikName      = trim($_POST['payment_blik_name'] ?? '');
            $transferTitle = trim($_POST['payment_transfer_title'] ?? 'Za jedzenie');
            $bankAcc       = trim($_POST['payment_bank_account'] ?? '');
            $bankName      = trim($_POST['payment_bank_name'] ?? '');
            $pscEmail      = trim($_POST['payment_psc_email'] ?? 'herbscripts@gmail.com');

            set_setting('payment_blik_phone', $blikPhone);
            set_setting('payment_blik_name', $blikName);
            set_setting('payment_transfer_title', $transferTitle);
            set_setting('payment_bank_account', $bankAcc);
            set_setting('payment_bank_name', $bankName);
            set_setting('payment_psc_email', $pscEmail);

            $msg = "Dane do płatności BLIK, przelewu bankowego oraz Paysafecard zostały pomyślnie zaktualizowane!";
        }
        // 15. Tworzenie i przypisywanie nowego kodu twórcy (Program Media)
        elseif ($action === 'create_media_code') {
            $code = strtoupper(trim($_POST['code'] ?? ''));
            $targetUserId = (int)($_POST['user_id'] ?? 0);
            $discount = (float)str_replace(',', '.', $_POST['discount_percent'] ?? 5.00);
            $commission = (float)str_replace(',', '.', $_POST['commission_percent'] ?? 10.00);
            $setRole = !empty($_POST['set_media_role']);

            if (empty($code) || $targetUserId <= 0) {
                $msg = "Wpisz kod promocyjny oraz wybierz użytkownika, do którego ma być przypisany.";
                $msgType = 'error';
            } else {
                $chk = $db->prepare("SELECT id FROM media_codes WHERE UPPER(code) = ?");
                $chk->execute([$code]);
                if ($chk->fetch()) {
                    $msg = "Kod '{$code}' już istnieje w bazie! Wpisz inny, unikalny kod.";
                    $msgType = 'error';
                } else {
                    $ins = $db->prepare("INSERT INTO media_codes (code, user_id, discount_percent, commission_percent, is_active) VALUES (?, ?, ?, ?, 1)");
                    $ins->execute([$code, $targetUserId, $discount, $commission]);
                    if ($setRole) {
                        $db->exec("UPDATE users SET role = 'media' WHERE id = {$targetUserId} AND role = 'client'");
                    }
                    $msg = "Pomyślnie utworzono i przypisano kod twórcy '{$code}' (Rabat dla widza: {$discount}%, Prowizja twórcy: {$commission}%)!";
                }
            }
        }
        // 16. Zmiana statusu aktywności kodu twórcy
        elseif ($action === 'toggle_media_code') {
            $codeId = (int)$_POST['code_id'];
            $newStatus = (int)$_POST['is_active'];
            $stmt = $db->prepare("UPDATE media_codes SET is_active = ? WHERE id = ?");
            $stmt->execute([$newStatus, $codeId]);
            $msg = "Zmieniono status aktywności kodu twórcy.";
        }
        // 17. Usunięcie kodu twórcy
        elseif ($action === 'delete_media_code') {
            $codeId = (int)$_POST['code_id'];
            $stmt = $db->prepare("DELETE FROM media_codes WHERE id = ?");
            $stmt->execute([$codeId]);
            $msg = "Kod twórcy został pomyślnie usunięty.";
        }
    } catch (Exception $e) {
        $msg = "Błąd: " . $e->getMessage();
        $msgType = 'error';
    }
}

// Pobieranie danych do panelu
$orders = [];
$quotes = [];
$users = [];
$products = [];
$reviews = [];
$mediaCodes = [];
$totalRevenue = 0.00; // Zysk na czysto Właściciela (po odliczeniu 10% dla mediów)
$totalGrossRevenue = 0.00; // Łączny obrót wpłacony przez klientów
$pendingOrders = 0;
$activeProductsCount = 0;
$totalMediaCommissions = 0.00;
$totalMediaRevenue = 0.00;
$totalMediaOrdersCount = 0;

$blikPhoneVal     = get_setting('payment_blik_phone', '500 123 456');
$blikNameVal      = get_setting('payment_blik_name', 'HerbScripts Studio');
$transferTitleVal = get_setting('payment_transfer_title', 'Za jedzenie');
$bankAccVal       = get_setting('payment_bank_account', '12 1020 0000 0000 0000 0000 0000');
$bankNameVal      = get_setting('payment_bank_name', 'PKO Bank Polski');

if ($db) {
    try {
        $orders   = $db->query("SELECT * FROM orders ORDER BY id DESC")->fetchAll();
        $quotes   = $db->query("SELECT * FROM quotes ORDER BY id DESC")->fetchAll();
        $users    = $db->query("SELECT id, username, email, discord_tag, role, created_at FROM users ORDER BY id DESC")->fetchAll();
        $products = $db->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
        $reviews  = $db->query("SELECT * FROM reviews ORDER BY id DESC")->fetchAll();

        foreach ($orders as $o) {
            $orderTotal = (float)$o['total_amount'];
            $commAmount = (float)($o['commission_amount'] ?? 0);
            if ($commAmount <= 0 && !empty($o['promo_code'])) {
                $commAmount = round($orderTotal * 0.10, 2);
            }

            if ($o['is_paid']) {
                $totalGrossRevenue += $orderTotal;
                // Zysk Właściciela: po odjęciu 10% prowizji dla twórcy
                $totalRevenue += ($orderTotal - $commAmount);
            }
            if ($o['status'] === 'Oczekujące') {
                $pendingOrders++;
            }
        }

        foreach ($products as $p) {
            if ($p['is_active']) {
                $activeProductsCount++;
            }
        }

        // Pobieranie kodów twórców i ich statystyk
        try {
            $mcStmt = $db->query("
                SELECT mc.*, u.username as creator_name, u.email as creator_email, u.discord_tag as creator_discord, u.role as creator_role,
                (SELECT COUNT(*) FROM orders o WHERE UPPER(o.promo_code) = UPPER(mc.code)) as usage_count,
                (SELECT COALESCE(SUM(o.total_amount), 0.00) FROM orders o WHERE UPPER(o.promo_code) = UPPER(mc.code) AND o.status != 'Anulowane') as total_generated,
                (SELECT COALESCE(SUM(CASE WHEN o.commission_amount > 0 THEN o.commission_amount ELSE (o.total_amount * mc.commission_percent / 100) END), 0.00) FROM orders o WHERE UPPER(o.promo_code) = UPPER(mc.code) AND o.is_paid = 1 AND o.status != 'Anulowane') as commission_paid,
                (SELECT COALESCE(SUM(CASE WHEN o.commission_amount > 0 THEN o.commission_amount ELSE (o.total_amount * mc.commission_percent / 100) END), 0.00) FROM orders o WHERE UPPER(o.promo_code) = UPPER(mc.code) AND o.status != 'Anulowane') as total_commission
                FROM media_codes mc
                JOIN users u ON u.id = mc.user_id
                ORDER BY mc.id DESC
            ");
            $mediaCodes = $mcStmt->fetchAll();

            foreach ($mediaCodes as $mc) {
                $totalMediaOrdersCount += (int)$mc['usage_count'];
                $totalMediaRevenue += (float)$mc['total_generated'];
                $totalMediaCommissions += (float)$mc['commission_paid'];
            }
        } catch (Throwable $eMc) {}
    } catch (Exception $e) {
        $msg = "Błąd pobierania danych: " . $e->getMessage();
        $msgType = 'error';
    }
}

$blikPhoneVal     = get_setting('payment_blik_phone', '500 123 456');
$blikNameVal      = get_setting('payment_blik_name', 'HerbScripts Studio');
$transferTitleVal = get_setting('payment_transfer_title', 'Za jedzenie');
$bankAccVal       = get_setting('payment_bank_account', '12 1020 0000 0000 0000 0000 0000');
$bankNameVal      = get_setting('payment_bank_name', 'PKO Bank Polski');
$pscEmailVal      = get_setting('payment_psc_email', 'herbscripts@gmail.com');

function safe_str_shorten($str, $len = 90) {
    if (empty($str)) return '';
    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($str, 0, $len, '...');
    }
    return (strlen($str) > $len) ? substr($str, 0, $len) . '...' : $str;
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel Administratora | HerbScripts</title>
    <link rel="stylesheet" href="style.css?v=<?= time() ?>">
    <script>
        function switchAdminTab(tabId, btn) {
            document.querySelectorAll('.tab-btn-admin').forEach(function(b) { b.classList.remove('active'); });
            document.querySelectorAll('.tab-section-admin').forEach(function(s) { s.classList.remove('active'); });
            if (btn) btn.classList.add('active');
            var target = document.getElementById('admin-' + tabId);
            if (target) target.classList.add('active');
        }

        function filterOrdersTable(query) {
            query = (query || '').toLowerCase();
            var rows = document.querySelectorAll('#ordersMainTable tbody tr');
            rows.forEach(function(r) {
                var text = r.innerText.toLowerCase();
                r.style.display = text.includes(query) ? '' : 'none';
            });
        }

        function filterProductsTable(query) {
            query = (query || '').toLowerCase();
            var rows = document.querySelectorAll('#productsMainTable tbody tr');
            rows.forEach(function(r) {
                var text = r.innerText.toLowerCase();
                r.style.display = text.includes(query) ? '' : 'none';
            });
        }

        function openEditProductModal(p) {
            if (!p) return;
            document.getElementById('edit_product_id').value = p.id || '';
            document.getElementById('edit_title').value = p.title || '';
            document.getElementById('edit_price').value = p.price || '';
            document.getElementById('edit_category').value = p.category || 'discord';
            document.getElementById('edit_tag').value = p.tag || 'Bot Discord';
            document.getElementById('edit_techs').value = p.techs || '';
            document.getElementById('edit_description').value = p.description || '';
            document.getElementById('edit_details').value = p.details || '';
            document.getElementById('edit_is_active').value = (p.is_active == 1) ? '1' : '0';
            var modal = document.getElementById('editProductModal');
            if (modal) modal.classList.add('active');
        }

        function closeProductModal() {
            var modal = document.getElementById('editProductModal');
            if (modal) modal.classList.remove('active');
        }
    </script>
    <style>
        .admin-page-container {
            max-width: 1350px;
            margin: 25px auto;
            padding: 0 20px 80px;
        }
        .admin-topbar {
            background: linear-gradient(135deg, rgba(113, 39, 245, 0.22), rgba(168, 85, 247, 0.12));
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 22px 28px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 28px;
            backdrop-filter: blur(14px);
            box-shadow: 0 10px 35px rgba(0,0,0,0.35);
        }
        .admin-topbar h1 {
            font-size: 1.6rem;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .admin-badge-pill {
            background: #ef4444;
            color: #fff;
            font-size: 0.72rem;
            font-weight: 800;
            padding: 3px 8px;
            border-radius: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .stats-grid-admin {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 28px;
        }
        .admin-stat-box {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            text-align: left;
            backdrop-filter: blur(10px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        .admin-stat-box .val {
            font-size: 1.85rem;
            font-weight: 800;
            margin-bottom: 4px;
        }
        .admin-stat-box .lbl {
            font-size: 0.78rem;
            color: var(--text-muted);
            text-transform: uppercase;
            font-weight: 600;
        }
        .tabs-header-admin {
            display: flex;
            gap: 10px;
            border-bottom: 1px solid var(--border);
            margin-bottom: 24px;
            overflow-x: auto;
        }
        .tab-btn-admin {
            background: none;
            border: none;
            color: var(--text-muted);
            padding: 12px 20px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.2s;
            white-space: nowrap;
        }
        .tab-btn-admin.active {
            color: var(--accent-cyan);
            border-bottom-color: var(--accent-cyan);
        }
        .tab-section-admin {
            display: none;
        }
        .tab-section-admin.active {
            display: block;
        }
        .table-responsive {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            overflow-x: auto;
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.35);
        }
        .custom-admin-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
            text-align: left;
        }
        .custom-admin-table th {
            background: rgba(22, 15, 46, 0.95);
            color: var(--text-muted);
            padding: 14px 16px;
            font-weight: 600;
            border-bottom: 1px solid var(--border);
            white-space: nowrap;
        }
        .custom-admin-table td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--border);
            vertical-align: middle;
        }
        .custom-admin-table tr:hover {
            background: rgba(168, 85, 247, 0.05);
        }
        .badge-status {
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 700;
            display: inline-block;
        }
        .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); }
        .filter-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            gap: 12px;
            flex-wrap: wrap;
        }
        .action-btn-sm {
            padding: 5px 10px;
            font-size: 0.78rem;
            border-radius: 6px;
            border: 1px solid var(--border);
            background: rgba(22, 15, 46, 0.85);
            color: #fff;
            cursor: pointer;
            transition: all 0.2s;
        }
        .action-btn-sm:hover {
            border-color: var(--accent-cyan);
            background: rgba(113, 39, 245, 0.3);
        }
        .btn-danger-sm {
            background: rgba(239, 68, 68, 0.15);
            color: #f87171;
            border-color: rgba(239, 68, 68, 0.3);
        }
        .btn-danger-sm:hover {
            background: #ef4444;
            color: #fff;
        }

        /* Responsywność na telefony i tablety */
        @media (max-width: 900px) {
            #admin-users > div,
            #adminProductsGrid,
            #adminMediaGrid {
                grid-template-columns: 1fr !important;
                gap: 20px;
            }
        }

        @media (max-width: 768px) {
            .admin-page-container {
                padding: 0 14px 40px;
                margin: 15px auto;
            }
            .admin-topbar {
                padding: 18px 16px;
                border-radius: 12px;
                flex-direction: column;
                align-items: stretch;
                gap: 14px;
            }
            .admin-topbar h1 {
                font-size: 1.25rem;
                flex-wrap: wrap;
                line-height: 1.3;
            }
            .admin-topbar-actions {
                display: flex;
                gap: 8px;
                width: 100%;
            }
            .admin-topbar-actions .btn {
                flex: 1;
                justify-content: center;
                text-align: center;
                padding: 9px 12px;
            }
            .stats-grid-admin {
                grid-template-columns: repeat(2, 1fr);
                gap: 10px;
                margin-bottom: 20px;
            }
            .admin-stat-box {
                padding: 14px 16px;
            }
            .admin-stat-box .val {
                font-size: 1.45rem;
            }
            .tabs-header-admin {
                gap: 6px;
                padding-bottom: 6px;
                -webkit-overflow-scrolling: touch;
            }
            .tab-btn-admin {
                padding: 10px 14px;
                font-size: 0.84rem;
            }
            .filter-controls {
                flex-direction: column;
                align-items: stretch;
                gap: 8px;
            }
            #orderSearch {
                max-width: 100% !important;
                width: 100%;
            }
            .table-responsive {
                border-radius: 10px;
                -webkit-overflow-scrolling: touch;
            }
            .custom-admin-table {
                min-width: 600px;
            }
            .custom-admin-table th, 
            .custom-admin-table td {
                padding: 10px 12px;
                font-size: 0.8rem;
            }
            .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;
            }
            .stats-grid-admin {
                grid-template-columns: 1fr;
            }
            .admin-topbar-actions {
                flex-direction: column;
            }
            .admin-topbar-actions .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <header>
        <a href="index.html" class="logo">Herb<span>Scripts.</span> <small style="font-size:0.75rem; color:#fbbf24;">OWNER</small></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;">
                👑 Panele Właściciela
            </div>
            <a href="panel-wlasciciela.php" class="btn btn-outline full-width" style="border-color: #fbbf24; color: #fbbf24; margin-bottom: 8px;">
                👑 Panel Właściciela (Aktywny)
            </a>
            <a href="panel-admina.php" class="btn btn-outline full-width" style="border-color: #34d399; color: #34d399; margin-bottom: 8px;">
                🛡️ Panel Administratora
            </a>
            <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>
            <a href="panel-klienta.php" class="btn btn-outline full-width" style="border-color: #a855f7; color: #a855f7; margin-bottom: 8px;">
                👤 Panel Klienta
            </a>
            <a href="logout.php" class="btn btn-outline full-width" style="border-color: #ef4444; color: #f87171;">
                🚪 Wyloguj się
            </a>
        </div>
    </div>

    <div class="admin-page-container">
        <!-- Pasek powitalny właściciela -->
        <div class="admin-topbar">
            <div>
                <h1>
                    <span>Pulpit Główny Właściciela</span>
                    <span class="admin-badge-pill" style="background:linear-gradient(135deg, #f59e0b, #d97706); color:#fff; box-shadow:0 0 10px rgba(245, 158, 11, 0.4);">👑 Właściciel</span>
                </h1>
                <p style="color:var(--text-muted); font-size:0.88rem; margin-top:4px;">
                    Zalogowany jako: <strong style="color:#fff;"><?= htmlspecialchars($admin['username']) ?></strong> 
                    (<?= htmlspecialchars($admin['email']) ?> &bull; Rola: <strong style="color:#fbbf24;">👑 Główny Właściciel Sklepu</strong>)
                </p>
            </div>
            <div class="admin-topbar-actions">
                <a href="panel-admina.php" class="btn btn-outline btn-sm" style="border-color:#34d399; color:#34d399;">🛡️ Podgląd Panelu Admina</a>
                <a href="panel-wlasciciela.php" class="btn btn-outline btn-sm">🔄 Odśwież dane</a>
                <a href="index.html" class="btn btn-gradient btn-sm">🛒 Przejdź do sklepu</a>
            </div>
        </div>

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

        <!-- Statystyki sklepu -->
        <div class="stats-grid-admin">
            <div class="admin-stat-box">
                <div class="val" style="color:#34d399;"><?= number_format($totalRevenue, 2) ?> PLN</div>
                <div class="lbl">👑 Twój Zysk (Po -10% dla Mediów)</div>
                <small style="color:var(--text-muted); font-size:0.72rem; display:block; margin-top:2px;">
                    Obrót od klientów: <?= number_format($totalGrossRevenue, 2) ?> PLN
                </small>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:var(--accent-cyan);"><?= count($orders) ?></div>
                <div class="lbl">Wszystkie Zamówienia</div>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:#fbbf24;"><?= $pendingOrders ?></div>
                <div class="lbl">Zamówienia Oczekujące</div>
            </div>
            <div class="admin-stat-box" style="border-color:rgba(236, 72, 153, 0.4);">
                <div class="val" style="color:#f472b6;"><?= number_format($totalMediaCommissions, 2) ?> PLN</div>
                <div class="lbl">🎬 Prowizje Media (-10% do wypłaty)</div>
                <small style="color:var(--text-muted); font-size:0.72rem; display:block; margin-top:2px;">
                    Do przekazania twórcom (np. BLIK)
                </small>
            </div>
            <div class="admin-stat-box" style="border-color:rgba(236, 72, 153, 0.4);">
                <div class="val" style="color:#ec4899;"><?= number_format($totalMediaRevenue, 2) ?> PLN</div>
                <div class="lbl">🎬 Obrót z Kodów Twórców</div>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:#c084fc;"><?= count($users) ?></div>
                <div class="lbl">Zarejestrowani Użytkownicy</div>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:#38bdf8;"><?= count($quotes) ?></div>
                <div class="lbl">Wyceny Custom</div>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:#a855f7;"><?= $activeProductsCount ?> / <?= count($products) ?></div>
                <div class="lbl">Produkty w Sklepie</div>
            </div>
            <div class="admin-stat-box">
                <div class="val" style="color:#fbbf24;">⭐ <?= count($reviews) ?></div>
                <div class="lbl">Opinie Klientów</div>
            </div>
        </div>

        <!-- Zakładki -->
        <div class="tabs-header-admin">
            <button class="tab-btn-admin active" onclick="switchAdminTab('orders', this)">
                📦 Zarządzanie Zamówieniami (<?= count($orders) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('products', this)">
                🛍️ Produkty w Sklepie (<?= count($products) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('quotes', this)">
                💬 Wyceny Custom (<?= count($quotes) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('media', this)">
                🎬 Kody Twórców (Media) (<?= count($mediaCodes) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('users', this)">
                👥 Użytkownicy & Konta (<?= count($users) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('reviews', this)">
                ⭐ Opinie Klientów (<?= count($reviews) ?>)
            </button>
            <button class="tab-btn-admin" onclick="switchAdminTab('settings', this)">
                💳 Płatności BLIK & Przelew
            </button>
        </div>

        <!-- SEKCJA 1: ZAMÓWIENIA -->
        <div id="admin-orders" class="tab-section-admin active">
            <div class="filter-controls">
                <input type="text" id="orderSearch" class="form-control" placeholder="🔍 Szukaj po ID, Discord, e-mailu..." style="max-width:320px;" oninput="filterOrdersTable(this.value)">
                <div style="font-size:0.85rem; color:var(--text-muted);">
                    Zamówienia są na bieżąco pobierane z tabeli <code>orders</code> w MySQL (phpMyAdmin).
                </div>
            </div>

            <div class="table-responsive">
                <table class="custom-admin-table" id="ordersMainTable">
                    <thead>
                        <tr>
                            <th>ID / Numer</th>
                            <th>Klient</th>
                            <th>Zakupione produkty</th>
                            <th>Kwota & Płatność</th>
                            <th>Status zamówienia</th>
                            <th>Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($orders)): ?>
                            <tr>
                                <td colspan="6" style="text-align:center; padding:30px; color:var(--text-muted);">
                                    Brak zamówień w bazie MySQL.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($orders as $o): 
                                $items = json_decode($o['items_json'], true) ?: [];
                                $statusClass = 'badge-' . strtolower(str_replace([' ', 'ą', 'ę'], ['-', 'a', 'e'], $o['status']));
                            ?>
                                <tr>
                                    <td>
                                        <strong style="color:#fff;"><?= htmlspecialchars($o['order_number']) ?></strong><br>
                                        <small style="color:var(--text-muted);">ID: #<?= $o['id'] ?> | <?= date('d.m.Y H:i', strtotime($o['created_at'])) ?></small>
                                    </td>
                                    <td>
                                        <strong style="color:var(--accent-cyan);"><?= htmlspecialchars($o['customer_discord']) ?></strong><br>
                                        <small style="color:var(--text-muted);"><?= htmlspecialchars($o['customer_email']) ?></small>
                                    </td>
                                    <td>
                                        <?php if (empty($items)): ?>
                                            <span style="color:var(--text-muted);">Brak danych</span>
                                        <?php else: ?>
                                            <ul style="list-style:none; padding:0; margin:0; font-size:0.82rem;">
                                                <?php foreach ($items as $it): ?>
                                                    <li>• <?= htmlspecialchars($it['title'] ?? 'Produkt') ?> (x<?= (int)($it['qty'] ?? 1) ?>)</li>
                                                <?php endforeach; ?>
                                            </ul>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <strong style="color:#fff; font-size:0.95rem;"><?= number_format((float)$o['total_amount'], 2) ?> PLN</strong><br>
                                        <small style="color:var(--text-muted);"><?= htmlspecialchars($o['payment_method']) ?></small>
                                        
                                        <?php if (!empty($o['promo_code'])): ?>
                                            <div style="margin-top:6px;">
                                                <span class="badge-status" style="background:rgba(236,72,153,0.22); color:#f472b6; border:1px solid rgba(236,72,153,0.45); font-size:0.75rem; font-weight:800; display:inline-block; padding:4px 8px;">
                                                    🏷️ Kod rabatowy: <?= htmlspecialchars($o['promo_code']) ?> (-5% klient + -10% dla mediów)
                                                </span>
                                            </div>
                                            <?php 
                                                $commAmount = (float)($o['commission_amount'] ?? 0);
                                                if ($commAmount <= 0) {
                                                    $commAmount = round((float)$o['total_amount'] * 0.10, 2);
                                                }
                                                $ownerProfit = (float)$o['total_amount'] - $commAmount;
                                            ?>
                                            <div style="margin-top:5px; font-size:0.74rem; color:#fbbf24; background:rgba(245,158,11,0.1); border:1px dashed rgba(245,158,11,0.3); border-radius:6px; padding:5px 8px; line-height:1.4;">
                                                💰 <strong>Prowizja twórcy (-10%):</strong> <?= number_format($commAmount, 2) ?> PLN
                                                <br><span style="color:#34d399; font-weight:700;">👑 Twój zysk po odjęciu 10%: <?= number_format($ownerProfit, 2) ?> PLN</span>
                                                <div style="font-size:0.67rem; color:var(--text-muted); margin-top:2px;">
                                                    (Klient wpłacił: <?= number_format((float)$o['total_amount'], 2) ?> PLN &bull; 10% rozliczasz z twórcą)
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <?php if (!empty($o['notes'])): ?>
                                            <div style="margin-top:6px; font-size:0.75rem; background:rgba(16,185,129,0.12); border:1px solid rgba(16,185,129,0.3); border-radius:6px; padding:6px 8px; color:#34d399; line-height:1.4;">
                                                📝 <strong>Uwagi / Kod kuponu:</strong><br>
                                                <?= nl2br(htmlspecialchars($o['notes'])) ?>
                                            </div>
                                        <?php endif; ?>

                                        <form method="POST" action="panel-wlasciciela.php" style="margin-top:6px;">
                                            <input type="hidden" name="admin_action" value="update_order_paid">
                                            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                                            <select name="is_paid" class="form-control" style="padding:2px 6px; font-size:0.75rem; width:auto; border-color:<?= $o['is_paid'] ? '#34d399' : '#f87171' ?>; color:<?= $o['is_paid'] ? '#34d399' : '#f87171' ?>;" onchange="this.form.submit()">
                                                <option value="0" <?= !$o['is_paid'] ? 'selected' : '' ?>>❌ Nieopłacone</option>
                                                <option value="1" <?= $o['is_paid'] ? 'selected' : '' ?>>✅ Opłacone</option>
                                            </select>
                                        </form>
                                    </td>
                                    <td>
                                        <div style="margin-bottom:6px;">
                                            <span class="badge-status <?= $statusClass ?>"><?= htmlspecialchars($o['status']) ?></span>
                                        </div>
                                        <form method="POST" action="panel-wlasciciela.php">
                                            <input type="hidden" name="admin_action" value="update_order_status">
                                            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                                            <select name="status" class="form-control" style="padding:4px 8px; font-size:0.8rem; width:auto;" onchange="this.form.submit()">
                                                <option value="Oczekujące" <?= $o['status'] === 'Oczekujące' ? 'selected' : '' ?>>Oczekujące</option>
                                                <option value="W realizacji" <?= $o['status'] === 'W realizacji' ? 'selected' : '' ?>>W realizacji</option>
                                                <option value="Zrealizowane" <?= $o['status'] === 'Zrealizowane' ? 'selected' : '' ?>>Zrealizowane</option>
                                                <option value="Anulowane" <?= $o['status'] === 'Anulowane' ? 'selected' : '' ?>>Anulowane</option>
                                            </select>
                                        </form>
                                    </td>
                                    <td>
                                        <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Czy na pewno chcesz usunąć zamówienie #<?= $o['order_number'] ?> z bazy MySQL?')">
                                            <input type="hidden" name="admin_action" value="delete_order">
                                            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                                            <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- SEKCJA 2: WYCENY CUSTOM -->
        <div id="admin-quotes" class="tab-section-admin">
            <div class="table-responsive">
                <table class="custom-admin-table">
                    <thead>
                        <tr>
                            <th>ID / Data</th>
                            <th>Klient (Discord)</th>
                            <th>Kategoria & Budżet</th>
                            <th>Opis projektu</th>
                            <th>Wycena ceny (PLN) & Status</th>
                            <th>Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($quotes)): ?>
                            <tr>
                                <td colspan="6" style="text-align:center; padding:30px; color:var(--text-muted);">
                                    Brak zapytań o wycenę w bazie danych.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($quotes as $q): ?>
                                <tr>
                                    <td>
                                        <strong>#<?= $q['id'] ?></strong><br>
                                        <small style="color:var(--text-muted);"><?= date('d.m.Y H:i', strtotime($q['created_at'])) ?></small>
                                    </td>
                                    <td>
                                        <strong style="color:var(--accent-cyan);"><?= htmlspecialchars($q['discord_tag']) ?></strong>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($q['project_type']) ?></strong><br>
                                        <small style="color:#fbbf24;">Budżet klienta: <?= htmlspecialchars($q['budget']) ?> PLN</small>
                                        <?php if ($q['status'] === 'Zamówione'): ?>
                                            <div style="margin-top:4px;">
                                                <span class="badge-status badge-zrealizowane" style="font-size:0.75rem; padding:2px 8px; display:inline-block;">🛒 Kupione przez klienta</span>
                                                <?php if (!empty($q['order_id'])): ?>
                                                    <small style="color:var(--accent-cyan); font-weight:700;">(Zamówienie #<?= $q['order_id'] ?>)</small>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td style="max-width:320px;">
                                        <p style="margin:0; font-size:0.83rem; color:#cbd5e1; white-space:pre-wrap;"><?= htmlspecialchars($q['description']) ?></p>
                                    </td>
                                    <td>
                                        <form method="POST" action="panel-wlasciciela.php" style="display:flex; flex-direction:column; gap:6px; min-width:190px;">
                                            <input type="hidden" name="admin_action" value="update_quote_status">
                                            <input type="hidden" name="active_tab" value="quotes">
                                            <input type="hidden" name="quote_id" value="<?= $q['id'] ?>">

                                            <div style="display:flex; align-items:center; gap:6px;">
                                                <span style="color:#34d399; font-weight:800; font-size:0.8rem;">PLN:</span>
                                                <input type="number" step="0.01" name="quoted_price" class="form-control" placeholder="Wpisz cenę..." value="<?= isset($q['quoted_price']) && $q['quoted_price'] !== null ? htmlspecialchars($q['quoted_price']) : '' ?>" style="padding:4px 8px; font-size:0.82rem; font-weight:700; color:#34d399; border-color:rgba(16, 185, 129, 0.4);">
                                            </div>

                                            <div style="display:flex; gap:6px;">
                                                <select name="status" class="form-control" style="padding:4px 6px; font-size:0.78rem; flex-grow:1;">
                                                    <option value="Nowe" <?= $q['status'] === 'Nowe' ? 'selected' : '' ?>>Nowe</option>
                                                    <option value="W kontakcie" <?= $q['status'] === 'W kontakcie' ? 'selected' : '' ?>>W kontakcie</option>
                                                    <option value="Wycenione" <?= $q['status'] === 'Wycenione' ? 'selected' : '' ?>>Wycenione</option>
                                                    <option value="Zamówione" <?= $q['status'] === 'Zamówione' ? 'selected' : '' ?>>🛒 Zamówione (Kupione)</option>
                                                    <option value="Odrzucone" <?= $q['status'] === 'Odrzucone' ? 'selected' : '' ?>>Odrzucone</option>
                                                </select>
                                                <button type="submit" class="action-btn-sm" style="background:#10b981; color:#fff; border:none; padding:4px 8px;" title="Zapisz cenę i status">💾 Zapisz</button>
                                            </div>
                                        </form>
                                    </td>
                                    <td>
                                        <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Usunąć to zapytanie o wycenę?')">
                                            <input type="hidden" name="admin_action" value="delete_quote">
                                            <input type="hidden" name="active_tab" value="quotes">
                                            <input type="hidden" name="quote_id" value="<?= $q['id'] ?>">
                                            <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- SEKCJA: PROGRAM PARTNERSKI & KODY TWÓRCÓW (MEDIA) -->
        <div id="admin-media" class="tab-section-admin">
            <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.3); border-radius:14px; padding:20px; margin-bottom:24px;">
                <div style="display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:14px;">
                    <div>
                        <h3 style="color:#fff; font-size:1.3rem; margin-bottom:6px; display:flex; align-items:center; gap:8px;">
                            <span>🎬 Centrala Programu Partnerskiego (Media)</span>
                            <span class="admin-badge-pill" style="background:#ec4899; color:#fff;">Sterowane przez Właściciela</span>
                        </h3>
                        <p style="color:var(--text-muted); font-size:0.88rem; line-height:1.5; margin:0; max-width:850px;">
                            W tym miejscu tworzysz kody promocyjne i podpinasz je bezpośrednio pod konta użytkowników w bazie MySQL.
                            <br>• <strong>Dla klienta:</strong> kod daje automatyczny rabat (np. <strong>-5%</strong>).
                            <br>• <strong>Dla twórcy:</strong> system nalicza <strong>10% prowizji</strong> od zamówienia.
                            <br>• <strong>Zasada rozliczeń:</strong> prowizja 10% <u>nie jest odejmowana</u> od ceny zamówienia klienta — to kwota do późniejszego rozliczenia między Tobą a twórcą (np. BLIK / przelew).
                        </p>
                    </div>
                    <div>
                        <a href="panel-media.php" target="_blank" class="btn btn-outline" style="border-color:#ec4899; color:#f472b6;">
                            👁️ Podgląd Panelu Twórcy ➔
                        </a>
                    </div>
                </div>
            </div>

            <!-- Karty podsumowania mediów -->
            <div class="stats-grid-admin" style="margin-bottom:24px;">
                <div class="admin-stat-box" style="border-color:rgba(236,72,153,0.4);">
                    <div class="val" style="color:#f472b6;"><?= number_format($totalMediaCommissions, 2) ?> PLN</div>
                    <div class="lbl">Łączna Prowizja 10% (Opłacone)</div>
                </div>
                <div class="admin-stat-box" style="border-color:rgba(168,85,247,0.4);">
                    <div class="val" style="color:var(--accent-cyan);"><?= number_format($totalMediaRevenue, 2) ?> PLN</div>
                    <div class="lbl">Łączny Obrót z Kodów</div>
                </div>
                <div class="admin-stat-box">
                    <div class="val" style="color:#fbbf24;"><?= $totalMediaOrdersCount ?></div>
                    <div class="lbl">Użycia Kodów w Zamówieniach</div>
                </div>
                <div class="admin-stat-box">
                    <div class="val" style="color:#34d399;"><?= count($mediaCodes) ?></div>
                    <div class="lbl">Zarejestrowane Kody Twórców</div>
                </div>
            </div>

            <div style="display:grid; grid-template-columns: 2fr 1fr; gap:22px; align-items:start;" id="adminMediaGrid">
                <!-- Tabela kodów twórców -->
                <div class="table-responsive">
                    <table class="custom-admin-table">
                        <thead>
                            <tr>
                                <th>Kod</th>
                                <th>Przypisany Twórca</th>
                                <th>Rabat / Prowizja</th>
                                <th>Użycia & Obrót</th>
                                <th>Zarobiona prowizja</th>
                                <th>Status</th>
                                <th>Akcje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($mediaCodes)): ?>
                                <tr>
                                    <td colspan="7" style="text-align:center; padding:30px; color:var(--text-muted);">
                                        Brak zarejestrowanych kodów twórców. Utwórz pierwszy kod formularzem obok!
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($mediaCodes as $mc): ?>
                                    <tr>
                                        <td>
                                            <strong style="color:#f472b6; font-size:1.05rem; letter-spacing:1px;"><?= htmlspecialchars($mc['code']) ?></strong>
                                        </td>
                                        <td>
                                            <strong style="color:#fff;"><?= htmlspecialchars($mc['creator_name']) ?></strong><br>
                                            <small style="color:var(--text-muted);"><?= htmlspecialchars($mc['creator_email']) ?></small>
                                            <?php if (!empty($mc['creator_discord'])): ?>
                                                <br><small style="color:var(--accent-cyan);">💬 <?= htmlspecialchars($mc['creator_discord']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span style="color:#34d399; font-weight:700;">-<?= number_format((float)$mc['discount_percent'], 1) ?>%</span> (widz)<br>
                                            <span style="color:#fbbf24; font-weight:700;">+<?= number_format((float)$mc['commission_percent'], 1) ?>%</span> (twórca)
                                        </td>
                                        <td>
                                            <strong style="color:#fff;"><?= (int)$mc['usage_count'] ?> zamówień</strong><br>
                                            <small style="color:var(--text-muted);"><?= number_format((float)$mc['total_generated'], 2) ?> PLN</small>
                                        </td>
                                        <td>
                                            <strong style="color:#34d399; font-size:1rem;"><?= number_format((float)$mc['commission_paid'], 2) ?> PLN</strong><br>
                                            <small style="color:var(--text-muted);" title="Łącznie ze wszystkimi zamówieniami">Całość: <?= number_format((float)$mc['total_commission'], 2) ?> PLN</small>
                                        </td>
                                        <td>
                                            <form method="POST" action="panel-wlasciciela.php">
                                                <input type="hidden" name="admin_action" value="toggle_media_code">
                                                <input type="hidden" name="active_tab" value="media">
                                                <input type="hidden" name="code_id" value="<?= $mc['id'] ?>">
                                                <input type="hidden" name="is_active" value="<?= $mc['is_active'] ? '0' : '1' ?>">
                                                <?php if ($mc['is_active']): ?>
                                                    <button type="submit" class="badge-status badge-zrealizowane" style="cursor:pointer; border:none;" title="Kliknij, aby wstrzymać kod">
                                                        ✅ Aktywny
                                                    </button>
                                                <?php else: ?>
                                                    <button type="submit" class="badge-status badge-anulowane" style="cursor:pointer; border:none;" title="Kliknij, aby aktywować kod">
                                                        ⏸️ Wstrzymany
                                                    </button>
                                                <?php endif; ?>
                                            </form>
                                        </td>
                                        <td>
                                            <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Czy na pewno chcesz usunąć kod twórcy <?= htmlspecialchars($mc['code']) ?>?')">
                                                <input type="hidden" name="admin_action" value="delete_media_code">
                                                <input type="hidden" name="active_tab" value="media">
                                                <input type="hidden" name="code_id" value="<?= $mc['id'] ?>">
                                                <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Formularz tworzenia kodu twórcy -->
                <div style="background:var(--card-bg); border:1px solid rgba(236,72,153,0.35); border-radius:12px; padding:22px; backdrop-filter:blur(10px); box-shadow:0 6px 20px rgba(0,0,0,0.3);">
                    <h4 style="color:#fff; margin-bottom:14px; font-size:1.05rem; display:flex; align-items:center; gap:8px;">
                        <span>➕ Utwórz i Podepnij Kod Twórcy</span>
                    </h4>
                    <form method="POST" action="panel-wlasciciela.php">
                        <input type="hidden" name="admin_action" value="create_media_code">
                        <input type="hidden" name="active_tab" value="media">

                        <div class="form-group">
                            <label>Kod promocyjny:*</label>
                            <input type="text" name="code" class="form-control" placeholder="np. MLODY5, TIKTOK, TWITTER" required style="text-transform:uppercase; font-weight:800; color:#f472b6; letter-spacing:1px;">
                            <small style="color:var(--text-muted);">Wpisz kod bez spacji (automatycznie wielkie litery).</small>
                        </div>

                        <div class="form-group">
                            <label>Wybierz użytkownika z bazy SQL:*</label>
                            <select name="user_id" class="form-control" required>
                                <option value="">-- Wybierz twórcę --</option>
                                <?php foreach ($users as $u): ?>
                                    <option value="<?= $u['id'] ?>">
                                        <?= htmlspecialchars($u['username']) ?> (<?= htmlspecialchars($u['email']) ?><?= !empty($u['discord_tag']) ? ' &bull; ' . htmlspecialchars($u['discord_tag']) : '' ?>) [Rola: <?= $u['role'] ?>]
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small style="color:var(--text-muted);">Kod zostanie na stałe przypisany do wybranego konta.</small>
                        </div>

                        <div class="form-group">
                            <label>Rabat dla kupującego (%):</label>
                            <input type="number" step="0.5" min="1" max="100" name="discount_percent" value="5.00" class="form-control" required style="font-weight:700; color:#34d399;">
                            <small style="color:var(--text-muted);">Standardowo: 5% zniżki dla widza.</small>
                        </div>

                        <div class="form-group">
                            <label>Prowizja twórcy (% z zamówienia):</label>
                            <input type="number" step="0.5" min="1" max="100" name="commission_percent" value="10.00" class="form-control" required style="font-weight:700; color:#fbbf24;">
                            <small style="color:var(--text-muted);">Standardowo: 10% naliczane twórcy (rozliczane osobno przez Ciebie).</small>
                        </div>

                        <div class="form-group" style="margin-top:10px;">
                            <label style="display:flex; align-items:center; gap:8px; cursor:pointer; color:#fff; font-size:0.86rem;">
                                <input type="checkbox" name="set_media_role" value="1" checked style="width:16px; height:16px;">
                                <span>Automatycznie nadaj rolę <strong>Twórca (Media)</strong> temu kontu</span>
                            </label>
                        </div>

                        <button type="submit" class="btn btn-gradient full-width" style="margin-top:14px; background:linear-gradient(135deg, #ec4899, #a855f7); font-weight:800;">
                            🚀 Utwórz kod i podepnij
                        </button>
                    </form>
                </div>
            </div>

            <!-- Tabela zamówień z kodami twórców -->
            <div style="margin-top:28px;">
                <h4 style="color:#fff; font-size:1.1rem; margin-bottom:12px; display:flex; align-items:center; gap:8px;">
                    <span>📦 Ostatnie zamówienia z kodami twórców (Media)</span>
                </h4>
                <div class="table-responsive">
                    <table class="custom-admin-table">
                        <thead>
                            <tr>
                                <th>Zamówienie / Data</th>
                                <th>Klient</th>
                                <th>Użyty Kod</th>
                                <th>Kwota Zamówienia</th>
                                <th>Rabat Klienta</th>
                                <th>Prowizja Twórcy (10%)</th>
                                <th>Status Płatności</th>
                                <th>Adnotacja Rozliczeniowa</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $mediaOrders = array_filter($orders, function($o) {
                                return !empty($o['promo_code']);
                            });
                            ?>
                            <?php if (empty($mediaOrders)): ?>
                                <tr>
                                    <td colspan="8" style="text-align:center; padding:24px; color:var(--text-muted);">
                                        Żadne zamówienie nie wykorzystało jeszcze kodu promocyjnego.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($mediaOrders as $mo): 
                                    $commVal = (float)($mo['commission_amount'] ?? 0);
                                    if ($commVal <= 0) {
                                        $commVal = round((float)$mo['total_amount'] * 0.10, 2);
                                    }
                                ?>
                                    <tr>
                                        <td>
                                            <strong style="color:#fff;"><?= htmlspecialchars($mo['order_number']) ?></strong><br>
                                            <small style="color:var(--text-muted);"><?= date('d.m.Y H:i', strtotime($mo['created_at'])) ?></small>
                                        </td>
                                        <td>
                                            <strong style="color:var(--accent-cyan);"><?= htmlspecialchars($mo['customer_discord']) ?></strong><br>
                                            <small style="color:var(--text-muted);"><?= htmlspecialchars($mo['customer_email']) ?></small>
                                        </td>
                                        <td>
                                            <strong style="color:#f472b6; font-size:0.95rem;"><?= htmlspecialchars($mo['promo_code']) ?></strong>
                                        </td>
                                        <td>
                                            <strong style="color:#fff;"><?= number_format((float)$mo['total_amount'], 2) ?> PLN</strong>
                                        </td>
                                        <td>
                                            <span style="color:#f472b6; font-weight:800; font-size:0.78rem; background:rgba(236,72,153,0.15); padding:3px 6px; border-radius:4px; border:1px solid rgba(236,72,153,0.3); display:inline-block;">
                                                -5% klient + -10% dla mediów
                                            </span>
                                        </td>
                                        <td>
                                            <strong style="color:#fbbf24; font-size:1.05rem;">-<?= number_format($commVal, 2) ?> PLN</strong><br>
                                            <small style="color:#34d399; font-weight:700;">Zysk netto: <?= number_format((float)$mo['total_amount'] - $commVal, 2) ?> PLN</small>
                                        </td>
                                        <td>
                                            <?php if ($mo['is_paid']): ?>
                                                <span class="badge-status badge-zrealizowane">✅ Opłacone</span>
                                            <?php else: ?>
                                                <span class="badge-status badge-anulowane">❌ Oczekuje na wpłatę</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div style="font-size:0.75rem; color:#fff; background:rgba(22,15,46,0.8); border:1px solid rgba(236,72,153,0.3); border-radius:6px; padding:6px 10px;">
                                                <?= !empty($mo['notes']) ? htmlspecialchars($mo['notes']) : 'Kod rabatowy: -5% klient + -10% dla mediów (Prowizja twórcy: ' . number_format($commVal, 2) . ' PLN, Twój zysk po potrąceniu 10%: ' . number_format((float)$mo['total_amount'] - $commVal, 2) . ' PLN)' ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- SEKCJA 3: UŻYTKOWNICY -->
        <div id="admin-users" class="tab-section-admin">
            <div style="display:grid; grid-template-columns: 2fr 1fr; gap:20px;">
                <div class="table-responsive">
                    <table class="custom-admin-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Użytkownik</th>
                                <th>E-mail</th>
                                <th>Discord Tag</th>
                                <th>Rola</th>
                                <th>Akcje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $u): ?>
                                <tr>
                                    <td>#<?= $u['id'] ?></td>
                                    <td>
                                        <strong style="color:#fff;"><?= htmlspecialchars($u['username']) ?></strong>
                                        <?php if ($u['role'] === 'owner'): ?>
                                            <span style="font-size:0.75rem; color:#fbbf24; margin-left:4px;">👑 Główny</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($u['email']) ?></td>
                                    <td><?= htmlspecialchars($u['discord_tag'] ?: '-') ?></td>
                                    <td>
                                        <?php if ((int)$u['id'] === (int)$admin['id']): ?>
                                            <span class="badge-status" style="background:rgba(245, 158, 11, 0.2); color:#fbbf24; border:1px solid rgba(245, 158, 11, 0.4); font-weight:800;">👑 Twoje Konto (Właściciel)</span>
                                        <?php elseif (is_owner()): ?>
                                            <form method="POST" action="panel-wlasciciela.php">
                                                <input type="hidden" name="admin_action" value="update_user_role">
                                                <input type="hidden" name="active_tab" value="users">
                                                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                                <select name="role" class="form-control" style="padding:2px 6px; font-size:0.75rem; width:auto; border-color:<?= $u['role'] === 'owner' ? '#fbbf24' : ($u['role'] === 'admin' ? '#34d399' : ($u['role'] === 'media' ? '#ec4899' : '#a855f7')) ?>;" onchange="this.form.submit()">
                                                    <option value="client" <?= in_array($u['role'], ['client', 'user']) ? 'selected' : '' ?>>👤 Klient</option>
                                                    <option value="media" <?= $u['role'] === 'media' ? 'selected' : '' ?>>🎬 Twórca (Media)</option>
                                                    <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>🛡️ Admin</option>
                                                    <option value="owner" <?= $u['role'] === 'owner' ? 'selected' : '' ?>>👑 Właściciel</option>
                                                </select>
                                            </form>
                                        <?php else: ?>
                                            <?php if ($u['role'] === 'media'): ?>
                                                <span class="badge-status" style="background:rgba(236,72,153,0.18); color:#f472b6; border:1px solid rgba(236,72,153,0.35);">🎬 Twórca</span>
                                            <?php else: ?>
                                                <span class="badge-status <?= $u['role'] === 'admin' ? 'badge-zrealizowane' : 'badge-w-realizacji' ?>">
                                                    <?= $u['role'] === 'admin' ? '🛡️ Admin' : '👤 Klient' ?>
                                                </span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($u['role'] === 'owner'): ?>
                                            <small style="color:#fbbf24; font-weight:700;">🔒 Nietykalny</small>
                                        <?php elseif ((int)$u['id'] === (int)$admin['id']): ?>
                                            <small style="color:var(--text-muted);">(Twoje konto)</small>
                                        <?php elseif (!is_owner() && $u['role'] === 'admin'): ?>
                                            <small style="color:var(--text-muted);">(Tylko Właściciel)</small>
                                        <?php else: ?>
                                            <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Czy na pewno chcesz usunąć konto użytkownika <?= htmlspecialchars($u['username']) ?>?')">
                                                <input type="hidden" name="admin_action" value="delete_user">
                                                <input type="hidden" name="active_tab" value="users">
                                                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                                <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                            </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Formularz dodawania użytkownika -->
                <div style="background:var(--card-bg); border:1px solid var(--border); border-radius:12px; padding:20px; height:fit-content;">
                    <h4 style="color:#fff; margin-bottom:14px;">➕ Dodaj Użytkownika / Twórcę / Admina</h4>
                    <form method="POST" action="panel-wlasciciela.php">
                        <input type="hidden" name="admin_action" value="create_user">
                        <input type="hidden" name="active_tab" value="users">

                        <div class="form-group">
                            <label>Login:*</label>
                            <input type="text" name="username" class="form-control" placeholder="np. twórca1" required>
                        </div>
                        <div class="form-group">
                            <label>Adres E-mail:*</label>
                            <input type="email" name="email" class="form-control" placeholder="media@herbscripts.pl" required>
                        </div>
                        <div class="form-group">
                            <label>Hasło:*</label>
                            <input type="password" name="password" class="form-control" placeholder="Hasło" required>
                        </div>
                        <div class="form-group">
                            <label>Discord Tag:</label>
                            <input type="text" name="discord_tag" class="form-control" placeholder="np. mod#0001">
                        </div>
                        <div class="form-group">
                            <label>Rola:</label>
                            <select name="role" class="form-control">
                                <option value="client">👤 Klient</option>
                                <option value="media">🎬 Twórca (Media)</option>
                                <option value="admin">🛡️ Administrator</option>
                                <option value="owner">👑 Właściciel</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-gradient full-width" style="margin-top:10px;">
                            ➕ Utwórz konto
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- SEKCJA 4: PRODUKTY W SKLEPIE -->
        <div id="admin-products" class="tab-section-admin">
            <div class="filter-controls">
                <input type="text" id="productSearch" class="form-control" placeholder="🔍 Szukaj produktu po nazwie, tagu, technologiach..." style="max-width:340px;" oninput="filterProductsTable(this.value)">
                <div style="font-size:0.85rem; color:var(--text-muted);">
                    Produkty są zapisywane w tabeli <code>products</code> w MySQL i natychmiast widoczne w sklepie.
                </div>
            </div>

            <div style="display:grid; grid-template-columns: 2fr 1fr; gap:24px; align-items:start;" id="adminProductsGrid">
                <!-- Lista produktów w MySQL -->
                <div class="table-responsive">
                    <table class="custom-admin-table" id="productsMainTable">
                        <thead>
                            <tr>
                                <th>Kod / Tytuł</th>
                                <th>Kategoria & Tag</th>
                                <th>Cena</th>
                                <th>Technologie</th>
                                <th>Status</th>
                                <th>Akcje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($products)): ?>
                                <tr>
                                    <td colspan="6" style="text-align:center; padding:30px; color:var(--text-muted);">
                                        Brak produktów w bazie. Dodaj swój pierwszy produkt formularzem obok!
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($products as $p): ?>
                                    <tr>
                                        <td>
                                            <strong style="color:#fff; font-size:0.95rem;"><?= htmlspecialchars($p['title']) ?></strong><br>
                                            <small style="color:var(--accent-cyan); font-weight:700;"><?= htmlspecialchars($p['product_code']) ?></small>
                                            <p style="color:var(--text-muted); font-size:0.75rem; margin-top:3px; max-width:280px; line-height:1.3;">
                                                <?= htmlspecialchars(safe_str_shorten($p['description'], 90)) ?>
                                            </p>
                                        </td>
                                        <td>
                                            <span class="tech-badge" style="display:inline-block; margin-bottom:4px;"><?= htmlspecialchars($p['category']) ?></span><br>
                                            <small style="color:var(--text-muted);"><?= htmlspecialchars($p['tag']) ?></small>
                                        </td>
                                        <td>
                                            <strong style="color:#c084fc; font-size:1.1rem;"><?= number_format((float)$p['price'], 2) ?> PLN</strong>
                                        </td>
                                        <td>
                                            <small style="color:var(--text-muted);"><?= htmlspecialchars($p['techs'] ?: 'Brak') ?></small>
                                        </td>
                                        <td>
                                            <form method="POST" action="panel-wlasciciela.php" style="display:inline;">
                                                <input type="hidden" name="admin_action" value="toggle_product_status">
                                                <input type="hidden" name="active_tab" value="products">
                                                <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                                                <input type="hidden" name="is_active" value="<?= $p['is_active'] ? '0' : '1' ?>">
                                                <?php if ($p['is_active']): ?>
                                                    <button type="submit" class="badge-status badge-zrealizowane" style="cursor:pointer; border:none;" title="Kliknij, aby ukryć w sklepie">
                                                        ✅ Widoczny
                                                    </button>
                                                <?php else: ?>
                                                    <button type="submit" class="badge-status badge-anulowane" style="cursor:pointer; border:none;" title="Kliknij, aby pokazać w sklepie">
                                                        👁️ Ukryty
                                                    </button>
                                                <?php endif; ?>
                                            </form>
                                        </td>
                                        <td>
                                            <div style="display:flex; gap:6px; flex-wrap:wrap;">
                                                <button type="button" class="action-btn-sm" onclick='openEditProductModal(<?= json_encode($p, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                                    ✏️ Edytuj
                                                </button>
                                                <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Czy na pewno chcesz usunąć produkt <?= htmlspecialchars($p['title']) ?> ze sklepu?')">
                                                    <input type="hidden" name="admin_action" value="delete_product">
                                                    <input type="hidden" name="active_tab" value="products">
                                                    <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                                                    <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Formularz dodawania nowego produktu -->
                <div style="background:var(--card-bg); border:1px solid var(--border); border-radius:12px; padding:22px; height:fit-content; backdrop-filter:blur(10px); box-shadow:0 6px 20px rgba(0,0,0,0.3);">
                    <h4 style="color:#fff; margin-bottom:14px; font-size:1.05rem;">➕ Dodaj Nowy Produkt do Sklepu</h4>
                    <form method="POST" action="panel-wlasciciela.php">
                        <input type="hidden" name="admin_action" value="add_product">
                        <input type="hidden" name="active_tab" value="products">

                        <div class="form-group">
                            <label>Nazwa Produktu:*</label>
                            <input type="text" name="title" class="form-control" placeholder="np. Bot Pod Shopa VIP" required>
                        </div>

                        <div class="form-group">
                            <label>Cena (w PLN):*</label>
                            <input type="number" step="0.01" min="0.01" name="price" class="form-control" placeholder="np. 49.99" required>
                        </div>

                        <div class="form-group">
                            <label>Kategoria:*</label>
                            <select name="category" class="form-control" required>
                                <option value="discord">🤖 Bot Discord (discord)</option>
                                <option value="web">🌐 Strona WWW (web)</option>
                                <option value="scripts">⚡ Skrypt FiveM / Gra (scripts)</option>
                                <option value="other">📦 Inny skrypt / API (other)</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Etykieta Tag:*</label>
                            <input type="text" name="tag" class="form-control" value="Bot Discord" placeholder="np. Bot Discord, Strona WWW" required>
                        </div>

                        <div class="form-group">
                            <label>Technologie (oddzielone przecinkami):</label>
                            <input type="text" name="techs" class="form-control" placeholder="np. Python, Discord.py, SQLite">
                        </div>

                        <div class="form-group">
                            <label>Krótki opis (na kafelku sklepu):*</label>
                            <textarea name="description" rows="2" class="form-control" placeholder="Krótki zarys funkcji widoczny na kafelku w katalogu..." required></textarea>
                        </div>

                        <div class="form-group">
                            <label>Szczegóły / Specyfikacja (po kliknięciu Info):</label>
                            <textarea name="details" rows="3" class="form-control" placeholder="Dokładniejszy opis funkcji, komend i wymagań bota/strony..."></textarea>
                        </div>

                        <button type="submit" class="btn btn-gradient full-width" style="margin-top:10px; padding:12px;">
                            🚀 Opublikuj produkt w sklepie
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- SEKCJA 5: OPINIE KLIENTÓW -->
        <div id="admin-reviews" class="tab-section-admin">
            <div class="filter-controls">
                <div style="font-size:0.85rem; color:var(--text-muted);">
                    Opinie klientów wystawione na stronie i przez bota Discord. Zapisane w tabeli <code>reviews</code> w MySQL.
                </div>
            </div>

            <div class="table-responsive">
                <table class="custom-admin-table">
                    <thead>
                        <tr>
                            <th>ID / Autor</th>
                            <th>Ocena</th>
                            <th>Treść recenzji</th>
                            <th>Źródło</th>
                            <th>Data</th>
                            <th>Akcje</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($reviews)): ?>
                            <tr>
                                <td colspan="6" style="text-align:center; padding:30px; color:var(--text-muted);">
                                    Brak wystawionych opinii w bazie danych.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($reviews as $rev): ?>
                                <tr>
                                    <td>
                                        <strong style="color:#fff;"><?= htmlspecialchars($rev['author']) ?></strong><br>
                                        <small style="color:var(--text-muted);">ID: #<?= (int)$rev['id'] ?><?= $rev['user_id'] ? ' (User #' . (int)$rev['user_id'] . ')' : '' ?></small>
                                    </td>
                                    <td>
                                        <span style="color:#fbbf24; font-size:1rem; letter-spacing:1px;">
                                            <?= str_repeat('★', (int)$rev['stars']) . str_repeat('☆', 5 - (int)$rev['stars']) ?>
                                        </span>
                                        <small style="color:var(--text-muted); display:block; font-weight:700;"><?= (int)$rev['stars'] ?> / 5</small>
                                    </td>
                                    <td>
                                        <p style="color:#e2e8f0; font-size:0.88rem; font-style:italic; max-width:400px; line-height:1.4;">
                                            „<?= htmlspecialchars($rev['content']) ?>”
                                        </p>
                                    </td>
                                    <td>
                                        <?php if (($rev['source'] ?? 'web') === 'discord'): ?>
                                            <span class="badge-status" style="background:rgba(88, 101, 242, 0.2); color:#818cf8; border:1px solid rgba(88, 101, 242, 0.4);">🤖 Discord</span>
                                        <?php else: ?>
                                            <span class="badge-status" style="background:rgba(168, 85, 247, 0.2); color:#c084fc; border:1px solid rgba(168, 85, 247, 0.4);">🌐 Strona WWW</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small style="color:var(--text-muted);"><?= htmlspecialchars($rev['created_at']) ?></small>
                                    </td>
                                    <td>
                                        <form method="POST" action="panel-wlasciciela.php" onsubmit="return confirm('Czy na pewno chcesz usunąć tę opinię?')">
                                            <input type="hidden" name="admin_action" value="delete_review">
                                            <input type="hidden" name="active_tab" value="reviews">
                                            <input type="hidden" name="review_id" value="<?= $rev['id'] ?>">
                                            <button type="submit" class="action-btn-sm btn-danger-sm">🗑️ Usuń</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- SEKCJA 6: USTAWIENIA PŁATNOŚCI (BLIK / PRZELEW) -->
        <div id="admin-settings" class="tab-section-admin">
            <div style="max-width: 820px; margin: 0 auto; background: var(--card-bg); border: 1px solid var(--border); border-radius: 14px; padding: 24px; box-shadow: 0 10px 30px rgba(0,0,0,0.4);">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom:1px solid var(--border); padding-bottom:14px; flex-wrap:wrap; gap:10px;">
                    <div>
                        <h3 style="color:#fff; font-size:1.25rem; margin-bottom:4px;">💳 Konfiguracja Płatności dla Klientów</h3>
                        <p style="color:var(--text-muted); font-size:0.85rem; margin:0;">
                            Poniższe dane wyświetlają się klientowi w oknie płatności po kliknięciu „Opłać zamówienie (BLIK / Przelew)”.
                        </p>
                    </div>
                    <span class="user-badge" style="background:rgba(16,185,129,0.2); color:#34d399; border-color:rgba(16,185,129,0.4);">
                        ⚡ Automatyczna synchronizacja
                    </span>
                </div>

                <form method="POST" action="panel-wlasciciela.php">
                    <input type="hidden" name="admin_action" value="update_payment_settings">
                    <input type="hidden" name="active_tab" value="settings">

                    <div style="background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 12px; padding: 18px; margin-bottom: 22px;">
                        <h4 style="color:#34d399; font-size:1rem; margin-bottom:12px; display:flex; align-items:center; gap:8px;">
                            <span>📱 Płatność BLIK (Przelew na telefon)</span>
                        </h4>

                        <div class="form-grid">
                            <div class="form-group">
                                <label style="color:#fff; font-weight:700;">Numer telefonu do przelewów BLIK:*</label>
                                <input type="text" name="payment_blik_phone" class="form-control" value="<?= htmlspecialchars($blikPhoneVal) ?>" placeholder="np. 500 123 456" required style="font-size:1rem; font-weight:800; color:#34d399; letter-spacing:0.5px;">
                                <small style="color:var(--text-muted);">Upewnij się, że ten numer ma aktywną usługę „Przelew na telefon BLIK” w Twoim banku.</small>
                            </div>

                            <div class="form-group">
                                <label style="color:#fff; font-weight:700;">Imię i nazwisko lub nazwa odbiorcy:*</label>
                                <input type="text" name="payment_blik_name" class="form-control" value="<?= htmlspecialchars($blikNameVal) ?>" placeholder="np. Jan Kowalski lub HerbScripts" required style="font-weight:700;">
                                <small style="color:var(--text-muted);">Wyświetla się w polu odbiorcy przelewu.</small>
                            </div>

                            <div class="form-group" style="grid-column: 1 / -1; margin-bottom: 0;">
                                <label style="color:#fff; font-weight:700;">Tytuł / opis przelewu:*</label>
                                <input type="text" name="payment_transfer_title" class="form-control" value="<?= htmlspecialchars($transferTitleVal) ?>" placeholder="np. Za jedzenie" required style="font-weight:800; color:#c084fc;">
                                <small style="color:var(--text-muted);">Klientowi wyświetli się tytuł z numerem zamówienia, np.: <strong><?= htmlspecialchars($transferTitleVal) ?> #HS-4821</strong></small>
                            </div>
                        </div>
                    </div>

                    <div style="background: rgba(168, 85, 247, 0.08); border: 1px solid rgba(168, 85, 247, 0.3); border-radius: 12px; padding: 18px; margin-bottom: 22px;">
                        <h4 style="color:var(--accent-cyan); font-size:1rem; margin-bottom:12px; display:flex; align-items:center; gap:8px;">
                            <span>🏦 Tradycyjny Przelew Bankowy (Alternatywa)</span>
                        </h4>

                        <div class="form-grid">
                            <div class="form-group">
                                <label style="color:#fff; font-weight:700;">Numer rachunku bankowego (IBAN):*</label>
                                <input type="text" name="payment_bank_account" class="form-control" value="<?= htmlspecialchars($bankAccVal) ?>" placeholder="np. 12 1020 0000 0000 0000 0000 0000" style="font-weight:700; color:#34d399; letter-spacing:0.5px;">
                            </div>

                            <div class="form-group">
                                <label style="color:#fff; font-weight:700;">Nazwa banku:*</label>
                                <input type="text" name="payment_bank_name" class="form-control" value="<?= htmlspecialchars($bankNameVal) ?>" placeholder="np. PKO Bank Polski / mBank / Santander" style="font-weight:700;">
                            </div>
                        </div>
                    </div>

                    <div style="background: rgba(14, 165, 233, 0.08); border: 1px solid rgba(14, 165, 233, 0.3); border-radius: 12px; padding: 18px; margin-bottom: 22px;">
                        <h4 style="color:#38bdf8; font-size:1rem; margin-bottom:12px; display:flex; align-items:center; gap:8px;">
                            <span>💳 Płatność Paysafecard (myPaysafecard / Kod PIN)</span>
                        </h4>

                        <div class="form-grid">
                            <div class="form-group" style="grid-column: 1 / -1; margin-bottom: 0;">
                                <label style="color:#fff; font-weight:700;">Adres e-mail konta myPaysafecard (do bezpośrednich przelewów PSC):*</label>
                                <input type="email" name="payment_psc_email" class="form-control" value="<?= htmlspecialchars($pscEmailVal) ?>" placeholder="np. herbscripts@gmail.com" required style="font-weight:700; color:#38bdf8;">
                                <small style="color:var(--text-muted);">
                                    Na ten adres e-mail klienci posiadający konto myPaysafecard mogą wysłać dokładną kwotę zamówienia (np. 19.99 PLN). Klienci płacący fizycznym kuponem PIN podają kod kuponu w oknie opłacania.
                                </small>
                            </div>
                        </div>
                    </div>

                    <div style="display:flex; justify-content:flex-end;">
                        <button type="submit" class="btn btn-gradient" style="padding: 12px 28px; font-size: 0.95rem; font-weight: 800;">
                            💾 Zapisz ustawienia płatności
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal edycji produktu -->
    <div class="modal-overlay" id="editProductModal" onclick="if(event.target==this) closeProductModal()">
        <div class="modal-box" style="max-width:550px;">
            <div class="modal-header">
                <h3>✏️ Edytuj Produkt</h3>
                <button type="button" class="btn-close" onclick="closeProductModal()">✕</button>
            </div>
            <form method="POST" action="panel-wlasciciela.php" id="editProductForm">
                <input type="hidden" name="admin_action" value="update_product">
                <input type="hidden" name="active_tab" value="products">
                <input type="hidden" name="product_id" id="edit_product_id">

                <div class="form-group">
                    <label>Nazwa Produktu:*</label>
                    <input type="text" name="title" id="edit_title" class="form-control" required>
                </div>

                <div class="form-group">
                    <label>Cena (PLN):*</label>
                    <input type="number" step="0.01" min="0.01" name="price" id="edit_price" class="form-control" required>
                </div>

                <div class="form-group">
                    <label>Kategoria:*</label>
                    <select name="category" id="edit_category" class="form-control" required>
                        <option value="discord">🤖 Bot Discord (discord)</option>
                        <option value="web">🌐 Strona WWW (web)</option>
                        <option value="scripts">⚡ Skrypt FiveM / Gra (scripts)</option>
                        <option value="other">📦 Inny skrypt / API (other)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Etykieta Tag:*</label>
                    <input type="text" name="tag" id="edit_tag" class="form-control" required>
                </div>

                <div class="form-group">
                    <label>Technologie (oddzielone przecinkami):</label>
                    <input type="text" name="techs" id="edit_techs" class="form-control">
                </div>

                <div class="form-group">
                    <label>Krótki opis (na kafelku):*</label>
                    <textarea name="description" id="edit_description" rows="2" class="form-control" required></textarea>
                </div>

                <div class="form-group">
                    <label>Szczegóły / Specyfikacja:</label>
                    <textarea name="details" id="edit_details" rows="3" class="form-control"></textarea>
                </div>

                <div class="form-group">
                    <label>Widoczność w sklepie:</label>
                    <select name="is_active" id="edit_is_active" class="form-control">
                        <option value="1">✅ Aktywny (widoczny w sklepie)</option>
                        <option value="0">👁️ Ukryty (niewidoczny w sklepie)</option>
                    </select>
                </div>

                <div style="display:flex; gap:10px; margin-top:16px;">
                    <button type="submit" class="btn btn-gradient full-width">💾 Zapisz zmiany</button>
                    <button type="button" class="btn btn-outline" onclick="closeProductModal()">Anuluj</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Przywracanie aktywnej zakładki po przeładowaniu strony
        document.addEventListener('DOMContentLoaded', function() {
            var currentActiveTab = <?= json_encode($activeTab) ?>;
            if (currentActiveTab && currentActiveTab !== 'orders') {
                var btn = document.querySelector('.tab-btn-admin[onclick*="\'' + currentActiveTab + '\'"]');
                if (btn) switchAdminTab(currentActiveTab, btn);
            }
        });

        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>
