<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | Buy Logs";
$page_title2 = "Buy Logs";

// Get active categories
try {
    $cat_stmt   = $pdo->query("SELECT * FROM sm_categories WHERE status='1' ORDER BY category_name ASC");
    $categories = $cat_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $categories = []; }

// ── XtraLogTools API products ─────────────────────────────────────────────────
$xtl_enabled  = (int)($site_data['xtralogtools_enabled'] ?? 0);
$xtl_products = [];
if ($xtl_enabled) {
    try {
        // Ensure table exists before querying
        $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_products (
            id           INT AUTO_INCREMENT PRIMARY KEY,
            product_id   VARCHAR(100) NOT NULL UNIQUE,
            product_name VARCHAR(255) NOT NULL,
            description  TEXT,
            server       TINYINT(1)   NOT NULL DEFAULT 1,
            api_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            our_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            category     VARCHAR(100) NOT NULL DEFAULT '',
            status       TINYINT(1)   NOT NULL DEFAULT 1,
            synced_at    TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_status   (status),
            KEY idx_category (category)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        $xtl_stmt = $pdo->query("SELECT * FROM xtralog_products WHERE status = 1 ORDER BY category, product_name ASC");
        $xtl_products = $xtl_stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) { $xtl_products = []; }
}

// Unique categories from API products
$xtl_categories = [];
foreach ($xtl_products as $xp) {
    if (!empty($xp['category']) && !in_array($xp['category'], $xtl_categories)) {
        $xtl_categories[] = $xp['category'];
    }
}

// Filters & pagination
$selected_category = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$items_per_page    = 12;
$current_page      = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset            = ($current_page - 1) * $items_per_page;

// Build query
$where  = "WHERE s.status = 'available'";
$params = [];
if ($selected_category) {
    $where           .= " AND s.category_id = :cat_id";
    $params['cat_id'] = $selected_category;
}

try {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM sm_services s $where");
    $count_stmt->execute($params);
    $total_services = (int)$count_stmt->fetchColumn();
    $total_pages    = (int)ceil($total_services / $items_per_page);

    $svc_stmt = $pdo->prepare("
        SELECT s.*, c.category_name, c.category_image
        FROM sm_services s
        LEFT JOIN sm_categories c ON s.category_id = c.id
        $where
        ORDER BY s.created_at DESC
        LIMIT :limit OFFSET :offset
    ");
    foreach ($params as $k => $v) $svc_stmt->bindValue(":$k", $v, PDO::PARAM_INT);
    $svc_stmt->bindValue(':limit',  $items_per_page, PDO::PARAM_INT);
    $svc_stmt->bindValue(':offset', $offset,         PDO::PARAM_INT);
    $svc_stmt->execute();
    $services = $svc_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $services       = [];
    $total_pages    = 1;
    $total_services = 0;
}

$user_balance = (float)$user['main_balance'];
?>
<title><?php echo htmlspecialchars($page_title); ?></title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.10s}.anim-3{animation-delay:.15s}

/* ── Hero ── */
.bl-hero{
    background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%);
    border:1px solid rgba(245,158,11,.18);
    box-shadow:0 8px 40px rgba(1,26,20,.4),inset 0 1px 0 rgba(245,158,11,.06);
    border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:16px;
}
.bl-hero::before{
    content:'';position:absolute;inset:0;pointer-events:none;
    background:repeating-linear-gradient(45deg,transparent,transparent 40px,
        rgba(245,158,11,.012) 40px,rgba(245,158,11,.012) 41px);
}
.bl-hero-orb{
    position:absolute;border-radius:50%;filter:blur(50px);pointer-events:none;
    width:180px;height:180px;
    background:radial-gradient(circle,rgba(245,158,11,.12),transparent);
    top:-40px;right:-40px;
}

/* ── Category filter bar ── */
.cat-bar{
    background:var(--card-bg);border:1px solid var(--card-border);
    box-shadow:var(--card-shadow);border-radius:14px;
    padding:12px 14px;margin-bottom:14px;overflow-x:auto;
    display:flex;align-items:center;gap:8px;flex-wrap:nowrap;
    -webkit-overflow-scrolling:touch;scrollbar-width:none;
}
.cat-bar::-webkit-scrollbar{display:none}

.cat-pill{
    display:inline-flex;align-items:center;gap:6px;
    padding:7px 14px;border-radius:99px;font-size:.75rem;font-weight:600;
    white-space:nowrap;cursor:pointer;text-decoration:none;
    border:1.5px solid var(--card-border);background:var(--btn-bg);
    color:var(--text-muted);transition:all .15s ease;flex-shrink:0;
}
.cat-pill:hover{border-color:rgba(77,20,140,.3);color:var(--text-primary);background:rgba(77,20,140,.04);}
.cat-pill.active{
    background:linear-gradient(135deg,#4D148C,#6b23c2);
    border-color:transparent;color:white;
    box-shadow:0 4px 12px rgba(77,20,140,.25);
}

/* ── Service cards ── */
.svc-grid{
    display:grid;
    grid-template-columns:repeat(1,1fr);
    gap:12px;
    margin-bottom:16px;
}
@media(min-width:540px){.svc-grid{grid-template-columns:repeat(2,1fr);}}
@media(min-width:900px){.svc-grid{grid-template-columns:repeat(3,1fr);}}

.svc-card{
    background:var(--card-bg);border:1px solid var(--card-border);
    box-shadow:var(--card-shadow);border-radius:16px;padding:16px;
    display:flex;flex-direction:column;
    transition:all .25s cubic-bezier(.4,0,.2,1);
}
.svc-card:hover{
    transform:translateY(-3px);
    box-shadow:0 12px 32px rgba(77,20,140,.12);
    border-color:rgba(77,20,140,.25);
}
.dark .svc-card:hover{
    box-shadow:0 12px 32px rgba(0,0,0,.35);
    border-color:rgba(77,20,140,.25);
}

.svc-cat-badge{
    font-size:.65rem;font-weight:700;padding:3px 9px;border-radius:99px;
    background:rgba(77,20,140,.08);color:#4D148C;
    display:inline-flex;align-items:center;gap:5px;
}
.dark .svc-cat-badge{background:rgba(77,20,140,.12);}

.svc-avail-badge{
    font-size:.65rem;font-weight:700;padding:3px 9px;border-radius:99px;
    background:rgba(77,20,140,.08);color:#6b23c2;
    display:inline-flex;align-items:center;gap:4px;
}

.svc-name{
    font-weight:700;font-size:.88rem;color:var(--text-primary);
    line-height:1.35;margin:10px 0 6px;
}
.svc-desc{
    font-size:.75rem;color:var(--text-muted);line-height:1.55;
    flex:1;
    display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;
}

.svc-price-row{
    display:flex;align-items:center;justify-content:space-between;
    background:rgba(77,20,140,.05);border:1px solid rgba(77,20,140,.1);
    border-radius:10px;padding:10px 14px;margin:12px 0 10px;
}
.dark .svc-price-row{background:rgba(77,20,140,.07);}
.svc-price{font-weight:800;font-size:1.1rem;color:#4D148C;font-family:monospace;}
.dark .svc-price{color:#7c3aed;}

.svc-actions{display:flex;gap:8px;}
.btn-preview{
    flex:1;display:flex;align-items:center;justify-content:center;gap:6px;
    padding:10px;border-radius:10px;font-size:.78rem;font-weight:600;
    border:1.5px solid var(--card-border);background:var(--btn-bg);
    color:var(--text-muted);text-decoration:none;transition:all .15s;cursor:pointer;
}
.btn-preview:hover{border-color:rgba(77,20,140,.3);color:var(--text-primary);}
.btn-buy{
    flex:2;display:flex;align-items:center;justify-content:center;gap:7px;
    padding:10px;border-radius:10px;font-size:.78rem;font-weight:700;
    background:linear-gradient(135deg,#4D148C,#6b23c2);
    color:white;border:none;cursor:pointer;
    box-shadow:0 4px 12px rgba(77,20,140,.25);
    transition:all .2s;
}
.btn-buy:hover{box-shadow:0 6px 20px rgba(77,20,140,.38);transform:translateY(-1px);}
.btn-buy:active{transform:translateY(0);}

/* ── Pagination ── */
.pag-btn{
    width:38px;height:38px;border-radius:9px;
    display:flex;align-items:center;justify-content:center;
    font-size:.78rem;font-weight:600;text-decoration:none;
    border:1.5px solid var(--card-border);background:var(--btn-bg);
    color:var(--text-muted);transition:all .15s;
}
.pag-btn:hover{border-color:rgba(77,20,140,.3);color:#4D148C;}
.pag-btn.active{
    background:linear-gradient(135deg,#4D148C,#6b23c2);
    border-color:transparent;color:white;
    box-shadow:0 4px 10px rgba(77,20,140,.25);
}

/* ── Modal ── */
.modal-overlay{
    position:fixed;inset:0;z-index:200;
    display:none;align-items:center;justify-content:center;
    background:rgba(0,0,0,.6);backdrop-filter:blur(8px);padding:16px;
}
.modal-overlay.flex{display:flex;}
.modal-box{
    background:var(--card-bg);border:1px solid var(--card-border);
    border-radius:20px;padding:24px;width:100%;max-width:440px;
    position:relative;box-shadow:0 24px 60px rgba(0,0,0,.25);
    animation:fadeUp .25s ease-out;
}
.modal-detail-row{
    display:flex;align-items:center;justify-content:space-between;
    padding:10px 0;border-bottom:1px solid var(--card-border);
}
.modal-detail-row:last-child{border-bottom:none;}
</style>

<div class="max-w-5xl mx-auto">

<!-- ── Hero ──────────────────────────────────────────────────── -->
<div class="bl-hero anim anim-1">
    <div class="bl-hero-orb"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;
                align-items:center;justify-content:space-between;gap:14px;">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;
                       margin-bottom:4px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-terminal text-yellow-300 text-base"></i>Buy Logs
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">
                Browse and purchase premium account logs instantly.
            </p>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
            <div style="background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.14);
                        border-radius:12px;padding:10px 16px;text-align:center;">
                <p style="font-size:.6rem;color:rgba(255,255,255,.5);font-weight:700;
                          text-transform:uppercase;letter-spacing:.06em;">Balance</p>
                <p style="font-weight:800;color:white;font-size:.95rem;font-family:monospace;">
                    ₦<?php echo number_format($user_balance,2); ?>
                </p>
            </div>
            <a href="fund-wallet"
               style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;
                      padding:10px 16px;border-radius:10px;text-decoration:none;
                      display:inline-flex;align-items:center;gap:6px;
                      box-shadow:0 4px 12px rgba(0,0,0,.15);transition:all .2s;">
                <i class="fas fa-plus text-xs"></i>Add Funds
            </a>
            <a href="my-logs"
               style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);
                      color:white;font-weight:600;font-size:.78rem;
                      padding:10px 16px;border-radius:10px;text-decoration:none;
                      display:inline-flex;align-items:center;gap:6px;transition:all .2s;">
                <i class="fas fa-bag-shopping text-xs"></i>My Logs
            </a>
        </div>
    </div>
</div>

<?php if ($xtl_enabled && !empty($xtl_products)): ?>
<!-- ── XtraLogTools API Products Section ─────────────────────── -->
<div class="anim anim-2" style="margin-top:28px;margin-bottom:8px;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;">
        <div style="width:32px;height:32px;border-radius:8px;
                    background:linear-gradient(135deg,#4D148C,#6b23c2);
                    display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-cloud-arrow-down" style="color:white;font-size:.8rem;"></i>
        </div>
        <div>
            <h3 style="font-weight:800;font-size:.9rem;color:var(--text-primary);margin:0;">
                API Logs Marketplace
            </h3>
            <p style="font-size:.72rem;color:var(--text-muted);margin:0;">
                Fresh logs delivered instantly via API — <?php echo count($xtl_products); ?> products available
            </p>
        </div>
    </div>

    <!-- API Category filter -->
    <?php if (!empty($xtl_categories)): ?>
    <div class="cat-bar" style="margin-bottom:12px;">
        <span style="font-size:.72rem;font-weight:700;color:var(--text-muted);
                     white-space:nowrap;display:flex;align-items:center;gap:5px;flex-shrink:0;">
            <i class="fas fa-filter" style="color:#4D148C;font-size:.65rem;"></i>Filter:
        </span>
        <button onclick="filterApiCat('all')" class="cat-pill active" id="api_cat_all">
            <i class="fas fa-th-large text-xs"></i>All
        </button>
        <?php foreach ($xtl_categories as $cat): ?>
        <button onclick="filterApiCat('<?php echo htmlspecialchars(addslashes($cat)); ?>')"
                class="cat-pill" data-apicat="<?php echo htmlspecialchars($cat); ?>">
            <?php echo htmlspecialchars($cat); ?>
        </button>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- API Products Grid -->
    <div class="svc-grid" id="apiProductsGrid">
        <?php foreach ($xtl_products as $xp): ?>
        <div class="svc-card" data-apicat="<?php echo htmlspecialchars($xp['category']); ?>">
            <!-- Top row -->
            <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;">
                <span class="svc-cat-badge">
                    <i class="fas fa-cloud text-xs"></i>
                    <?php echo htmlspecialchars($xp['category'] ?: 'API Log'); ?>
                </span>
                <span style="font-size:.65rem;font-weight:700;padding:3px 9px;border-radius:99px;
                             background:rgba(16,185,129,.08);color:#059669;
                             display:inline-flex;align-items:center;gap:4px;">
                    <span style="width:5px;height:5px;border-radius:50%;background:#059669;display:inline-block;"></span>
                    Server <?php echo (int)$xp['server']; ?>
                </span>
            </div>

            <!-- Name -->
            <h3 class="svc-name"><?php echo htmlspecialchars($xp['product_name']); ?></h3>

            <!-- Description -->
            <?php if (!empty($xp['description'])): ?>
            <p class="svc-desc"><?php echo htmlspecialchars($xp['description']); ?></p>
            <?php endif; ?>

            <!-- Quantity selector -->
            <div style="display:flex;align-items:center;gap:8px;margin:10px 0 4px;">
                <label style="font-size:.72rem;color:var(--text-muted);font-weight:500;white-space:nowrap;">Qty:</label>
                <input type="number"
                       id="qty_<?php echo (int)$xp['id']; ?>"
                       value="1" min="1" max="100"
                       style="width:70px;padding:5px 8px;border-radius:8px;
                              border:1.5px solid var(--card-border);background:var(--btn-bg);
                              color:var(--text-primary);font-size:.8rem;text-align:center;"
                       onchange="updateApiPrice(<?php echo (int)$xp['id']; ?>, <?php echo (float)$xp['our_price']; ?>)">
                <span style="font-size:.72rem;color:var(--text-muted);">
                    × ₦<?php echo number_format($xp['our_price'], 2); ?>/unit
                </span>
            </div>

            <!-- Price row -->
            <div class="svc-price-row">
                <span style="font-size:.72rem;color:var(--text-muted);font-weight:500;">Total</span>
                <span class="svc-price" id="price_<?php echo (int)$xp['id']; ?>">
                    ₦<?php echo number_format($xp['our_price'], 2); ?>
                </span>
            </div>

            <!-- Buy button -->
            <div class="svc-actions">
                <button onclick="buyApiLog(
                            <?php echo (int)$xp['id']; ?>,
                            '<?php echo htmlspecialchars(addslashes($xp['product_name']), ENT_QUOTES); ?>',
                            <?php echo (float)$xp['our_price']; ?>
                        )" class="btn-buy">
                    <i class="fas fa-bolt text-xs"></i>Buy via API
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ── API Purchase Confirmation Modal ──────────────────────── -->
<div id="apiPurchaseModal" class="modal-overlay">
    <div class="modal-box">
        <button onclick="closeApiModal()"
                style="position:absolute;top:14px;right:14px;width:32px;height:32px;
                       border-radius:50%;background:var(--btn-bg);
                       border:1px solid var(--card-border);cursor:pointer;
                       display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>

        <div style="text-align:center;margin-bottom:18px;">
            <div style="width:56px;height:56px;border-radius:50%;
                        background:rgba(5,150,105,.1);
                        display:flex;align-items:center;justify-content:center;
                        margin:0 auto 12px;">
                <i class="fas fa-bolt" style="font-size:1.3rem;color:#059669;"></i>
            </div>
            <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:4px;">
                Confirm API Purchase
            </h3>
            <p id="api_modal_name" style="font-size:.78rem;color:var(--text-muted);font-weight:500;"></p>
        </div>

        <div style="background:var(--btn-bg);border:1px solid var(--card-border);
                    border-radius:12px;overflow:hidden;margin-bottom:14px;">
            <div style="display:flex;align-items:center;justify-content:space-between;padding:11px 14px;border-bottom:1px solid var(--card-border);">
                <span style="font-size:.78rem;color:var(--text-muted);">Quantity</span>
                <span id="api_modal_qty" style="font-weight:700;font-size:.9rem;color:var(--text-primary);"></span>
            </div>
            <div style="display:flex;align-items:center;justify-content:space-between;padding:11px 14px;border-bottom:1px solid var(--card-border);">
                <span style="font-size:.78rem;color:var(--text-muted);">Total Charge</span>
                <span id="api_modal_price" style="font-weight:800;font-size:1rem;color:#4D148C;font-family:monospace;"></span>
            </div>
            <div style="display:flex;align-items:center;justify-content:space-between;padding:11px 14px;">
                <span style="font-size:.78rem;color:var(--text-muted);">Your Balance</span>
                <span style="font-weight:600;font-size:.88rem;color:var(--text-primary);font-family:monospace;">
                    ₦<?php echo number_format($user_balance, 2); ?>
                </span>
            </div>
        </div>

        <div style="background:rgba(5,150,105,.05);border:1px solid rgba(5,150,105,.15);
                    border-radius:10px;padding:11px 13px;margin-bottom:16px;
                    display:flex;gap:9px;align-items:flex-start;">
            <i class="fas fa-bolt" style="color:#059669;font-size:.85rem;flex-shrink:0;margin-top:1px;"></i>
            <p style="font-size:.72rem;color:var(--text-muted);line-height:1.55;">
                Logs are delivered <strong style="color:var(--text-primary);">instantly</strong> via API.
                View them in <strong style="color:var(--text-primary);">My Logs</strong> after purchase.
            </p>
        </div>

        <div style="display:flex;gap:10px;">
            <button onclick="closeApiModal()"
                    style="flex:1;border:1.5px solid var(--card-border);background:var(--btn-bg);
                           color:var(--text-muted);font-weight:600;padding:11px;
                           border-radius:10px;cursor:pointer;font-size:.82rem;">
                Cancel
            </button>
            <button id="confirmApiBtn" onclick="confirmApiPurchase()"
                    style="flex:2;background:linear-gradient(135deg,#059669,#10b981);color:white;
                           font-weight:700;padding:11px;border-radius:10px;border:none;
                           cursor:pointer;font-size:.82rem;
                           display:flex;align-items:center;justify-content:center;gap:8px;
                           box-shadow:0 4px 12px rgba(5,150,105,.28);">
                <i class="fas fa-bolt text-xs"></i><span>Confirm Purchase</span>
            </button>
        </div>
    </div>
</div>

<!-- ── API Logs Result Modal ─────────────────────────────────── -->
<div id="apiLogsResultModal" class="modal-overlay">
    <div class="modal-box" style="max-width:480px;">
        <button onclick="closeApiResultModal()"
                style="position:absolute;top:14px;right:14px;width:32px;height:32px;
                       border-radius:50%;background:var(--btn-bg);
                       border:1px solid var(--card-border);cursor:pointer;
                       display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding-right:36px;">
            <div style="width:36px;height:36px;border-radius:9px;background:rgba(5,150,105,.1);
                        display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-key" style="color:#059669;font-size:.9rem;"></i>
            </div>
            <div>
                <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);">Log Credentials</h3>
                <p style="font-size:.72rem;color:var(--text-muted);">Purchase successful — save these credentials now</p>
            </div>
        </div>
        <div style="background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15);
                    border-radius:10px;padding:10px 12px;margin-bottom:12px;
                    display:flex;gap:8px;">
            <i class="fas fa-triangle-exclamation" style="color:#dc2626;font-size:.85rem;flex-shrink:0;margin-top:1px;"></i>
            <p style="font-size:.72rem;color:#dc2626;">Keep these credentials safe. Change passwords immediately after first login.</p>
        </div>
        <div style="background:var(--btn-bg);border:1px solid var(--card-border);
                    border-radius:10px;padding:12px;max-height:220px;overflow-y:auto;margin-bottom:12px;">
            <pre id="api_logs_text" style="white-space:pre-wrap;word-break:break-words;
                                           font-family:monospace;font-size:.8rem;
                                           color:var(--text-primary);margin:0;"></pre>
        </div>
        <div style="display:flex;gap:8px;">
            <button onclick="copyApiLogs()"
                    style="flex:1;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;
                           font-weight:700;padding:11px;border-radius:10px;border:none;
                           cursor:pointer;display:flex;align-items:center;justify-content:center;
                           gap:8px;font-size:.82rem;">
                <i class="fas fa-copy"></i>Copy
            </button>
            <a href="my-logs"
               style="flex:1;background:var(--btn-bg);border:1.5px solid var(--card-border);
                      color:var(--text-primary);font-weight:600;padding:11px;border-radius:10px;
                      display:flex;align-items:center;justify-content:center;gap:8px;
                      font-size:.82rem;text-decoration:none;">
                <i class="fas fa-bag-shopping text-xs"></i>My Logs
            </a>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- ── Category filter bar ──────────────────────────────────── -->
<div class="cat-bar anim anim-1">
    <span style="font-size:.72rem;font-weight:700;color:var(--text-muted);
                 white-space:nowrap;display:flex;align-items:center;gap:5px;flex-shrink:0;">
        <i class="fas fa-filter" style="color:#4D148C;font-size:.65rem;"></i>Filter:
    </span>
    <a href="buy-logs" class="cat-pill <?php echo !$selected_category ? 'active' : ''; ?>">
        <i class="fas fa-th-large text-xs"></i>All
    </a>
    <?php foreach ($categories as $cat): ?>
    <a href="buy-logs?category=<?php echo $cat['id']; ?>"
       class="cat-pill <?php echo $selected_category == $cat['id'] ? 'active' : ''; ?>">
        <?php if (!empty($cat['category_image'])): ?>
        <img src="<?php echo htmlspecialchars($cat['category_image']); ?>"
             alt="" style="width:14px;height:14px;border-radius:3px;object-fit:contain;"
             onerror="this.style.display='none'">
        <?php endif; ?>
        <?php echo htmlspecialchars($cat['category_name']); ?>
    </a>
    <?php endforeach; ?>
</div>

<!-- ── Results count ─────────────────────────────────────────── -->
<div class="anim anim-2" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
    <p style="font-size:.78rem;color:var(--text-muted);">
        Showing
        <strong style="color:var(--text-primary);"><?php echo count($services); ?></strong>
        of
        <strong style="color:var(--text-primary);"><?php echo $total_services; ?></strong>
        logs
        <?php if ($selected_category): ?>
        <span style="color:#4D148C;">— filtered</span>
        <?php endif; ?>
    </p>
    <?php if ($selected_category): ?>
    <a href="buy-logs" style="font-size:.72rem;font-weight:600;color:#4D148C;text-decoration:none;
                              display:flex;align-items:center;gap:4px;">
        <i class="fas fa-xmark text-xs"></i>Clear filter
    </a>
    <?php endif; ?>
</div>

<!-- ── Services grid ─────────────────────────────────────────── -->
<?php if (!empty($services)): ?>
<div class="svc-grid anim anim-2">
    <?php foreach ($services as $service): ?>
    <div class="svc-card">

        <!-- Top row: category badge + available badge -->
        <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;">
            <div style="display:flex;align-items:center;gap:6px;min-width:0;">
                <?php if (!empty($service['category_image'])): ?>
                <img src="<?php echo htmlspecialchars($service['category_image']); ?>"
                     alt="<?php echo htmlspecialchars($service['category_name']); ?>"
                     style="width:26px;height:26px;border-radius:6px;object-fit:contain;
                            border:1px solid var(--card-border);flex-shrink:0;"
                     onerror="this.style.display='none'">
                <?php endif; ?>
                <span class="svc-cat-badge">
                    <?php echo htmlspecialchars($service['category_name']); ?>
                </span>
            </div>
            <span class="svc-avail-badge">
                <span style="width:5px;height:5px;border-radius:50%;background:#6b23c2;display:inline-block;"></span>
                Available
            </span>
        </div>

        <!-- Service name -->
        <h3 class="svc-name"><?php echo htmlspecialchars($service['service_name']); ?></h3>

        <!-- Description -->
        <p class="svc-desc"><?php echo htmlspecialchars($service['service_description']); ?></p>

        <!-- Price row -->
        <div class="svc-price-row">
            <span style="font-size:.72rem;color:var(--text-muted);font-weight:500;">Price</span>
            <span class="svc-price">₦<?php echo number_format($service['amount'],2); ?></span>
        </div>

        <!-- Actions -->
        <div class="svc-actions">
            <?php if (!empty($service['preview_link'])): ?>
            <a href="<?php echo htmlspecialchars($service['preview_link']); ?>"
               target="_blank" class="btn-preview">
                <i class="fas fa-eye text-xs"></i>Preview
            </a>
            <?php endif; ?>
            <button onclick="buyLog(
                        <?php echo (int)$service['id']; ?>,
                        '<?php echo htmlspecialchars(addslashes($service['service_name']),ENT_QUOTES); ?>',
                        <?php echo (float)$service['amount']; ?>
                    )" class="btn-buy">
                <i class="fas fa-cart-shopping text-xs"></i>Buy Now
            </button>
        </div>

    </div>
    <?php endforeach; ?>
</div>

<!-- ── Pagination ─────────────────────────────────────────────── -->
<?php if ($total_pages > 1): ?>
<div class="anim anim-3" style="display:flex;justify-content:center;gap:6px;flex-wrap:wrap;margin-bottom:8px;">
    <?php $prefix = $selected_category ? 'category='.$selected_category.'&' : ''; ?>

    <?php if ($current_page > 1): ?>
    <a href="?<?php echo $prefix; ?>page=<?php echo $current_page-1; ?>" class="pag-btn">
        <i class="fas fa-chevron-left text-xs"></i>
    </a>
    <?php endif; ?>

    <?php for ($p=1; $p<=$total_pages; $p++): ?>
    <a href="?<?php echo $prefix; ?>page=<?php echo $p; ?>"
       class="pag-btn <?php echo $p===$current_page?'active':''; ?>">
        <?php echo $p; ?>
    </a>
    <?php endfor; ?>

    <?php if ($current_page < $total_pages): ?>
    <a href="?<?php echo $prefix; ?>page=<?php echo $current_page+1; ?>" class="pag-btn">
        <i class="fas fa-chevron-right text-xs"></i>
    </a>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php else: ?>
<!-- ── Empty state ───────────────────────────────────────────── -->
<div class="anim anim-2"
     style="background:var(--card-bg);border:1px solid var(--card-border);
            border-radius:16px;padding:48px 24px;text-align:center;">
    <div style="width:60px;height:60px;border-radius:50%;
                background:rgba(77,20,140,.07);
                display:flex;align-items:center;justify-content:center;
                margin:0 auto 14px;">
        <i class="fas fa-box-open" style="font-size:1.5rem;color:var(--text-muted);"></i>
    </div>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:6px;">
        No Logs Available
    </h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:260px;margin:0 auto 16px;">
        <?php echo $selected_category ? 'No logs found in this category.' : 'Check back later for new listings.'; ?>
    </p>
    <?php if ($selected_category): ?>
    <a href="buy-logs"
       style="display:inline-flex;align-items:center;gap:8px;padding:10px 20px;
              background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;
              font-weight:700;font-size:.82rem;border-radius:10px;text-decoration:none;
              box-shadow:0 4px 12px rgba(77,20,140,.25);">
        <i class="fas fa-th-large text-xs"></i>View All
    </a>
    <?php endif; ?>
</div>
<?php endif; ?>

</div><!-- /max-w -->

<!-- ── Purchase Confirmation Modal ──────────────────────────── -->
<div id="purchaseModal" class="modal-overlay">
    <div class="modal-box">

        <button onclick="closePurchaseModal()"
                style="position:absolute;top:14px;right:14px;width:32px;height:32px;
                       border-radius:50%;background:var(--btn-bg);
                       border:1px solid var(--card-border);cursor:pointer;
                       display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>

        <!-- Icon + title -->
        <div style="text-align:center;margin-bottom:18px;">
            <div style="width:56px;height:56px;border-radius:50%;
                        background:rgba(77,20,140,.1);
                        display:flex;align-items:center;justify-content:center;
                        margin:0 auto 12px;">
                <i class="fas fa-cart-shopping" style="font-size:1.3rem;color:#4D148C;"></i>
            </div>
            <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:4px;">
                Confirm Purchase
            </h3>
            <p id="modal_service_name"
               style="font-size:.78rem;color:var(--text-muted);font-weight:500;"></p>
        </div>

        <!-- Price details -->
        <div style="background:var(--btn-bg);border:1px solid var(--card-border);
                    border-radius:12px;overflow:hidden;margin-bottom:14px;">
            <div class="modal-detail-row" style="padding:11px 14px;">
                <span style="font-size:.78rem;color:var(--text-muted);">Service Price</span>
                <span id="modal_price"
                      style="font-weight:800;font-size:1rem;color:#4D148C;font-family:monospace;"></span>
            </div>
            <div class="modal-detail-row" style="padding:11px 14px;">
                <span style="font-size:.78rem;color:var(--text-muted);">Your Balance</span>
                <span style="font-weight:600;font-size:.88rem;color:var(--text-primary);font-family:monospace;">
                    ₦<?php echo number_format($user_balance,2); ?>
                </span>
            </div>
        </div>

        <!-- Info notice -->
        <div style="background:rgba(59,130,246,.05);border:1px solid rgba(59,130,246,.15);
                    border-radius:10px;padding:11px 13px;margin-bottom:16px;
                    display:flex;gap:9px;align-items:flex-start;">
            <i class="fas fa-circle-info" style="color:#3b82f6;font-size:.85rem;flex-shrink:0;margin-top:1px;"></i>
            <p style="font-size:.72rem;color:var(--text-muted);line-height:1.55;">
                After purchase, log credentials will be instantly available in
                <strong style="color:var(--text-primary);">My Logs</strong>.
                Funds will be deducted from your main balance.
            </p>
        </div>

        <!-- Buttons -->
        <div style="display:flex;gap:10px;">
            <button onclick="closePurchaseModal()"
                    style="flex:1;border:1.5px solid var(--card-border);background:var(--btn-bg);
                           color:var(--text-muted);font-weight:600;padding:11px;
                           border-radius:10px;cursor:pointer;font-size:.82rem;transition:all .15s;">
                Cancel
            </button>
            <button id="confirmPurchaseBtn" onclick="confirmPurchase()"
                    style="flex:2;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;
                           font-weight:700;padding:11px;border-radius:10px;border:none;
                           cursor:pointer;font-size:.82rem;
                           display:flex;align-items:center;justify-content:center;gap:8px;
                           box-shadow:0 4px 12px rgba(77,20,140,.28);transition:all .2s;">
                <i class="fas fa-check text-xs"></i><span>Confirm</span>
            </button>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let currentServiceId  = null;
let currentServiceAmt = 0;
const userBalance     = <?php echo $user_balance; ?>;

function buyLog(serviceId, serviceName, amount) {
    currentServiceId  = serviceId;
    currentServiceAmt = parseFloat(amount);

    if (userBalance < currentServiceAmt) {
        Swal.fire({
            title: 'Insufficient Balance',
            html:  `You need <strong>₦${currentServiceAmt.toFixed(2)}</strong> but only have <strong>₦${userBalance.toFixed(2)}</strong>.<br><br>Please fund your wallet to continue.`,
            icon:  'warning',
            confirmButtonText: 'Fund Wallet',
            showCancelButton:  true,
            cancelButtonText:  'Cancel',
            confirmButtonColor: '#4D148C'
        }).then(r => { if (r.isConfirmed) window.location.href = 'fund-wallet'; });
        return;
    }

    document.getElementById('modal_service_name').textContent = serviceName;
    document.getElementById('modal_price').textContent        = '₦' + currentServiceAmt.toFixed(2);

    const m = document.getElementById('purchaseModal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}

function closePurchaseModal() {
    const m = document.getElementById('purchaseModal');
    m.classList.add('hidden');
    m.classList.remove('flex');
}

// Close on backdrop click
document.getElementById('purchaseModal').addEventListener('click', function(e) {
    if (e.target === this) closePurchaseModal();
});

// Close on Escape
document.addEventListener('keydown', e => { if (e.key === 'Escape') closePurchaseModal(); });

function confirmPurchase() {
    if (!currentServiceId) return;

    const btn = document.getElementById('confirmPurchaseBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i><span>Processing...</span>';

    $.ajax({
        url:      'ajax/purchase_log.php',
        type:     'POST',
        data:     { service_id: currentServiceId },
        dataType: 'json',
        success: function(res) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check text-xs"></i><span>Confirm</span>';
            closePurchaseModal();

            if (res.status === '1') {
                Swal.fire({
                    title: 'Purchase Successful! 🎉',
                    html:  'Your log credentials are now available in <strong>My Logs</strong>.',
                    icon:  'success',
                    confirmButtonText: 'View My Logs',
                    showCancelButton:  true,
                    cancelButtonText:  'Continue Shopping',
                    confirmButtonColor: '#4D148C'
                }).then(r => {
                    if (r.isConfirmed) window.location.href = 'my-logs';
                    else                window.location.reload();
                });
            } else {
                Swal.fire('Failed', res.msg || 'Purchase failed. Please try again.', 'error');
            }
        },
        error: function() {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check text-xs"></i><span>Confirm</span>';
            closePurchaseModal();
            Swal.fire('Error', 'An unexpected error occurred. Please try again.', 'error');
        }
    });
}

// ════════════════════════════════════════════════════════════════
//  XtraLogTools API Purchase Flow
// ════════════════════════════════════════════════════════════════

let currentApiProductId = null;
let currentApiQty       = 1;
let currentApiUnitPrice = 0;

function updateApiPrice(productId, unitPrice) {
    const qty   = parseInt(document.getElementById('qty_' + productId).value) || 1;
    const total = (qty * unitPrice).toFixed(2);
    document.getElementById('price_' + productId).textContent = '₦' + parseFloat(total).toLocaleString('en-NG', {minimumFractionDigits:2});
}

function buyApiLog(productId, productName, unitPrice) {
    const qty   = parseInt(document.getElementById('qty_' + productId).value) || 1;
    const total = parseFloat((qty * unitPrice).toFixed(2));

    if (userBalance < total) {
        Swal.fire({
            title: 'Insufficient Balance',
            html:  'You need <strong>₦' + total.toFixed(2) + '</strong> but only have <strong>₦' + userBalance.toFixed(2) + '</strong>.<br><br>Please fund your wallet.',
            icon:  'warning',
            confirmButtonText: 'Fund Wallet',
            showCancelButton:  true,
            cancelButtonText:  'Cancel',
            confirmButtonColor: '#4D148C'
        }).then(r => { if (r.isConfirmed) window.location.href = 'fund-wallet'; });
        return;
    }

    currentApiProductId = productId;
    currentApiQty       = qty;
    currentApiUnitPrice = unitPrice;

    document.getElementById('api_modal_name').textContent  = productName;
    document.getElementById('api_modal_qty').textContent   = qty + ' account' + (qty > 1 ? 's' : '');
    document.getElementById('api_modal_price').textContent = '₦' + total.toLocaleString('en-NG', {minimumFractionDigits:2});

    const m = document.getElementById('apiPurchaseModal');
    m.classList.remove('hidden');
    m.classList.add('flex');
}

function closeApiModal() {
    const m = document.getElementById('apiPurchaseModal');
    m.classList.add('hidden');
    m.classList.remove('flex');
}

function closeApiResultModal() {
    const m = document.getElementById('apiLogsResultModal');
    m.classList.add('hidden');
    m.classList.remove('flex');
}

document.getElementById('apiPurchaseModal')?.addEventListener('click', function(e) {
    if (e.target === this) closeApiModal();
});
document.getElementById('apiLogsResultModal')?.addEventListener('click', function(e) {
    if (e.target === this) closeApiResultModal();
});

function confirmApiPurchase() {
    if (!currentApiProductId) return;

    const btn = document.getElementById('confirmApiBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin text-xs"></i><span>Processing...</span>';

    $.ajax({
        url:      'ajax/purchase_log_api.php',
        type:     'POST',
        data:     { product_id: currentApiProductId, quantity: currentApiQty },
        dataType: 'json',
        success: function(res) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-bolt text-xs"></i><span>Confirm Purchase</span>';
            closeApiModal();

            if (res.status === '1') {
                if (res.logs) {
                    // Show credentials immediately
                    document.getElementById('api_logs_text').textContent = res.logs;
                    const rm = document.getElementById('apiLogsResultModal');
                    rm.classList.remove('hidden');
                    rm.classList.add('flex');
                } else {
                    Swal.fire({
                        title: 'Purchase Successful! 🎉',
                        html:  'Your log credentials are available in <strong>My Logs</strong>.',
                        icon:  'success',
                        confirmButtonText: 'View My Logs',
                        showCancelButton:  true,
                        cancelButtonText:  'Continue Shopping',
                        confirmButtonColor: '#4D148C'
                    }).then(r => {
                        if (r.isConfirmed) window.location.href = 'my-logs';
                    });
                }
            } else {
                Swal.fire('Purchase Failed', res.msg || 'Purchase failed. Please try again.', 'error');
            }
        },
        error: function() {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-bolt text-xs"></i><span>Confirm Purchase</span>';
            closeApiModal();
            Swal.fire('Error', 'An unexpected error occurred. Please try again.', 'error');
        }
    });
}

function copyApiLogs() {
    const text = document.getElementById('api_logs_text').textContent;
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function() {
            Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
        });
    } else {
        const ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
    }
}

// ── API category filter ───────────────────────────────────────
function filterApiCat(cat) {
    // Update active pill
    document.querySelectorAll('[data-apicat]').forEach(function(btn) {
        btn.classList.toggle('active', btn.dataset.apicat === cat);
    });
    document.getElementById('api_cat_all')?.classList.toggle('active', cat === 'all');

    // Filter cards
    document.querySelectorAll('#apiProductsGrid .svc-card').forEach(function(card) {
        if (cat === 'all' || card.dataset.apicat === cat) {
            card.style.display = '';
        } else {
            card.style.display = 'none';
        }
    });
}
</script>

<?php include('footer.php'); ?>