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

// Redirect to login if not logged in or NOT an admin
if (!isLoggedIn() || !isAdmin()) { redirect('../login.php'); }

// RBAC Protection
if (!hasPermission('manage_services')) { die("Access Denied: You do not have permission to manage services."); }

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

// UI Permissions map for Sidebar
$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');

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

/* =========================================================
   AUTO-SCHEMA — review columns (safe to run every load)
   status: 0 = pending, 1 = approved/live, 2 = rejected
   ========================================================= */
foreach ([
    'rejection_reason' => "TEXT NULL",
    'reviewed_by'      => "INT NULL",
    'reviewed_by_name' => "VARCHAR(120) NULL",
    'reviewed_at'      => "DATETIME NULL",
    'submitted_at'     => "DATETIME NULL",
] as $__c => $__def) {
    try {
        $__r = $conn->query("SHOW COLUMNS FROM seller_services LIKE '$__c'");
        if ($__r && $__r->num_rows === 0) { $conn->query("ALTER TABLE seller_services ADD COLUMN $__c $__def"); }
    } catch (\Throwable $e) { /* ignore */ }
}
try {
    $conn->query("CREATE TABLE IF NOT EXISTS product_update_history (
        id INT AUTO_INCREMENT PRIMARY KEY, service_id INT NOT NULL, service_type VARCHAR(20) NOT NULL DEFAULT 'seller',
        field_label VARCHAR(120) NOT NULL, old_value TEXT NULL, new_value TEXT NULL, updated_by INT NULL,
        updated_by_name VARCHAR(120) NULL, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (\Throwable $e) {}

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

/* Write one audit line */
function ps_log($db, $me, $sid, $label, $old, $new) {
    try {
        $db->insert("INSERT INTO product_update_history (service_id, service_type, field_label, old_value, new_value, updated_by, updated_by_name)
                     VALUES (?, 'seller', ?, ?, ?, ?, ?)", [$sid, $label, (string)$old, (string)$new, $me['id'], $me['name']]);
    } catch (\Throwable $e) {}
}

/* Admin-side image upload (same rules as the seller form) */
function ps_handle_image($current_icon, $current_is_img) {
    if (!empty($_FILES['image_upload']['tmp_name']) && (int)$_FILES['image_upload']['error'] === 0) {
        $dir = '../uploads/services/';
        if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
        $ext = strtolower(pathinfo($_FILES['image_upload']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','gif','webp','svg'], true)) {
            $fn = 'srv_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $dir . $fn)) {
                return ['icon_class' => 'uploads/services/' . $fn, 'is_img' => 1];
            }
        }
    }
    // No new file — fall back to the typed icon / URL
    $typed = trim((string)($_POST['icon_class'] ?? ''));
    if ($typed !== '') {
        $is_img = (strpos($typed, 'http') === 0 || strpos($typed, 'uploads/') === 0) ? 1 : 0;
        return ['icon_class' => $typed, 'is_img' => $is_img];
    }
    return ['icon_class' => $current_icon, 'is_img' => $current_is_img];
}

/* =========================================================
   AJAX — full detail of one submission (for the edit modal)
   ========================================================= */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'service') {
    header('Content-Type: application/json');
    $sid = intval($_GET['sid'] ?? 0);
    $r = $db->select("SELECT ss.*, u.name AS seller_name, u.mobile AS seller_mobile, u.email AS seller_email,
                             u.call_number, u.whatsapp_number, s.business_name,
                             c.title AS cat_name, sc.title AS sub_cat_name
                      FROM seller_services ss
                      LEFT JOIN sellers s ON ss.seller_id = s.user_id
                      LEFT JOIN users u ON ss.seller_id = u.id
                      LEFT JOIN service_categories c ON ss.category_id = c.id
                      LEFT JOIN agency_sub_categories sc ON ss.sub_category_id = sc.id
                      WHERE ss.id = ?", [$sid]);
    $row = !empty($r) ? $r[0] : null;
    if ($row) {
        foreach (['title','description','cat_name','sub_cat_name'] as $f) {
            $row[$f] = html_entity_decode((string)($row[$f] ?? ''), ENT_QUOTES);
        }
        $row['history'] = $db->select("SELECT field_label, old_value, new_value, updated_by_name, updated_at
                                       FROM product_update_history WHERE service_id = ? AND service_type = 'seller'
                                       ORDER BY updated_at DESC LIMIT 25", [$sid]);
    }
    echo json_encode($row);
    exit;
}

// ---------------------------------------------------------
// Handle Actions (Edit / Approve / Reject / Delete)
// ---------------------------------------------------------

/* ---- EDIT: admin may correct anything the seller submitted ----
   Two submit buttons post here: "Save Changes" and "Save & Approve". */
if (isset($_POST['edit_service']) || isset($_POST['edit_then_approve'])) {
    $sid = intval($_POST['service_id']);
    $old = $db->select("SELECT * FROM seller_services WHERE id = ?", [$sid]);
    if (empty($old)) { $_SESSION['flash_error'] = "Service not found."; redirect('pending_services.php'); }
    $old = $old[0];

    $cat_id = intval($_POST['category_id'] ?? $old['category_id']);
    $sub_id = intval($_POST['sub_category_id'] ?? $old['sub_category_id']);
    $price  = (float)($_POST['price'] ?? $old['price']);
    $disc   = (float)($_POST['discount_price'] ?? $old['discount_price']);

    // Government Portals are never priced
    if ($cat_id == 1) { $price = 0.00; $disc = 0.00; }
    if ($disc > $price && $price > 0) {
        $_SESSION['flash_error'] = "Discount price cannot be higher than the MRP.";
        redirect('pending_services.php');
    }

    $img = ps_handle_image($old['icon_class'], (int)$old['is_img']);

    $new = [
        'category_id'     => $cat_id,
        'sub_category_id' => $sub_id,
        'title'           => sanitize($_POST['title'] ?? $old['title']),
        'description'     => sanitize($_POST['description'] ?? $old['description']),
        'price'           => $price,
        'discount_price'  => $disc,
        'color_class'     => sanitize($_POST['color_class'] ?? $old['color_class']),
        'web_url'         => sanitize($_POST['web_url'] ?? $old['web_url']),
        'app_url'         => sanitize($_POST['app_url'] ?? $old['app_url']),
        'tutorial_url'    => sanitize($_POST['tutorial_url'] ?? $old['tutorial_url']),
        'icon_class'      => $img['icon_class'],
        'is_img'          => $img['is_img'],
    ];

    $labels = [
        'category_id' => 'Category', 'sub_category_id' => 'Sub Category', 'title' => 'Service Name',
        'description' => 'Description', 'price' => 'MRP', 'discount_price' => 'Discount Price',
        'color_class' => 'Card Colour', 'web_url' => 'Website URL', 'app_url' => 'App URL',
        'tutorial_url' => 'Tutorial URL', 'icon_class' => 'Icon / Image', 'is_img' => 'Image Mode',
    ];

    $changed = 0;
    foreach ($new as $col => $val) {
        $oldv = (string)($old[$col] ?? '');
        $newv = (string)$val;
        if (in_array($col, ['price','discount_price'], true)) {
            if (abs((float)$oldv - (float)$newv) < 0.005) continue;
        } elseif ($oldv === $newv) { continue; }

        $db->insert("UPDATE seller_services SET `$col` = ? WHERE id = ?", [$val, $sid]); // whitelisted key
        ps_log($db, $me, $sid, 'Admin edit — ' . $labels[$col], $oldv, $newv);
        $changed++;
    }

    // Editing a rejected submission puts it back in the pending queue
    if ((int)$old['status'] === 2) {
        $db->insert("UPDATE seller_services SET status = 0, rejection_reason = NULL WHERE id = ?", [$sid]);
        ps_log($db, $me, $sid, 'Status', 'Rejected', 'Pending (admin edited)');
    }

    if (isset($_POST['edit_then_approve'])) {
        $db->insert("UPDATE seller_services SET status = 1, rejection_reason = NULL, reviewed_by = ?, reviewed_by_name = ?, reviewed_at = NOW() WHERE id = ?",
            [$me['id'], $me['name'], $sid]);
        ps_log($db, $me, $sid, 'Status', 'Pending', 'Approved');
        $_SESSION['flash_success'] = "Saved $changed change(s) and approved — the service is now live.";
    } else {
        $_SESSION['flash_success'] = $changed > 0
            ? "Service updated ($changed field" . ($changed > 1 ? 's' : '') . " changed). Still awaiting your approval."
            : "No changes were made.";
    }
    redirect('pending_services.php');
}

/* ---- APPROVE ---- */
if (isset($_POST['approve_service'])) {
    $sid = intval($_POST['service_id']);
    $old = $db->select("SELECT status FROM seller_services WHERE id = ?", [$sid]);
    $db->insert("UPDATE seller_services SET status = 1, rejection_reason = NULL, reviewed_by = ?, reviewed_by_name = ?, reviewed_at = NOW() WHERE id = ?",
        [$me['id'], $me['name'], $sid]);
    ps_log($db, $me, $sid, 'Status', (!empty($old) && (int)$old[0]['status'] === 2) ? 'Rejected' : 'Pending', 'Approved');
    $_SESSION['flash_success'] = "Service has been approved and is now live!";
    redirect('pending_services.php');
}

/* ---- REJECT: keeps the record + the reason so the seller can fix it ---- */
if (isset($_POST['reject_service'])) {
    $sid    = intval($_POST['service_id']);
    $reason = trim(sanitize($_POST['rejection_reason'] ?? ''));
    if ($reason === '') {
        $_SESSION['flash_error'] = "Please write a reason so the seller knows what to correct.";
        redirect('pending_services.php');
    }
    $db->insert("UPDATE seller_services SET status = 2, rejection_reason = ?, reviewed_by = ?, reviewed_by_name = ?, reviewed_at = NOW() WHERE id = ?",
        [$reason, $me['id'], $me['name'], $sid]);
    ps_log($db, $me, $sid, 'Status', 'Pending', 'Rejected — ' . $reason);

    // Tell the seller
    try {
        $s = $db->select("SELECT seller_id, title FROM seller_services WHERE id = ?", [$sid]);
        if (!empty($s)) {
            $db->insert("INSERT INTO notifications (user_id, title, message, type, link, is_read) VALUES (?, ?, ?, 'service', 'seller/services.php', 0)",
                [$s[0]['seller_id'], 'Service rejected', 'Your service "' . $s[0]['title'] . '" was rejected. Reason: ' . $reason]);
        }
    } catch (\Throwable $e) { /* notifications table may differ — non-fatal */ }

    $_SESSION['flash_success'] = "Service rejected. The seller can see your reason and resubmit.";
    redirect('pending_services.php');
}

/* ---- RESTORE a rejected submission back to the pending queue ---- */
if (isset($_POST['restore_service'])) {
    $sid = intval($_POST['service_id']);
    $db->insert("UPDATE seller_services SET status = 0, rejection_reason = NULL WHERE id = ?", [$sid]);
    ps_log($db, $me, $sid, 'Status', 'Rejected', 'Pending (restored)');
    $_SESSION['flash_success'] = "Moved back to the pending queue.";
    redirect('pending_services.php?tab=rejected');
}

/* ---- DELETE permanently (only offered on rejected rows) ---- */
if (isset($_POST['delete_service'])) {
    $sid = intval($_POST['service_id']);
    $sd = $db->select("SELECT icon_class, is_img FROM seller_services WHERE id = ?", [$sid]);
    if (!empty($sd) && (int)$sd[0]['is_img'] === 1 && strpos($sd[0]['icon_class'], 'uploads/') === 0) {
        $fp = '../' . $sd[0]['icon_class'];
        if (file_exists($fp)) { @unlink($fp); }
    }
    $db->insert("DELETE FROM seller_services WHERE id = ?", [$sid]);
    $_SESSION['flash_success'] = "Submission deleted permanently.";
    redirect('pending_services.php?tab=rejected');
}

// ---------------------------------------------------------
// Filters & Data Fetching
// ---------------------------------------------------------
$filter_cat    = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;
$filter_seller = isset($_GET['seller_id']) ? intval($_GET['seller_id']) : 0;
$tab           = (isset($_GET['tab']) && $_GET['tab'] === 'rejected') ? 'rejected' : 'pending';
$status_filter = $tab === 'rejected' ? 2 : 0;

$query = "SELECT ss.*, u.name as seller_name, u.mobile as seller_mobile, u.email as seller_email,
                 u.call_number, u.whatsapp_number, s.business_name,
                 c.title as cat_name, sc.title as sub_cat_name
          FROM seller_services ss
          JOIN sellers s ON ss.seller_id = s.user_id
          JOIN users u ON ss.seller_id = u.id
          LEFT JOIN service_categories c ON ss.category_id = c.id
          LEFT JOIN agency_sub_categories sc ON ss.sub_category_id = sc.id
          WHERE ss.status = ?";
$params = [$status_filter];

if ($filter_cat > 0) {
    $query .= " AND ss.category_id = ?";
    $params[] = $filter_cat;
}
if ($filter_seller > 0) {
    $query .= " AND ss.seller_id = ?";
    $params[] = $filter_seller;
}
$query .= " ORDER BY ss.created_at DESC";

$pending_services = $db->select($query, $params);

// Counts for the tab badges
$cnt_pending = 0; $cnt_rejected = 0;
try {
    $c = $db->select("SELECT status, COUNT(*) AS n FROM seller_services WHERE status IN (0,2) GROUP BY status");
    foreach ($c as $r) { if ((int)$r['status'] === 0) $cnt_pending = (int)$r['n']; else $cnt_rejected = (int)$r['n']; }
} catch (\Throwable $e) {}

// Dropdown data for the edit modal
$all_sub_cats = $db->select("SELECT id, category_id, title FROM agency_sub_categories WHERE status = 1 ORDER BY category_id, id");
foreach ($all_sub_cats as $k => $v) { $all_sub_cats[$k]['title'] = html_entity_decode($v['title'] ?? '', ENT_QUOTES); }

// Decode entities for proper display
if (!empty($pending_services)) {
    foreach ($pending_services as $key => $srv) {
        foreach (['cat_name','sub_cat_name','title','description','rejection_reason'] as $f) {
            $pending_services[$key][$f] = html_entity_decode($srv[$f] ?? '', ENT_QUOTES);
        }
    }
}

// Fetch filter dropdowns
$categories = $db->select("SELECT id, title FROM service_categories ORDER BY display_order ASC");
if (!empty($categories)) {
    foreach ($categories as $key => $cat) {
        $categories[$key]['title'] = html_entity_decode($cat['title'] ?? '', ENT_QUOTES);
    }
}

$sellers_with_pending = $db->select("SELECT DISTINCT u.id, u.name, u.mobile, s.business_name 
                                     FROM users u 
                                     JOIN sellers s ON u.id = s.user_id 
                                     JOIN seller_services ss ON u.id = ss.seller_id
                                     WHERE ss.status IN (0,2) ORDER BY u.name ASC");

// General details
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$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>Review Pending Services - Admin Panel</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 }">

    <div class="flex h-screen overflow-hidden">
        
        <aside :class="sidebarOpen ? 'w-64' : 'w-20'" class="flex-shrink-0 bg-gradient-to-b from-slate-800 to-slate-900 text-white transition-all duration-300 flex flex-col shadow-2xl z-50 overflow-x-hidden relative">
            <div class="flex items-center h-20 px-4 border-b border-white/10" :class="sidebarOpen ? 'justify-between' : 'justify-center'">
                <a href="../index.php" class="flex items-center">
                    <img src="<?php echo $company_logo; ?>" alt="Logo" class="h-10 w-10 bg-white rounded p-1 flex-shrink-0 object-contain">
                    <span x-show="sidebarOpen" class="ml-3 text-xl font-bold tracking-wider whitespace-nowrap text-emerald-400">ADMIN</span>
                </a>
            </div>

            <nav class="flex-1 px-3 py-6 space-y-1.5 overflow-y-auto hide-scrollbar text-sm font-medium">
    
    <a href="index.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
        <i class="fas fa-chart-line flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
        <span x-show="sidebarOpen" class="ml-3 font-semibold">Dashboard</span>
    </a>
    
    <div x-data="{ profileMenuOpen: false }">
        <button @click="profileMenuOpen = !profileMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-user-tie flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Profile</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="profileMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="profileMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="profile.php#profile" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">My Profile</a>
            <a href="profile.php#edit" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Edit Profile</a>
            <a href="profile.php#kyc" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">KYC</a>
            <a href="profile.php#password" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Change Password</a>
            <a href="profile.php#id_card" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">ID Card</a>
        </div>
    </div>

    <div x-data="{ walletMenuOpen: false }">
        <button @click="walletMenuOpen = !walletMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-wallet flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Wallet Management</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="walletMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="walletMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="wallet.php#add_money" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Add Money</a>
            <a href="wallet.php#my_history" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">My wallet history</a>
            <a href="wallet.php#move_bank" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Move to Bank</a>
            <a href="wallet.php#all_history" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">All Wallet History</a>
            <a href="wallet.php#customer_history" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer Wallet History</a>
            <a href="wallet.php#seller_history" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller Wallet History</a>
            <a href="wallet.php#staff_history" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff Wallet History</a>
            <a href="wallet_history.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Wallet History</a>
            <a href="withdrawals.php#bank_requests" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Bank Request Pending</a>
            <a href="withdrawals.php#transactions" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Transaction Update</a>
        </div>
    </div>

    <div x-data="{ userMenuOpen: false }">
        <button @click="userMenuOpen = !userMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-users-cog flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">User Management</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="userMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="userMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="users.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer</a>
            <a href="notifications.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Notifications</a>
            <a href="sellers.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller</a>
            <a href="staff.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff</a>
            <a href="roles.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Custom Role</a>
        </div>
    </div>

    <div x-data="{ serviceMenuOpen: false }">
        <button @click="serviceMenuOpen = !serviceMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-layer-group flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Services Management</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="serviceMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="serviceMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="product_management.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Product Management</a>
            <a href="services.php#main_cats" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Main Services</a>
            <a href="services.php#sub_cats" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Sub Categories</a>
            <a href="pending_services.php" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Services List</a>
        </div>
    </div>

    <div x-data="{ settingMenuOpen: false }">
        <button @click="settingMenuOpen = !settingMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-cogs flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Website Settings</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="settingMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="settingMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="settings.php#home_settings" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Home Page All Settings</a>
            <a href="settings.php#customer_settings" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer Panel Settings</a>
            <a href="settings.php#seller_settings" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller Panel Settings</a>
            <a href="settings.php#staff_settings" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff Panel Settings</a>
        </div>
    </div>

    <div x-data="{ commMenuOpen: false }">
        <button @click="commMenuOpen = !commMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-percentage flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Commission Mgt</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="commMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="commMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="commissions.php#customer" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer</a>
            <a href="commissions.php#seller" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller</a>
            <a href="commissions.php#staff" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff</a>
            <a href="commissions.php#admin" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Super Admin</a>
        </div>
    </div>

    <div x-data="{ reportMenuOpen: false }">
        <button @click="reportMenuOpen = !reportMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-chart-pie flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Report Management</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="reportMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="reportMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="reports.php#all" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">All Report</a>
            <a href="reports.php#customer" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Customer</a>
            <a href="reports.php#seller" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller</a>
            <a href="reports.php#staff" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Staff</a>
            <a href="reports.php#admin" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Super Admin</a>
        </div>
    </div>

    <div x-data="{ helpdeskMenuOpen: false }">
        <button @click="helpdeskMenuOpen = !helpdeskMenuOpen" class="w-full flex items-center justify-between px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all group" :class="sidebarOpen ? '' : 'justify-center'">
            <div class="flex items-center">
                <i class="fas fa-headset flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
                <span x-show="sidebarOpen" class="ml-3 font-semibold">Helpdesk</span>
            </div>
            <i x-show="sidebarOpen" class="fas fa-chevron-down text-xs transition-transform" :class="helpdeskMenuOpen ? 'rotate-180' : ''"></i>
        </button>
        <div x-show="helpdeskMenuOpen && sidebarOpen" x-transition class="pl-10 pr-3 py-2 space-y-1" style="display:none;">
            <a href="tickets.php#customer" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">User</a>
            <a href="tickets.php#seller" class="block py-2 text-sm text-gray-400 hover:text-emerald-400 transition-colors">Seller</a>
        </div>
    </div>

    <a href="refer.php" class="flex items-center px-3 py-3 text-gray-300 hover:bg-white/5 hover:text-white rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
        <i class="fas fa-gift flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
        <span x-show="sidebarOpen" class="ml-3 font-semibold">Refer & Earn</span>
    </a>

    <div class="pt-6 mt-6 border-t border-white/10">
        <a href="../logout.php" onclick="return confirm('Are you sure you want to logout?');" class="flex items-center px-3 py-3 text-rose-400 hover:bg-rose-500/20 hover:text-rose-300 rounded-xl transition-all" :class="sidebarOpen ? '' : 'justify-center'">
            <i class="fas fa-sign-out-alt flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-xl'"></i>
            <span x-show="sidebarOpen" class="ml-3">Logout</span>
        </a>
    </div>
</nav>
        </aside>

        <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">Pending Services</h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <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'], ENT_QUOTES, 'UTF-8', false); ?></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('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">
                
                <?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">
                    <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">
                    <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; ?>

                <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 $tab === 'rejected' ? 'Rejected Submissions' : 'Review Pending Services'; ?></h2>
                        <p class="text-gray-500 text-sm">Every detail the seller submitted is shown below. You can edit anything before approving.</p>
                    </div>
                </div>

                <!-- TABS -->
                <div class="flex gap-2 mb-5 border-b border-gray-200">
                    <?php
                        $qs = function($t) use ($filter_cat, $filter_seller) {
                            $p = ['tab' => $t];
                            if ($filter_cat > 0) $p['cat_id'] = $filter_cat;
                            if ($filter_seller > 0) $p['seller_id'] = $filter_seller;
                            return 'pending_services.php?' . http_build_query($p);
                        };
                    ?>
                    <a href="<?php echo $qs('pending'); ?>" class="px-5 py-3 text-sm font-bold border-b-2 transition-colors <?php echo $tab==='pending' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500 hover:text-slate-700'; ?>">
                        <i class="fas fa-hourglass-half mr-1.5"></i>Pending Review
                        <span class="ml-1.5 px-2 py-0.5 rounded-full text-[10px] <?php echo $tab==='pending' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'; ?>"><?php echo $cnt_pending; ?></span>
                    </a>
                    <a href="<?php echo $qs('rejected'); ?>" class="px-5 py-3 text-sm font-bold border-b-2 transition-colors <?php echo $tab==='rejected' ? 'border-rose-600 text-rose-700' : 'border-transparent text-slate-500 hover:text-slate-700'; ?>">
                        <i class="fas fa-circle-xmark mr-1.5"></i>Rejected
                        <span class="ml-1.5 px-2 py-0.5 rounded-full text-[10px] <?php echo $tab==='rejected' ? 'bg-rose-100 text-rose-700' : 'bg-slate-100 text-slate-500'; ?>"><?php echo $cnt_rejected; ?></span>
                    </a>
                </div>

                <div class="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 mb-6">
                    <form method="GET" class="flex flex-col sm:flex-row gap-4">
                        <input type="hidden" name="tab" value="<?php echo htmlspecialchars($tab); ?>">
                        <div class="flex-1">
                            <label class="block text-xs font-bold text-gray-700 mb-1">Filter by Category</label>
                            <select name="cat_id" class="w-full px-4 py-2 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-emerald-500 font-semibold text-gray-700 outline-none">
                                <option value="0">All Categories</option>
                                <?php foreach($categories as $c): ?>
                                    <option value="<?php echo $c['id']; ?>" <?php echo $filter_cat == $c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="flex-1">
                            <label class="block text-xs font-bold text-gray-700 mb-1">Filter by Seller</label>
                            <select name="seller_id" class="w-full px-4 py-2 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-emerald-500 font-semibold text-gray-700 outline-none">
                                <option value="0">All Sellers</option>
                                <?php foreach($sellers_with_pending as $s): ?>
                                    <option value="<?php echo $s['id']; ?>" <?php echo $filter_seller == $s['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['business_name'] . ' (' . $s['name'] . ')'); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="flex items-end space-x-2">
                            <button type="submit" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 px-6 rounded-xl shadow-sm transition-colors h-[42px]">
                                Filter
                            </button>
                            <a href="pending_services.php" class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-xl transition-colors h-[42px] flex items-center justify-center">
                                Reset
                            </a>
                        </div>
                    </form>
                </div>

                <!-- ============ REQUEST CARDS ============ -->
                <div class="space-y-4">
                <?php if(!empty($pending_services)): foreach($pending_services as $srv):
                    $img_src = ($srv['is_img'] == 1)
                        ? ((strpos($srv['icon_class'], 'http') === 0) ? $srv['icon_class'] : '../' . $srv['icon_class'])
                        : '';
                    $is_govt  = ((int)$srv['category_id'] === 1);
                    $mrp      = (float)$srv['price'];
                    $disc     = (float)$srv['discount_price'];
                    $save_pct = ($mrp > 0 && $disc > 0 && $disc < $mrp) ? round((($mrp - $disc) / $mrp) * 100) : 0;
                    $rejected = ((int)$srv['status'] === 2);
                    $jsName   = htmlspecialchars(addslashes($srv['title']), ENT_QUOTES);
                ?>
                <div class="bg-white rounded-2xl shadow-sm border-2 overflow-hidden transition-shadow hover:shadow-md <?php echo $rejected ? 'border-rose-200' : 'border-gray-200'; ?>"
                     x-data="{ open: false }">

                    <!-- ---------- HEADER ---------- -->
                    <div class="p-4 md:p-5 flex flex-col lg:flex-row lg:items-center gap-4">

                        <!-- icon + title -->
                        <div class="flex items-start gap-4 flex-1 min-w-0">
                            <div class="w-16 h-16 rounded-2xl bg-gray-50 border border-gray-200 flex items-center justify-center flex-shrink-0 overflow-hidden shadow-sm">
                                <?php if($img_src): ?>
                                    <img src="<?php echo htmlspecialchars($img_src); ?>" class="w-full h-full object-cover" alt="">
                                <?php else: ?>
                                    <i class="fa-solid <?php echo htmlspecialchars($srv['icon_class'] ?: 'fa-box'); ?> text-2xl text-emerald-600"></i>
                                <?php endif; ?>
                            </div>
                            <div class="min-w-0 flex-1">
                                <div class="flex flex-wrap items-center gap-2 mb-1">
                                    <span class="text-[10px] font-mono font-bold text-slate-400">#REQ-<?php echo str_pad($srv['id'], 5, '0', STR_PAD_LEFT); ?></span>
                                    <?php if($rejected): ?>
                                        <span class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-rose-100 text-rose-700 border border-rose-200"><i class="fas fa-circle-xmark mr-1"></i>Rejected</span>
                                    <?php else: ?>
                                        <span class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 border border-amber-200"><i class="fas fa-hourglass-half mr-1"></i>Awaiting review</span>
                                    <?php endif; ?>
                                    <span class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-700 border border-indigo-100"><?php echo htmlspecialchars($srv['cat_name'] ?: 'Unknown'); ?></span>
                                    <?php if(!empty($srv['sub_cat_name'])): ?>
                                        <span class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 border border-slate-200"><?php echo htmlspecialchars($srv['sub_cat_name']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <p class="font-extrabold text-slate-800 text-base leading-tight truncate"><?php echo htmlspecialchars($srv['title']); ?></p>
                                <p class="text-[11px] text-gray-500 mt-1">
                                    <i class="fas fa-store mr-1"></i><b class="text-slate-600"><?php echo htmlspecialchars($srv['business_name'] ?: '—'); ?></b>
                                    &nbsp;•&nbsp; <?php echo htmlspecialchars($srv['seller_name']); ?>
                                    &nbsp;•&nbsp; <i class="fas fa-clock mr-1"></i><?php echo date('d M Y, h:i A', strtotime($srv['created_at'])); ?>
                                </p>
                            </div>
                        </div>

                        <!-- pricing -->
                        <div class="flex-shrink-0 lg:text-right">
                            <?php if($is_govt): ?>
                                <span class="text-xs text-gray-400 font-semibold italic">N/A (Govt Portal)</span>
                            <?php elseif($mrp > 0 || $disc > 0): ?>
                                <div class="flex lg:justify-end items-baseline gap-2">
                                    <span class="text-xl font-black text-emerald-600">₹<?php echo number_format($disc > 0 ? $disc : $mrp, 2); ?></span>
                                    <?php if($disc > 0 && $mrp > 0): ?><span class="text-xs text-gray-400 line-through">₹<?php echo number_format($mrp, 2); ?></span><?php endif; ?>
                                </div>
                                <?php if($save_pct > 0): ?><span class="text-[10px] font-bold text-emerald-500"><?php echo $save_pct; ?>% off</span><?php endif; ?>
                            <?php else: ?>
                                <span class="text-sm font-bold text-emerald-600">Free / Custom</span>
                            <?php endif; ?>
                        </div>

                        <!-- ---------- 3 ACTION BUTTONS ---------- -->
                        <div class="flex flex-wrap items-center gap-2 flex-shrink-0">
                            <button type="button" @click="$dispatch('open-edit', <?php echo $srv['id']; ?>)"
                                    class="px-4 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold shadow-sm transition-colors">
                                <i class="fas fa-pen mr-1.5"></i>Edit
                            </button>
                            <form method="POST" class="inline" onsubmit="return confirm('Approve this service? It will become live immediately.');">
                                <input type="hidden" name="service_id" value="<?php echo $srv['id']; ?>">
                                <button type="submit" name="approve_service" class="px-4 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold shadow-sm transition-colors">
                                    <i class="fas fa-check mr-1.5"></i>Approve
                                </button>
                            </form>
                            <?php if(!$rejected): ?>
                                <button type="button" @click="$dispatch('open-reject', { id: <?php echo $srv['id']; ?>, name: '<?php echo $jsName; ?>' })"
                                        class="px-4 py-2.5 rounded-xl bg-rose-600 hover:bg-rose-700 text-white text-xs font-bold shadow-sm transition-colors">
                                    <i class="fas fa-xmark mr-1.5"></i>Reject
                                </button>
                            <?php else: ?>
                                <form method="POST" class="inline">
                                    <input type="hidden" name="service_id" value="<?php echo $srv['id']; ?>">
                                    <button type="submit" name="restore_service" class="px-4 py-2.5 rounded-xl bg-slate-600 hover:bg-slate-700 text-white text-xs font-bold shadow-sm transition-colors">
                                        <i class="fas fa-rotate-left mr-1.5"></i>Restore
                                    </button>
                                </form>
                                <form method="POST" class="inline" onsubmit="return confirm('Delete this submission permanently? This cannot be undone.');">
                                    <input type="hidden" name="service_id" value="<?php echo $srv['id']; ?>">
                                    <button type="submit" name="delete_service" class="px-3 py-2.5 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-600 border border-rose-200 text-xs font-bold transition-colors" title="Delete permanently">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                            <button type="button" @click="open = !open"
                                    class="px-3 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-bold transition-colors">
                                <i class="fas fa-chevron-down transition-transform" :class="open && 'rotate-180'"></i>
                            </button>
                        </div>
                    </div>

                    <!-- rejection reason strip -->
                    <?php if($rejected && !empty($srv['rejection_reason'])): ?>
                    <div class="mx-4 md:mx-5 mb-4 bg-rose-50 border border-rose-200 rounded-xl px-4 py-3">
                        <p class="text-[10px] font-bold uppercase tracking-wider text-rose-400 mb-1">Rejection reason<?php echo !empty($srv['reviewed_by_name']) ? ' — by ' . htmlspecialchars($srv['reviewed_by_name']) : ''; ?></p>
                        <p class="text-sm text-rose-800 font-semibold whitespace-pre-wrap"><?php echo htmlspecialchars($srv['rejection_reason']); ?></p>
                    </div>
                    <?php endif; ?>

                    <!-- ---------- FULL SUBMITTED DETAILS ---------- -->
                    <div x-show="open" x-transition style="display:none;" class="border-t border-gray-100 bg-slate-50/60">
                        <div class="p-4 md:p-5 grid gap-5 lg:grid-cols-3">

                            <!-- description -->
                            <div class="lg:col-span-2 space-y-5">
                                <div>
                                    <p class="ps-lbl">Description submitted by seller</p>
                                    <div class="bg-white border border-gray-200 rounded-xl p-4 text-sm text-slate-700 whitespace-pre-wrap leading-relaxed max-h-64 overflow-y-auto">
<?php echo htmlspecialchars($srv['description'] ?: '(no description provided)'); ?>
                                    </div>
                                </div>

                                <!-- links -->
                                <div>
                                    <p class="ps-lbl">Links</p>
                                    <div class="grid sm:grid-cols-3 gap-2">
                                        <?php foreach ([
                                            ['Website', $srv['web_url'], 'fa-globe', 'text-blue-600'],
                                            ['App', $srv['app_url'], 'fa-download', 'text-emerald-600'],
                                            ['Tutorial', $srv['tutorial_url'], 'fa-play', 'text-rose-600'],
                                        ] as $lnk): ?>
                                            <div class="bg-white border border-gray-200 rounded-xl p-3">
                                                <p class="text-[10px] font-bold uppercase text-slate-400 mb-1"><i class="fas <?php echo $lnk[2]; ?> mr-1 <?php echo $lnk[3]; ?>"></i><?php echo $lnk[0]; ?></p>
                                                <?php if(!empty($lnk[1])): ?>
                                                    <a href="<?php echo htmlspecialchars($lnk[1]); ?>" target="_blank" rel="noopener noreferrer"
                                                       class="text-[11px] font-semibold text-indigo-600 hover:underline break-all"><?php echo htmlspecialchars($lnk[1]); ?></a>
                                                <?php else: ?>
                                                    <span class="text-[11px] text-slate-400 italic">Not provided</span>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <!-- raw field table -->
                                <div>
                                    <p class="ps-lbl">All submitted fields</p>
                                    <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
                                        <table class="w-full text-xs">
                                            <tbody class="divide-y divide-gray-100">
                                            <?php
                                                $rows = [
                                                    'Request ID'        => '#REQ-' . str_pad($srv['id'], 5, '0', STR_PAD_LEFT),
                                                    'Service Name'      => $srv['title'],
                                                    'Category'          => ($srv['cat_name'] ?: '—') . ' (ID ' . (int)$srv['category_id'] . ')',
                                                    'Sub Category'      => ($srv['sub_cat_name'] ?: '— none —') . ((int)$srv['sub_category_id'] > 0 ? ' (ID ' . (int)$srv['sub_category_id'] . ')' : ''),
                                                    'MRP'               => $is_govt ? 'N/A' : '₹' . number_format($mrp, 2),
                                                    'Discount Price'    => $is_govt ? 'N/A' : '₹' . number_format($disc, 2),
                                                    'Icon / Image'      => $srv['icon_class'] ?: '—',
                                                    'Image Mode'        => ((int)$srv['is_img'] === 1 ? 'Uploaded image / URL' : 'Font Awesome icon'),
                                                    'Card Colour'       => $srv['color_class'] ?: '—',
                                                    'Submitted On'      => date('d M Y, h:i A', strtotime($srv['created_at'])),
                                                ];
                                                if (!empty($srv['reviewed_at'])) {
                                                    $rows['Last Reviewed'] = date('d M Y, h:i A', strtotime($srv['reviewed_at']))
                                                        . (!empty($srv['reviewed_by_name']) ? ' by ' . $srv['reviewed_by_name'] : '');
                                                }
                                            ?>
                                            <?php foreach($rows as $k => $v): ?>
                                                <tr>
                                                    <td class="px-4 py-2.5 font-bold text-slate-500 w-40 align-top"><?php echo htmlspecialchars($k); ?></td>
                                                    <td class="px-4 py-2.5 text-slate-800 font-semibold break-all"><?php echo htmlspecialchars((string)$v); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- seller card + preview -->
                            <div class="space-y-5">
                                <div>
                                    <p class="ps-lbl">Seller</p>
                                    <div class="bg-white border border-gray-200 rounded-xl p-4 space-y-2">
                                        <p class="font-extrabold text-slate-800 text-sm"><?php echo htmlspecialchars($srv['business_name'] ?: '—'); ?></p>
                                        <p class="text-[11px] text-slate-500"><?php echo htmlspecialchars($srv['seller_name']); ?> &nbsp;•&nbsp; ID <?php echo (int)$srv['seller_id']; ?></p>
                                        <div class="pt-2 border-t border-gray-100 space-y-1.5 text-[11px]">
                                            <p><i class="fas fa-phone w-4 text-slate-400"></i> <a href="tel:<?php echo htmlspecialchars($srv['call_number'] ?: $srv['seller_mobile']); ?>" class="font-semibold text-slate-700 hover:text-indigo-600"><?php echo htmlspecialchars($srv['call_number'] ?: $srv['seller_mobile'] ?: '—'); ?></a></p>
                                            <p><i class="fas fa-envelope w-4 text-slate-400"></i> <a href="mailto:<?php echo htmlspecialchars($srv['seller_email']); ?>" class="font-semibold text-slate-700 hover:text-indigo-600 break-all"><?php echo htmlspecialchars($srv['seller_email'] ?: '—'); ?></a></p>
                                        </div>
                                        <div class="flex gap-2 pt-2">
                                            <a href="tel:<?php echo htmlspecialchars($srv['call_number'] ?: $srv['seller_mobile']); ?>" class="flex-1 text-center py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-[11px] font-bold"><i class="fas fa-phone mr-1"></i>Call</a>
                                            <a href="https://wa.me/91<?php echo preg_replace('/\D/','', $srv['whatsapp_number'] ?: $srv['seller_mobile']); ?>" target="_blank" rel="noopener noreferrer" class="flex-1 text-center py-2 rounded-lg bg-green-500 hover:bg-green-600 text-white text-[11px] font-bold"><i class="fab fa-whatsapp mr-1"></i>WhatsApp</a>
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <p class="ps-lbl">Customer card preview</p>
                                    <div class="bg-white border-2 border-gray-200 rounded-xl p-4 text-center" style="border-top:4px solid <?php
                                        echo ['color-1'=>'#ef4444','color-2'=>'#3b82f6','color-3'=>'#10b981','color-4'=>'#f59e0b','color-5'=>'#8b5cf6'][$srv['color_class']] ?? '#94a3b8'; ?>;">
                                        <div class="w-20 h-20 mx-auto mb-3 rounded-2xl bg-slate-50 flex items-center justify-center overflow-hidden">
                                            <?php if($img_src): ?>
                                                <img src="<?php echo htmlspecialchars($img_src); ?>" class="w-full h-full object-contain p-1" alt="">
                                            <?php else: ?>
                                                <i class="fa-solid <?php echo htmlspecialchars($srv['icon_class'] ?: 'fa-box'); ?> text-3xl text-slate-400"></i>
                                            <?php endif; ?>
                                        </div>
                                        <p class="font-bold text-xs text-slate-800 leading-tight"><?php echo htmlspecialchars($srv['title']); ?></p>
                                        <?php if(!$is_govt && ($mrp > 0 || $disc > 0)): ?>
                                            <p class="mt-2 text-sm font-black text-emerald-600">₹<?php echo number_format($disc > 0 ? $disc : $mrp, 2); ?>
                                                <?php if($disc > 0 && $mrp > 0): ?><span class="text-[10px] text-gray-400 line-through font-normal ml-1">₹<?php echo number_format($mrp, 2); ?></span><?php endif; ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; else: ?>
                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-16 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 <?php echo $tab === 'rejected' ? 'fa-inbox' : 'fa-check-double'; ?>"></i>
                        </div>
                        <p class="text-lg font-medium text-slate-700 mb-1"><?php echo $tab === 'rejected' ? 'Nothing rejected' : 'All caught up!'; ?></p>
                        <p class="text-sm"><?php echo $tab === 'rejected' ? 'No rejected submissions to show.' : 'There are no pending services requiring your approval.'; ?></p>
                    </div>
                <?php endif; ?>
                </div>

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

<!-- ================= EDIT / REJECT MODALS ================= -->
<div x-data="psModals()" @open-edit.window="openEdit($event.detail)" @open-reject.window="openReject($event.detail)" @keydown.escape.window="close()">

    <!-- ---------- EDIT SUBMISSION ---------- -->
    <div x-show="modal==='edit'" x-cloak x-transition.opacity class="fixed inset-0 z-[200] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="close()"></div>
        <div class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
            <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
                <div class="min-w-0">
                    <h3 class="text-white font-bold text-lg"><i class="fas fa-pen mr-2"></i>Edit Submission</h3>
                    <p class="text-white/70 text-[11px] truncate" x-text="'#REQ-' + String(f.id || '').padStart(5,'0') + ' • ' + (f.business_name || f.seller_name || '')"></p>
                </div>
                <button @click="close()" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
            </div>

            <form method="POST" enctype="multipart/form-data" class="flex flex-col overflow-hidden">
                <input type="hidden" name="service_id" :value="f.id">

                <div class="p-5 overflow-y-auto space-y-4">
                    <template x-if="loading"><p class="text-center text-slate-400 py-10"><i class="fas fa-spinner fa-spin mr-2"></i>Loading submission...</p></template>

                    <div x-show="!loading" class="space-y-4">
                        <!-- category -->
                        <div class="grid sm:grid-cols-2 gap-3">
                            <div>
                                <label class="ps-l">Category</label>
                                <select name="category_id" x-model.number="f.category_id" class="ps-f">
                                    <?php foreach($categories as $c): ?>
                                        <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['title']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label class="ps-l">Sub Category</label>
                                <select name="sub_category_id" x-model.number="f.sub_category_id" class="ps-f">
                                    <option value="0">— None —</option>
                                    <template x-for="sc in subsFor(f.category_id)" :key="sc.id">
                                        <option :value="sc.id" x-text="sc.title"></option>
                                    </template>
                                </select>
                                <p x-show="subsFor(f.category_id).length === 0" class="text-[10px] text-slate-400 mt-1">This category has no sub-categories.</p>
                            </div>
                        </div>

                        <div>
                            <label class="ps-l">Service / Product Name <span class="text-rose-500">*</span></label>
                            <input name="title" x-model="f.title" required class="ps-f">
                        </div>

                        <div>
                            <label class="ps-l">Description</label>
                            <textarea name="description" x-model="f.description" rows="6" class="ps-f resize-y"></textarea>
                            <p class="text-[10px] text-slate-400 mt-1"><span x-text="(f.description || '').length"></span> characters</p>
                        </div>

                        <!-- pricing -->
                        <div x-show="Number(f.category_id) !== 1">
                            <p class="ps-sec">Pricing</p>
                            <div class="grid sm:grid-cols-3 gap-3 items-end">
                                <div>
                                    <label class="ps-l">MRP (₹)</label>
                                    <input type="number" step="0.01" min="0" name="price" x-model.number="f.price" class="ps-f">
                                </div>
                                <div>
                                    <label class="ps-l">Discount Price (₹)</label>
                                    <input type="number" step="0.01" min="0" name="discount_price" x-model.number="f.discount_price" class="ps-f"
                                           :class="badPrice() && 'border-rose-400 bg-rose-50'">
                                </div>
                                <div class="pb-2">
                                    <p class="text-xs font-bold" :class="badPrice() ? 'text-rose-600' : 'text-emerald-600'">
                                        <template x-if="badPrice()"><span><i class="fas fa-triangle-exclamation mr-1"></i>Discount is above MRP</span></template>
                                        <template x-if="!badPrice()"><span x-text="savings()"></span></template>
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div x-show="Number(f.category_id) === 1" class="bg-slate-50 border border-slate-200 rounded-xl p-3 text-xs text-slate-500">
                            <i class="fas fa-circle-info mr-1"></i> Government Portals are always free — pricing is forced to ₹0.00 on save.
                        </div>

                        <!-- image -->
                        <p class="ps-sec">Icon / Image</p>
                        <div class="grid sm:grid-cols-[auto,1fr] gap-4 items-start">
                            <div class="w-24 h-24 rounded-2xl bg-slate-50 border-2 border-slate-200 flex items-center justify-center overflow-hidden">
                                <template x-if="previewUrl()">
                                    <img :src="previewUrl()" class="w-full h-full object-contain p-1" alt="">
                                </template>
                                <template x-if="!previewUrl()">
                                    <i class="fa-solid text-3xl text-slate-400" :class="f.icon_class || 'fa-box'"></i>
                                </template>
                            </div>
                            <div class="space-y-2">
                                <div>
                                    <label class="ps-l">Replace image (jpg, png, gif, webp, svg)</label>
                                    <input type="file" name="image_upload" accept="image/*" @change="newFile = $event.target.files[0]?.name || ''"
                                           class="w-full text-xs text-slate-600 file:mr-2 file:py-2 file:px-3 file:rounded-lg file:border-0 file:bg-blue-50 file:text-blue-700 file:font-semibold">
                                    <p x-show="newFile" class="text-[10px] text-emerald-600 font-bold mt-1"><i class="fas fa-check mr-1"></i><span x-text="newFile"></span> will replace the current image.</p>
                                </div>
                                <div>
                                    <label class="ps-l">…or Font Awesome class / image URL</label>
                                    <input name="icon_class" x-model="f.icon_class" placeholder="fa-id-card OR https://..." class="ps-f">
                                </div>
                            </div>
                        </div>

                        <div>
                            <label class="ps-l">Card Colour</label>
                            <select name="color_class" x-model="f.color_class" class="ps-f">
                                <option value="color-1">Red</option>
                                <option value="color-2">Blue</option>
                                <option value="color-3">Green</option>
                                <option value="color-4">Amber</option>
                                <option value="color-5">Purple</option>
                            </select>
                        </div>

                        <p class="ps-sec">Links</p>
                        <div class="grid sm:grid-cols-3 gap-3">
                            <div><label class="ps-l">Website URL</label><input type="url" name="web_url" x-model="f.web_url" placeholder="https://" class="ps-f"></div>
                            <div><label class="ps-l">App URL</label><input type="url" name="app_url" x-model="f.app_url" placeholder="https://" class="ps-f"></div>
                            <div><label class="ps-l">Tutorial URL</label><input type="url" name="tutorial_url" x-model="f.tutorial_url" placeholder="https://youtu.be/..." class="ps-f"></div>
                        </div>

                        <!-- audit trail -->
                        <div x-show="(f.history || []).length">
                            <p class="ps-sec">Change history</p>
                            <div class="border border-slate-200 rounded-xl overflow-hidden max-h-44 overflow-y-auto">
                                <table class="w-full text-[11px]">
                                    <tbody class="divide-y divide-slate-100">
                                        <template x-for="(h, i) in (f.history || [])" :key="i">
                                            <tr>
                                                <td class="px-3 py-2 font-bold text-slate-600 align-top" x-text="h.field_label"></td>
                                                <td class="px-3 py-2 text-rose-500 align-top break-all" x-text="(h.old_value || '—').slice(0,60)"></td>
                                                <td class="px-3 py-2 text-emerald-600 align-top break-all" x-text="(h.new_value || '—').slice(0,60)"></td>
                                                <td class="px-3 py-2 text-slate-400 whitespace-nowrap align-top" x-text="h.updated_by_name"></td>
                                            </tr>
                                        </template>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex flex-col sm:flex-row justify-end gap-2 px-5 py-4 border-t bg-slate-50 flex-shrink-0">
                    <button type="button" @click="close()" class="px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-200 rounded-xl">Cancel</button>
                    <button type="submit" name="edit_service" value="1" :disabled="badPrice()"
                            class="px-5 py-2.5 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-xl shadow disabled:opacity-40 disabled:cursor-not-allowed">
                        <i class="fas fa-save mr-1.5"></i>Save Changes
                    </button>
                    <button type="submit" name="edit_then_approve" value="1" :disabled="badPrice()"
                            onclick="return confirm('Save these changes and make the service live now?');"
                            class="px-5 py-2.5 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl shadow disabled:opacity-40 disabled:cursor-not-allowed">
                        <i class="fas fa-check-double mr-1.5"></i>Save &amp; Approve
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ---------- REJECT WITH REASON ---------- -->
    <div x-show="modal==='reject'" x-cloak x-transition.opacity class="fixed inset-0 z-[200] flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="close()"></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>
                <div class="min-w-0">
                    <h3 class="text-white font-bold text-lg">Reject Submission</h3>
                    <p class="text-white/70 text-[11px] truncate" x-text="rej.name"></p>
                </div>
            </div>
            <form method="POST" class="p-5 space-y-4">
                <input type="hidden" name="service_id" :value="rej.id">
                <p class="text-xs text-slate-500">The submission is kept, not deleted. The seller sees your reason, fixes the service and resubmits it.</p>

                <div>
                    <label class="ps-l">Reason <span class="text-rose-500">*</span></label>
                    <textarea name="rejection_reason" x-model="rej.reason" rows="4" required
                              placeholder="e.g. The image is blurry and the description does not mention the commission slab."
                              class="ps-f resize-y"></textarea>
                </div>

                <div>
                    <p class="text-[10px] font-bold uppercase text-slate-400 mb-1.5">Quick reasons</p>
                    <div class="flex flex-wrap gap-1.5">
                        <template x-for="q in quick" :key="q">
                            <button type="button" @click="rej.reason = rej.reason ? rej.reason + ' ' + q : q"
                                    class="px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-[11px] font-semibold text-slate-600" x-text="q"></button>
                        </template>
                    </div>
                </div>

                <div class="flex justify-end gap-2 pt-1">
                    <button type="button" @click="close()" class="px-4 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-100 rounded-xl">Cancel</button>
                    <button type="submit" name="reject_service" :disabled="!rej.reason.trim()"
                            class="px-5 py-2.5 text-sm font-bold text-white bg-rose-600 hover:bg-rose-700 rounded-xl shadow disabled:opacity-40 disabled:cursor-not-allowed">
                        <i class="fas fa-xmark mr-1.5"></i>Reject &amp; Notify Seller
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    [x-cloak] { display: none !important; }
    .ps-lbl { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: #94a3b8; margin-bottom: .5rem; }
    .ps-l   { display:block; font-size: 11px; font-weight: 700; color:#475569; margin-bottom:.25rem; }
    .ps-f   { width:100%; padding:.6rem .75rem; background:#fff; border:1px solid #cbd5e1; border-radius:.75rem; font-size:.8rem; outline:none; transition:box-shadow .15s; }
    .ps-f:focus { box-shadow: 0 0 0 2px rgba(59,130,246,.4); border-color:#3b82f6; }
    .ps-sec { font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:.06em; color:#64748b; border-bottom:1px solid #e2e8f0; padding-bottom:.35rem; margin-top:.5rem; }
</style>

<script>
function psModals() {
    return {
        modal: null,
        loading: false,
        newFile: '',
        f: { history: [] },
        rej: { id: null, name: '', reason: '' },
        subCats: <?php echo json_encode($all_sub_cats, JSON_UNESCAPED_UNICODE); ?>,
        quick: [
            'Image quality is poor.',
            'Description is incomplete.',
            'Pricing looks incorrect.',
            'Wrong category selected.',
            'Website / app link is not working.',
            'Duplicate of an existing service.',
        ],
        subsFor(catId) {
            return this.subCats.filter(s => Number(s.category_id) === Number(catId));
        },
        badPrice() {
            const m = parseFloat(this.f.price) || 0, d = parseFloat(this.f.discount_price) || 0;
            return m > 0 && d > m;
        },
        savings() {
            const m = parseFloat(this.f.price) || 0, d = parseFloat(this.f.discount_price) || 0;
            if (m <= 0 || d <= 0 || d >= m) return 'Customer pays ₹' + ((d > 0 ? d : m) || 0).toFixed(2);
            return 'Customer saves ₹' + (m - d).toFixed(2) + ' (' + Math.round(((m - d) / m) * 100) + '% off)';
        },
        previewUrl() {
            if (Number(this.f.is_img) !== 1 || !this.f.icon_class) return '';
            return String(this.f.icon_class).startsWith('http') ? this.f.icon_class : '../' + this.f.icon_class;
        },
        openEdit(id) {
            this.newFile = '';
            this.f = { id: id, history: [] };
            this.modal = 'edit';
            this.loading = true;
            document.body.style.overflow = 'hidden';
            fetch('pending_services.php?ajax=service&sid=' + id)
                .then(r => r.json())
                .then(d => {
                    this.f = Object.assign({ history: [] }, d || {}, { id: id });
                    // Re-apply the sub-category once its <option> list has been rendered
                    const sub = Number(this.f.sub_category_id) || 0;
                    this.$nextTick(() => { this.f.sub_category_id = sub; });
                })
                .catch(() => {})
                .finally(() => { this.loading = false; });
        },
        openReject(d) {
            this.rej = { id: d.id, name: d.name, reason: '' };
            this.modal = 'reject';
            document.body.style.overflow = 'hidden';
        },
        close() { this.modal = null; document.body.style.overflow = ''; }
    }
}
</script>

</body>
</html>