<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';
require_once __DIR__ . '/includes/shares.php';
require_once __DIR__ . '/includes/purchase.php';

if (!isLoggedIn()) { redirect('login.php'); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$cat_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$sub_id = isset($_GET['sub_id']) ? intval($_GET['sub_id']) : 0;

$category = $db->select("SELECT * FROM service_categories WHERE id = ?", [$cat_id]);
if (empty($category) && $cat_id > 0) { redirect('dashboard.php'); }

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : 0.00;

/* Dual wallet: virtual (referral earnings) is spent before the main wallet */
wallet_ensure_schema($db);
$wal = wallet_balances($db, $user_id);

shares_ensure_schema($db);
$is_subscriber = shares_is_subscribed($db, $user_id);

$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');
$rzp_key = getSetting('razorpay_key_id', '');
$rzp_secret = getSetting('razorpay_key_secret', '');

// Fetch ALL active categories for the Sidebar Dropdown
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

// Sub-categories for the sidebar nested menu (Government Portals=1, Agency & Software=5)
$sidebar_subcats = [1 => [], 5 => []];
$__sc = $db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id");
foreach ($__sc as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

/* ---------------------------------------------------------------------------
   QUICK BUY — the popup on the product card
   ----------------------------------------------------------------------------
   Wallet first, always. A ₹99 service against an ₹11 wallet takes the ₹11 and
   asks for ₹88 online; a wallet that covers the whole thing needs no card at
   all. There is no "insufficient balance" any more — a short wallet is simply
   topped up by the gateway for that one purchase.

   Everything is worked out again here from the product row, so nothing in the
   form can change what is charged.
   --------------------------------------------------------------------------- */
if (isset($_POST['process_payment'])) {
    $service_id = intval($_POST['service_id']);
    $pay_id     = sanitize($_POST['payment_id'] ?? '');
    $use_wallet = !empty($_POST['use_wallet']);

    $svc = shares_get_service($db, $service_id);
    if (!$svc) {
        echo "<script>alert('Service not found.'); window.location.href=window.location.href;</script>";
        exit;
    }

    /* Customer Data Recruitment gates (KYC + serviceable area), re-checked on the
       server so a hidden or forged form cannot slip past the popup. */
    $gate = product_purchase_gate($db, $svc, $user_id);
    if (!$gate['ok']) {
        $msg = product_gate_message(product_gate_payload($db, $svc, $user_id, $gate));
        echo "<script>alert(" . json_encode($msg) . "); window.location.href=window.location.href;</script>";
        exit;
    }

    $line = buy_quote($db, $svc, $user_id, $is_subscriber);
    $line['qty'] = 1; $line['cart_id'] = 0; $line['svc'] = $svc;

    /* A visit product cannot finish in this popup — send it to the booking page. */
    if ($line['fulfilment'] === 'visit') {
        redirect('product.php?id=' . (int)$svc['id']);
    }

    $plan = buy_wallet_plan($db, $user_id, $line['payable'], $use_wallet);
    $ref  = '';

    /* Whatever the wallet could not cover has to arrive through the gateway,
       and it is verified with Razorpay before a single rupee is recorded. */
    if ($plan['gateway'] > 0.009) {
        if ($pay_id === '') {
            echo "<script>alert('The online payment did not complete. Nothing has been charged.'); window.location.href=window.location.href;</script>";
            exit;
        }
        $ok = false;
        if ($rzp_key !== '' && $rzp_secret !== '') {
            $ch = curl_init("https://api.razorpay.com/v1/payments/" . rawurlencode($pay_id));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_USERPWD, $rzp_key . ':' . $rzp_secret);
            $resp = curl_exec($ch);
            curl_close($ch);
            $d = json_decode((string)$resp, true);
            if (isset($d['status']) && in_array($d['status'], ['authorized', 'captured'], true)
                && ((float)$d['amount'] / 100) + 0.009 >= $plan['gateway']) {
                $ok = true;
            }
        }
        if (!$ok) {
            echo "<script>alert('We could not verify that payment. If money has left your account it will come back — please contact support with payment id " . addslashes($pay_id) . ".'); window.location.href=window.location.href;</script>";
            exit;
        }
        $ref = $pay_id;
    }

    $res = buy_place_order($db, $user_id, [$line], [
        'payment_mode' => 'full',
        'use_wallet'   => $use_wallet,
        'gateway_ref'  => $ref,
    ]);

    if (empty($res['ok'])) {
        echo "<script>alert(" . json_encode($res['error'] ?: 'The order could not be placed.') . "); window.location.href=window.location.href;</script>";
        exit;
    }
    redirect('order.php?id=' . (int)$res['order_id'] . '&new=1');
}

// Data Fetching Based on Category (Unified for both Free and Paid)
$agency_sub_cats = [];
$services_list = [];
$current_sub_cat = null;

/* Every live category can be opened now — not only Government Portals and
   Agency & Software. A category with sub-categories shows them as tabs and
   lists that tab's services; one without any simply lists everything it has,
   so a brand new category is usable the moment a product lands in it. */
$CAT_OPEN = !empty($category);

if ($CAT_OPEN) {
    // Sub-categories are always loaded — they render as tabs above the products
    $agency_sub_cats = $db->select("SELECT * FROM agency_sub_categories WHERE category_id = ? AND status = 1 ORDER BY id ASC", [$cat_id]);

    // No tab chosen yet? open the first one so products show straight away
    if ($sub_id == 0 && !empty($agency_sub_cats)) { $sub_id = (int)$agency_sub_cats[0]['id']; }

    if ($sub_id > 0) {
        $sub_data = $db->select("SELECT * FROM agency_sub_categories WHERE id = ?", [$sub_id]);
        $current_sub_cat = !empty($sub_data) ? $sub_data[0] : null;

        $services_list = $db->select("SELECT ss.*, u.name as seller_name, u.call_number, u.whatsapp_number
                                      FROM seller_services ss JOIN users u ON ss.seller_id = u.id
                                      WHERE ss.category_id = ? AND ss.sub_category_id = ? AND ss.status = 1",
                                     [$cat_id, $sub_id]);
    } else {
        // no sub-categories at all — show the whole category
        $services_list = $db->select("SELECT ss.*, u.name as seller_name, u.call_number, u.whatsapp_number
                                      FROM seller_services ss JOIN users u ON ss.seller_id = u.id
                                      WHERE ss.category_id = ? AND ss.status = 1",
                                     [$cat_id]);
    }
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);

// Fetch order statuses for the user
$my_orders = $db->select("SELECT service_name, status FROM orders WHERE user_id = ?", [$user_id]);
$purchased_services = [];
foreach ($my_orders as $mo) {
    $purchased_services[$mo['service_name']] = $mo['status'];
}

$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }

$page_title = !empty($category) ? esc($category[0]['title']) : 'Services';
if ($CAT_OPEN && $sub_id > 0 && $current_sub_cat) {
    $page_title = esc($current_sub_cat['title']) . " - " . $page_title;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc;} 
        .font-poppins { font-family: 'Poppins', sans-serif; }
        .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } 
        
        .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; justify-items: center; }
        .product-card { background: white; border-radius: 12px; padding: 12px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.05); display: flex; flex-direction: column; justify-content: flex-start; width: 100%; height: auto; min-height: auto; border-top: 4px solid #ccc; transition: all 0.3s; position: relative; overflow: hidden; }
        .product-card:hover { transform: translateY(-4px); box-shadow: 0 8px 16px rgba(0,0,0,0.1); }
        .image-area { height: 100px; display: flex; align-items: center; justify-content: center; font-size: 3rem; width: 100px; margin: 8px auto 12px; background: #f8fafc; border-radius: 16px; overflow: hidden; padding: 8px; }
        .image-area img { width: 100%; height: 100%; object-fit: contain; }
        .p-title { font-size: 0.75rem; font-weight: 700; color: #1f2937; min-height: 36px; display: flex; align-items: center; justify-content: center; line-height: 1.2; overflow: hidden; font-family: 'Poppins', sans-serif;}
        .seller-badge { font-size: 0.55rem; color: #64748b; background: #f1f5f9; padding: 2px 5px; border-radius: 4px; margin-bottom: 5px; display:inline-block;}
        
        /* New Read More/Less setup */
        .clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }

        /* Document popup — glass action buttons */
        .glass-btn { display:flex; align-items:center; justify-content:center; gap:.6rem; width:100%; padding:.9rem 1rem; border-radius:1rem; font-weight:700; font-size:.95rem; transition:transform .2s ease, box-shadow .2s ease; border:1px solid rgba(255,255,255,.35); -webkit-backdrop-filter:blur(10px); backdrop-filter:blur(10px); color:#fff; }
        .glass-app { background:linear-gradient(135deg, rgba(16,185,129,.92), rgba(5,150,105,.92)); box-shadow:0 10px 24px -8px rgba(16,185,129,.6); }
        .glass-web { background:linear-gradient(135deg, rgba(59,130,246,.92), rgba(79,70,229,.92)); box-shadow:0 10px 24px -8px rgba(59,130,246,.6); }
        .glass-tut { background:linear-gradient(135deg, rgba(244,63,94,.92), rgba(225,29,72,.92)); box-shadow:0 10px 24px -8px rgba(244,63,94,.6); }
        .glass-btn:hover { transform:translateY(-2px); }
        .doc-scroll::-webkit-scrollbar { width:6px; } .doc-scroll::-webkit-scrollbar-thumb { background:#cbd5e1; border-radius:9999px; }
        /* Document popup sizing — keeps the action buttons visible on mobile */
        .doc-modal { max-height: 92vh; }
        @supports (height: 100dvh) { .doc-modal { max-height: 92dvh; } }
        @media (max-width: 639px) {
            .doc-modal { max-height: 88vh; }
            @supports (height: 100dvh) { .doc-modal { max-height: 88dvh; } }
            /* smaller hero on phones so title + text + buttons all fit */
            .doc-modal .doc-hero { height: 150px !important; }
            .doc-modal .doc-hero-img { width: 112px !important; height: 112px !important; padding: .75rem !important; }
        }
        [x-cloak] { display:none !important; }


        .price-tag { display: flex; flex-direction: column; margin-top: auto; margin-bottom: 8px; }
        .original-price { font-size: 0.65rem; text-decoration: line-through; color: #9ca3af; } 
        .discount-price { font-size: 0.85rem; font-weight: 700; }
        .card-buttons { display: flex; flex-direction: column; gap: 5px; margin-top: auto;}
        .action-btn { width: 100%; padding: 8px 4px; border: none; border-radius: 6px; font-size: 0.7rem; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 4px; text-decoration: none; transition: opacity 0.2s; }
        .buy-btn { color: white; }
        .tutorial-btn { background-color: #f1f5f9; color: #4b5563; border: 1px solid #e5e7eb; }

        /* Customer Data Recruitment — blocked "Buy Now" states */
        .gate-btn { font-size: 0.62rem; line-height: 1.15; text-align: center; }
        .gate-btn.gate-area { background-color: #64748b !important; }
        .gate-btn.gate-kyc  { background-color: #f59e0b !important; }
        .gate-btn:hover { opacity: .9; }
        
        .purchased-card { border-top: 4px solid #10b981 !important; }
        .purchased-card .price-tag, .purchased-card .buy-btn, .purchased-card .tutorial-btn { display: none !important; }
        .purchased-card .image-area { color: #10b981 !important; background: #ecfdf5; }
        .success-badge { display: none; font-size: 0.75rem; font-weight: 700; color: #10b981; margin-bottom: 10px; }
        .purchased-card .success-badge { display: block; }
        
        .pending-badge { display: none; font-size: 0.7rem; font-weight: 700; color: #f59e0b; margin-bottom: 10px; }
        .pending-card { border-top: 4px solid #f59e0b !important; background-color: #fdfbf7; }
        .pending-card .price-tag, .pending-card .buy-btn, .pending-card .tutorial-btn, .pending-card .final-btn-group { display: none !important; }
        .pending-card .pending-badge { display: block; }
        
        /* Free Services directly show links */
        .free-card .price-tag, .free-card .card-buttons { display: none !important; }
        .free-card .final-btn-group { display: flex !important; margin-top: 4px !important; } /* GAP KNOB (Govt/free cards) */
        .free-card { min-height: auto; }
        .product-grid { align-items: start; }

        /* Pending/Processing UI */
        .processing-area { display: none; flex-direction: column; align-items: center; gap: 8px; margin: 15px 0; padding: 10px; background-color: #fffbeb; border-radius: 8px; border: 1px dashed #fcd34d; }
        .pending-card .processing-area { display: flex; }
        .spinner { width: 22px; height: 22px; border: 3px solid #fde68a; border-top: 3px solid #f59e0b; border-radius: 50%; animation: spin 1s linear infinite; } 
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        .final-btn-group { display: none; flex-direction: column; gap: 6px; margin-top: 4px; } /* GAP KNOB: increase/decrease this margin-top */
        .purchased-card .final-btn-group { display: flex; }
        .pending-btn-group { display: none; flex-direction: column; gap: 6px; margin-top: auto; width: 100%; }
        .pending-card .pending-btn-group { display: flex; }
        
        .btn-web { background-color: #1e3a5f; color: white; } 
        .btn-app { background-color: #0d9488; color: white; } 
        .btn-call { background-color: #10b981; color: white; } 
        .btn-wa { background-color: #25d366; color: white; }
        
        .color-1 { border-top-color: #ef4444; } .color-1 .image-area { color: #ef4444; } .color-1 .buy-btn { background-color: #ef4444; } .color-1 .discount-price { color: #ef4444; } 
        .color-2 { border-top-color: #3b82f6; } .color-2 .image-area { color: #3b82f6; } .color-2 .buy-btn { background-color: #3b82f6; } .color-2 .discount-price { color: #3b82f6; } 
        .color-3 { border-top-color: #10b981; } .color-3 .image-area { color: #10b981; } .color-3 .buy-btn { background-color: #10b981; } .color-3 .discount-price { color: #10b981; } 
        .color-4 { border-top-color: #f59e0b; } .color-4 .image-area { color: #f59e0b; } .color-4 .buy-btn { background-color: #f59e0b; } .color-4 .discount-price { color: #f59e0b; } 
        .color-5 { border-top-color: #8b5cf6; } .color-5 .image-area { color: #8b5cf6; } .color-5 .buy-btn { background-color: #8b5cf6; } .color-5 .discount-price { color: #8b5cf6; }

        /* ===================== SUB-CATEGORY TABS ===================== */
        .subtabs-wrap { position: sticky; top: 0; z-index: 30; background: #f8fafc;
                        padding: 10px 0 12px; margin-top: -4px;
                        box-shadow: 0 8px 14px -12px rgba(15,23,42,.35); }
        .subtabs { display: flex; gap: 8px; overflow-x: auto; padding: 2px 2px 4px; scroll-behavior: smooth; }
        .subtab {
            display: inline-flex; align-items: center; gap: 8px; flex-shrink: 0;
            padding: 8px 14px 8px 8px; border-radius: 999px;
            background: #fff; border: 1.5px solid #e6ebf5; text-decoration: none;
            font-size: .72rem; font-weight: 800; color: #64748b; white-space: nowrap;
            transition: all .22s cubic-bezier(.34,1.3,.64,1);
            box-shadow: 0 1px 2px rgba(15,23,42,.04);
        }
        .subtab:hover { border-color: #c9d4ea; transform: translateY(-1px); box-shadow: 0 6px 14px -8px rgba(15,23,42,.3); }
        .subtab-ico { width: 26px; height: 26px; border-radius: 50%; display: flex; align-items: center;
                      justify-content: center; color: #fff; font-size: .68rem; flex-shrink: 0;
                      box-shadow: 0 2px 6px rgba(15,23,42,.18); }
        .subtab-txt { line-height: 1.1; }
        .subtab.is-on {
            background: linear-gradient(135deg, #0b1220, #1e293b);
            border-color: #0b1220; color: #fff;
            box-shadow: 0 8px 18px -8px rgba(11,18,32,.7);
        }
        .subtab.is-on .subtab-ico { box-shadow: 0 0 0 2px rgba(212,175,55,.55); }
        @media (max-width: 640px) { .subtab { font-size: .68rem; padding: 7px 12px 7px 7px; } }

        /* ===================== PRODUCT CARD — navy + gold theme ===================== */
        .product-card {
            border-radius: 16px !important;
            border-top: 0 !important;
            border: 1px solid #e6ebf5 !important;
            background: linear-gradient(170deg, #ffffff 0%, #fcfdff 60%, #f7f9ff 100%) !important;
            box-shadow: 0 2px 10px -4px rgba(15,23,42,.10) !important;
            padding: 14px 12px 12px !important;
        }
        .product-card::before {
            content: ''; position: absolute; inset: 0 0 auto 0; height: 3px;
            background: linear-gradient(90deg, #0b1220, #C8901B 45%, #f0d878 60%, #0b1220);
            opacity: .9;
        }
        .product-card:hover {
            transform: translateY(-5px) !important;
            border-color: rgba(200,144,27,.45) !important;
            box-shadow: 0 16px 32px -14px rgba(11,18,32,.35), 0 0 0 1px rgba(200,144,27,.25) !important;
        }
        .product-card .image-area {
            border-radius: 18px;
            background: linear-gradient(150deg, #ffffff, #eef2fa);
            box-shadow: inset 0 1px 0 rgba(255,255,255,.9), 0 4px 12px -6px rgba(11,18,32,.28);
            border: 1px solid #eef2f8;
        }
        .product-card .p-title { color: #0b1220; font-weight: 700; letter-spacing: .005em; }
        .product-card .seller-badge {
            background: #f4f7ff; color: #46557a; border: 1px solid #e4ebfa;
            font-weight: 700; letter-spacing: .02em;
        }
        .product-card .original-price { color: #9aa5b8; }
        .product-card .discount-price { color: #0b1220 !important; font-weight: 800; }

        /* Buy button — navy base with a gold sheen */
        .product-card .buy-btn {
            background: linear-gradient(135deg, #0b1220, #1e293b) !important;
            color: #fff !important; border-radius: 10px; font-weight: 800; letter-spacing: .02em;
            box-shadow: 0 6px 14px -7px rgba(11,18,32,.75);
            position: relative; overflow: hidden;
        }
        .product-card .buy-btn::after {
            content: ''; position: absolute; inset: 0; border-radius: 10px;
            border: 1px solid rgba(200,144,27,.45); pointer-events: none;
        }
        .product-card .buy-btn:hover { background: linear-gradient(135deg, #14203a, #26364f) !important; }
        .product-card .gate-btn.gate-area { background: #64748b !important; }
        .product-card .gate-btn.gate-kyc  { background: linear-gradient(135deg,#C8901B,#a8760f) !important; }

        .product-card .tutorial-btn {
            background: #fff; border: 1px solid #e6ebf5; color: #46557a; border-radius: 10px; font-weight: 700;
        }
        .product-card .tutorial-btn:hover { border-color: #C8901B; color: #0b1220; }
        .product-card .btn-web {
            background: linear-gradient(135deg,#1d4ed8,#4f46e5) !important; color:#fff !important;
            border-radius: 10px; font-weight: 700;
        }
        .product-card .btn-app {
            background: linear-gradient(135deg,#059669,#047857) !important; color:#fff !important;
            border-radius: 10px; font-weight: 700;
        }

        /* Category accent now only tints the icon, not the whole card */
        .color-1 .image-area i { color: #ef4444; } .color-2 .image-area i { color: #3b82f6; }
        .color-3 .image-area i { color: #10b981; } .color-4 .image-area i { color: #f59e0b; }
        .color-5 .image-area i { color: #8b5cf6; }
        .color-1 .buy-btn, .color-2 .buy-btn, .color-3 .buy-btn, .color-4 .buy-btn, .color-5 .buy-btn {
            background: linear-gradient(135deg, #0b1220, #1e293b) !important;
        }
        .color-1 .discount-price, .color-2 .discount-price, .color-3 .discount-price,
        .color-4 .discount-price, .color-5 .discount-price { color: #0b1220 !important; }

        .purchased-card { border-color: rgba(16,185,129,.5) !important; }
        .purchased-card::before { background: linear-gradient(90deg,#059669,#34d399,#059669); }
        .pending-card::before   { background: linear-gradient(90deg,#d97706,#fbbf24,#d97706); }

        /* ===================== GOVERNMENT PORTAL — premium cards ===================== */
        .govt-card {
            border-top: 0 !important;
            border-radius: 18px;
            padding: 14px 12px 12px;
            background: linear-gradient(168deg,#ffffff 0%,#fbfcff 52%,#f4f7ff 100%);
            border: 1px solid #e6ebf5;
            box-shadow: 0 4px 18px -6px rgba(15,23,42,.10), 0 1px 3px rgba(15,23,42,.05);
        }
        .govt-card::before {
            content: ''; position: absolute; inset: 0 0 auto 0; height: 4px;
            background: linear-gradient(90deg,#f97316 0%,#ffffff 50%,#15803d 100%);
        }
        .govt-card::after {
            content: ''; position: absolute; right: -46px; top: -46px; width: 120px; height: 120px; border-radius: 50%;
            background: radial-gradient(circle, rgba(212,175,55,.16) 0%, transparent 68%);
            pointer-events: none;
        }
        .govt-card:hover {
            transform: translateY(-6px);
            box-shadow: 0 18px 38px -12px rgba(15,23,42,.24), 0 0 0 1px rgba(212,175,55,.35);
        }

        /* The icon tile itself — glass disc, gold ring, moving sheen */
        .govt-icon {
            position: relative;
            width: 92px; height: 92px; margin: 10px auto 14px;
            border-radius: 26px;
            background: linear-gradient(150deg,#ffffff 0%,#eef3ff 100%);
            box-shadow: inset 0 1px 0 rgba(255,255,255,.9),
                        0 8px 20px -8px rgba(30,58,138,.30),
                        0 0 0 1px rgba(226,232,240,.9);
            overflow: hidden;
            transition: transform .35s cubic-bezier(.34,1.4,.64,1), box-shadow .35s;
        }
        .govt-icon img { width: 76%; height: 76%; object-fit: contain; position: relative; z-index: 3;
                         filter: drop-shadow(0 3px 6px rgba(15,23,42,.18)); }
        .govt-icon i { position: relative; z-index: 3; font-size: 2.3rem;
                       background: linear-gradient(140deg,#1d4ed8,#7c3aed 55%,#c026d3);
                       -webkit-background-clip: text; background-clip: text;
                       -webkit-text-fill-color: transparent; }

        /* rotating gold ring */
        .govt-ring {
            position: absolute; inset: 4px; border-radius: 22px; z-index: 1;
            background: conic-gradient(from 0deg, rgba(212,175,55,0) 0deg, rgba(212,175,55,.75) 90deg, rgba(212,175,55,0) 200deg, rgba(59,130,246,.55) 300deg, rgba(212,175,55,0) 360deg);
            opacity: 0; transition: opacity .35s;
            -webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2.5px));
                    mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 calc(100% - 2.5px));
        }
        .govt-card:hover .govt-ring { opacity: 1; animation: govtSpin 3.2s linear infinite; }
        @keyframes govtSpin { to { transform: rotate(360deg); } }

        /* diagonal light sweep */
        .govt-shine {
            position: absolute; top: 0; left: -120%; width: 60%; height: 100%; z-index: 2;
            background: linear-gradient(100deg, transparent, rgba(255,255,255,.85), transparent);
            transform: skewX(-18deg); pointer-events: none;
        }
        .govt-card:hover .govt-shine { animation: govtSweep .85s ease-out; }
        @keyframes govtSweep { to { left: 130%; } }

        .govt-card:hover .govt-icon {
            transform: translateY(-3px) scale(1.05);
            box-shadow: inset 0 1px 0 rgba(255,255,255,.9),
                        0 14px 28px -10px rgba(30,58,138,.42),
                        0 0 0 1px rgba(212,175,55,.55);
        }

        .govt-badge {
            display: inline-flex; align-items: center; gap: 4px;
            font-size: .55rem; font-weight: 800; letter-spacing: .07em; text-transform: uppercase;
            padding: 3px 9px; border-radius: 999px; margin-bottom: 6px;
            color: #1e3a8a; background: linear-gradient(90deg,#eef4ff,#e0e9ff);
            border: 1px solid #c7d7fe;
        }
        .govt-card .p-title { font-size: .78rem; letter-spacing: .01em; color: #0f172a; }
        .govt-card .action-btn { border-radius: 10px; font-weight: 700; }
        .govt-card .btn-web {
            background: linear-gradient(135deg,#1d4ed8,#4f46e5) !important; color: #fff !important;
            box-shadow: 0 6px 14px -5px rgba(29,78,216,.65);
        }
        .govt-card .tutorial-btn { background:#fff; border:1px solid #e2e8f0; }
        .govt-card .buy-btn { border-radius: 10px; box-shadow: 0 6px 14px -6px rgba(15,23,42,.4); }

        @media (prefers-reduced-motion: reduce) {
            .govt-card:hover .govt-ring, .govt-card:hover .govt-shine { animation: none; }
        }
        
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); display: none; justify-content: center; align-items: center; z-index: 2000; backdrop-filter: blur(4px); }
        .modal-card { background: white; width: 90%; max-width: 400px; padding: 24px; border-radius: 16px; position: relative; animation: popIn 0.3s ease-out; }
        @keyframes popIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .close-modal { position: absolute; top: 12px; right: 15px; background: none; border: none; font-size: 1.2rem; color: #9ca3af; cursor: pointer; }

        /* =====================================================================
           UNIFORM CARD SIZE — must win over every rule above.
           Cards keep the SAME height in every condition (free / purchased /
           pending / long titles / long descriptions), because the row itself
           stretches and the buttons are pinned to the bottom.
           ===================================================================== */
        .product-grid {
            grid-template-columns: repeat(auto-fill, minmax(158px, 1fr)) !important;
            align-items: stretch !important;
            justify-items: stretch !important;
            grid-auto-rows: 1fr !important;
        }
        @media (min-width: 640px) { .product-grid { grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)) !important; gap: 16px !important; } }

        .product-card,
        .product-card.free-card,
        .product-card.govt-card,
        .product-card.purchased-card,
        .product-card.pending-card {
            height: 100% !important;
            min-height: 320px !important;
            display: flex !important;
            flex-direction: column !important;
            justify-content: space-between !important;
        }
        @media (min-width: 640px) { .product-card { min-height: 348px !important; } }

        /* The top block grows, the action block always sits at the bottom */
        .product-card > div:first-child { flex: 1 1 auto; min-height: 0; width: 100%; }
        .product-card .card-buttons,
        .product-card .final-btn-group,
        .product-card .pending-btn-group,
        .product-card .price-tag { width: 100%; }

        /* Icon + title always occupy the same vertical space */
        .product-card .image-area { flex: 0 0 auto; }
        .product-card .p-title { min-height: 34px !important; }
        .product-card .clamp-2 { min-height: 30px; }
    </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [1=>[],5=>[]]; foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => $page_title,
    'active' => 'services',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : 'assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => '',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">

                <?php if($CAT_OPEN): ?>
                <div class="bg-[url('https://images.unsplash.com/photo-1517048676732-d65bc937f952?q=80&w=1200&auto=format&fit=crop')] bg-cover bg-center rounded-2xl mb-8 overflow-hidden relative shadow-lg">
                    <div class="absolute inset-0 bg-slate-900/80"></div>
                    <div class="relative z-10 p-8 md:p-12 text-center text-white">
                        <span class="text-xs md:text-sm font-bold uppercase tracking-widest text-indigo-400 mb-2 block">
                            <?php echo esc($category[0]['title'] ?? 'Services'); ?>
                        </span>
                        <h1 class="text-2xl md:text-4xl font-extrabold uppercase"><?php echo $sub_id > 0 ? esc($current_sub_cat['title']) : 'Dashboard'; ?></h1>
                        <p class="mt-3 text-sm text-slate-300 max-w-2xl mx-auto">
                            <?php
                                $__cd = trim((string)($category[0]['description'] ?? ''));
                                if ($__cd === '') {
                                    $__cd = $cat_id == 1
                                        ? 'Access important government documents, schemes, jobs, and scholarship portals easily.'
                                        : 'Pick a section above, then choose the service you want to work on.';
                                }
                                echo esc($__cd);
                            ?>
                        </p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="max-w-3xl mx-auto mb-8 flex flex-col sm:flex-row items-stretch gap-3">
                    <div class="relative flex-1">
                        <i class="fa-solid fa-magnifying-glass absolute left-5 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        <input type="text" id="searchInput" class="w-full py-4 pl-12 pr-4 border border-gray-200 rounded-full focus:ring-2 focus:ring-indigo-500 outline-none shadow-sm text-sm font-medium" placeholder="Search..." onkeyup="filterServices()">
                    </div>
                    <!-- Ask for another website / portal to be made live -->
                    <a href="website_request.php?cat=<?php echo (int)$cat_id; ?>&sub=<?php echo (int)$sub_id; ?>"
                       class="inline-flex items-center justify-center gap-2 whitespace-nowrap px-6 py-4 rounded-full bg-slate-900 hover:bg-slate-800 text-white font-bold text-sm shadow-md transition-colors">
                        <i class="fas fa-plus"></i> Request a Website
                    </a>
                </div>

                <?php if($CAT_OPEN): ?>
                    
                    <!-- ===== SUB-CATEGORY TABS ===== -->
                    <?php if(!empty($agency_sub_cats)): ?>
                    <div class="subtabs-wrap mb-6">
                        <div class="subtabs hide-scrollbar" id="subTabs">
                            <?php foreach($agency_sub_cats as $cat):
                                $on = ((int)$cat['id'] === (int)$sub_id);
                            ?>
                            <a href="category.php?id=<?php echo $cat_id; ?>&sub_id=<?php echo $cat['id']; ?>"
                               class="subtab <?php echo $on ? 'is-on' : ''; ?>">
                                <span class="subtab-ico bg-gradient-to-br <?php echo htmlspecialchars($cat['gradient_class'] ?: 'from-slate-400 to-slate-500'); ?>">
                                    <i class="fas <?php echo htmlspecialchars($cat['icon_class'] ?: 'fa-folder'); ?>"></i>
                                </span>
                                <span class="subtab-txt"><?php echo esc($cat['title']); ?></span>
                            </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if(true): ?>
                        <div class="product-grid pb-24" id="serviceGrid">
                            <?php if(!empty($services_list)): ?>
                                <?php $docs = []; ?>
                                <?php foreach($services_list as $sub):
                                    
                                    // Determine if the service is effectively "Free"
                                    $is_free = ($sub['price'] <= 0 && $sub['discount_price'] <= 0);
                                    
                                    // Determine Purchase State
                                    $order_status = isset($purchased_services[$sub['title']]) ? $purchased_services[$sub['title']] : null;
                                    
                                    $card_state = '';
                                    if ($is_free) {
                                        $card_state = 'free-card';
                                    } else {
                                        if ($order_status === 'Completed') $card_state = 'purchased-card';
                                        elseif ($order_status === 'Pending' || $order_status === 'Processing') $card_state = 'pending-card';
                                    }
                                    
                                    $seller_call = !empty($sub['call_number']) ? $sub['call_number'] : '';
                                    $seller_wa = !empty($sub['whatsapp_number']) ? $sub['whatsapp_number'] : '';

                                    // Action links (App Download / Visit Website) only unlock for free
                                    // services or after the user has completed the purchase.
                                    $doc_unlocked = ($is_free || $order_status === 'Completed');

                                    $docs[$sub['id']] = [
                                        'title'    => $sub['title'],
                                        'unlocked' => $doc_unlocked ? 1 : 0,
                                        'pending'  => ($order_status === 'Pending' || $order_status === 'Processing') ? 1 : 0,
                                        'seller'   => ($cat_id == 1) ? '' : ($sub['seller_name'] ?? ''),
                                        'desc'     => nl2br(esc($sub['description'])),
                                        'is_img'   => (int)$sub['is_img'],
                                        'img'      => ($sub['is_img'] == 1) ? $sub['icon_class'] : '',
                                        'icon'     => ($sub['is_img'] == 1) ? '' : 'fa-solid ' . $sub['icon_class'],
                                        'web'      => $sub['web_url'] ?? '',
                                        'app'      => $sub['app_url'] ?? '',
                                        'tutorial' => $sub['tutorial_url'] ?? '',
                                    ];
                                ?>
                                <div class="product-card <?php echo htmlspecialchars($sub['color_class']); ?> service-item <?php echo $card_state; ?><?php echo $cat_id == 1 ? ' govt-card' : ''; ?>">
                                    <div>
                                        <div class="image-area<?php echo $cat_id == 1 ? ' govt-icon' : ''; ?>">
                                            <?php if($cat_id == 1): ?><span class="govt-ring"></span><span class="govt-shine"></span><?php endif; ?>
                                            <?php if($sub['is_img'] == 1): ?><img src="<?php echo htmlspecialchars($sub['icon_class']); ?>" alt="logo">
                                            <?php else: ?><i class="fa-solid <?php echo htmlspecialchars($sub['icon_class']); ?>"></i><?php endif; ?>
                                        </div>
                                        <?php if($cat_id == 1): ?>
                                            <div class="govt-badge"><i class="fas fa-shield-halved"></i> Govt. Portal</div>
                                        <?php endif; ?>
                                        <?php if($cat_id != 1): ?><div class="seller-badge"><i class="fas fa-store text-[8px]"></i> <?php echo htmlspecialchars($sub['seller_name']); ?></div><?php endif; ?>
                                        <div class="p-title mb-1"><?php echo esc($sub['title']); ?></div>
                                        
                                        <div class="success-badge"><i class="fa-solid fa-circle-check"></i> পারচেজ সম্পন্ন!</div>
                                        
                                        <div class="pending-badge"><i class="fa-solid fa-clock"></i> Pending Approval</div>
                                        <div class="processing-area">
                                            <div class="spinner"></div>
                                            <div class="text-xs font-bold text-yellow-700 mt-1">অপেক্ষা করুন...</div>
                                        </div>

                                        <div class="text-left w-full mt-2 mb-1">
                                            <div class="clamp-2 text-[0.65rem] text-gray-500 leading-snug break-words">
                                                <?php echo nl2br(esc($sub['description'])); ?>
                                            </div>
                                            <?php if(strlen($sub['description']) > 70): ?>
                                                <button type="button" @click="$dispatch('open-doc', <?php echo $sub['id']; ?>)" class="text-indigo-500 font-bold text-[10px] mt-1 hover:text-indigo-700 outline-none inline-flex items-center gap-1">Read More <i class="fas fa-arrow-up-right-from-square text-[8px]"></i></button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <?php
                                        // Subscriber price (server is the source of truth at checkout too)
                                        $pinfo    = shares_price_for_user($db, $sub, $user_id, $is_subscriber);
                                        $pay_now  = $pinfo['final'];
                                        $has_disc = $pinfo['discount'] > 0;
                                        $sub_pct  = (float)($sub['subscription_discount_pct'] ?? 0);

                                        /* How this one sells. A visit product cannot be finished in
                                           the quick modal — it needs the booking screen, so the button
                                           goes to the product page instead. */
                                        $__q   = buy_quote($db, $sub, $user_id, $is_subscriber);
                                        $__vis = ($__q['fulfilment'] === 'visit');

                                        // Customer Data Recruitment gates
                                        $g          = product_purchase_gate($db, $sub, $user_id);
                                        $gate_ok    = $g['ok'];
                                        /* KYC is no longer a wall: only the service area is. Anything the
                                           product still needs is asked for on the checkout page. */
                                        $area_ok    = !empty($g['area']['ok']);
                                        $gate_pl    = product_gate_payload($db, $sub, $user_id, $g);
                                        $gate_json  = htmlspecialchars(json_encode($gate_pl), ENT_QUOTES);
                                    ?>
                                    <div class="mt-1">
                                        <div class="price-tag">
                                            <span class="original-price">₹<?php echo htmlspecialchars($sub['price']); ?></span>
                                            <span class="discount-price">₹<?php echo number_format($pay_now, 2); ?></span>
                                        </div>
                                        <?php if($has_disc): ?>
                                            <div class="text-[9px] font-bold text-emerald-600 mb-1"><i class="fas fa-crown"></i> Subscriber −<?php echo rtrim(rtrim(number_format($sub_pct,2),'0'),'.'); ?>% (saved ₹<?php echo number_format($pinfo['discount'],2); ?>)</div>
                                        <?php elseif(!$is_subscriber && $sub_pct > 0): ?>
                                            <div class="text-[9px] font-bold text-amber-600 mb-1"><i class="fas fa-lock"></i> Subscribe &amp; save <?php echo rtrim(rtrim(number_format($sub_pct,2),'0'),'.'); ?>%</div>
                                        <?php endif; ?>

                                        <?php if($__vis): ?>
                                            <div class="text-[9px] font-bold text-amber-700 mb-1">
                                                <i class="fas fa-person-walking"></i> ₹<?php echo number_format($__q['advance'], 0); ?> to book · ₹<?php echo number_format($__q['due'], 0); ?> at the visit
                                            </div>
                                        <?php endif; ?>

                                        <div class="card-buttons">
                                            <?php if(!$area_ok): ?>
                                                <button type="button" class="action-btn buy-btn gate-btn gate-area" @click='$dispatch("open-gate", <?php echo $gate_json; ?>)'>
                                                    <i class="fa-solid fa-location-crosshairs"></i>
                                                    Not available in your area
                                                </button>
                                            <?php elseif($__vis): ?>
                                                <a class="action-btn buy-btn" href="product.php?id=<?php echo (int)$sub['id']; ?>">
                                                    <i class="fa-solid fa-person-walking"></i> Book Now
                                                </a>
                                            <?php elseif($gate_ok): ?>
                                                <button class="action-btn buy-btn" onclick="openCheckoutModal(<?php echo $sub['id']; ?>, <?php echo $sub['seller_id']; ?>, '<?php echo addslashes($sub['title']); ?>', <?php echo $pay_now; ?>)">
                                                    <i class="fa-solid fa-cart-shopping"></i> Buy Now
                                                </button>
                                            <?php else: ?>
                                                <?php /* Details are still missing — the checkout page collects them. */ ?>
                                                <a class="action-btn buy-btn" href="checkout.php?id=<?php echo (int)$sub['id']; ?>">
                                                    <i class="fa-solid fa-cart-shopping"></i> Buy Now
                                                </a>
                                            <?php endif; ?>
                                            <?php if($area_ok): ?>
                                                <a class="action-btn tutorial-btn" href="product.php?id=<?php echo (int)$sub['id']; ?>">
                                                    <i class="fa-solid fa-circle-info"></i> Details
                                                </a>
                                            <?php endif; ?>
                                        </div>

                                        <div class="final-btn-group">
                                            <?php if(!empty($sub['web_url'])): ?>
                                                <a href="<?php echo htmlspecialchars($sub['web_url']); ?>" target="_blank" class="action-btn btn-web"><i class="fa-solid fa-globe"></i> Visit Website</a>
                                            <?php endif; ?>
                                            <?php /* Government Portals: card shows only "Visit Website" — App Download lives in the popup */ ?>
                                            <?php if(!empty($sub['app_url']) && $cat_id != 1): ?>
                                                <a href="<?php echo htmlspecialchars($sub['app_url']); ?>" target="_blank" class="action-btn btn-app"><i class="fa-solid fa-download"></i> App Download</a>
                                            <?php endif; ?>
                                            <?php if(!empty($sub['tutorial_url'])): ?>
                                                <a href="<?php echo htmlspecialchars($sub['tutorial_url']); ?>" target="_blank" class="action-btn tutorial-btn mt-1"><i class="fa-brands fa-youtube text-rose-500"></i> Tutorial</a>
                                            <?php endif; ?>
                                        </div>

                                        <div class="pending-btn-group">
                                            <?php if(!empty($seller_call)): ?>
                                                <a href="tel:<?php echo htmlspecialchars($seller_call); ?>" class="action-btn btn-call"><i class="fa-solid fa-phone"></i> কল করুন</a>
                                            <?php endif; ?>
                                            <?php if(!empty($seller_wa)): ?>
                                                <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $seller_wa); ?>" target="_blank" class="action-btn btn-wa"><i class="fa-brands fa-whatsapp"></i> হোয়াটসঅ্যাপ করুন</a>
                                            <?php endif; ?>
                                            <?php if(empty($seller_call) && empty($seller_wa)): ?>
                                                <span class="text-[10px] text-gray-500 italic block mt-2">The seller is processing your order.</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="col-span-full p-8 text-center text-gray-500 bg-white rounded-xl shadow-sm border border-gray-200 w-full">No Services Found in this category.</div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>

                <?php endif; ?>

            </main>
        </div>
    </div>

    <!-- ===== DOCUMENT DETAILS POPUP ===== -->
    <div x-data="docViewer()" @open-doc.window="show($event.detail)" @keydown.escape.window="close()">
        <div x-show="open" x-cloak x-transition.opacity class="fixed inset-0 z-[200] flex items-end sm:items-center justify-center sm:p-4">
            <div class="absolute inset-0 bg-slate-900/70 backdrop-blur-md" @click="close()"></div>
            <div x-show="open" x-transition.scale.origin.bottom
                 class="doc-modal relative w-full sm:max-w-lg bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl overflow-hidden flex flex-col">

                <!-- Hero: video (if video/tutorial URL) else image / icon -->
                <div class="relative flex-shrink-0">
                    <template x-if="videoSrc()">
                        <div class="aspect-video bg-black">
                            <iframe :src="videoSrc()" class="w-full h-full" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                        </div>
                    </template>
                    <template x-if="!videoSrc()">
                        <div class="doc-hero h-52 sm:h-64 bg-gradient-to-br from-indigo-500 via-purple-500 to-fuchsia-500 flex items-center justify-center relative overflow-hidden">
                            <div class="absolute -right-8 -top-8 w-32 h-32 bg-white/15 rounded-full blur-2xl"></div>
                            <template x-if="cur.is_img == 1 && cur.img">
                                <div class="doc-hero-img w-44 h-44 sm:w-48 sm:h-48 rounded-3xl bg-white flex items-center justify-center shadow-2xl p-5"><img :src="cur.img" class="max-h-full max-w-full object-contain"></div>
                            </template>
                            <template x-if="!(cur.is_img == 1 && cur.img)">
                                <i class="text-white text-7xl drop-shadow-lg" :class="cur.icon"></i>
                            </template>
                        </div>
                    </template>
                    <button @click="close()" class="absolute top-3 right-3 w-9 h-9 rounded-full bg-black/40 hover:bg-black/60 text-white flex items-center justify-center transition-colors"><i class="fas fa-times"></i></button>
                </div>

                <!-- Title + seller -->
                <div class="px-5 pt-4 pb-2 flex-shrink-0">
                    <h3 class="text-xl font-extrabold text-slate-800 leading-tight font-poppins" x-text="cur.title"></h3>
                    <p class="text-xs text-slate-400 mt-1" x-show="cur.seller"><i class="fas fa-store mr-1"></i><span x-text="cur.seller"></span></p>
                </div>

                <!-- Scrollable description (min-h-0 lets it shrink so the buttons stay visible) -->
                <div class="px-5 py-2 overflow-y-auto doc-scroll text-sm text-slate-600 leading-relaxed flex-1 min-h-0" x-html="cur.desc"></div>

                <!-- Footer: action links after purchase, otherwise a clear status note -->
                <div class="p-4 flex-shrink-0 border-t border-slate-100 bg-gradient-to-b from-white to-slate-50 space-y-2.5" style="padding-bottom: calc(1rem + env(safe-area-inset-bottom));">
                    <template x-if="cur.unlocked == 1">
                        <div class="space-y-2.5">
                            <a x-show="cur.app" :href="cur.app" target="_blank" class="glass-btn glass-app"><i class="fa-solid fa-download"></i> App Download</a>
                            <a x-show="cur.web" :href="cur.web" target="_blank" class="glass-btn glass-web"><i class="fa-solid fa-globe"></i> Visit Website</a>
                        </div>
                    </template>
                    <template x-if="cur.unlocked != 1 && cur.pending == 1">
                        <div class="flex items-center justify-center gap-2 py-2.5 px-4 rounded-xl bg-amber-50 border border-amber-200 text-amber-700 text-sm font-semibold text-center">
                            <i class="fas fa-clock"></i> Pending approval — links will unlock once approved.
                        </div>
                    </template>
                    <template x-if="cur.unlocked != 1 && cur.pending != 1">
                        <div class="flex items-center justify-center gap-2 py-2.5 px-4 rounded-xl bg-slate-100 border border-slate-200 text-slate-500 text-sm font-semibold text-center">
                            <i class="fas fa-lock"></i> Purchase this service to unlock the links.
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
    <script>
    function docViewer() {
        return {
            open: false,
            cur: {},
            docs: <?php echo json_encode($docs ?? [], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            show(id) { this.cur = this.docs[id] || {}; this.open = true; document.body.style.overflow = 'hidden'; },
            close() { this.open = false; document.body.style.overflow = ''; },
            ytEmbed(url) {
                if (!url) return '';
                var m = String(url).match(/(?:youtu\.be\/|[?&]v=|\/embed\/|\/shorts\/)([\w-]{11})/);
                return m ? 'https://www.youtube.com/embed/' + m[1] : '';
            },
            // The service's video URL (stored in tutorial_url) — embedded at the top when it's a YouTube link
            videoSrc() { return this.ytEmbed(this.cur.tutorial); }
        }
    }
    </script>

    <!-- ===== PURCHASE GATE POPUP (KYC / Available Area) ===== -->
    <div x-data="gateViewer()" @open-gate.window="show($event.detail)" @keydown.escape.window="close()">
        <div x-show="open" x-cloak x-transition.opacity class="fixed inset-0 z-[300] flex items-end sm:items-center justify-center sm:p-4">
            <div class="absolute inset-0 bg-slate-900/70 backdrop-blur-md" @click="close()"></div>

            <div x-show="open" x-transition
                 class="relative w-full sm:max-w-md bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">

                <!-- header -->
                <div class="px-5 py-4 flex items-start gap-3 text-white"
                     :class="g.block==='area' ? 'bg-gradient-to-r from-rose-500 to-red-600' : 'bg-gradient-to-r from-amber-500 to-orange-600'">
                    <div class="w-11 h-11 rounded-2xl bg-white/20 flex items-center justify-center text-xl flex-shrink-0">
                        <i class="fa-solid" :class="g.block==='area' ? 'fa-location-crosshairs' : 'fa-id-card'"></i>
                    </div>
                    <div class="min-w-0 flex-1">
                        <h3 class="font-bold text-base leading-tight" x-text="g.block==='area' ? 'Not Available in Your Area' : 'KYC Verification Required'"></h3>
                        <p class="text-[11px] text-white/80 truncate mt-0.5" x-text="g.title"></p>
                    </div>
                    <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
                </div>

                <div class="p-5 overflow-y-auto space-y-4 text-left">

                    <!-- ---------- AREA BLOCK ---------- -->
                    <template x-if="g.block==='area'">
                        <div class="space-y-3">
                            <div class="bg-rose-50 border border-rose-200 rounded-2xl p-4">
                                <p class="text-sm text-rose-800 font-semibold leading-relaxed" x-text="msg"></p>
                            </div>
                            <div class="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-xl px-4 py-3">
                                <span class="text-xs font-semibold text-slate-500">Your registered pincode</span>
                                <span class="text-sm font-extrabold text-slate-800" x-text="g.pincode || '— not set —'"></span>
                            </div>
                            <p class="text-[11px] text-slate-500 leading-relaxed">
                                এই সার্ভিসটি শুধুমাত্র নির্দিষ্ট কিছু পিনকোডে (<span class="font-bold" x-text="g.area_count"></span> টি) উপলব্ধ।
                                আপনার রেজিস্ট্রেশন পিনকোড সেই তালিকায় নেই, তাই আপনি এটি কিনতে পারবেন না।
                            </p>
                            <a :href="g.pincode ? 'services.php' : 'profile.php#edit'"
                               class="flex items-center justify-center gap-2 w-full py-3 rounded-2xl font-bold text-sm text-white bg-gradient-to-r from-rose-500 to-red-600 shadow-lg shadow-rose-500/30">
                                <i class="fa-solid" :class="g.pincode ? 'fa-grid-2' : 'fa-user-pen'"></i>
                                <span x-text="g.pincode ? 'Browse other services' : 'Update my pincode'"></span>
                            </a>
                        </div>
                    </template>

                    <!-- ---------- KYC BLOCK ---------- -->
                    <template x-if="g.block==='kyc'">
                        <div class="space-y-3">
                            <div class="border rounded-2xl p-4"
                                 :class="g.reason==='rejected' ? 'bg-rose-50 border-rose-200' : (g.reason==='awaiting' ? 'bg-blue-50 border-blue-200' : 'bg-amber-50 border-amber-200')">
                                <p class="text-sm font-semibold leading-relaxed"
                                   :class="g.reason==='rejected' ? 'text-rose-800' : (g.reason==='awaiting' ? 'text-blue-800' : 'text-amber-900')"
                                   x-text="msg"></p>
                                <p x-show="g.remark" class="text-[11px] mt-2 pt-2 border-t border-current/10 opacity-80">
                                    <i class="fa-solid fa-comment-dots mr-1"></i><span x-text="g.remark"></span>
                                </p>
                            </div>

                            <!-- exactly what is still blank, grouped by section -->
                            <div x-show="(g.groups||[]).length">
                                <p class="text-[10px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                                    Still needed for this service
                                    <span class="text-rose-500">(<span x-text="(g.missing||[]).length"></span>)</span>
                                </p>
                                <div class="space-y-2">
                                    <template x-for="grp in (g.groups||[])" :key="grp.group">
                                        <div class="rounded-xl border border-rose-200 bg-rose-50 px-3 py-2.5">
                                            <p class="text-[11px] font-black uppercase tracking-wide text-rose-700 mb-1.5" x-text="grp.group"></p>
                                            <div class="flex flex-wrap gap-1.5">
                                                <template x-for="it in grp.items" :key="it">
                                                    <span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg bg-white border border-rose-200 text-[11px] font-bold text-rose-700">
                                                        <i class="fa-solid fa-circle-xmark text-[9px]"></i><span x-text="it"></span>
                                                    </span>
                                                </template>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                                <p class="text-[10.5px] text-emerald-600 font-semibold mt-2" x-show="(g.filled||[]).length">
                                    <i class="fa-solid fa-circle-check mr-1"></i>
                                    <span x-text="(g.filled||[]).length"></span> item(s) you already filled are not asked for again.
                                </p>
                            </div>

                            <!-- approval status strip -->
                            <div class="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-xl px-4 py-3">
                                <span class="text-xs font-semibold text-slate-500">KYC approval status</span>
                                <span class="text-[11px] font-extrabold px-2.5 py-1 rounded-full"
                                      :class="{
                                        'bg-emerald-100 text-emerald-700': g.kyc_stat==='approved',
                                        'bg-blue-100 text-blue-700': g.kyc_stat==='pending',
                                        'bg-rose-100 text-rose-700': g.kyc_stat==='rejected',
                                        'bg-slate-200 text-slate-600': g.kyc_stat==='not_submitted'
                                      }" x-text="statusLabel()"></span>
                            </div>

                            <p class="text-[11px] text-slate-500 leading-relaxed">
                                উপরের KYC গুলি পূরণ করে সাবমিট করুন। অ্যাডমিন অ্যাপ্রুভ করার পরেই আপনি এই সার্ভিসটি কিনতে পারবেন।
                            </p>

                            <a href="profile.php#kyc"
                               class="flex items-center justify-center gap-2 w-full py-3 rounded-2xl font-bold text-sm text-white bg-gradient-to-r from-amber-500 to-orange-600 shadow-lg shadow-amber-500/30">
                                <i class="fa-solid fa-id-card"></i>
                                <span x-text="g.reason==='awaiting' ? 'View my KYC' : 'Complete KYC now'"></span>
                            </a>

                            <!-- some of the missing boxes are the admin's own questions -->
                            <a x-show="needsExtra()" href="kyc_extra.php" style="display:none"
                               class="flex items-center justify-center gap-2 w-full py-3 rounded-2xl font-bold text-sm text-white bg-gradient-to-r from-violet-500 to-indigo-600 shadow-lg shadow-violet-500/30">
                                <i class="fa-solid fa-list-check"></i> Fill the extra information
                            </a>
                        </div>
                    </template>

                    <button @click="close()" class="w-full py-2.5 rounded-2xl font-bold text-sm text-slate-500 bg-slate-100 hover:bg-slate-200 transition-colors">Close</button>
                </div>
            </div>
        </div>
    </div>
    <script>
    function gateViewer() {
        return {
            open: false,
            g: { block: '', required: [], missing: [], filled: [], groups: [], need_keys: [] },
            msg: '',
            show(d) {
                this.g = Object.assign({ block: '', required: [], missing: [], filled: [], groups: [], need_keys: [] }, d || {});
                this.msg = this.buildMsg();
                this.open = true;
                document.body.style.overflow = 'hidden';
            },
            close() { this.open = false; document.body.style.overflow = ''; },
            statusLabel() {
                return { approved: 'Approved', pending: 'Awaiting approval', rejected: 'Rejected', not_submitted: 'Not submitted' }[this.g.kyc_stat] || 'Not submitted';
            },
            /* true when one of the blank boxes is a question the admin wrote */
            needsExtra() {
                return (this.g.need_keys || []).some(function (k) { return String(k).indexOf('custom.') === 0; });
            },
            buildMsg() {
                var g = this.g;
                if (g.block === 'area') {
                    return g.pincode
                        ? 'This service is not available in your area (pincode ' + g.pincode + ').'
                        : 'Your account has no pincode set, so we cannot confirm your service area. Please update your profile.';
                }
                if (g.reason === 'incomplete') {
                    var m = g.missing || [];
                    var head = m.length === 1
                        ? 'One more detail is needed: '
                        : m.length + ' details are still needed: ';
                    return head + m.slice(0, 6).join(', ') + (m.length > 6 ? ' and ' + (m.length - 6) + ' more' : '')
                         + '. Purchase unlocks once they are filled and the admin approves.';
                }
                if (g.reason === 'rejected') {
                    return 'Your KYC was rejected. Please correct the details and resubmit before purchasing.';
                }
                if (g.reason === 'awaiting') {
                    return 'Your KYC is submitted but not approved yet. You can purchase as soon as it is approved.';
                }
                return 'You are not eligible to purchase this service yet.';
            }
        }
    }
    </script>

    <?php
    /* The popup belongs to any open category, not only one that happens to have
       sub-categories. It used to be tied to $sub_id, so on a category with no
       sub-categories the markup and its script were never printed and Buy Now
       did nothing at all. */
    ?>
    <?php if($CAT_OPEN): ?>
        <div id="checkoutModal" class="modal-overlay">
            <div class="modal-card">
                <button class="close-modal" onclick="document.getElementById('checkoutModal').style.display='none'"><i class="fa-solid fa-xmark"></i></button>
                <h3 class="text-lg font-bold text-gray-800 border-b pb-2 mb-4">Complete Purchase</h3>

                <div class="bg-slate-50 p-4 rounded-lg mb-4 text-left">
                    <p class="text-xs text-gray-500 mb-1">Service Name</p>
                    <p class="font-bold text-sm text-gray-800 font-poppins" id="checkout_title"></p>
                    <div class="flex justify-between mt-3 pt-3 border-t">
                        <p class="font-bold text-gray-600 text-sm">Service price</p>
                        <p class="font-extrabold text-slate-800 text-lg">&#8377;<span id="checkout_amount_display"></span></p>
                    </div>
                </div>

                <form id="checkoutForm" method="POST">
                    <input type="hidden" name="service_id" id="checkout_service_id">
                    <input type="hidden" name="amount" id="checkout_amount">
                    <input type="hidden" name="payment_id" id="checkout_payment_id">
                    <input type="hidden" name="use_wallet" id="checkout_use_wallet" value="1">

                    <!-- Wallet first, gateway for the rest. No all-or-nothing choice
                         any more: the two work together on the same purchase. -->
                    <div class="border rounded-xl p-3 mb-3 text-left" id="wallet_box">
                        <label class="flex items-start cursor-pointer">
                            <input type="checkbox" id="wallet_toggle" checked onchange="recalcPay()" class="w-4 h-4 mt-0.5 text-indigo-600 rounded focus:ring-indigo-500">
                            <div class="ml-3 flex-1">
                                <p class="font-bold text-sm"><i class="fas fa-wallet text-indigo-500 mr-1"></i> Use my wallet first</p>
                                <div class="mt-1.5 space-y-1">
                                    <div class="flex items-center justify-between text-[11px]">
                                        <span class="text-amber-600 font-semibold"><i class="fas fa-gift mr-1"></i>Virtual Wallet</span>
                                        <span class="font-bold text-amber-700">&#8377;<?php echo number_format($wal['virtual'], 2); ?></span>
                                    </div>
                                    <div class="flex items-center justify-between text-[11px]">
                                        <span class="text-slate-500 font-semibold"><i class="fas fa-wallet mr-1"></i>Main Wallet</span>
                                        <span class="font-bold text-slate-700">&#8377;<?php echo number_format($wal['main'], 2); ?></span>
                                    </div>
                                    <div class="flex items-center justify-between text-[11px] pt-1 border-t border-gray-200">
                                        <span class="text-slate-600 font-bold">Total available</span>
                                        <span class="font-extrabold text-emerald-600">&#8377;<?php echo number_format($wal['total'], 2); ?></span>
                                    </div>
                                </div>
                                <p class="text-[10px] text-slate-400 mt-1.5 leading-snug">Virtual wallet is spent first, then the main wallet.</p>
                            </div>
                        </label>
                    </div>

                    <!-- what is actually taken, and from where -->
                    <div class="bg-white border rounded-xl p-3 mb-4 text-left space-y-1.5">
                        <div class="flex items-center justify-between text-[12.5px]" id="row_wallet">
                            <span class="text-slate-500 font-semibold">From wallet</span>
                            <span class="font-bold text-emerald-600">&minus; &#8377;<span id="pay_wallet">0.00</span></span>
                        </div>
                        <div class="flex items-center justify-between pt-1.5 border-t">
                            <span class="text-slate-800 font-bold text-sm" id="pay_label">Pay online now</span>
                            <span class="font-extrabold text-indigo-600 text-xl">&#8377;<span id="pay_gateway">0.00</span></span>
                        </div>
                        <p class="text-[11px] text-emerald-700 font-semibold hidden" id="covered_note">
                            <i class="fas fa-circle-check"></i> Your wallet covers this fully &mdash; no card needed.
                        </p>
                        <p class="text-[11px] text-slate-400 hidden" id="gateway_note">
                            <i class="fas fa-credit-card"></i> UPI, cards or netbanking, through Razorpay.
                        </p>
                    </div>

                    <button type="button" onclick="processPayment()" id="pay_btn" class="w-full bg-indigo-600 hover:bg-indigo-700 transition-colors text-white font-bold py-3 rounded-lg">
                        <i class="fas fa-lock mr-2"></i> Pay Securely
                    </button>
                    <input type="hidden" name="process_payment" value="1">
                </form>
            </div>
        </div>

        <script>
        // Spendable = virtual + main (virtual is consumed first on the server)
        /* Spendable = virtual + main. The virtual part is consumed first on the
           server; here we only need the total to work out the split. */
        const userWalletBal = <?php echo (float)$wal['total']; ?>;
        const rzpKey        = "<?php echo $rzp_key; ?>";
        const companyName   = "<?php echo addslashes($company_name); ?>";

        var checkoutTitle = '';

        function money(n) {
            return Number(n || 0).toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        }

        function openCheckoutModal(id, seller_id, title, price) {
            checkoutTitle = title;
            document.getElementById('checkout_service_id').value = id;
            document.getElementById('checkout_amount').value = price;
            document.getElementById('checkout_payment_id').value = '';
            document.getElementById('checkout_title').innerText = title;
            document.getElementById('checkout_amount_display').innerText = money(price);

            document.getElementById('wallet_toggle').checked = true;
            recalcPay();
            document.getElementById('checkoutModal').style.display = 'flex';
        }

        /* Wallet first, gateway for whatever is left. ₹99 against an ₹11 wallet
           means ₹11 off the wallet and ₹88 online — never a refusal. */
        function splitNow() {
            var amount  = parseFloat(document.getElementById('checkout_amount').value) || 0;
            var use     = document.getElementById('wallet_toggle').checked;
            var wallet  = use ? Math.min(userWalletBal, amount) : 0;
            var gateway = Math.max(0, Math.round((amount - wallet) * 100) / 100);
            return { amount: amount, wallet: Math.round(wallet * 100) / 100, gateway: gateway };
        }

        function recalcPay() {
            var s = splitNow();
            document.getElementById('checkout_use_wallet').value = document.getElementById('wallet_toggle').checked ? '1' : '';
            document.getElementById('pay_wallet').innerText  = money(s.wallet);
            document.getElementById('pay_gateway').innerText = money(s.gateway);
            document.getElementById('row_wallet').style.display = s.wallet > 0 ? 'flex' : 'none';

            var covered = (s.gateway <= 0);
            document.getElementById('pay_label').innerText = covered ? 'Nothing left to pay' : 'Pay online now';
            document.getElementById('covered_note').classList.toggle('hidden', !covered);
            document.getElementById('gateway_note').classList.toggle('hidden', covered);
            document.getElementById('pay_btn').innerHTML = covered
                ? '<i class="fas fa-wallet mr-2"></i> Pay &#8377;' + money(s.wallet) + ' from wallet'
                : '<i class="fas fa-lock mr-2"></i> Pay &#8377;' + money(s.gateway) + ' securely';
        }

        function processPayment() {
            var s = splitNow();
            var form = document.getElementById('checkoutForm');

            /* the wallet covers it — no card involved at all */
            if (s.gateway <= 0) { form.submit(); return; }

            if (!rzpKey) { alert('Online payment is not set up yet. Please contact support.'); return; }

            new Razorpay({
                key: rzpKey,
                amount: Math.round(s.gateway * 100),          // only the shortfall
                currency: "INR",
                name: companyName,
                description: "Purchase: " + checkoutTitle,
                handler: function (res) {
                    document.getElementById('checkout_payment_id').value = res.razorpay_payment_id;
                    form.submit();
                }
            }).open();
        }
        </script>
    <?php endif; ?>
    
    <script>
    function filterServices() {
        const searchInput = document.getElementById('searchInput').value.toLowerCase();
        const cards = document.getElementsByClassName('service-item');
        for (let i = 0; i < cards.length; i++) {
            let titleEl = cards[i].querySelector('.card-title') || cards[i].querySelector('.p-title');
            if (titleEl) {
                cards[i].style.display = titleEl.innerText.toLowerCase().includes(searchInput) ? "flex" : "none";
            }
        }
    }
    </script>
</body>
</html>