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

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

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

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

// Fetch categories ONLY if Admin allowed them to show (show_to_seller = 1)
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 AND show_to_seller = 1 ORDER BY display_order ASC");

/* ---------------------------------------------------------------------------
   Which categories may a seller ADD a service to?
   `service_categories.seller_can_add` = 0 means the seller can still SELL and
   USE what is already there, but cannot submit a new service request.
   Government Portals is set to 0 by msimigration.php.
   --------------------------------------------------------------------------- */
$no_add_cats = [];   // category_id => title
try {
    foreach ($db->select("SELECT id, title FROM service_categories WHERE COALESCE(seller_can_add, 1) = 0") as $__nc) {
        $no_add_cats[(int)$__nc['id']] = $__nc['title'];
    }
} catch (\Throwable $e) { /* column not created yet — nothing blocked */ }

function seller_can_add_to($cat_id, $no_add_cats) {
    return !isset($no_add_cats[(int)$cat_id]);
}

// Safely map Seller's Assigned Categories
$sidebar_allowed_cats = [];
// Default to 1 and 5 if the admin hasn't assigned categories to this seller yet to prevent locking them out
$seller_cat_ids = !empty($user['seller_categories']) ? explode(',', $user['seller_categories']) : [1, 5]; 

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

// Check if filtering by a specific category and sub-category
$filter_cat = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;
$filter_sub = isset($_GET['sub_id']) ? intval($_GET['sub_id']) : 0;

$redirect_url = 'services.php';
$qParams = [];
if ($filter_cat > 0) $qParams[] = "cat_id=$filter_cat";
if ($filter_sub > 0) $qParams[] = "sub_id=$filter_sub";
if (!empty($qParams)) $redirect_url .= '?' . implode('&', $qParams);

// Image Upload Helper Function
function handleServiceImageUpload($icon_class_input) {
    $icon_class = $icon_class_input;
    $is_img = (strpos($icon_class, 'http') === 0 || strpos($icon_class, 'uploads/') === 0) ? 1 : 0;

    if (isset($_FILES['image_upload']) && $_FILES['image_upload']['error'] == 0) {
        $upload_dir = '../uploads/services/';
        if (!is_dir($upload_dir)) {
            @mkdir($upload_dir, 0777, true);
        }
        
        $ext = strtolower(pathinfo($_FILES['image_upload']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
        
        if (in_array($ext, $allowed)) {
            $filename = 'srv_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $upload_dir . $filename)) {
                $icon_class = 'uploads/services/' . $filename;
                $is_img = 1;
            }
        }
    }
    return ['icon_class' => $icon_class, 'is_img' => $is_img];
}

// Handle Add Service
if (isset($_POST['add_service'])) {
    $cat_id = intval($_POST['category_id']);

    // Hard block — this category does not accept seller submissions
    if (!seller_can_add_to($cat_id, $no_add_cats)) {
        $_SESSION['flash_error'] = "You cannot add services to " . ($no_add_cats[$cat_id] ?? 'this category')
                                 . ". These services are managed by the admin — you can still use and sell them.";
        redirect($redirect_url);
    }

    $sub_cat_id = isset($_POST['sub_category_id']) ? intval($_POST['sub_category_id']) : 0;
    $title = sanitize($_POST['title']);
    $desc = sanitize($_POST['description']);
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0.00;
    $discount_price = isset($_POST['discount_price']) ? floatval($_POST['discount_price']) : 0.00;
    $color_class = sanitize($_POST['color_class']);
    $web_url = sanitize($_POST['web_url']);
    $app_url = sanitize($_POST['app_url']);
    $tut_url = sanitize($_POST['tutorial_url']);

    // Ensure govt portals bypass price if accidentally sent
    if($cat_id == 1) {
        $price = 0.00;
        $discount_price = 0.00;
    }

    $image_data = handleServiceImageUpload(sanitize($_POST['icon_class'] ?? ''));
    $icon_class = $image_data['icon_class'];
    $is_img = $image_data['is_img'];

    $new_id = $db->insert("INSERT INTO seller_services (seller_id, category_id, sub_category_id, title, description, price, discount_price, is_img, icon_class, color_class, web_url, app_url, tutorial_url, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)",
        [$user_id, $cat_id, $sub_cat_id, $title, $desc, $price, $discount_price, $is_img, $icon_class, $color_class, $web_url, $app_url, $tut_url]);

    if ($new_id) { svc_fulfilment_save($db, (int)$new_id, $user_id, svc_fulfilment_post()); }
    
    $_SESSION['flash_success'] = "Service submitted successfully and is pending admin approval!";
    redirect($redirect_url);
}

/* ---------------------------------------------------------------------------
   HOW THE SELLER WANTS THIS ONE TO SELL
   Online, or an advance here and the rest collected at a visit. The seller
   picks it when they submit the product; the office still has to approve the
   product itself, so nothing goes live unchecked.
   --------------------------------------------------------------------------- */
function svc_fulfilment_post() {
    /* An empty choice is stored as NULL: the product then follows its category,
       and a later change to the category still reaches it. */
    $f  = (string)($_POST['fulfilment'] ?? '');
    if (!in_array($f, ['online', 'visit'], true)) { $f = ''; }
    $am = (string)($_POST['advance_mode'] ?? '');
    if (!in_array($am, ['company', 'fixed', 'percent'], true)) { $am = ''; }
    return [
        'fulfilment'      => $f !== ''  ? $f  : null,
        'advance_mode'    => $am !== '' ? $am : null,
        'advance_amount'  => round((float)($_POST['advance_amount'] ?? 0), 2),
        'advance_percent' => round((float)($_POST['advance_percent'] ?? 0), 2),
        'allow_cart'      => !empty($_POST['allow_cart']) ? 1 : 0,
        'allow_code'      => !empty($_POST['allow_code']) ? 1 : 0,
        'visit_note'      => substr(trim((string)($_POST['visit_note'] ?? '')), 0, 255),
    ];
}

/** Save those seven columns, quietly doing nothing if the migration is not in yet. */
function svc_fulfilment_save($db, $service_id, $seller_id, $v) {
    try {
        $db->insert(
            "UPDATE seller_services
                SET fulfilment = ?, advance_mode = ?, advance_amount = ?, advance_percent = ?,
                    allow_cart = ?, allow_code = ?, visit_note = ?
              WHERE id = ? AND seller_id = ?",
            [$v['fulfilment'], $v['advance_mode'], $v['advance_amount'], $v['advance_percent'],
             $v['allow_cart'], $v['allow_code'], $v['visit_note'] !== '' ? $v['visit_note'] : null,
             (int)$service_id, (int)$seller_id]);
    } catch (\Throwable $e) { /* ordmigration.php has not been run yet */ }
}

// Handle Edit Service
if (isset($_POST['edit_service'])) {
    $service_id = intval($_POST['service_id']);
    $cat_id = intval($_POST['category_id']);

    // Cannot move a service INTO a category that blocks seller submissions
    if (!seller_can_add_to($cat_id, $no_add_cats)) {
        $_SESSION['flash_error'] = "Services cannot be moved into " . ($no_add_cats[$cat_id] ?? 'this category') . ".";
        redirect($redirect_url);
    }

    $sub_cat_id = isset($_POST['sub_category_id']) ? intval($_POST['sub_category_id']) : 0;
    $title = sanitize($_POST['title']);
    $desc = sanitize($_POST['description']);
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0.00;
    $discount_price = isset($_POST['discount_price']) ? floatval($_POST['discount_price']) : 0.00;
    $color_class = sanitize($_POST['color_class']);
    $web_url = sanitize($_POST['web_url']);
    $app_url = sanitize($_POST['app_url']);
    $tut_url = sanitize($_POST['tutorial_url']);

    if($cat_id == 1) {
        $price = 0.00;
        $discount_price = 0.00;
    }

    $image_data = handleServiceImageUpload(sanitize($_POST['icon_class'] ?? ''));
    $icon_class = $image_data['icon_class'];
    $is_img = $image_data['is_img'];

    // status = 0 added to query so edited services go back to pending state for admin review
    $db->insert("UPDATE seller_services SET category_id=?, sub_category_id=?, title=?, description=?, price=?, discount_price=?, is_img=?, icon_class=?, color_class=?, web_url=?, app_url=?, tutorial_url=?, status=0 WHERE id=? AND seller_id=?",
        [$cat_id, $sub_cat_id, $title, $desc, $price, $discount_price, $is_img, $icon_class, $color_class, $web_url, $app_url, $tut_url, $service_id, $user_id]);

    // A resubmitted service is a fresh request — drop the old rejection reason
    try {
        $db->insert("UPDATE seller_services SET rejection_reason = NULL WHERE id = ? AND seller_id = ?", [$service_id, $user_id]);
    } catch (\Throwable $e) { /* column may not exist until the migration runs */ }

    svc_fulfilment_save($db, $service_id, $user_id, svc_fulfilment_post());

    $_SESSION['flash_success'] = "Service updated successfully and is now pending admin approval!";
    redirect($redirect_url);
}

// Handle Delete Service
if (isset($_POST['delete_service'])) {
    $service_id = intval($_POST['service_id']);
    
    $service_data = $db->select("SELECT icon_class, is_img FROM seller_services WHERE id = ? AND seller_id = ?", [$service_id, $user_id]);
    if (!empty($service_data) && $service_data[0]['is_img'] == 1 && strpos($service_data[0]['icon_class'], 'uploads/') === 0) {
        $file_path = '../' . $service_data[0]['icon_class'];
        if (file_exists($file_path)) { @unlink($file_path); }
    }

    $db->insert("DELETE FROM seller_services WHERE id = ? AND seller_id = ?", [$service_id, $user_id]);
    $_SESSION['flash_success'] = "Service deleted successfully!";
    redirect($redirect_url);
}

$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);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : '../' . ltrim($company_logo, '/');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

// Fetch Sub Categories globally for Alpine
$sub_cats = $db->select("SELECT * FROM agency_sub_categories WHERE status = 1 ORDER BY id ASC");

// Fetch Services (Filtered by cat_id and optionally sub_id)
$cat_sub_categories = [];
if ($filter_cat > 0) {
    // Check if this category has sub-categories
    $cat_sub_categories = $db->select("SELECT * FROM agency_sub_categories WHERE category_id = ? AND status = 1 ORDER BY id ASC", [$filter_cat]);
    
    if (!empty($cat_sub_categories)) {
        if ($filter_sub > 0) {
            $my_services = $db->select("SELECT ss.*, sc.title as cat_name, sub.title as sub_cat_name FROM seller_services ss JOIN service_categories sc ON ss.category_id = sc.id LEFT JOIN agency_sub_categories sub ON ss.sub_category_id = sub.id WHERE ss.seller_id = ? AND ss.category_id = ? AND ss.sub_category_id = ? ORDER BY ss.id DESC", [$user_id, $filter_cat, $filter_sub]);
        } else {
            $my_services = []; // Display nothing until sub-category is chosen
        }
    } else {
        $my_services = $db->select("SELECT ss.*, sc.title as cat_name, sub.title as sub_cat_name FROM seller_services ss JOIN service_categories sc ON ss.category_id = sc.id LEFT JOIN agency_sub_categories sub ON ss.sub_category_id = sub.id WHERE ss.seller_id = ? AND ss.category_id = ? ORDER BY ss.id DESC", [$user_id, $filter_cat]);
    }
} else {
    $my_services = $db->select("SELECT ss.*, sc.title as cat_name, sub.title as sub_cat_name FROM seller_services ss JOIN service_categories sc ON ss.category_id = sc.id LEFT JOIN agency_sub_categories sub ON ss.sub_category_id = sub.id WHERE ss.seller_id = ? ORDER BY ss.id DESC", [$user_id]);
}

$show_add_btn = false;
if (!empty($sidebar_allowed_cats)) {
    if ($filter_cat > 0 && !empty($cat_sub_categories)) {
        if ($filter_sub > 0) $show_add_btn = true;
    } else {
        $show_add_btn = true;
    }
}
// Never offer "Add" inside a category the admin has locked for sellers
$cat_locked = ($filter_cat > 0 && !seller_can_add_to($filter_cat, $no_add_cats));
if ($cat_locked) { $show_add_btn = false; }

// Categories this seller may actually submit a new service to
$addable_cats = [];
foreach ($sidebar_allowed_cats as $__c) {
    if (seller_can_add_to($__c['id'], $no_add_cats)) $addable_cats[] = $__c;
}
$no_addable = empty($addable_cats);
if ($no_addable) { $show_add_btn = false; }
// Label used by the amber notice below
$locked_notice = $cat_locked ? ($no_add_cats[$filter_cat] ?? 'These') : ($no_addable ? 'Your assigned' : '');
?>
<!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>My Services - WBMCZ Seller</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=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Inter', sans-serif; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; }</style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
if (isset($categories)) { $__ids = isset($seller_cat_ids) ? $seller_cat_ids : null; foreach ($categories as $__c) { if ($__ids === null || in_array($__c['id'], $__ids)) $__scats[] = $__c; } }
$__menu = theme_seller_menu($__scats);

// Service add/edit form state (Alpine) — built here so PHP values interpolate correctly
$__blank = "{ id: '', category_id: '" . ($filter_cat > 0 ? $filter_cat : '') . "', sub_category_id: " . ($filter_sub > 0 ? $filter_sub : 0)
         . ", title: '', description: '', price: '0.00', discount_price: '0.00', icon_class: '', color_class: 'color-1', web_url: '', app_url: '', tutorial_url: ''"
         . ", fulfilment: '', advance_mode: '', advance_amount: '0.00', advance_percent: '0.00'"
         . ", allow_cart: true, allow_code: true, visit_note: '' }";
$__svc_state = "addModal: false, formMode: 'add', subCategories: " . json_encode($sub_cats)
    . ", formData: " . $__blank
    . ", hasSubCategories(catId) { return this.subCategories.some(sc => sc.category_id == catId); }"
    . ", openAddModal() { this.formMode = 'add'; this.formData = " . $__blank . "; this.addModal = true; }"
    . ", openEditModal(service) { this.formMode = 'edit'; var d = { ...service };"
    . "   d.fulfilment = (d.fulfilment === 'visit' || d.fulfilment === 'online') ? d.fulfilment : '';"
    . "   d.advance_mode = d.advance_mode || '';"
    . "   d.allow_cart = (d.allow_cart === undefined) ? true : (String(d.allow_cart) === '1');"
    . "   d.allow_code = (d.allow_code === undefined) ? true : (String(d.allow_code) === '1');"
    . "   this.formData = d; this.addModal = true; }";

theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'My Services',
    'active' => 'services',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : '../assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => $__svc_state,
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-8">
                
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800 mb-1">
                            <?php 
                            if ($filter_cat > 0) {
                                $found = false;
                                foreach($sidebar_allowed_cats as $c) { 
                                    if($c['id'] == $filter_cat) { 
                                        echo htmlspecialchars($c['title']); 
                                        $found = true;
                                        break; 
                                    } 
                                }
                                if(!$found) echo "Filtered Services";
                            } else {
                                echo "All My Services";
                            }
                            ?>
                        </h2>
                        <p class="text-gray-500 text-sm">Add, edit, or remove the services you offer to customers.</p>
                    </div>
                    <?php if($show_add_btn): ?>
                    <button @click="openAddModal()" class="bg-teal-600 hover:bg-teal-700 text-white px-5 py-2.5 rounded-xl font-bold shadow-md transition-colors flex items-center">
                        <i class="fas fa-plus-circle mr-2 text-lg"></i> Add New Service
                    </button>
                    <?php elseif($cat_locked || $no_addable): ?>
                    <span class="inline-flex items-center gap-2 bg-slate-100 text-slate-500 px-5 py-2.5 rounded-xl font-bold border border-slate-200 cursor-not-allowed select-none">
                        <i class="fas fa-lock"></i> Adding Not Allowed
                    </span>
                    <?php endif; ?>
                </div>

                <?php if($cat_locked || $no_addable): ?>
                <div class="mb-6 bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3.5 rounded-xl flex items-start gap-3 shadow-sm">
                    <i class="fas fa-circle-info mt-0.5 text-lg text-amber-500"></i>
                    <div class="text-sm leading-relaxed">
                        <b><?php echo htmlspecialchars($locked_notice); ?></b> services are managed by the admin —
                        sellers cannot submit a new service request<?php echo $cat_locked ? ' in this category' : ''; ?>.
                        <span class="block mt-0.5 text-amber-700/90">You can still <b>use</b> and <b>sell</b> every service listed here as usual.</span>
                    </div>
                </div>
                <?php endif; ?>

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

                <?php if ($filter_cat > 0 && !empty($cat_sub_categories)): ?>
                    <div class="mb-6 bg-white p-4 sm:p-5 rounded-2xl shadow-sm border border-gray-200">
                        <h3 class="text-sm font-bold text-gray-700 mb-3"><i class="fas fa-filter text-teal-500 mr-2"></i>Select a Sub-Category</h3>
                        <div class="flex flex-wrap gap-2 sm:gap-3">
                            <?php foreach($cat_sub_categories as $csc): ?>
                                <a href="services.php?cat_id=<?php echo $filter_cat; ?>&sub_id=<?php echo $csc['id']; ?>" 
                                   class="px-4 py-2 sm:px-5 sm:py-2.5 rounded-xl text-xs sm:text-sm font-bold transition-all border shadow-sm flex items-center <?php echo $filter_sub == $csc['id'] ? 'bg-teal-600 text-white border-teal-600 ring-2 ring-teal-200 ring-offset-1' : 'bg-white text-gray-700 border-gray-200 hover:bg-teal-50 hover:text-teal-700 hover:border-teal-300'; ?>">
                                    <i class="fas <?php echo htmlspecialchars($csc['icon_class']); ?> mr-2"></i>
                                    <?php echo htmlspecialchars($csc['title']); ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($filter_cat > 0 && !empty($cat_sub_categories) && $filter_sub == 0): ?>
                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden p-12 text-center">
                         <div class="w-20 h-20 bg-teal-50 rounded-full flex items-center justify-center mx-auto mb-5 text-teal-400 text-3xl border border-teal-100">
                             <i class="fas fa-hand-pointer"></i>
                         </div>
                         <h3 class="text-xl font-bold text-gray-800 mb-2">Select a Sub-Category</h3>
                         <p class="text-sm font-medium text-gray-500">Please choose a sub-category from the list above to view or add services.</p>
                    </div>
                <?php else: ?>
                    <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-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                        <th class="p-4 pl-6 font-semibold">Service Details</th>
                                        <th class="p-4 font-semibold">Category & Status</th>
                                        <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-50">
                                    <?php if(!empty($my_services)): foreach($my_services as $srv): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="p-4 pl-6 flex items-center">
                                            <div class="w-10 h-10 rounded-xl bg-gray-100 border border-gray-200 flex items-center justify-center mr-4 flex-shrink-0 overflow-hidden">
                                                <?php if($srv['is_img'] == 1): ?>
                                                    <?php $img_src = (strpos($srv['icon_class'], 'http') === 0) ? $srv['icon_class'] : '../' . $srv['icon_class']; ?>
                                                    <img src="<?php echo htmlspecialchars($img_src); ?>" class="w-full h-full object-cover">
                                                <?php else: ?>
                                                    <i class="fa-solid <?php echo htmlspecialchars($srv['icon_class']); ?> text-lg text-teal-600"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div>
                                                <p class="font-bold text-sm text-gray-800"><?php echo htmlspecialchars($srv['title']); ?></p>
                                                <p class="text-xs text-gray-500 truncate max-w-[200px]"><?php echo htmlspecialchars($srv['description']); ?></p>
                                                <?php if($srv['category_id'] != 1 && ($srv['price'] > 0 || $srv['discount_price'] > 0)): ?>
                                                    <div class="mt-1 flex items-center gap-2">
                                                        <?php if($srv['discount_price'] > 0): ?>
                                                            <span class="text-xs font-bold text-teal-600">₹<?php echo number_format($srv['discount_price'], 2); ?></span>
                                                            <span class="text-[10px] text-gray-400 line-through">₹<?php echo number_format($srv['price'], 2); ?></span>
                                                        <?php else: ?>
                                                            <span class="text-xs font-bold text-teal-600">₹<?php echo number_format($srv['price'], 2); ?></span>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="p-4 text-xs font-bold text-gray-600">
                                            <div class="mb-2">
                                                <span class="bg-gray-100 px-2 py-1 rounded-md border border-gray-200 inline-block mb-1 w-max"><?php echo htmlspecialchars($srv['cat_name']); ?></span>
                                                <?php if(!empty($srv['sub_cat_name'])): ?>
                                                    <span class="text-[10px] font-semibold text-gray-400 block ml-1"><i class="fas fa-level-up-alt rotate-90 mr-1"></i><?php echo htmlspecialchars($srv['sub_cat_name']); ?></span>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if($srv['status'] == 1): ?>
                                                <span class="bg-emerald-100 text-emerald-700 px-2 py-1 rounded text-[10px] uppercase tracking-wider"><i class="fas fa-check-circle mr-1"></i> Approved</span>
                                            <?php elseif($srv['status'] == 2): ?>
                                                <span class="bg-rose-100 text-rose-700 px-2 py-1 rounded text-[10px] uppercase tracking-wider"><i class="fas fa-circle-xmark mr-1"></i> Rejected</span>
                                                <?php if(!empty($srv['rejection_reason'])): ?>
                                                    <div class="mt-2 bg-rose-50 border border-rose-200 rounded-lg p-2.5 max-w-[260px]">
                                                        <p class="text-[9px] font-bold uppercase tracking-wider text-rose-400 mb-1">Why it was rejected</p>
                                                        <p class="text-[11px] text-rose-800 font-semibold normal-case whitespace-pre-wrap leading-snug"><?php echo htmlspecialchars(html_entity_decode($srv['rejection_reason'], ENT_QUOTES)); ?></p>
                                                        <p class="text-[10px] text-rose-500 mt-1.5 font-normal normal-case"><i class="fas fa-pen-to-square mr-1"></i>Edit this service to fix it — it goes back for review automatically.</p>
                                                    </div>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="bg-yellow-100 text-yellow-700 px-2 py-1 rounded text-[10px] uppercase tracking-wider"><i class="fas fa-clock mr-1"></i> Pending</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-4 pr-6 text-right space-x-2 whitespace-nowrap">
                                            <button @click="openEditModal(<?php echo htmlspecialchars(json_encode($srv)); ?>)" class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors inline-flex items-center justify-center tooltip" title="Edit Service">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" onsubmit="return confirm('Are you sure you want to delete this service?');" class="inline-block">
                                                <input type="hidden" name="service_id" value="<?php echo $srv['id']; ?>">
                                                <button type="submit" name="delete_service" class="w-8 h-8 rounded-lg bg-rose-50 text-rose-600 hover:bg-rose-100 transition-colors inline-flex items-center justify-center tooltip" title="Delete Service">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; else: ?>
                                        <tr>
                                            <td colspan="3" 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-300 text-2xl border border-gray-100">
                                                    <i class="fas fa-layer-group"></i>
                                                </div>
                                                <p class="text-lg font-medium">You haven't added any services to this category yet.</p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>

    <div x-show="addModal" 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="addModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col border border-gray-100">
            
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50 flex-shrink-0">
                <h3 class="font-bold text-gray-900 text-lg flex items-center">
                    <i class="fas fa-layer-group text-teal-600 mr-2"></i> 
                    <span x-text="formMode === 'add' ? 'Add New Service' : 'Edit Service'"></span>
                </h3>
                <button @click="addModal = false" class="text-gray-400 hover:text-rose-500 transition-colors"><i class="fas fa-times text-xl"></i></button>
            </div>
            
            <div class="p-6 overflow-y-auto flex-1">
                <form method="POST" enctype="multipart/form-data" class="space-y-6">
                    <input type="hidden" name="service_id" x-model="formData.id">
                    
                    <?php if ($filter_cat > 0): ?>
                        <input type="hidden" name="category_id" x-model="formData.category_id" required>
                        <div class="mb-6 p-4 bg-teal-50 border border-teal-200 rounded-xl flex items-center shadow-sm">
                            <?php 
                            $cat_title = ''; $cat_icon = '';
                            foreach($sidebar_allowed_cats as $c) { 
                                if($c['id'] == $filter_cat) { $cat_title = $c['title']; $cat_icon = $c['icon_class']; break; } 
                            }
                            ?>
                            <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-sm border border-teal-100 mr-4">
                                <i class="fas <?php echo $cat_icon; ?> text-teal-600 text-xl"></i>
                            </div>
                            <div>
                                <p class="text-[10px] text-teal-600 font-bold uppercase tracking-widest mb-0.5">Adding to Category</p>
                                <p class="text-lg font-bold text-teal-900 leading-none"><?php echo htmlspecialchars($cat_title); ?></p>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="mb-2" x-show="formMode === 'add'">
                            <label class="block text-sm font-bold mb-3 text-gray-700">1. Select Main Category <span class="text-rose-500">*</span></label>
                            <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
                                <?php foreach($addable_cats as $cat): ?>
                                <div @click="formData.category_id = <?php echo $cat['id']; ?>; formData.sub_category_id = 0;"
                                     :class="formData.category_id == <?php echo $cat['id']; ?> ? 'ring-2 ring-teal-500 border-teal-500 shadow-md scale-[1.02] bg-teal-50/30' : 'border-gray-200 hover:shadow-md hover:border-teal-300 cursor-pointer'"
                                     class="bg-white rounded-2xl p-4 text-center border transition-all duration-200 flex flex-col items-center justify-center relative overflow-hidden">
                                    <div class="w-12 h-12 rounded-2xl flex items-center justify-center mb-3 bg-gradient-to-br <?php echo htmlspecialchars($cat['gradient_class']); ?> text-white shadow-sm">
                                        <i class="fas <?php echo htmlspecialchars($cat['icon_class']); ?> text-xl"></i>
                                    </div>
                                    <h3 class="font-bold text-xs sm:text-sm text-gray-800 leading-tight">
                                        <?php echo $lang->translate($cat['category_key'], $cat['title']); ?>
                                    </h3>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="category_id" x-model="formData.category_id" required>
                        </div>
                    <?php endif; ?>

                    <div x-show="hasSubCategories(formData.category_id)" x-transition.opacity.duration.300ms class="bg-purple-50 p-4 rounded-2xl border border-purple-100" style="display:none;">
                        <label class="block text-sm font-bold mb-3 text-purple-900">2. Select Sub-Category <span class="text-rose-500">*</span></label>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 max-h-48 overflow-y-auto pr-2 hide-scrollbar">
                            <template x-for="sc in subCategories.filter(s => s.category_id == formData.category_id)" :key="sc.id">
                                <div @click="formData.sub_category_id = sc.id" 
                                     :class="formData.sub_category_id == sc.id ? 'ring-2 ring-purple-500 border-purple-500 shadow-md bg-white' : 'border-purple-200 bg-white/60 hover:shadow-sm hover:border-purple-300'"
                                     class="cursor-pointer rounded-xl p-3 text-center border transition-all duration-200 flex flex-col items-center justify-center">
                                    <div :class="'w-8 h-8 rounded-lg flex items-center justify-center mb-2 shadow-sm text-white bg-gradient-to-br ' + sc.gradient_class">
                                        <i :class="'fas text-sm ' + sc.icon_class"></i>
                                    </div>
                                    <h3 class="font-bold text-[10px] sm:text-xs text-gray-800 leading-tight" x-text="sc.title"></h3>
                                </div>
                            </template>
                        </div>
                        <input type="hidden" name="sub_category_id" x-model="formData.sub_category_id">
                    </div>

                    <div class="bg-gray-50 p-5 rounded-2xl border border-gray-100 space-y-4">
                        <h4 class="font-bold text-gray-800 border-b border-gray-200 pb-2 mb-4">Service Details</h4>
                        
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Service Title <span class="text-rose-500">*</span></label>
                            <input type="text" name="title" x-model="formData.title" required placeholder="e.g. PAN Agency Portal" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow">
                        </div>
                        
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Short Description</label>
                            <textarea name="description" x-model="formData.description" rows="2" placeholder="Write a short engaging description..." class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow resize-none"></textarea>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4" x-show="formData.category_id != 1">
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Regular Price (₹)</label>
                                <input type="number" step="0.01" name="price" x-model="formData.price" placeholder="0.00" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Discount/Sale Price (₹)</label>
                                <input type="number" step="0.01" name="discount_price" x-model="formData.discount_price" placeholder="0.00" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow">
                            </div>
                        </div>
                    </div>

                    <div class="bg-gray-50 p-5 rounded-2xl border border-gray-100 space-y-4">
                        <h4 class="font-bold text-gray-800 border-b border-gray-200 pb-2 mb-4">Media & Links</h4>
                        
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Upload Service Image <span class="text-rose-500">*</span></label>
                                <div class="space-y-3">
                                    <input type="file" name="image_upload" accept="image/*" class="w-full px-4 py-2 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow text-sm">
                                    
                                    <div class="flex items-center text-xs text-gray-400 font-bold uppercase tracking-widest">
                                        <span class="flex-1 border-t border-gray-200"></span>
                                        <span class="px-3">OR use text link</span>
                                        <span class="flex-1 border-t border-gray-200"></span>
                                    </div>
                                    
                                    <input type="text" name="icon_class" x-model="formData.icon_class" placeholder="fa-id-card OR https://..." class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Card Color Theme</label>
                                <select name="color_class" x-model="formData.color_class" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow">
                                    <option value="color-1">Red Theme</option>
                                    <option value="color-2">Blue Theme</option>
                                    <option value="color-3">Green Theme</option>
                                    <option value="color-4">Orange Theme</option>
                                    <option value="color-5">Purple Theme</option>
                                </select>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 pt-2">
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Website URL</label>
                                <input type="url" name="web_url" x-model="formData.web_url" placeholder="https://" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">App URL</label>
                                <input type="url" name="app_url" x-model="formData.app_url" placeholder="https://" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow text-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1"><i class="fa-brands fa-youtube text-rose-500 mr-1"></i> Video URL <span class="text-gray-400 font-normal">(optional — YouTube, shows at top of popup)</span></label>
                                <input type="url" name="tutorial_url" x-model="formData.tutorial_url" placeholder="https://youtu.be/..." class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 outline-none transition-shadow text-sm">
                            </div>
                        </div>
                    </div>

                    <!-- ============ how this service is delivered ============
                         Online, or an advance now and the rest taken at a visit.
                         The office still approves the product itself, so nothing
                         reaches customers unchecked. -->
                    <div class="pt-4 border-t border-gray-100">
                        <label class="block text-xs font-bold text-gray-700 mb-2">How is this service delivered?</label>
                        <input type="hidden" name="fulfilment" :value="formData.fulfilment || ''">
                        <div class="grid grid-cols-3 gap-2">
                            <button type="button" @click="formData.fulfilment = ''"
                                    class="py-3 rounded-xl text-[11px] font-black border-2 transition-all"
                                    :class="!formData.fulfilment ? 'border-slate-800 bg-slate-100 text-slate-800' : 'border-gray-200 text-gray-500'">
                                <i class="fas fa-layer-group mr-1"></i> AS THE CATEGORY
                            </button>
                            <button type="button" @click="formData.fulfilment = 'online'"
                                    class="py-3 rounded-xl text-[11px] font-black border-2 transition-all"
                                    :class="formData.fulfilment === 'online' ? 'border-teal-500 bg-teal-50 text-teal-700' : 'border-gray-200 text-gray-500'">
                                <i class="fas fa-bolt mr-1"></i> FULL PAYMENT
                            </button>
                            <button type="button" @click="formData.fulfilment = 'visit'"
                                    class="py-3 rounded-xl text-[11px] font-black border-2 transition-all"
                                    :class="formData.fulfilment === 'visit' ? 'border-amber-500 bg-amber-50 text-amber-700' : 'border-gray-200 text-gray-500'">
                                <i class="fas fa-person-walking mr-1"></i> I VISIT &amp; COLLECT
                            </button>
                        </div>
                        <p class="text-[11px] text-gray-400 mt-1.5">
                            Left on <b>As the category</b>, this follows however the office sells that category.
                        </p>

                        <div x-show="formData.fulfilment === 'visit'" class="mt-3 space-y-3 rounded-xl border border-amber-200 bg-amber-50/50 p-3">
                            <p class="text-[11px] text-amber-800 leading-snug">
                                The customer pays a booking amount on the site and you take the rest when you go.
                                Left on the recommended setting, the booking amount is the company's share, so what you
                                collect is exactly what you earn and nothing has to be handed over afterwards.
                            </p>
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Booking amount</label>
                                <select name="advance_mode" x-model="formData.advance_mode" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl text-sm outline-none focus:ring-2 focus:ring-amber-500">
                                    <option value="">Whatever the category says</option>
                                    <option value="company">The company's share &mdash; recommended</option>
                                    <option value="fixed">A fixed amount</option>
                                    <option value="percent">A percentage of the price</option>
                                </select>
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <div x-show="formData.advance_mode === 'fixed'">
                                    <label class="block text-xs font-bold text-gray-700 mb-1">Booking &#8377;</label>
                                    <input type="number" step="0.01" min="0" name="advance_amount" x-model="formData.advance_amount" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl text-sm outline-none focus:ring-2 focus:ring-amber-500">
                                </div>
                                <div x-show="formData.advance_mode === 'percent'">
                                    <label class="block text-xs font-bold text-gray-700 mb-1">Booking %</label>
                                    <input type="number" step="0.01" min="0" max="100" name="advance_percent" x-model="formData.advance_percent" class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl text-sm outline-none focus:ring-2 focus:ring-amber-500">
                                </div>
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">What should the customer expect?</label>
                                <input name="visit_note" x-model="formData.visit_note" maxlength="255"
                                       placeholder="I will come to your address with the papers"
                                       class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl text-sm outline-none focus:ring-2 focus:ring-amber-500">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-3">
                            <label class="flex items-center gap-2.5 rounded-xl border border-gray-200 p-3 cursor-pointer hover:bg-gray-50">
                                <input type="checkbox" name="allow_cart" value="1" x-model="formData.allow_cart" class="accent-teal-600">
                                <span class="text-xs font-bold text-gray-700">Can go in the cart
                                    <span class="block font-normal text-[11px] text-gray-400">Untick if it has to be bought on its own</span>
                                </span>
                            </label>
                            <label class="flex items-center gap-2.5 rounded-xl border border-gray-200 p-3 cursor-pointer hover:bg-gray-50">
                                <input type="checkbox" name="allow_code" value="1" x-model="formData.allow_code" class="accent-teal-600">
                                <span class="text-xs font-bold text-gray-700">Payment code allowed
                                    <span class="block font-normal text-[11px] text-gray-400">Customer can pay at the counter against a code</span>
                                </span>
                            </label>
                        </div>
                    </div>

                    <div class="pt-4 flex gap-3">
                        <button type="button" @click="addModal = false" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold py-3.5 rounded-xl transition-colors">Cancel</button>
                        
                        <button type="submit" name="add_service" x-show="formMode === 'add'" class="flex-[2] bg-teal-600 hover:bg-teal-700 text-white font-bold py-3.5 rounded-xl shadow-md transition-colors flex items-center justify-center" :disabled="!formData.category_id || (hasSubCategories(formData.category_id) && !formData.sub_category_id)">
                            <i class="fas fa-plus-circle mr-2"></i> Save New Service
                        </button>
                        
                        <button type="submit" name="edit_service" x-show="formMode === 'edit'" class="flex-[2] bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl shadow-md transition-colors flex items-center justify-center" style="display:none;" :disabled="!formData.category_id || (hasSubCategories(formData.category_id) && !formData.sub_category_id)">
                            <i class="fas fa-save mr-2"></i> Update Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
</html>