<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/admin_list.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."); }

/* ---------------------------------------------------------------------------
   EVERY CATEGORY HAS ITS OWN PAGES

   The catalogue and the seller-submission queue are both split one page per
   category, so a category that has just been created needs its two files
   writing before anybody can open it. That happens here, on the screen where
   categories are managed, so nobody has to remember to do it.

   Files that already exist are left alone, and a folder that cannot be written
   to is not an error — the menu falls back to the shared ?cat= pages.
   --------------------------------------------------------------------------- */
require_once __DIR__ . '/../includes/product_pages.php';
$SVC_PAGES = pmp_sync($db, __DIR__);

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

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

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

// ---------------------------------------------------------
// 1. Handle Main Services (Categories)
// ---------------------------------------------------------
if (isset($_POST['edit_main_cat'])) {
    $id = intval($_POST['cat_id']);
    $title = sanitize($_POST['title']);
    $desc = sanitize($_POST['description']);
    $icon = sanitize($_POST['icon_class']);
    $gradient = sanitize($_POST['gradient_class']);
    $order = intval($_POST['display_order']);
    $show = isset($_POST['show_to_seller']) ? 1 : 0;
    $can_add = isset($_POST['seller_can_add']) ? 1 : 0;
    $status = intval($_POST['status']);

    $db->insert("UPDATE service_categories SET title=?, description=?, icon_class=?, gradient_class=?, display_order=?, show_to_seller=?, status=? WHERE id=?", 
        [$title, $desc, $icon, $gradient, $order, $show, $status, $id]);

    // Seller add-permission (column created by msimigration.php)
    try {
        $db->insert("UPDATE service_categories SET seller_can_add=? WHERE id=?", [$can_add, $id]);
    } catch (\Throwable $e) { /* column not created yet */ }

    /* ---- how products in this category sell, unless a product says otherwise ----
       This is the switch the office asked for: pick a category, say that its
       services are sold with a visit, and every product under it follows —
       except the ones that were deliberately set the other way. Columns come
       from ordmigration.php, so the whole block stays quiet without it. */
    try {
        $ful = (($_POST['cat_fulfilment'] ?? 'online') === 'visit') ? 'visit' : 'online';
        $am  = (string)($_POST['cat_advance_mode'] ?? 'company');
        if (!in_array($am, ['company', 'fixed', 'percent'], true)) { $am = 'company'; }
        $db->insert("UPDATE service_categories
                        SET fulfilment = ?, advance_mode = ?, advance_amount = ?, advance_percent = ?
                      WHERE id = ?",
            [$ful, $am, round((float)($_POST['cat_advance_amount'] ?? 0), 2),
             round((float)($_POST['cat_advance_percent'] ?? 0), 2), $id]);

        /* "apply to every product in this category" — only when it is asked for */
        if (!empty($_POST['cat_apply_all'])) {
            $db->insert("UPDATE seller_services SET fulfilment = ?, advance_mode = ?, advance_amount = ?, advance_percent = ?
                          WHERE category_id = ?",
                [$ful, $am, round((float)($_POST['cat_advance_amount'] ?? 0), 2),
                 round((float)($_POST['cat_advance_percent'] ?? 0), 2), $id]);
        }
    } catch (\Throwable $e) { /* ordmigration.php has not been run yet */ }
    
    $_SESSION['flash_success'] = "Main Category updated successfully!";
    redirect('services.php#main_cats');
}

// ---------------------------------------------------------
// 2. Handle Sub-Categories
//    Only an admin or a staff member holding "Manage Services" can create,
//    rename or delete a sub-category. Sellers never can — they pick from the
//    list when they load a product, and that is all.
// ---------------------------------------------------------
require_once __DIR__ . '/../includes/rbac.php';
if (isset($_POST['add_sub_cat']) || isset($_POST['edit_sub_cat']) || isset($_POST['delete_sub_cat'])) {
    if (!isAdmin() || !rbac_can('manage_services')) {
        $_SESSION['flash_error'] = 'Sub-categories can only be managed by an administrator or a staff member with Service access.';
        redirect('services.php#sub_cats');
    }
}

if (isset($_POST['add_sub_cat'])) {
    $cat_id = intval($_POST['category_id']);
    $title = sanitize($_POST['title']);
    $icon = sanitize($_POST['icon_class']);
    $gradient = sanitize($_POST['gradient_class']);
    $status = intval($_POST['status']);
    
    $db->insert("INSERT INTO agency_sub_categories (category_id, title, icon_class, gradient_class, status) VALUES (?, ?, ?, ?, ?)", [$cat_id, $title, $icon, $gradient, $status]);
    $_SESSION['flash_success'] = "Sub-Category added successfully!";
    redirect('services.php#sub_cats');
}
if (isset($_POST['edit_sub_cat'])) {
    $id = intval($_POST['id']);
    $cat_id = intval($_POST['category_id']);
    $title = sanitize($_POST['title']);
    $icon = sanitize($_POST['icon_class']);
    $gradient = sanitize($_POST['gradient_class']);
    $status = intval($_POST['status']);
    
    $db->insert("UPDATE agency_sub_categories SET category_id=?, title=?, icon_class=?, gradient_class=?, status=? WHERE id=?", [$cat_id, $title, $icon, $gradient, $status, $id]);
    $_SESSION['flash_success'] = "Sub-Category updated successfully!";
    redirect('services.php#sub_cats');
}
if (isset($_POST['delete_sub_cat'])) {
    $id = intval($_POST['id']);
    $db->insert("DELETE FROM agency_sub_categories WHERE id=?", [$id]);
    $_SESSION['flash_success'] = "Sub-Category deleted successfully!";
    redirect('services.php#sub_cats');
}

// Fetch Data for Tables
/* ---------------- STICKY FILTERS ---------------- */
$SV_DEFAULTS = ['q' => '', 'cat' => '', 'status' => ''];
$SV = alist_filters('services', $SV_DEFAULTS);

$cat_where = "1"; $cat_params = [];
if ($SV['q'] !== '')      { $cat_where .= " AND title LIKE ?"; $cat_params[] = "%{$SV['q']}%"; }
if ($SV['status'] !== '') { $cat_where .= " AND status = ?";   $cat_params[] = (int)$SV['status']; }

$sub_where = "1"; $sub_params = [];
if ($SV['q'] !== '')      { $sub_where .= " AND (a.title LIKE ? OR c.title LIKE ?)"; $l = "%{$SV['q']}%"; $sub_params[] = $l; $sub_params[] = $l; }
if ($SV['cat'] !== '')    { $sub_where .= " AND a.category_id = ?"; $sub_params[] = (int)$SV['cat']; }
if ($SV['status'] !== '') { $sub_where .= " AND a.status = ?";      $sub_params[] = (int)$SV['status']; }

/* ---------------- CSV EXPORT ---------------- */
if (isset($_GET['export'])) {
    $what = ($_GET['export'] === 'sub') ? 'sub' : 'cat';
    if ($what === 'cat') {
        $rows = $db->select("SELECT * FROM service_categories WHERE $cat_where ORDER BY display_order ASC", $cat_params);
        alist_export_csv('service_categories', [
            'ID' => 'id', 'Title' => 'title', 'Icon' => 'icon_class',
            'Gradient' => 'gradient_class', 'Order' => 'display_order',
            'Status' => function ($r) { return (int)$r['status'] === 1 ? 'Active' : 'Inactive'; },
        ], $rows);
    } else {
        $rows = $db->select("SELECT a.*, c.title AS main_cat_name FROM agency_sub_categories a
                             JOIN service_categories c ON a.category_id = c.id
                             WHERE $sub_where ORDER BY a.id DESC", $sub_params);
        alist_export_csv('service_sub_categories', [
            'ID' => 'id', 'Sub Category' => 'title', 'Main Category' => 'main_cat_name',
            'Icon' => 'icon_class', 'Gradient' => 'gradient_class',
            'Status' => function ($r) { return (int)$r['status'] === 1 ? 'Active' : 'Inactive'; },
        ], $rows);
    }
}

$main_categories = $db->select("SELECT * FROM service_categories WHERE $cat_where ORDER BY display_order ASC", $cat_params);
$all_main_cats   = $db->select("SELECT id, title FROM service_categories ORDER BY display_order ASC");
$sub_categories  = $db->select("SELECT a.*, c.title as main_cat_name FROM agency_sub_categories a
                                JOIN service_categories c ON a.category_id = c.id
                                WHERE $sub_where ORDER BY a.id DESC", $sub_params);

// Fix for '&amp;' showing in UI: Decode HTML entities after fetching from DB
if (!empty($main_categories)) {
    foreach ($main_categories as $key => $cat) {
        $main_categories[$key]['title'] = html_entity_decode($cat['title'] ?? '', ENT_QUOTES);
        $main_categories[$key]['description'] = html_entity_decode($cat['description'] ?? '', ENT_QUOTES);
    }
}
if (!empty($sub_categories)) {
    foreach ($sub_categories as $key => $scat) {
        $sub_categories[$key]['title'] = html_entity_decode($scat['title'] ?? '', ENT_QUOTES);
        $sub_categories[$key]['main_cat_name'] = html_entity_decode($scat['main_cat_name'] ?? '', ENT_QUOTES);
    }
}

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
?>
<!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>Manage 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, 
    currentTab: window.location.hash ? window.location.hash.substring(1) : 'main_cats',
    mainCatModal: false, activeMainCat: {},
    subCatModal: false, subCatMode: 'add', activeSubCat: {}
}" @hashchange.window="currentTab = window.location.hash.substring(1) || 'main_cats'">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 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 rounded-lg"><i class="fas fa-bars text-xl"></i></button><h2 class="text-xl font-bold hidden md:block text-slate-800">Service Directory</h2></div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6">
                
                <?php if (!empty($SVC_PAGES['failed'])): ?>
                <div class="mb-4 bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-xl text-sm">
                    <i class="fas fa-triangle-exclamation mr-2"></i>
                    <b>These category pages could not be written:</b>
                    <?php echo htmlspecialchars(implode(', ', $SVC_PAGES['failed'])); ?>.
                    The admin folder is read-only, so those categories open through the shared
                    <code>?cat=</code> page instead — which needs the whole-catalogue permission
                    rather than the category's own.
                </div>
                <?php elseif (!empty($SVC_PAGES['made'])): ?>
                <div class="mb-4 bg-sky-50 border border-sky-200 text-sky-800 px-4 py-3 rounded-xl text-sm">
                    <i class="fas fa-file-circle-plus mr-2"></i>
                    Made <?php echo count($SVC_PAGES['made']); ?> new category page(s) —
                    <?php echo htmlspecialchars(implode(', ', $SVC_PAGES['made'])); ?>.
                    They are in the sidebar now.
                </div>
                <?php endif; ?>

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

                <?php echo alist_banner('services.php', 'services', $SV, $SV_DEFAULTS, ['q'=>'Search','cat'=>'Category','status'=>'Status']); ?>

                <form method="GET" class="al-panel p-3 mb-5 grid grid-cols-2 lg:grid-cols-5 gap-2 items-end">
                    <input type="hidden" name="f" value="services">
                    <div class="col-span-2">
                        <label class="al-l">Search</label>
                        <div class="relative">
                            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                            <input name="q" value="<?php echo htmlspecialchars($SV['q']); ?>" placeholder="Category or sub-category name" class="al-f pl-9">
                        </div>
                    </div>
                    <div><label class="al-l">Main Category</label>
                        <select name="cat" class="al-f">
                            <option value="">All</option>
                            <?php foreach ($all_main_cats as $mc): ?>
                                <option value="<?php echo (int)$mc['id']; ?>" <?php echo $SV['cat']===(string)$mc['id']?'selected':''; ?>><?php echo htmlspecialchars($mc['title']); ?></option>
                            <?php endforeach; ?>
                        </select></div>
                    <div><label class="al-l">Status</label>
                        <select name="status" class="al-f">
                            <option value="">Any</option>
                            <option value="1" <?php echo $SV['status']==='1'?'selected':''; ?>>Active</option>
                            <option value="0" <?php echo $SV['status']==='0'?'selected':''; ?>>Inactive</option>
                        </select></div>
                    <div class="flex gap-2">
                        <button class="al-btn al-btn-apply flex-1"><i class="fas fa-filter"></i> Apply</button>
                        <a href="services.php?reset=1" class="al-btn al-btn-ghost">Reset</a>
                    </div>
                    <div class="col-span-2 lg:col-span-5 flex flex-wrap gap-2">
                        <a href="<?php echo alist_url('services.php','services',$SV,['export'=>'cat']); ?>" class="al-btn al-btn-csv"><i class="fas fa-file-csv"></i> Export Categories</a>
                        <a href="<?php echo alist_url('services.php','services',$SV,['export'=>'sub']); ?>" class="al-btn al-btn-csv"><i class="fas fa-file-csv"></i> Export Sub Categories</a>
                        <span class="text-[11px] text-slate-400 self-center ml-1">
                            <?php echo count($main_categories); ?> categor(y/ies) · <?php echo count($sub_categories); ?> sub-categor(y/ies)
                        </span>
                    </div>
                </form>
                <?php echo alist_styles(); ?>

                <div x-show="currentTab === 'main_cats'" style="display:none;" class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="px-6 py-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                        <div>
                            <h3 class="text-lg font-bold text-gray-800">Main Categories</h3>
                            <p class="text-xs text-gray-500">Edit the display order, icons, and visibility of your top-level services.</p>
                        </div>
                    </div>
                    <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 text-center">Display Order</th>
                                    <th class="p-4 font-semibold text-center">Status</th>
                                    <th class="p-4 font-semibold text-center">Visibility</th>
                                    <th class="p-4 pr-6 font-semibold text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php foreach($main_categories as $cat): ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="p-4 pl-6 flex items-center">
                                        <div class="w-12 h-12 rounded-xl bg-gradient-to-br <?php echo $cat['gradient_class']; ?> text-white flex items-center justify-center mr-4 flex-shrink-0 shadow-sm">
                                            <i class="fas <?php echo $cat['icon_class']; ?> text-xl"></i>
                                        </div>
                                        <div>
                                            <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($cat['title']); ?></p>
                                            <p class="text-xs text-gray-500 truncate max-w-[200px]"><?php echo htmlspecialchars($cat['description']); ?></p>
                                        </div>
                                    </td>
                                    <td class="p-4 text-center font-bold text-slate-600"><?php echo $cat['display_order']; ?></td>
                                    <td class="p-4 text-center">
                                        <span class="px-2 py-1 text-[10px] font-bold uppercase rounded <?php echo $cat['status'] == 1 ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'; ?>">
                                            <?php echo $cat['status'] == 1 ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="p-4 text-center">
                                        <?php if($cat['show_to_seller'] == 1): ?>
                                            <span class="text-emerald-500 tooltip" title="Visible in Seller Panel"><i class="fas fa-eye"></i> Sellers</span>
                                        <?php else: ?>
                                            <span class="text-gray-400 tooltip" title="Hidden from Sellers"><i class="fas fa-eye-slash"></i> Hidden</span>
                                        <?php endif; ?>
                                        <?php if(array_key_exists('seller_can_add', $cat) && (int)$cat['seller_can_add'] === 0): ?>
                                            <span class="block mt-1 text-[10px] font-bold text-amber-600 tooltip" title="Sellers can use &amp; sell these, but cannot submit a new service here"><i class="fas fa-lock"></i> No Add</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 pr-6 text-right">
                                        <button @click="activeMainCat = <?php echo htmlspecialchars(json_encode($cat)); ?>; mainCatModal = true;" class="w-8 h-8 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors inline-flex items-center justify-center tooltip" title="Edit Service">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div x-show="currentTab === 'sub_cats'" style="display:none;" class="space-y-4">
                    <div class="bg-purple-50 rounded-2xl shadow-sm border border-purple-100 p-4 flex items-center justify-between mb-4">
                        <div>
                            <h3 class="text-lg font-bold text-purple-800">Sub Categories Management</h3>
                            <p class="text-xs text-purple-600">Select a Main Category below to add or edit its sub-categories.</p>
                        </div>
                    </div>

                    <?php foreach($main_categories as $m_cat): ?>
                    <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden" x-data="{ expanded: false }">
                        <div @click="expanded = !expanded" class="px-6 py-4 bg-gray-50 flex justify-between items-center cursor-pointer hover:bg-gray-100 transition-colors">
                            <div class="flex items-center">
                                <div class="w-10 h-10 rounded-lg bg-gradient-to-br <?php echo $m_cat['gradient_class']; ?> text-white flex items-center justify-center mr-4 shadow-sm">
                                    <i class="fas <?php echo $m_cat['icon_class']; ?> text-lg"></i>
                                </div>
                                <h3 class="font-bold text-gray-800 text-lg"><?php echo htmlspecialchars($m_cat['title']); ?></h3>
                            </div>
                            <div class="flex items-center space-x-4">
                                <button @click.stop="subCatMode = 'add'; activeSubCat = {category_id:'<?php echo $m_cat['id']; ?>', title:'', icon_class:'', gradient_class:'from-blue-500 to-cyan-400', status:1}; subCatModal = true;" class="bg-purple-600 hover:bg-purple-700 text-white px-3 py-1.5 rounded-lg font-bold text-xs shadow-sm transition-colors">
                                    <i class="fas fa-plus mr-1"></i> Add Sub
                                </button>
                                <i class="fas fa-chevron-down text-gray-400 transition-transform duration-200" :class="expanded ? 'rotate-180' : ''"></i>
                            </div>
                        </div>
                        
                        <div x-show="expanded" class="border-t border-gray-100 overflow-x-auto" style="display:none;">
                            <table class="w-full text-left border-collapse">
                                <thead class="bg-white border-b border-gray-100">
                                    <tr class="text-xs text-gray-500 uppercase tracking-wider">
                                        <th class="p-4 pl-6 font-semibold">Sub-Category Name</th>
                                        <th class="p-4 font-semibold text-center">Status</th>
                                        <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-50">
                                    <?php 
                                    $has_subs = false;
                                    if(!empty($sub_categories)): 
                                        foreach($sub_categories as $scat): 
                                            if($scat['category_id'] == $m_cat['id']):
                                                $has_subs = true;
                                    ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="p-4 pl-6 flex items-center">
                                            <div class="w-8 h-8 rounded bg-gradient-to-br <?php echo $scat['gradient_class']; ?> text-white flex items-center justify-center mr-3 shadow-sm">
                                                <i class="fas <?php echo $scat['icon_class']; ?> text-sm"></i>
                                            </div>
                                            <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($scat['title']); ?></p>
                                        </td>
                                        <td class="p-4 text-center">
                                            <span class="px-2 py-1 text-[10px] font-bold uppercase rounded <?php echo $scat['status'] == 1 ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-200 text-gray-700'; ?>">
                                                <?php echo $scat['status'] == 1 ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td class="p-4 pr-6 text-right whitespace-nowrap">
                                            <button @click="activeSubCat = <?php echo htmlspecialchars(json_encode($scat)); ?>; subCatMode = 'edit'; subCatModal = true;" class="w-8 h-8 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors inline-flex items-center justify-center mr-1">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <form method="POST" onsubmit="return confirm('Delete this sub-category?');" class="inline-block">
                                                <input type="hidden" name="id" value="<?php echo $scat['id']; ?>">
                                                <button type="submit" name="delete_sub_cat" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors inline-flex items-center justify-center">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php 
                                            endif;
                                        endforeach; 
                                    endif; 
                                    
                                    if(!$has_subs): 
                                    ?>
                                        <tr><td colspan="3" class="p-6 text-center text-gray-400 font-medium">No sub-categories added yet.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

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

    <div x-show="mainCatModal" 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="mainCatModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="font-bold text-gray-900 text-lg">Edit Main Category</h3>
                <button @click="mainCatModal = false" class="text-gray-400 hover:text-rose-500"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6">
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="cat_id" x-model="activeMainCat.id">
                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Title</label>
                        <input type="text" name="title" x-model="activeMainCat.title" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Description</label>
                        <textarea name="description" x-model="activeMainCat.description" rows="2" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500"></textarea>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Icon Class</label>
                            <input type="text" name="icon_class" x-model="activeMainCat.icon_class" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Gradient Class</label>
                            <input type="text" name="gradient_class" x-model="activeMainCat.gradient_class" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500">
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Display Order</label>
                            <input type="number" name="display_order" x-model="activeMainCat.display_order" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-700 mb-1">Status</label>
                            <select name="status" x-model="activeMainCat.status" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-emerald-500">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <label class="flex items-center space-x-2 cursor-pointer bg-gray-50 p-3 rounded-lg border border-gray-200 mt-2">
                        <input type="checkbox" name="show_to_seller" value="1" x-bind:checked="activeMainCat.show_to_seller == 1" class="w-4 h-4 text-emerald-600 rounded border-gray-300 focus:ring-emerald-500">
                        <span class="text-sm font-bold text-gray-700">Allow Sellers to list their products here</span>
                    </label>
                    <label class="flex items-start space-x-2 cursor-pointer bg-amber-50 p-3 rounded-lg border border-amber-200 mt-2">
                        <input type="checkbox" name="seller_can_add" value="1" x-bind:checked="activeMainCat.seller_can_add != 0" class="w-4 h-4 mt-0.5 text-amber-600 rounded border-gray-300 focus:ring-amber-500">
                        <span class="text-sm font-bold text-gray-700">Allow Sellers to <u>add</u> a new service here
                            <span class="block text-[11px] font-medium text-gray-500 mt-0.5">Untick for admin-managed categories such as Government Portals. Sellers can still use and sell what is already listed &mdash; they just cannot submit an add request.</span>
                        </span>
                    </label>
                    <!-- ============ how this category sells ============
                         Products under it follow this unless one of them was set
                         differently. Ticking "apply to every product" pushes it
                         down to all of them in one go. -->
                    <div class="mt-4 pt-4 border-t border-gray-100">
                        <label class="block text-xs font-bold text-gray-700 mb-2">How are these services sold?</label>
                        <input type="hidden" name="cat_fulfilment" x-bind:value="activeMainCat.fulfilment === 'visit' ? 'visit' : 'online'">
                        <div class="grid grid-cols-2 gap-2">
                            <button type="button" @click="activeMainCat.fulfilment = 'online'"
                                    class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                                    :class="activeMainCat.fulfilment !== 'visit' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-gray-200 text-gray-500'">
                                <i class="fas fa-bolt mr-1"></i> FULL PAYMENT
                            </button>
                            <button type="button" @click="activeMainCat.fulfilment = 'visit'"
                                    class="py-2.5 rounded-xl text-xs font-black border-2 transition-all"
                                    :class="activeMainCat.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> VISIT &amp; COLLECT
                            </button>
                        </div>

                        <div x-show="activeMainCat.fulfilment === 'visit'" class="mt-3 space-y-3 rounded-xl border border-amber-200 bg-amber-50/50 p-3">
                            <div>
                                <label class="block text-xs font-bold text-gray-700 mb-1">Booking amount taken on the site</label>
                                <select name="cat_advance_mode" x-model="activeMainCat.advance_mode" class="w-full px-4 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-amber-500">
                                    <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="activeMainCat.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="cat_advance_amount" x-model="activeMainCat.advance_amount" class="w-full px-4 py-2 border rounded-lg text-sm">
                                </div>
                                <div x-show="activeMainCat.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="cat_advance_percent" x-model="activeMainCat.advance_percent" class="w-full px-4 py-2 border rounded-lg text-sm">
                                </div>
                            </div>
                        </div>

                        <label class="flex items-start space-x-2 cursor-pointer bg-rose-50 p-3 rounded-lg border border-rose-200 mt-3">
                            <input type="checkbox" name="cat_apply_all" value="1" class="w-4 h-4 mt-0.5 text-rose-600 rounded border-gray-300 focus:ring-rose-500">
                            <span class="text-sm font-bold text-gray-700">Apply this to every product already in this category
                                <span class="block text-[11px] font-medium text-gray-500 mt-0.5">Leave it unticked and the setting is only the default for products that have not been set themselves.</span>
                            </span>
                        </label>
                    </div>

                    <button type="submit" name="edit_main_cat" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-lg shadow-md mt-4">Save Changes</button>
                </form>
            </div>
        </div>
    </div>

    <div x-show="subCatModal" 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="subCatModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="font-bold text-gray-900 text-lg" x-text="subCatMode === 'add' ? 'Add Sub-Category' : 'Edit Sub-Category'"></h3>
                <button @click="subCatModal = false" class="text-gray-400 hover:text-rose-500"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6">
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="id" x-model="activeSubCat.id">
                    
                    <div class="bg-purple-50 p-3 border border-purple-200 rounded-lg">
                        <label class="block text-xs font-bold text-purple-900 mb-1">Place inside Main Category:</label>
                        <select name="category_id" x-model="activeSubCat.category_id" required class="w-full px-3 py-2 border border-purple-300 rounded focus:ring-2 focus:ring-purple-500 bg-white font-semibold text-slate-700">
                            <?php foreach($main_categories as $m_cat): ?>
                                <option value="<?php echo $m_cat['id']; ?>"><?php echo htmlspecialchars($m_cat['title']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Sub-Category Name</label>
                        <input type="text" name="title" x-model="activeSubCat.title" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Icon Class (FontAwesome)</label>
                        <input type="text" name="icon_class" x-model="activeSubCat.icon_class" placeholder="fa-folder" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Gradient Theme (Tailwind)</label>
                        <input type="text" name="gradient_class" x-model="activeSubCat.gradient_class" placeholder="from-blue-500 to-cyan-400" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-gray-700 mb-1">Status</label>
                        <select name="status" x-model="activeSubCat.status" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-purple-500">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                    <button type="submit" :name="subCatMode === 'add' ? 'add_sub_cat' : 'edit_sub_cat'" class="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded-lg shadow-md mt-2" x-text="subCatMode === 'add' ? 'Add Sub-Category' : 'Save Changes'"></button>
                </form>
            </div>
        </div>
    </div>

</body>
</html>