<?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/credentials.php';

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

if (!hasPermission('manage_sellers')) { die("Access Denied: You do not have permission to manage sellers."); }

cred_ensure_schema($db);

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

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

$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']);
}

// Handle Status Toggle
if (isset($_POST['toggle_status'])) {
    $target_seller_id = sanitize($_POST['target_seller_id']);
    $current_status = sanitize($_POST['current_status']);
    $new_status = ($current_status == 1) ? 0 : 1;
    
    $db->insert("UPDATE users SET status = ? WHERE id = ?", [$new_status, $target_seller_id]);
    $_SESSION['flash_success'] = $lang->translate('status_updated', 'Status updated successfully!');
    redirect('sellers.php');
}

// Handle Request Approval
if (isset($_POST['approve_request'])) {
    $req_user_id = intval($_POST['req_user_id']);
    $db->insert("UPDATE users SET user_type = 'seller' WHERE id = ?", [$req_user_id]);
    $db->insert("UPDATE sellers SET status = 1, business_category = 'other' WHERE user_id = ?", [$req_user_id]);

    // Issue the partnership certificate the moment the account becomes a seller
    $__cert = cred_issue_seller_certificate($db, $req_user_id);
    try {
        $db->insert("INSERT INTO notifications (user_id, title, message, type, link, is_read) VALUES (?, ?, ?, 'certificate', 'profile.php#certificate', 0)", [
            $req_user_id, 'Welcome, partner!',
            'Your seller account is approved. Your official certificate' .
            ($__cert ? ' (' . $__cert['cert_no'] . ')' : '') .
            ' and member ID card are ready in My Profile.',
        ]);
    } catch (\Throwable $e) {}

    $_SESSION['flash_success'] = "Seller request approved" . ($__cert ? " — certificate {$__cert['cert_no']} issued." : "!");
    redirect('sellers.php');
}

// Handle Request Rejection
if (isset($_POST['reject_request'])) {
    $req_user_id = intval($_POST['req_user_id']);
    $db->insert("DELETE FROM sellers WHERE user_id = ? AND status = 0", [$req_user_id]);
    $_SESSION['flash_success'] = "Seller request rejected.";
    redirect('sellers.php');
}

// Handle Category Assignment Update
if (isset($_POST['update_categories'])) {
    $target_seller_id = intval($_POST['target_seller_id']);
    $categories = isset($_POST['categories']) ? implode(',', $_POST['categories']) : '';
    
    $db->insert("UPDATE users SET seller_categories = ? WHERE id = ?", [$categories, $target_seller_id]);
    $_SESSION['flash_success'] = "Seller categories updated successfully!";
    redirect('sellers.php');
}

// Handle Seller Deletion
if (isset($_POST['delete_seller'])) {
    $target_seller_id = sanitize($_POST['target_seller_id']);
    
    $target_data = $db->select("SELECT profile_pic FROM users WHERE id = ?", [$target_seller_id]);
    if (!empty($target_data[0]['profile_pic'])) {
        $pic_path = '../uploads/profiles/' . $target_data[0]['profile_pic'];
        if (file_exists($pic_path)) {
            @unlink($pic_path);
        }
    }
    
    $db->insert("DELETE FROM users WHERE id = ?", [$target_seller_id]);
    $_SESSION['flash_success'] = $lang->translate('seller_deleted', 'Seller deleted successfully!');
    redirect('sellers.php');
}

// Handle Bulk Deletion (multiple selected sellers)
if (isset($_POST['bulk_delete'])) {
    $ids = (isset($_POST['seller_ids']) && is_array($_POST['seller_ids'])) ? array_map('intval', $_POST['seller_ids']) : [];
    $deleted = 0;
    foreach ($ids as $id) {
        if ($id <= 0) continue;
        $td = $db->select("SELECT profile_pic FROM users WHERE id = ? AND user_type = 'seller'", [$id]);
        if (empty($td)) continue;
        if (!empty($td[0]['profile_pic'])) {
            $p = '../uploads/profiles/' . $td[0]['profile_pic'];
            if (file_exists($p)) { @unlink($p); }
        }
        $db->insert("DELETE FROM users WHERE id = ?", [$id]);
        $deleted++;
    }
    $_SESSION['flash_success'] = $deleted > 0 ? "$deleted seller(s) deleted successfully!" : "No sellers were deleted.";
    redirect('sellers.php');
}

// Handle Seller Update (edit basic details)
if (isset($_POST['update_seller'])) {
    $id     = intval($_POST['target_seller_id']);
    $name   = sanitize($_POST['name'] ?? '');
    $mobile = sanitize($_POST['mobile'] ?? '');
    $email  = sanitize($_POST['email'] ?? '');
    $gender = sanitize($_POST['gender'] ?? 'male');
    $status = intval($_POST['status'] ?? 1);
    $wallet = floatval($_POST['wallet_balance'] ?? 0);
    if ($id > 0 && $name !== '') {
        $db->insert("UPDATE users SET name = ?, mobile = ?, email = ?, gender = ?, status = ?, wallet_balance = ? WHERE id = ? AND user_type = 'seller'",
            [$name, $mobile, $email, $gender, $status, $wallet, $id]);
        $_SESSION['flash_success'] = "Seller updated successfully!";
    } else {
        $_SESSION['flash_error'] = "Name is required.";
    }
    redirect('sellers.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);
$total_tickets = count($db->select("SELECT id FROM support_tickets WHERE status = 'Open'"));

// Fetch available service categories for mapping and assignment
$service_cats = $db->select("SELECT id, title FROM service_categories ORDER BY display_order ASC");
$cat_map = [];
foreach($service_cats as $c) {
    $cat_map[$c['id']] = $c['title'];
}

$search_query = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$f_status = isset($_GET['f_status']) ? $_GET['f_status'] : '';   // '', '1', '0'
$f_cat    = isset($_GET['f_cat']) ? $_GET['f_cat'] : '';         // '', category id, 'uncat'
$f_wallet = isset($_GET['f_wallet']) ? $_GET['f_wallet'] : '';   // '', 'zero', 'nonzero'

$where_clause = "user_type = 'seller'";
$params = [];

if (!empty($search_query)) {
    $where_clause .= " AND (id = ? OR name LIKE ? OR mobile LIKE ? OR email LIKE ?)";
    $like_term = "%$search_query%";
    $params[] = intval(str_replace('#', '', $search_query));
    $params[] = $like_term; $params[] = $like_term; $params[] = $like_term;
}
if ($f_status === '1' || $f_status === '0') {
    $where_clause .= " AND status = ?";
    $params[] = intval($f_status);
}
if ($f_wallet === 'zero') {
    $where_clause .= " AND wallet_balance = 0";
} elseif ($f_wallet === 'nonzero') {
    $where_clause .= " AND wallet_balance > 0";
}
if ($f_cat === 'uncat') {
    $where_clause .= " AND (seller_categories IS NULL OR seller_categories = '')";
} elseif ($f_cat !== '') {
    $where_clause .= " AND FIND_IN_SET(?, seller_categories)";
    $params[] = intval($f_cat);
}

$sellers = $db->select("SELECT * FROM users WHERE $where_clause ORDER BY id DESC", $params);

// ID arrays for the bulk-select quick buttons
$all_ids = array_map('intval', array_column($sellers, 'id'));
$active_ids = []; $inactive_ids = [];
foreach ($sellers as $s) { if ($s['status'] == 1) $active_ids[] = intval($s['id']); else $inactive_ids[] = intval($s['id']); }
$filters_active = ($search_query !== '' || $f_status !== '' || $f_cat !== '' || $f_wallet !== '');
$pending_requests = $db->select("SELECT s.*, u.profile_pic FROM sellers s JOIN users u ON s.user_id = u.id WHERE s.status = 0 AND s.business_category = 'requested' AND u.user_type != 'seller'");

$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;
?>
<!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('manage_sellers', 'Manage Sellers'); ?> - <?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>
    <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; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, notifOpen: false, categoryModal: false, activeSellerId: '', activeCategories: [],
    selected: [],
    allIds: <?php echo json_encode($all_ids); ?>,
    activeIds: <?php echo json_encode($active_ids); ?>,
    inactiveIds: <?php echo json_encode($inactive_ids); ?>,
    bulkConfirm: false,
    updateModal: false,
    editSeller: {},
    filtersOpen: <?php echo $filters_active ? 'true' : 'false'; ?> }">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center">
                    <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 focus:outline-none rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-bars text-xl"></i>
                    </button>
                    <h2 class="text-xl font-bold hidden md:block text-slate-800"><?php echo $lang->translate('manage_sellers', 'Manage Sellers'); ?></h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <a href="../index.php" target="_blank" class="hidden sm:flex items-center text-sm font-semibold text-gray-500 hover:text-emerald-600 transition-colors">
                        <i class="fas fa-external-link-alt mr-2"></i> Visit Site
                    </a>

                    <div class="relative">
                        <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center focus:outline-none">
                            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 shadow-sm object-cover">
                            <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-emerald-100 border-2 border-emerald-200 text-emerald-600 flex items-center justify-center text-lg font-bold shadow-sm">
                                    <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                            <i class="fas fa-chevron-down text-xs ml-2 text-slate-400 hidden sm:block"></i>
                        </button>
                        
                        <div x-show="profileOpen" x-transition class="absolute right-0 mt-3 w-56 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 z-50" style="display: none;">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <p class="text-sm text-gray-500">Signed in as Admin</p>
                                <p class="text-sm font-bold text-gray-900 truncate"><?php echo htmlspecialchars($user['name']); ?></p>
                            </div>
                            <a href="profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-600 transition-colors"><i class="fas fa-user mr-2 w-4"></i> My Profile</a>
                            <div class="border-t border-gray-100 mt-2 pt-2">
                                <a href="../logout.php" onclick="return confirm('<?php echo $lang->translate('confirm_logout', 'Are you sure you want to logout?'); ?>');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors"><i class="fas fa-sign-out-alt mr-2 w-4"></i> Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">
                
                <div class="mb-6 flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-slate-800 mb-1"><?php echo $lang->translate('seller_list', 'Seller List'); ?></h2>
                        <p class="text-gray-500 text-sm"><?php echo $lang->translate('manage_sellers_desc', 'Manage all registered sellers on your platform.'); ?></p>
                    </div>
                    
                    <div class="flex items-center gap-2">
                        <button type="button" @click="filtersOpen = !filtersOpen" class="flex items-center gap-2 px-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 shadow-sm hover:shadow-md hover:border-indigo-300 transition-all">
                            <i class="fas fa-sliders text-indigo-500"></i> Filters
                            <?php if($filters_active): ?><span class="w-2 h-2 rounded-full bg-indigo-500"></span><?php endif; ?>
                            <i class="fas fa-chevron-down text-xs" :class="filtersOpen ? 'rotate-180' : ''"></i>
                        </button>
                        <form method="GET" class="relative group">
                            <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                                <i class="fas fa-search text-slate-400 group-focus-within:text-indigo-500 transition-colors"></i>
                            </div>
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="Search ID, Name, Phone..." class="w-full md:w-64 pl-10 pr-10 py-2.5 bg-white border border-slate-200 rounded-xl text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all shadow-sm">
                            <?php foreach(['f_status'=>$f_status,'f_cat'=>$f_cat,'f_wallet'=>$f_wallet] as $hk=>$hv): if($hv!==''): ?><input type="hidden" name="<?php echo $hk; ?>" value="<?php echo htmlspecialchars($hv); ?>"><?php endif; endforeach; ?>
                            <?php if(!empty($search_query)): ?>
                                <a href="sellers.php" class="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-400 hover:text-rose-500 transition-colors"><i class="fas fa-times-circle text-lg"></i></a>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>

                <!-- ===== FILTER PANEL ===== -->
                <div x-show="filtersOpen" x-transition style="display:none;" class="mb-6 bg-white border border-slate-200 rounded-2xl shadow-sm p-5">
                    <form method="GET" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                        <?php if(!empty($search_query)): ?><input type="hidden" name="search" value="<?php echo htmlspecialchars($search_query); ?>"><?php endif; ?>
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase mb-1.5">Status</label>
                            <select name="f_status" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:bg-white">
                                <option value="">All Status</option>
                                <option value="1" <?php echo $f_status==='1'?'selected':''; ?>>Active</option>
                                <option value="0" <?php echo $f_status==='0'?'selected':''; ?>>Inactive</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase mb-1.5">Category</label>
                            <select name="f_cat" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:bg-white">
                                <option value="">All Categories</option>
                                <option value="uncat" <?php echo $f_cat==='uncat'?'selected':''; ?>>Uncategorized</option>
                                <?php foreach($service_cats as $sc): ?>
                                    <option value="<?php echo $sc['id']; ?>" <?php echo $f_cat===(string)$sc['id']?'selected':''; ?>><?php echo htmlspecialchars($sc['title']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase mb-1.5">Wallet Balance</label>
                            <select name="f_wallet" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:bg-white">
                                <option value="">Any Balance</option>
                                <option value="zero" <?php echo $f_wallet==='zero'?'selected':''; ?>>Zero (₹0)</option>
                                <option value="nonzero" <?php echo $f_wallet==='nonzero'?'selected':''; ?>>Has Balance (&gt; ₹0)</option>
                            </select>
                        </div>
                        <div class="flex gap-2">
                            <button type="submit" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2.5 rounded-lg shadow-sm text-sm"><i class="fas fa-filter mr-1"></i>Apply</button>
                            <a href="sellers.php" class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold rounded-lg text-sm flex items-center">Reset</a>
                        </div>
                    </form>
                </div>

                <?php if ($success_msg): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-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; ?>

                <?php if(!empty($pending_requests)): ?>
                <div class="mb-8 bg-blue-50 border border-blue-200 rounded-2xl overflow-hidden shadow-sm">
                    <div class="p-4 bg-blue-100/50 border-b border-blue-200">
                        <h3 class="font-bold text-blue-900"><i class="fas fa-clock mr-2"></i> Pending Seller Upgrades</h3>
                    </div>
                    <div class="overflow-x-auto p-4">
                        <table class="w-full text-left border-collapse bg-white rounded-xl overflow-hidden shadow-sm">
                            <thead>
                                <tr class="bg-gray-50 text-xs uppercase text-gray-500 tracking-wider">
                                    <th class="p-3 font-semibold border-b">User</th>
                                    <th class="p-3 font-semibold border-b">Contact</th>
                                    <th class="p-3 font-semibold border-b text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($pending_requests as $req): ?>
                                <tr class="border-b last:border-0 hover:bg-gray-50 transition">
                                    <td class="p-3">
                                        <div class="flex items-center">
                                            <div class="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center font-bold text-xs mr-3">
                                                <?php echo strtoupper(substr($req['name'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($req['name']); ?></p>
                                                <p class="text-xs text-gray-500">Business: <?php echo htmlspecialchars($req['business_name']); ?></p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="p-3 text-sm text-gray-600">
                                        <?php echo htmlspecialchars($req['phone']); ?>
                                    </td>
                                    <td class="p-3 text-right">
                                        <form method="POST" class="inline-block mr-2" onsubmit="return confirm('Approve seller request?');">
                                            <input type="hidden" name="req_user_id" value="<?php echo $req['user_id']; ?>">
                                            <button type="submit" name="approve_request" class="bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-bold py-1.5 px-3 rounded shadow-sm">
                                                Approve
                                            </button>
                                        </form>
                                        <form method="POST" class="inline-block" onsubmit="return confirm('Reject seller request?');">
                                            <input type="hidden" name="req_user_id" value="<?php echo $req['user_id']; ?>">
                                            <button type="submit" name="reject_request" class="bg-rose-500 hover:bg-rose-600 text-white text-xs font-bold py-1.5 px-3 rounded shadow-sm">
                                                Reject
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>

                <!-- ===== BULK ACTION BAR ===== -->
                <div x-show="selected.length > 0" x-transition style="display:none;" class="mb-4 bg-slate-800 text-white rounded-2xl shadow-lg px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-3">
                    <div class="flex items-center gap-2 font-semibold text-sm">
                        <span class="w-7 h-7 rounded-full bg-indigo-500 flex items-center justify-center text-xs font-bold" x-text="selected.length"></span>
                        seller(s) selected
                    </div>
                    <div class="flex flex-wrap items-center gap-2 sm:ml-auto">
                        <button type="button" @click="selected = [...allIds]" class="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-xs font-bold"><i class="fas fa-check-double mr-1"></i>Select All</button>
                        <button type="button" @click="selected = [...activeIds]" class="px-3 py-1.5 rounded-lg bg-emerald-500/80 hover:bg-emerald-500 text-xs font-bold"><i class="fas fa-circle-check mr-1"></i>All Active</button>
                        <button type="button" @click="selected = [...inactiveIds]" class="px-3 py-1.5 rounded-lg bg-rose-500/80 hover:bg-rose-500 text-xs font-bold"><i class="fas fa-ban mr-1"></i>All Inactive</button>
                        <button type="button" @click="selected = []" class="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-xs font-bold"><i class="fas fa-xmark mr-1"></i>Clear</button>
                        <button type="button" @click="bulkConfirm = true" class="px-4 py-1.5 rounded-lg bg-red-600 hover:bg-red-700 text-xs font-bold shadow"><i class="fas fa-trash-alt mr-1"></i>Delete Selected</button>
                    </div>
                </div>
                <p class="text-xs text-slate-400 mb-3" x-show="selected.length === 0">Tip: tick rows to bulk-delete. Use <b>All Active / All Inactive</b> quick-selects, then untick any you want to keep (exclude) before deleting.</p>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 text-xs uppercase text-slate-500 tracking-wider">
                                    <th class="p-4 pl-6 border-b border-gray-200 w-10">
                                        <input type="checkbox" class="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 cursor-pointer"
                                               :checked="allIds.length > 0 && selected.length === allIds.length"
                                               @change="selected = $event.target.checked ? [...allIds] : []">
                                    </th>
                                    <th class="p-4 font-semibold border-b border-gray-200">Seller Details</th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('contact_info', 'Contact Info'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200">Categories</th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('wallet_balance', 'Wallet Balance'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('join_date', 'Join Date'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200"><?php echo $lang->translate('status', 'Status'); ?></th>
                                    <th class="p-4 font-semibold border-b border-gray-200 text-center">Update</th>
                                    <th class="p-4 pr-6 font-semibold border-b border-gray-200 text-right"><?php echo $lang->translate('action', 'Action'); ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php if(!empty($sellers)): ?>
                                    <?php foreach($sellers as $seller): ?>
                                    <tr class="hover:bg-slate-50/50 transition group" :class="selected.includes(<?php echo $seller['id']; ?>) ? 'bg-indigo-50/40' : ''">
                                        <td class="p-4 pl-6">
                                            <input type="checkbox" :value="<?php echo $seller['id']; ?>" x-model.number="selected" class="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 cursor-pointer">
                                        </td>
                                        <td class="p-4 pl-6">
                                            <div class="flex items-center">
                                                <?php if(!empty($seller['profile_pic']) && file_exists('../uploads/profiles/'.$seller['profile_pic'])): ?>
                                                    <img src="../uploads/profiles/<?php echo $seller['profile_pic']; ?>" class="w-10 h-10 rounded-full object-cover border border-gray-200 mr-3">
                                                <?php else: ?>
                                                    <div class="w-10 h-10 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center font-bold text-sm mr-3">
                                                        <?php echo strtoupper(substr($seller['name'], 0, 1)); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <p class="font-bold text-slate-800 text-sm"><?php echo htmlspecialchars($seller['name']); ?></p>
                                                    <p class="text-xs text-gray-500">ID: #<?php echo str_pad($seller['id'], 5, '0', STR_PAD_LEFT); ?> &bull; <?php echo ucfirst($seller['gender']); ?></p>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="p-4">
                                            <p class="text-sm text-slate-700 font-medium"><i class="fas fa-phone-alt text-gray-400 w-4 text-center mr-1"></i> <?php echo htmlspecialchars($seller['mobile']); ?></p>
                                            <p class="text-xs text-gray-500 mt-1"><i class="fas fa-envelope text-gray-400 w-4 text-center mr-1"></i> <?php echo htmlspecialchars($seller['email']); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <?php 
                                            $assigned = [];
                                            if (!empty($seller['seller_categories'])) {
                                                $assigned_ids = explode(',', $seller['seller_categories']);
                                                foreach($assigned_ids as $aid) {
                                                    if(isset($cat_map[$aid])) $assigned[] = $cat_map[$aid];
                                                }
                                            }
                                            
                                            if(!empty($assigned)): ?>
                                                <div class="flex flex-wrap gap-1">
                                                    <?php foreach($assigned as $cat_name): ?>
                                                        <span class="bg-indigo-50 text-indigo-600 border border-indigo-100 px-2 py-0.5 rounded text-[10px] font-bold"><?php echo htmlspecialchars($cat_name); ?></span>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-xs text-gray-400 italic">Uncategorized</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-4">
                                            <span class="font-bold text-emerald-600">₹<?php echo number_format($seller['wallet_balance'], 2); ?></span>
                                        </td>
                                        <td class="p-4">
                                            <p class="text-sm text-slate-700 font-medium whitespace-nowrap"><i class="far fa-calendar-alt text-gray-400 mr-1"></i> <?php echo date('d M, Y', strtotime($seller['created_at'])); ?></p>
                                        </td>
                                        <td class="p-4">
                                            <?php if($seller['status'] == 1): ?>
                                                <span class="bg-emerald-100 text-emerald-700 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider border border-emerald-200 whitespace-nowrap">
                                                    <i class="fas fa-check-circle mr-1"></i> <?php echo $lang->translate('active', 'Active'); ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="bg-rose-100 text-rose-700 text-[10px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider border border-rose-200 whitespace-nowrap">
                                                    <i class="fas fa-ban mr-1"></i> <?php echo $lang->translate('inactive', 'Inactive'); ?>
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-4 text-center">
                                            <?php $editJson = htmlspecialchars(json_encode([
                                                'id' => (int)$seller['id'],
                                                'name' => $seller['name'],
                                                'mobile' => $seller['mobile'],
                                                'email' => $seller['email'],
                                                'gender' => $seller['gender'],
                                                'status' => (int)$seller['status'],
                                                'wallet_balance' => $seller['wallet_balance'],
                                            ]), ENT_QUOTES); ?>
                                            <button type="button" @click='editSeller = <?php echo $editJson; ?>; updateModal = true;' class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-lime-500 hover:bg-lime-600 text-white text-xs font-bold shadow-sm transition-colors" title="Update Seller">
                                                <i class="fas fa-pen"></i> Update
                                            </button>
                                        </td>
                                        <td class="p-4 pr-6 text-right space-x-2 whitespace-nowrap">

                                            <button type="button" @click="activeSellerId = <?php echo $seller['id']; ?>; activeCategories = '<?php echo $seller['seller_categories'] ?? ''; ?>'.split(',').filter(Boolean); categoryModal = true;" class="w-8 h-8 rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-600 transition-colors tooltip inline-flex items-center justify-center" title="Assign Categories">
                                                <i class="fas fa-tags"></i>
                                            </button>
                                            
                                            <form method="POST" class="inline-block">
                                                <input type="hidden" name="target_seller_id" value="<?php echo $seller['id']; ?>">
                                                <input type="hidden" name="current_status" value="<?php echo $seller['status']; ?>">
                                                <button type="submit" name="toggle_status" class="w-8 h-8 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors tooltip flex items-center justify-center" title="<?php echo $seller['status'] == 1 ? 'Suspend Seller' : 'Activate Seller'; ?>">
                                                    <i class="fas <?php echo $seller['status'] == 1 ? 'fa-user-lock' : 'fa-user-check'; ?>"></i>
                                                </button>
                                            </form>

                                            <form method="POST" class="inline-block" onsubmit="return confirm('<?php echo $lang->translate('confirm_delete_seller', 'Are you sure you want to delete this seller? This action cannot be undone!'); ?>');">
                                                <input type="hidden" name="target_seller_id" value="<?php echo $seller['id']; ?>">
                                                <button type="submit" name="delete_seller" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors tooltip flex items-center justify-center" title="Delete Seller">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" class="p-12 text-center text-gray-500">
                                            <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-400 text-2xl border border-gray-100">
                                                <i class="fas fa-store-slash"></i>
                                            </div>
                                            <p class="text-lg font-medium"><?php echo $lang->translate('no_sellers_found', 'No sellers found.'); ?></p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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

    <div x-show="categoryModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" style="display:none;">
        <div @click.away="categoryModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden flex flex-col">
            <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 flex items-center"><i class="fas fa-tags text-indigo-600 mr-2"></i> Assign Categories</h3>
                <button @click="categoryModal = false" class="text-gray-400 hover:text-rose-500"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6">
                <form method="POST">
                    <input type="hidden" name="target_seller_id" x-model="activeSellerId">
                    <p class="text-sm text-gray-600 mb-4">Select the services categories this seller operates under:</p>
                    
                    <div class="max-h-60 overflow-y-auto border border-gray-200 rounded-xl p-3 bg-slate-50 space-y-2 mb-6">
                        <?php foreach($service_cats as $c): ?>
                        <label class="flex items-center space-x-3 cursor-pointer bg-white p-3 rounded-lg border border-gray-100 shadow-sm hover:border-indigo-300 transition-colors">
                            <input type="checkbox" name="categories[]" value="<?php echo $c['id']; ?>" x-model="activeCategories" class="w-4 h-4 text-indigo-600 rounded focus:ring-indigo-500 border-gray-300">
                            <span class="text-sm font-bold text-gray-700"><?php echo htmlspecialchars($c['title']); ?></span>
                        </label>
                        <?php endforeach; ?>
                        
                        <?php if(empty($service_cats)): ?>
                            <p class="text-xs text-gray-500 text-center py-4">No categories created yet.</p>
                        <?php endif; ?>
                    </div>
                    
                    <button type="submit" name="update_categories" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 rounded-xl shadow-md transition-colors flex items-center justify-center">
                        <i class="fas fa-save mr-2"></i> Save Categories
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- ===== BULK DELETE CONFIRM MODAL ===== -->
    <div x-show="bulkConfirm" x-transition.opacity style="display:none;" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="bulkConfirm = false"></div>
        <div class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden">
            <div class="bg-gradient-to-r from-rose-500 to-red-600 px-5 py-4 flex items-center gap-3">
                <i class="fas fa-triangle-exclamation text-white text-xl"></i>
                <h3 class="text-white font-bold text-lg">Delete Selected Sellers</h3>
            </div>
            <div class="p-6">
                <p class="text-slate-600 text-sm">You are about to permanently delete <b class="text-rose-600" x-text="selected.length"></b> seller(s). This action cannot be undone.</p>
                <form method="POST" class="mt-5">
                    <template x-for="id in selected" :key="id"><input type="hidden" name="seller_ids[]" :value="id"></template>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="bulkConfirm = false" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                        <button type="submit" name="bulk_delete" class="px-5 py-2 text-sm font-bold text-white bg-red-600 hover:bg-red-700 rounded-lg shadow"><i class="fas fa-trash-alt mr-1"></i>Delete <span x-text="selected.length"></span></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ===== UPDATE SELLER MODAL ===== -->
    <div x-show="updateModal" x-transition.opacity style="display:none;" class="fixed inset-0 z-[110] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="updateModal = false"></div>
        <div class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden">
            <div class="bg-gradient-to-r from-lime-600 to-emerald-600 px-5 py-4 flex items-center justify-between">
                <h3 class="text-white font-bold text-lg"><i class="fas fa-pen mr-2"></i>Update Seller</h3>
                <button @click="updateModal = false" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
            </div>
            <form method="POST" class="p-6 space-y-4">
                <input type="hidden" name="target_seller_id" :value="editSeller.id">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Name</label><input name="name" x-model="editSeller.name" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"></div>
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Gender</label><select name="gender" x-model="editSeller.gender" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"><option value="male">Male</option><option value="female">Female</option><option value="other">Other</option></select></div>
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Mobile</label><input name="mobile" x-model="editSeller.mobile" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"></div>
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Email</label><input name="email" x-model="editSeller.email" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"></div>
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Wallet Balance (₹)</label><input type="number" step="0.01" name="wallet_balance" x-model="editSeller.wallet_balance" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"></div>
                    <div><label class="block text-xs font-bold text-slate-500 uppercase mb-1">Status</label><select name="status" x-model="editSeller.status" class="w-full px-3 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:bg-white"><option value="1">Active</option><option value="0">Inactive</option></select></div>
                </div>
                <div class="flex justify-end gap-2 pt-2 border-t">
                    <button type="button" @click="updateModal = false" class="px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-lg">Cancel</button>
                    <button type="submit" name="update_seller" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

</body>
</html>