<?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/wallet.php';
require_once __DIR__ . '/../includes/shares.php';
require_once __DIR__ . '/../includes/purchase.php';

if (!isLoggedIn() || $_SESSION['user_type'] !== 'seller') {
    redirect('../login.php');
}

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

// PRG Flash Messages Setup
$success_msg = '';
$error_msg = '';
if (isset($_SESSION['flash_success'])) {
    $success_msg = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (isset($_SESSION['flash_error'])) {
    $error_msg = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

$rzp_key = getSetting('razorpay_key_id', '');
$rzp_secret = getSetting('razorpay_key_secret', '');

// Handle Secure Razorpay Wallet Recharge from Dashboard Header
if(isset($_POST['payment_id']) && isset($_POST['amount'])) {
    $amount = floatval($_POST['amount']);
    $pay_id = sanitize($_POST['payment_id']);
    
    if($amount > 0 && !empty($pay_id)) {
        
        $url = "https://api.razorpay.com/v1/payments/" . $pay_id;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERPWD, $rzp_key . ":" . $rzp_secret);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $rzp_data = json_decode($response, true);
        
        if (isset($rzp_data['status']) && in_array($rzp_data['status'], ['authorized', 'captured'])) {
            $paid_amount = floatval($rzp_data['amount']) / 100; 
            
            if ($paid_amount >= $amount) {
                wallet_credit($db, $user_id, WALLET_MAIN, $amount, ['category' => 'deposit', 'description' => "B2B Wallet Recharge via Razorpay (Txn: $pay_id)", 'reference_type' => 'transaction']);
                
                $_SESSION['flash_success'] = "Money added to wallet successfully!";
                redirect('index.php');
            }
        }
        
        $_SESSION['flash_error'] = "Payment Verification Failed! If money was deducted, please contact support.";
        redirect('index.php');
    }
}

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

if (!$user) {
    session_destroy();
    redirect('../login.php');
}

$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);

$purchases_data = $db->select("SELECT SUM(amount) as total FROM orders WHERE user_id = ? AND status = 'Completed'", [$user_id]);
$total_purchases = !empty($purchases_data[0]['total']) ? $purchases_data[0]['total'] : 0.00;
$total_orders = count($db->select("SELECT id FROM orders WHERE user_id = ?", [$user_id]));

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';

$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

// Fetch Dynamic Seller Sliders from Database
$dashboard_slides = $db->select("SELECT * FROM seller_slides WHERE status = 1 ORDER BY slide_order ASC");

/* ============================================================================
   TWO DIFFERENT CATEGORY LISTS — this is what was wrong before.

   $customer_categories  → what the seller can BUY as a normal member.
                           NEVER locked: a seller is still a customer.
   $sell_categories      → what the seller is allowed to SELL (B2B).
                           Locked when the admin has not assigned it to them.
   ============================================================================ */
$customer_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

// Categories the admin exposes to sellers at all
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 AND show_to_seller = 1 ORDER BY display_order ASC");

// This seller's assigned selling categories (defaults to 1 & 5)
$seller_cat_ids = !empty($user['seller_categories']) ? array_map('intval', explode(',', $user['seller_categories'])) : [1, 5];

$sidebar_allowed_cats = [];
foreach ($categories as $cat) {
    if (in_array((int)$cat['id'], $seller_cat_ids, true)) { $sidebar_allowed_cats[] = $cat; }
}

/* ---------------------------- SELLER + MEMBER REPORTS ---------------------------- */
require_once __DIR__ . '/../includes/kyc.php';
kyc_ensure_schema($db);

/* my own buying activity (member side) */
$__mo  = $db->select("SELECT COUNT(id) AS c FROM orders WHERE user_id = ?", [$user_id]);
$__mop = $db->select("SELECT COUNT(id) AS c FROM orders WHERE user_id = ? AND status IN ('Pending','Processing')", [$user_id]);
$my_orders  = !empty($__mo[0]['c'])  ? (int)$__mo[0]['c']  : 0;
$my_pending = !empty($__mop[0]['c']) ? (int)$__mop[0]['c'] : 0;

/* my selling activity (seller side) */
$__co  = $db->select("SELECT COUNT(id) AS c FROM orders WHERE seller_id = ?", [$user_id]);
$__cop = $db->select("SELECT COUNT(id) AS c FROM orders WHERE seller_id = ? AND status IN ('Pending','Processing')", [$user_id]);
$__cs  = $db->select("SELECT SUM(amount) AS t FROM orders WHERE seller_id = ? AND status = 'Completed'", [$user_id]);
$cust_orders  = !empty($__co[0]['c'])  ? (int)$__co[0]['c']  : 0;
$cust_pending = !empty($__cop[0]['c']) ? (int)$__cop[0]['c'] : 0;
$total_sales  = !empty($__cs[0]['t'])  ? (float)$__cs[0]['t'] : 0.00;

$my_services = 0;
try {
    $__ms = $db->select("SELECT COUNT(id) AS c FROM seller_services WHERE seller_id = ?", [$user_id]);
    $my_services = !empty($__ms[0]['c']) ? (int)$__ms[0]['c'] : 0;
} catch (\Throwable $e) {}

/* seller earnings from the share ledger */
$seller_earning = 0.00;
try {
    $__se = $db->select("SELECT SUM(amount) AS t FROM product_share_ledger WHERE share_type = 'seller' AND beneficiary_id = ?", [$user_id]);
    $seller_earning = !empty($__se[0]['t']) ? (float)$__se[0]['t'] : 0.00;
} catch (\Throwable $e) {}

/* referrals */
$__rf = $db->select("SELECT COUNT(id) AS c FROM users WHERE referred_by = ?", [$user_id]);
$stat_refs = !empty($__rf[0]['c']) ? (int)$__rf[0]['c'] : 0;

/* subscription + KYC */
$is_sub = !empty($user['is_subscribed']);
$kyc_p  = kyc_progress($db, $user_id, 'seller');
$kyc_map = [
    'approved'      => ['Approved',   'from-emerald-500 to-teal-500', 'bg-emerald-50 text-emerald-700'],
    'pending'       => ['Pending',    'from-amber-400 to-orange-500', 'bg-amber-50 text-amber-700'],
    'rejected'      => ['Rejected',   'from-rose-500 to-pink-500',    'bg-rose-50 text-rose-700'],
    'not_submitted' => ['Not filled', 'from-slate-400 to-slate-500',  'bg-slate-100 text-slate-500'],
];
$kyc_ui = $kyc_map[$kyc_p['status']] ?? $kyc_map['not_submitted'];

/* SELLER-ONLY report row (this is the "extra" block over the member dashboard) */
$seller_tiles = [
    ['Total Sales',     '₹' . number_format($total_sales, 0),   'completed',                                     'fa-indian-rupee-sign', 'from-emerald-500 to-teal-600',  'bg-emerald-50 text-emerald-600', 'reports.php'],
    ['Customer Orders', number_format($cust_orders),            $cust_pending . ' pending',                      'fa-users',             'from-indigo-500 to-blue-600',   'bg-indigo-50 text-indigo-600',   'orders.php'],
    ['My Services',     number_format($my_services),            'listed',                                        'fa-screwdriver-wrench','from-purple-500 to-fuchsia-500','bg-purple-50 text-purple-600',   'services.php'],
    ['Seller Earning',  '₹' . number_format($seller_earning, 0),'share credited',                                'fa-sack-dollar',       'from-amber-400 to-yellow-600',  'bg-amber-50 text-amber-700',     'earning_report.php'],
    ['Sell Report',     'View',                                 'full breakdown',                                'fa-chart-simple',      'from-slate-700 to-slate-900',   'bg-slate-100 text-slate-600',    'reports.php'],
];

/* ---- the new order engine: what needs this seller's attention today ---- */
buy_ensure_schema($db);
$buy_stats = buy_stats($db, ['seller_id' => $user_id]);
$__action_orders = [];
try {
    $__action_orders = $db->select(
        "SELECT o.*, u.name as buyer_name, u.mobile as buyer_mobile
           FROM orders o JOIN users u ON o.user_id = u.id
          WHERE o.seller_id = ? AND o.stage NOT IN ('cancelled','completed')
            AND (o.due_amount > 0 OR o.stage IN ('assigned','visit'))
          ORDER BY o.created_at ASC LIMIT 6", [$user_id]);
} catch (\Throwable $e) {}

$__visit_today = [];
try {
    $__visit_today = $db->select(
        "SELECT o.*, u.name as buyer_name, u.mobile as buyer_mobile
           FROM orders o JOIN users u ON o.user_id = u.id
          WHERE o.seller_id = ? AND o.fulfilment = 'visit' AND o.stage NOT IN ('cancelled','completed')
            AND DATE(COALESCE(o.visit_at, o.created_at)) = CURDATE()
          ORDER BY o.visit_at ASC LIMIT 8", [$user_id]);
} catch (\Throwable $e) {}

/* MEMBER report row — identical to the customer dashboard */
$member_tiles = [
    ['My Orders',     number_format($my_orders),                     $my_pending . ' in progress',                   'fa-cart-shopping', 'from-indigo-500 to-blue-600',  'bg-indigo-50 text-indigo-600',  '../orders.php'],
    ['My Referrals',  number_format($stat_refs),                     'direct',                                       'fa-user-group',    'from-purple-500 to-fuchsia-500','bg-purple-50 text-purple-600', '../refer.php'],
    ['Wallet',        '₹' . number_format((float)$wallet_balance, 0),'balance',                                      'fa-wallet',        'from-slate-700 to-slate-900',  'bg-slate-100 text-slate-600',   'wallet.php'],
    ['Subscription',  $is_sub ? 'Active' : 'Inactive',               $is_sub ? 'premium' : 'subscribe now',          'fa-crown',         $is_sub ? 'from-amber-400 to-yellow-600' : 'from-slate-400 to-slate-500', $is_sub ? 'bg-amber-50 text-amber-700' : 'bg-slate-100 text-slate-500', '../subscription.php'],
    ['KYC Status',    $kyc_ui[0],                                    $kyc_p['percent'] . '% complete',               'fa-id-card',       $kyc_ui[1],                     $kyc_ui[2],                      'profile.php#kyc'],
    ['Helpdesk',      'Support',                                     'raise a ticket',                               'fa-headset',       'from-rose-500 to-pink-500',    'bg-rose-50 text-rose-600',      'helpdesk.php'],
];
?>
<!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 $lang->translate('seller_dashboard', 'Seller Dashboard'); ?> - <?php echo $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://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" />
    <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=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
if (isset($categories)) { $__ids = isset($seller_cat_ids) ? $seller_cat_ids : null; foreach ($categories as $__c) { if ($__ids === null || in_array($__c['id'], $__ids)) $__scats[] = $__c; } }
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'Seller Dashboard',
    'active' => 'dashboard',
    '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'  => 'addMoneyModal: false',
]);
?>

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

                <?php if ($success_msg): ?>
                <div class="mb-6 bg-teal-50 border border-teal-200 text-teal-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-check-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $success_msg; ?></span>
                </div>
                <?php endif; ?>

                <?php if ($error_msg): ?>
                <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl relative flex items-center shadow-sm" role="alert">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i>
                    <span class="block sm:inline font-medium"><?php echo $error_msg; ?></span>
                </div>
                <?php endif; ?>
                
                <!-- ===================== 1. HERO BANNER (top of the page) ===================== -->
                <div class="mb-6">
                    <div class="w-full rounded-2xl overflow-hidden shadow-lg border border-gray-200 bg-white">
                        <div class="swiper dashboardSwiper h-[200px] md:h-[280px] lg:h-[330px]">
                            <div class="swiper-wrapper">
                                <?php if(!empty($dashboard_slides)): foreach($dashboard_slides as $slide): ?>
                                <div class="swiper-slide relative">
                                    <div class="absolute inset-0 bg-gradient-to-r from-gray-900/60 to-transparent z-10"></div>
                                    <img src="<?php echo htmlspecialchars($slide['image_path']); ?>" alt="Offer Banner" class="w-full h-full object-cover">
                                    <div class="absolute inset-y-0 left-0 z-20 flex flex-col justify-center px-8 md:px-12 w-full md:w-2/3 text-white">
                                        <span class="bg-teal-600 text-xs font-bold uppercase tracking-wider py-1 px-3 rounded-full w-max mb-3 shadow-md"><?php echo htmlspecialchars($slide['button_text']); ?></span>
                                        <h2 class="text-2xl md:text-3xl font-extrabold mb-2 leading-tight"><?php echo htmlspecialchars($slide['title']); ?></h2>
                                        <p class="text-sm md:text-base text-gray-200"><?php echo htmlspecialchars($slide['subtitle']); ?></p>
                                    </div>
                                </div>
                                <?php endforeach; else: ?>
                                <div class="swiper-slide bg-gray-200 flex items-center justify-center">
                                    <p class="font-bold text-gray-500">No Banners Available</p>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="swiper-pagination"></div>
                        </div>
                    </div>
                </div>

                <!-- ===================== 2. WELCOME STRIP ===================== -->
                <div class="tp-stat mb-6 flex flex-wrap items-center justify-between gap-4">
                    <div class="relative z-10 min-w-0">
                        <p class="text-[11px] uppercase tracking-[.2em] text-[#F5C451] font-bold">Welcome back</p>
                        <h2 class="tp-title text-xl sm:text-2xl mt-1 truncate"><?php echo htmlspecialchars($user['name']); ?></h2>
                        <p class="text-white/60 text-xs mt-1">
                            WBMCZ<?php echo str_pad($user_id, 4, '0', STR_PAD_LEFT); ?>
                            <span class="ml-2 text-[#F5C451] font-bold"><i class="fas fa-store"></i> Authorised Seller</span>
                        </p>
                    </div>
                    <div class="relative z-10 flex items-center gap-4">
                        <div class="text-right">
                            <p class="text-[10px] uppercase tracking-wider text-white/50 font-bold">Wallet Balance</p>
                            <p class="text-2xl font-extrabold">₹<?php echo number_format((float)$wallet_balance, 2); ?></p>
                        </div>
                        <button type="button" @click="addMoneyModal = true" class="tp-btn-gold text-xs !py-2 !px-4 whitespace-nowrap"><i class="fas fa-plus mr-1"></i>Add</button>
                    </div>
                </div>

                <!-- ============ SUBSCRIPTION CALL-TO-ACTION ============
                     A seller account created (or converted) by an admin does not
                     come with a subscription, so the option has to stay visible
                     here — the seller can buy it exactly like a normal member. -->
                <?php if (!$is_sub): ?>
                <a href="../subscription.php"
                   class="block mb-6 rounded-2xl overflow-hidden border border-amber-200 bg-gradient-to-r from-amber-50 to-orange-50 hover:shadow-lg transition-shadow">
                    <div class="p-4 sm:p-5 flex flex-wrap items-center gap-4">
                        <span class="w-12 h-12 rounded-xl grid place-items-center text-white text-lg bg-gradient-to-br from-amber-400 to-orange-500 flex-shrink-0">
                            <i class="fas fa-crown"></i>
                        </span>
                        <div class="min-w-0 flex-1">
                            <p class="font-extrabold text-slate-800 text-sm sm:text-base">Your subscription is not active yet</p>
                            <p class="text-slate-500 text-xs mt-0.5">
                                Take the premium subscription to unlock referral income and member discounts &mdash;
                                it works for seller accounts too.
                            </p>
                        </div>
                        <span class="tp-btn-gold text-xs !py-2 !px-4 whitespace-nowrap">
                            <i class="fas fa-bolt mr-1"></i>Subscribe now
                        </span>
                    </div>
                </a>
                <?php endif; ?>

                <!-- ===================== 2b. ORDER ENGINE — advance-booked orders needing action ===================== -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                    <div class="bg-white rounded-2xl p-5 shadow-sm border border-slate-200">
                        <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Total Orders</p>
                        <p class="text-2xl font-extrabold text-slate-800 mt-1"><?php echo number_format($buy_stats['orders']); ?></p>
                    </div>
                    <div class="bg-white rounded-2xl p-5 shadow-sm border border-slate-200">
                        <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Pending Visit</p>
                        <p class="text-2xl font-extrabold text-amber-600 mt-1"><?php echo number_format($buy_stats['pending_visits']); ?></p>
                    </div>
                    <div class="bg-white rounded-2xl p-5 shadow-sm border border-slate-200">
                        <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Cash to Collect</p>
                        <p class="text-2xl font-extrabold text-rose-600 mt-1">₹<?php echo number_format($buy_stats['due'], 2); ?></p>
                    </div>
                    <div class="bg-white rounded-2xl p-5 shadow-sm border border-slate-200">
                        <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide">Completed</p>
                        <p class="text-2xl font-extrabold text-emerald-600 mt-1"><?php echo number_format($buy_stats['completed']); ?></p>
                    </div>
                </div>

                <?php if (!empty($__action_orders)): ?>
                <div class="bg-white rounded-2xl border border-amber-200 shadow-sm mb-6 overflow-hidden">
                    <div class="px-5 py-3 bg-amber-50 border-b border-amber-100 flex items-center justify-between">
                        <p class="text-sm font-extrabold text-amber-800"><i class="fas fa-triangle-exclamation mr-1.5"></i>Action Required Orders</p>
                        <a href="orders.php" class="text-xs font-bold text-amber-700 hover:underline">View All</a>
                    </div>
                    <div class="divide-y divide-slate-50">
                    <?php foreach ($__action_orders as $a): $__meta = buy_stage_meta($a['stage']); ?>
                        <div class="p-4 flex flex-wrap items-center justify-between gap-3">
                            <div>
                                <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($a['service_name']); ?> <span class="text-slate-400 font-semibold">· <?php echo htmlspecialchars($__meta[0]); ?></span></p>
                                <p class="text-xs text-slate-500"><?php echo htmlspecialchars($a['buyer_name']); ?> · <?php echo htmlspecialchars($a['buyer_mobile']); ?></p>
                            </div>
                            <div class="flex items-center gap-2">
                                <?php if ((float)$a['due_amount'] > 0): ?><span class="text-xs font-bold text-rose-600">₹<?php echo number_format($a['due_amount'], 2); ?> to collect</span><?php endif; ?>
                                <a href="tel:<?php echo htmlspecialchars($a['buyer_mobile']); ?>" class="w-8 h-8 rounded-lg bg-slate-800 text-white inline-flex items-center justify-center"><i class="fas fa-phone"></i></a>
                                <a href="https://wa.me/91<?php echo htmlspecialchars(preg_replace('~\D~', '', $a['buyer_mobile'])); ?>" target="_blank" class="w-8 h-8 rounded-lg inline-flex items-center justify-center" style="background:#25D366;color:#fff"><i class="fab fa-whatsapp"></i></a>
                                <a href="orders.php" class="px-3 py-1.5 rounded-lg bg-[#C8901B] text-[#14202f] text-xs font-extrabold">Manage</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($__visit_today)): ?>
                <div class="bg-white rounded-2xl border border-slate-200 shadow-sm mb-8 overflow-hidden">
                    <div class="px-5 py-3 bg-slate-50 border-b border-slate-100 flex items-center justify-between">
                        <p class="text-sm font-extrabold text-slate-700"><i class="fas fa-calendar-day mr-1.5"></i>Today's Visit Schedule</p>
                        <a href="orders.php" class="text-xs font-bold text-slate-500 hover:underline">View All</a>
                    </div>
                    <div class="divide-y divide-slate-50">
                    <?php foreach ($__visit_today as $v): ?>
                        <div class="p-4 flex flex-wrap items-center justify-between gap-3">
                            <div class="flex items-center gap-3">
                                <span class="text-xs font-extrabold text-slate-500 w-16"><?php echo $v['visit_at'] ? date('h:i A', strtotime($v['visit_at'])) : '—'; ?></span>
                                <div>
                                    <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($v['buyer_name']); ?></p>
                                    <p class="text-xs text-slate-500"><?php echo htmlspecialchars($v['service_name']); ?><?php if (!empty($v['address'])): ?> · <?php echo htmlspecialchars($v['address']); ?><?php endif; ?></p>
                                </div>
                            </div>
                            <a href="orders.php" class="px-3 py-1.5 rounded-lg bg-slate-800 text-white text-xs font-extrabold">Navigate</a>
                        </div>
                    <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- ===================== 3. SELLER REPORT (extra over the member dashboard) ===================== -->
                <div class="mb-4 flex items-end justify-between gap-3">
                    <div>
                        <h2 class="tp-title text-lg sm:text-xl">Seller Report</h2>
                        <p class="text-slate-500 text-xs mt-0.5">Your selling business — sales, customer orders, listed services and share income.</p>
                    </div>
                    <a href="reports.php" class="hidden sm:inline-flex tp-chip bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-arrow-right"></i> Full report</a>
                </div>
                <div class="tile-grid mb-8">
                    <?php foreach ($seller_tiles as $rt): ?>
                        <a href="<?php echo htmlspecialchars($rt[6]); ?>" class="sq-tile">
                            <span class="sq-ico bg-gradient-to-br <?php echo $rt[4]; ?>"><i class="fas <?php echo $rt[3]; ?>"></i></span>
                            <span class="sq-val"><?php echo htmlspecialchars($rt[1]); ?></span>
                            <span class="sq-lbl"><?php echo htmlspecialchars($rt[0]); ?></span>
                            <span class="sq-pill <?php echo $rt[5]; ?>"><?php echo htmlspecialchars($rt[2]); ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>

                <!-- ===================== 4. MY REPORTS (same as the member dashboard) ===================== -->
                <div class="mb-4">
                    <h2 class="tp-title text-lg sm:text-xl">My Reports</h2>
                    <p class="text-slate-500 text-xs mt-0.5">Your own member account — orders, referrals, wallet, subscription and KYC.</p>
                </div>
                <div class="tile-grid mb-8">
                    <?php foreach ($member_tiles as $rt): ?>
                        <a href="<?php echo htmlspecialchars($rt[6]); ?>" class="sq-tile">
                            <span class="sq-ico bg-gradient-to-br <?php echo $rt[4]; ?>"><i class="fas <?php echo $rt[3]; ?>"></i></span>
                            <span class="sq-val"><?php echo htmlspecialchars($rt[1]); ?></span>
                            <span class="sq-lbl"><?php echo htmlspecialchars($rt[0]); ?></span>
                            <span class="sq-pill <?php echo $rt[5]; ?>"><?php echo htmlspecialchars($rt[2]); ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>

                <!-- ===================== 5. SERVICES HUB — NEVER LOCKED =====================
                     A seller is still a member: these are the services they BUY.        -->
                <div class="mb-4 flex items-end justify-between gap-3">
                    <div>
                        <h2 class="tp-title text-lg sm:text-xl">Services Hub</h2>
                        <p class="text-slate-500 text-xs mt-0.5">Everything you can buy as a member — exactly the same as the customer dashboard.</p>
                    </div>
                    <span class="hidden sm:inline-flex tp-chip bg-slate-100 text-slate-500"><i class="fas fa-grip"></i> <?php echo count($customer_categories); ?> categories</span>
                </div>

                <div class="tile-grid mb-8">
                    <?php foreach ($customer_categories as $cat):
                        $__soon = !in_array((int)$cat['id'], [1, 5], true);   // not built yet, for everybody
                        $target_url   = $__soon ? '#' : '../category.php?id=' . $cat['id'];
                        $click_action = $__soon ? "onclick=\"alert('Coming Soon!'); return false;\"" : '';
                    ?>
                    <a href="<?php echo $target_url; ?>" <?php echo $click_action; ?> class="sq-tile <?php echo $__soon ? 'is-locked' : ''; ?>">
                        <span class="sq-ico bg-gradient-to-br <?php echo htmlspecialchars($cat['gradient_class']); ?>">
                            <i class="fas <?php echo htmlspecialchars($cat['icon_class']); ?>"></i>
                        </span>
                        <span class="sq-title"><?php echo $lang->translate($cat['category_key'], $cat['title']); ?></span>
                        <?php if ($__soon): ?>
                            <span class="sq-pill bg-slate-100 text-slate-400"><i class="fas fa-lock"></i> Soon</span>
                        <?php else: ?>
                            <span class="sq-pill bg-emerald-50 text-emerald-600">Open</span>
                        <?php endif; ?>
                    </a>
                    <?php endforeach; ?>
                </div>

                <!-- ===================== 6. B2B SELLING CATEGORIES — the ONLY lockable grid ===================== -->
                <div class="mb-4 flex items-end justify-between gap-3">
                    <div>
                        <h2 class="tp-title text-lg sm:text-xl">What I Can Sell</h2>
                        <p class="text-slate-500 text-xs mt-0.5">Categories the admin has assigned to you. A locked tile means you cannot sell in it yet.</p>
                    </div>
                    <a href="../helpdesk.php" class="hidden sm:inline-flex tp-chip bg-amber-50 text-amber-700 hover:bg-amber-100"><i class="fas fa-unlock"></i> Request access</a>
                </div>

                <div class="tile-grid pb-20">
                    <?php if (!empty($categories)): ?>
                        <?php foreach ($categories as $cat):
                            $is_allowed   = in_array((int)$cat['id'], $seller_cat_ids, true);
                            $target_url   = $is_allowed ? 'services.php?cat_id=' . $cat['id'] : '#';
                            $click_action = $is_allowed ? '' : "onclick=\"alert('You are not assigned to this selling category yet. Please contact the admin.'); return false;\"";
                        ?>
                        <a href="<?php echo $target_url; ?>" <?php echo $click_action; ?> class="sq-tile <?php echo $is_allowed ? '' : 'is-locked cursor-not-allowed'; ?>">
                            <span class="sq-ico bg-gradient-to-br <?php echo htmlspecialchars($cat['gradient_class']); ?>">
                                <i class="fas <?php echo htmlspecialchars($cat['icon_class']); ?>"></i>
                            </span>
                            <span class="sq-title"><?php echo $lang->translate($cat['category_key'], $cat['title']); ?></span>
                            <?php if (!$is_allowed): ?>
                                <span class="sq-pill bg-rose-50 text-rose-500"><i class="fas fa-lock"></i> Locked</span>
                            <?php else: ?>
                                <span class="sq-pill bg-emerald-50 text-emerald-600">Sellable</span>
                            <?php endif; ?>
                        </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-span-full p-8 text-center text-gray-500 bg-white rounded-xl border border-gray-200">
                            No selling categories have been enabled yet.
                        </div>
                    <?php endif; ?>
                </div>

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

    <div x-show="addMoneyModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm" style="display: none;">
        <div @click.away="addMoneyModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 overflow-hidden border border-gray-100">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="font-bold text-gray-900 text-lg"><?php echo $lang->translate('add_money', 'Add Money'); ?></h3>
                <button @click="addMoneyModal = false" class="text-gray-400 hover:text-rose-500 transition-colors"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6">
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('enter_amount', 'Enter Amount (₹)'); ?></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 w-12 flex items-center justify-center text-gray-500 font-bold text-xl pointer-events-none">₹</span>
                        <input type="number" id="amount_input" min="1" step="1" required class="w-full pl-12 pr-4 py-4 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-teal-500 text-2xl font-bold text-gray-800 transition-all" placeholder="0.00">
                    </div>
                </div>
                
                <div class="flex gap-2 mb-6">
                    <button type="button" onclick="document.getElementById('amount_input').value = 500" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-600 hover:bg-teal-50 hover:text-teal-600 hover:border-teal-200 transition-colors">+ ₹500</button>
                    <button type="button" onclick="document.getElementById('amount_input').value = 1000" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-600 hover:bg-teal-50 hover:text-teal-600 hover:border-teal-200 transition-colors">+ ₹1000</button>
                    <button type="button" onclick="document.getElementById('amount_input').value = 5000" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-600 hover:bg-teal-50 hover:text-teal-600 hover:border-teal-200 transition-colors">+ ₹5000</button>
                </div>

                <form id="razorpayForm" method="POST" class="hidden">
                    <input type="hidden" name="amount" id="rzp_amount">
                    <input type="hidden" name="payment_id" id="rzp_payment_id">
                </form>

                <button type="button" @click="payViaRazorpay()" class="w-full bg-slate-800 hover:bg-slate-900 text-white font-bold py-4 px-6 rounded-xl shadow-md transition-colors text-lg flex items-center justify-center">
                    <i class="fas fa-shield-alt mr-2"></i> Pay Securely with Razorpay
                </button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
    <script>
        const dashboardSwiper = new Swiper('.dashboardSwiper', {
            loop: true,
            autoplay: { delay: 4000, disableOnInteraction: false },
            effect: 'fade', fadeEffect: { crossFade: true },
            pagination: { el: '.swiper-pagination', clickable: true },
        });

        // Razorpay Logic
        const rzpKey = "<?php echo $rzp_key; ?>";
        const companyName = "<?php echo addslashes($company_name); ?>";
        const userName = "<?php echo addslashes($user['name']); ?>";
        const userEmail = "<?php echo addslashes($user['email']); ?>";
        const userPhone = "<?php echo addslashes($user['mobile']); ?>";

        function payViaRazorpay() {
            const amount = parseFloat(document.getElementById('amount_input').value);
            if(isNaN(amount) || amount <= 0) {
                alert('Please enter a valid amount!');
                return;
            }

            var options = {
                "key": rzpKey,
                "amount": amount * 100, // Amount in paise
                "currency": "INR",
                "name": companyName,
                "description": "B2B Wallet Recharge",
                "handler": function (response) {
                    document.getElementById('rzp_amount').value = amount;
                    document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
                    document.getElementById('razorpayForm').submit();
                },
                "prefill": {
                    "name": userName,
                    "email": userEmail,
                    "contact": userPhone
                },
                "theme": {
                    "color": "#0d9488" // Tailwind teal-600
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        }
    </script>
</body>
</html>