<?php
require_once dirname(__DIR__) . '/config/config.php';
requireLogin();
requireAdmin();

$pdo = getDBConnection();

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

$message = '';
$messageType = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $csrfToken) {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'create':
                $name = trim($_POST['name'] ?? '');
                if ($name) {
                    $check = $pdo->prepare("SELECT id FROM smm_categories WHERE name = ?");
                    $check->execute([$name]);
                    if ($check->fetch()) {
                        $message = "Category '$name' already exists!";
                        $messageType = 'error';
                    } else {
                        $sortOrder = (int)($_POST['sort_order'] ?? 0);
                        $status = $_POST['status'] ?? 'active';
                        $icon = trim($_POST['icon'] ?? '');
                        $iconColor = trim($_POST['icon_color'] ?? '#ffffff');
                        $stmt = $pdo->prepare("INSERT INTO smm_categories (name, sort_order, status, icon, icon_color, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                        $stmt->execute([$name, $sortOrder, $status, $icon, $iconColor]);
                        $message = "Category '$name' created!";
                        $messageType = 'success';
                    }
                }
                break;
                
            case 'update':
                $id = (int)($_POST['id'] ?? 0);
                $name = trim($_POST['name'] ?? '');
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                $status = $_POST['status'] ?? 'active';
                $icon = trim($_POST['icon'] ?? '');
                $iconColor = trim($_POST['icon_color'] ?? '#ffffff');
                
                if ($id && $name) {
                    $stmt = $pdo->prepare("UPDATE smm_categories SET name = ?, sort_order = ?, status = ?, icon = ?, icon_color = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$name, $sortOrder, $status, $icon, $iconColor, $id]);
                    $message = "Category updated!";
                    $messageType = 'success';
                }
                break;
                
            case 'delete':
                $id = (int)($_POST['id'] ?? 0);
                if ($id) {
                    $stmt = $pdo->prepare("SELECT name FROM smm_categories WHERE id = ?");
                    $stmt->execute([$id]);
                    $catName = $stmt->fetchColumn();
                    $pdo->prepare("UPDATE smm_services SET category_id = NULL, status = 'inactive' WHERE category_id = ?")->execute([$id]);
                    $pdo->prepare("DELETE FROM smm_categories WHERE id = ?")->execute([$id]);
                    $message = "Category '$catName' deleted! Services moved to uncategorized.";
                    $messageType = 'success';
                }
                break;
                
            case 'bulk_delete':
                $ids = $_POST['cat_ids'] ?? [];
                if (!empty($ids)) {
                    $ids = array_map('intval', $ids);
                    $placeholders = implode(',', array_fill(0, count($ids), '?'));
                    $pdo->prepare("UPDATE smm_services SET category_id = NULL, status = 'inactive' WHERE category_id IN ($placeholders)")->execute($ids);
                    $pdo->prepare("DELETE FROM smm_categories WHERE id IN ($placeholders)")->execute($ids);
                    $message = "Deleted " . count($ids) . " categories!";
                    $messageType = 'success';
                }
                break;
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = 'error';
    }
    
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = $messageType;
    header("Location: smm-categories.php");
    exit;
}

if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

$categories = $pdo->query("
    SELECT c.*, 
           (SELECT COUNT(*) FROM smm_services WHERE category_id = c.id) as total_services,
           (SELECT COUNT(*) FROM smm_services WHERE category_id = c.id AND status = 'active') as active_services
    FROM smm_categories c 
    ORDER BY c.sort_order ASC, c.name ASC
")->fetchAll();

// Preset icons for quick selection
$presetIcons = [
    ['icon' => 'fab fa-instagram', 'color' => '#E1306C', 'label' => 'Instagram'],
    ['icon' => 'fab fa-facebook', 'color' => '#1877F2', 'label' => 'Facebook'],
    ['icon' => 'fab fa-tiktok', 'color' => '#010101', 'label' => 'TikTok'],
    ['icon' => 'fab fa-youtube', 'color' => '#FF0000', 'label' => 'YouTube'],
    ['icon' => 'fab fa-twitter', 'color' => '#1DA1F2', 'label' => 'Twitter/X'],
    ['icon' => 'fab fa-x-twitter', 'color' => '#000000', 'label' => 'X'],
    ['icon' => 'fab fa-telegram', 'color' => '#2CA5E0', 'label' => 'Telegram'],
    ['icon' => 'fab fa-whatsapp', 'color' => '#25D366', 'label' => 'WhatsApp'],
    ['icon' => 'fab fa-snapchat', 'color' => '#FFFC00', 'label' => 'Snapchat'],
    ['icon' => 'fab fa-linkedin', 'color' => '#0A66C2', 'label' => 'LinkedIn'],
    ['icon' => 'fab fa-pinterest', 'color' => '#E60023', 'label' => 'Pinterest'],
    ['icon' => 'fab fa-spotify', 'color' => '#1DB954', 'label' => 'Spotify'],
    ['icon' => 'fab fa-soundcloud', 'color' => '#FF5500', 'label' => 'SoundCloud'],
    ['icon' => 'fab fa-twitch', 'color' => '#9146FF', 'label' => 'Twitch'],
    ['icon' => 'fab fa-discord', 'color' => '#5865F2', 'label' => 'Discord'],
    ['icon' => 'fab fa-reddit', 'color' => '#FF4500', 'label' => 'Reddit'],
    ['icon' => 'fab fa-google', 'color' => '#4285F4', 'label' => 'Google'],
    ['icon' => 'fab fa-apple', 'color' => '#555555', 'label' => 'Apple'],
    ['icon' => 'fas fa-globe', 'color' => '#3B82F6', 'label' => 'Website'],
    ['icon' => 'fas fa-star', 'color' => '#F5A623', 'label' => 'General'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMM Categories - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0A1628; color: #fff; min-height: 100vh; }
        
        .sidebar { width: 250px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; overflow-y: auto; }
        .sidebar-header { padding: 1.25rem; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.1rem; }
        .nav-link { display: flex; align-items: center; gap: 10px; padding: 0.75rem 1.25rem; color: #E5E7EB; text-decoration: none; font-size: 0.9rem; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.5rem 1rem; }
        
        .main { margin-left: 250px; padding: 1.5rem; }
        .header { background: #0F2744; padding: 1rem 1.5rem; margin: -1.5rem -1.5rem 1.5rem; display: flex; justify-content: space-between; align-items: center; }
        
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-success { background: rgba(16,185,129,0.2); border: 1px solid #10B981; color: #10B981; }
        .alert-error { background: rgba(239,68,68,0.2); border: 1px solid #EF4444; color: #EF4444; }
        
        .grid { display: grid; grid-template-columns: 380px 1fr; gap: 1.5rem; }
        
        .card { background: #0F2744; border-radius: 10px; overflow: hidden; }
        .card-header { padding: 1rem; background: #0A1628; border-bottom: 1px solid #1E3A5F; }
        .card-title { color: #F5A623; font-size: 1rem; }
        .card-body { padding: 1rem; }
        
        .form-group { margin-bottom: 1rem; }
        .form-label { display: block; margin-bottom: 0.5rem; color: #9CA3AF; font-size: 0.85rem; }
        .form-control { width: 100%; padding: 0.75rem; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 6px; color: #fff; font-size: 0.9rem; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        
        .btn { padding: 0.75rem 1.25rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9rem; font-weight: 600; display: inline-flex; align-items: center; gap: 0.5rem; }
        .btn-gold { background: #F5A623; color: #0A1628; }
        .btn-green { background: #10B981; color: #fff; }
        .btn-red { background: #EF4444; color: #fff; }
        .btn-navy { background: #1E3A5F; color: #fff; }
        .btn-block { width: 100%; justify-content: center; }
        
        .toolbar { display: flex; gap: 0.5rem; padding: 1rem; background: #0A1628; border-bottom: 1px solid #1E3A5F; align-items: center; flex-wrap: wrap; }
        
        .table-wrap { max-height: 600px; overflow: auto; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #1E3A5F; }
        th { background: #1E3A5F; color: #F5A623; position: sticky; top: 0; font-size: 0.8rem; }
        tr:hover { background: rgba(255,255,255,0.02); }
        
        .chk { width: 40px; text-align: center; }
        .chk input { width: 16px; height: 16px; accent-color: #F5A623; }
        
        .badge { display: inline-block; padding: 0.2rem 0.5rem; border-radius: 10px; font-size: 0.75rem; }
        .badge-green { background: rgba(16,185,129,0.2); color: #10B981; }
        .badge-red { background: rgba(239,68,68,0.2); color: #EF4444; }
        .badge-blue { background: rgba(59,130,246,0.2); color: #3B82F6; }
        
        .action-btn { background: none; border: none; cursor: pointer; padding: 0.25rem 0.5rem; border-radius: 4px; }
        .action-btn:hover { background: #1E3A5F; }
        .action-btn.edit { color: #F5A623; }
        .action-btn.delete { color: #EF4444; }
        
        .stats { display: flex; gap: 1rem; margin-bottom: 1rem; }
        .stat { background: #0A1628; padding: 0.75rem 1rem; border-radius: 8px; text-align: center; flex: 1; }
        .stat-val { font-size: 1.5rem; font-weight: 700; color: #F5A623; }
        .stat-lbl { font-size: 0.7rem; color: #9CA3AF; }
        
        .empty { text-align: center; padding: 2rem; color: #6B7280; }

        /* Icon Picker */
        .icon-picker-section { margin-bottom: 1rem; }
        .icon-picker-label { display: block; margin-bottom: 0.5rem; color: #9CA3AF; font-size: 0.85rem; }
        .preset-icons { display: grid; grid-template-columns: repeat(5, 1fr); gap: 0.5rem; margin-bottom: 0.75rem; }
        .preset-icon-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 0.5rem 0.25rem;
            background: #0A1628;
            border: 2px solid #1E3A5F;
            border-radius: 8px;
            cursor: pointer;
            gap: 0.25rem;
            transition: border-color 0.2s;
        }
        .preset-icon-btn:hover { border-color: #F5A623; }
        .preset-icon-btn.selected { border-color: #F5A623; background: rgba(245,166,35,0.1); }
        .preset-icon-btn i { font-size: 1.25rem; }
        .preset-icon-btn span { font-size: 0.6rem; color: #9CA3AF; text-align: center; }
        .icon-preview-box {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem;
            background: #0A1628;
            border: 1px solid #1E3A5F;
            border-radius: 8px;
            margin-bottom: 0.75rem;
        }
        .icon-preview-box i { font-size: 1.5rem; }
        .icon-preview-box span { color: #9CA3AF; font-size: 0.85rem; }
        .icon-inputs { display: flex; gap: 0.5rem; }
        .icon-inputs input[type="text"] { flex: 1; }
        .icon-inputs input[type="color"] { width: 48px; height: 42px; padding: 2px; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 6px; cursor: pointer; }

        /* Category icon display in table */
        .cat-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1rem; background: #0A1628; }

        /* Modal */
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; align-items: center; justify-content: center; overflow-y: auto; padding: 1rem; }
        .modal-overlay.active { display: flex; }
        .modal-box { background: #0F2744; border-radius: 10px; padding: 1.5rem; width: 500px; max-width: 100%; }
        .modal-title { color: #F5A623; margin-bottom: 1.5rem; font-size: 1rem; }

        @media (max-width: 1024px) {
            .grid { grid-template-columns: 1fr; }
            .sidebar { display: none; }
            .main { margin-left: 0; }
        }
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt" style="color:#F5A623;"></i> <span><?php echo SITE_NAME; ?></span></div>
        <nav>
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link"><i class="fas fa-shopping-cart"></i> Orders</a>
            <div class="nav-divider"></div>
            <a href="smm-services.php" class="nav-link"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="smm-categories.php" class="nav-link active"><i class="fas fa-folder"></i> SMM Categories</a>
            <a href="sms-services.php" class="nav-link"><i class="fas fa-sms"></i> SMS Services</a>
            <div class="nav-divider"></div>
            <a href="settings.php" class="nav-link"><i class="fas fa-cog"></i> Settings</a>
            <a href="<?php echo SITE_URL; ?>/logout" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <h1 style="font-size:1.25rem;"><i class="fas fa-folder" style="color:#F5A623;"></i> SMM Categories</h1>
            <a href="smm-services.php" class="btn btn-navy"><i class="fas fa-arrow-left"></i> Back to Services</a>
        </header>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <div class="grid">
            <!-- Left: Create New Category -->
            <div>
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-plus"></i> Create New Category</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="createForm">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                            <input type="hidden" name="action" value="create">
                            <input type="hidden" name="icon" id="createIcon" value="">
                            <input type="hidden" name="icon_color" id="createIconColor" value="#ffffff">
                            
                            <div class="form-group">
                                <label class="form-label">Category Name</label>
                                <input type="text" name="name" class="form-control" placeholder="e.g., Instagram Followers" required>
                            </div>

                            <!-- Icon Picker -->
                            <div class="icon-picker-section">
                                <label class="icon-picker-label">Icon / Logo</label>
                                
                                <!-- Preview -->
                                <div class="icon-preview-box" id="createPreviewBox">
                                    <i id="createPreviewIcon" class="fas fa-folder" style="color:#9CA3AF;"></i>
                                    <span id="createPreviewLabel">No icon selected</span>
                                </div>

                                <!-- Preset Icons -->
                                <div class="preset-icons" id="createPresetGrid">
                                    <?php foreach ($presetIcons as $pi): ?>
                                    <button type="button" class="preset-icon-btn" 
                                        data-icon="<?php echo $pi['icon']; ?>" 
                                        data-color="<?php echo $pi['color']; ?>"
                                        data-label="<?php echo $pi['label']; ?>"
                                        onclick="selectPresetIcon(this, 'create')"
                                        title="<?php echo $pi['label']; ?>">
                                        <i class="<?php echo $pi['icon']; ?>" style="color:<?php echo $pi['color']; ?>;"></i>
                                        <span><?php echo $pi['label']; ?></span>
                                    </button>
                                    <?php endforeach; ?>
                                </div>

                                <!-- Custom Icon Input -->
                                <label class="icon-picker-label">Or enter custom FontAwesome class + color:</label>
                                <div class="icon-inputs">
                                    <input type="text" class="form-control" id="createCustomIcon" placeholder="fab fa-instagram" oninput="updateCustomIcon('create')">
                                    <input type="color" id="createCustomColor" value="#ffffff" oninput="updateCustomColor('create')" title="Icon Color">
                                </div>
                                <small style="color:#6B7280;margin-top:0.25rem;display:block;">Find icons at <a href="https://fontawesome.com/icons" target="_blank" style="color:#F5A623;">fontawesome.com</a></small>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Sort Order</label>
                                <input type="number" name="sort_order" class="form-control" value="0" min="0">
                                <small style="color:#6B7280;">Lower numbers appear first</small>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-control">
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                            
                            <button type="submit" class="btn btn-gold btn-block"><i class="fas fa-plus"></i> Create Category</button>
                        </form>
                    </div>
                </div>
                
                <div class="stats">
                    <div class="stat">
                        <div class="stat-val"><?php echo count($categories); ?></div>
                        <div class="stat-lbl">Total Categories</div>
                    </div>
                    <div class="stat">
                        <div class="stat-val"><?php echo count(array_filter($categories, fn($c) => $c['status'] === 'active')); ?></div>
                        <div class="stat-lbl">Active</div>
                    </div>
                </div>
            </div>
            
            <!-- Right: Categories List -->
            <div class="card">
                <form method="POST" id="categoriesForm">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" id="formAction" value="">
                    
                    <div class="toolbar">
                        <button type="button" class="btn btn-navy" onclick="selectAll()"><i class="fas fa-check-square"></i> All</button>
                        <button type="button" class="btn btn-navy" onclick="selectNone()"><i class="fas fa-square"></i> None</button>
                        <span style="color:#F5A623;margin:0 0.5rem;"><span id="selectedCount">0</span> selected</span>
                        <button type="submit" class="btn btn-red" onclick="return confirmBulkDelete()"><i class="fas fa-trash"></i> Delete Selected</button>
                    </div>
                    
                    <div class="table-wrap">
                        <?php if (empty($categories)): ?>
                        <div class="empty">
                            <i class="fas fa-folder-open" style="font-size:2rem;margin-bottom:0.5rem;display:block;"></i>
                            No categories yet. Create one above.
                        </div>
                        <?php else: ?>
                        <table>
                            <thead>
                                <tr>
                                    <th class="chk"><input type="checkbox" id="checkAll" onchange="toggleAll(this)"></th>
                                    <th>Icon</th>
                                    <th>Name</th>
                                    <th>Order</th>
                                    <th>Services</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($categories as $cat): ?>
                                <tr>
                                    <td class="chk"><input type="checkbox" name="cat_ids[]" value="<?php echo $cat['id']; ?>" class="cat-chk" onchange="updateCount()"></td>
                                    <td>
                                        <?php if (!empty($cat['icon'])): ?>
                                        <div class="cat-icon">
                                            <i class="<?php echo htmlspecialchars($cat['icon']); ?>" style="color:<?php echo htmlspecialchars($cat['icon_color'] ?? '#ffffff'); ?>;"></i>
                                        </div>
                                        <?php else: ?>
                                        <div class="cat-icon"><i class="fas fa-folder" style="color:#6B7280;"></i></div>
                                        <?php endif; ?>
                                    </td>
                                    <td><strong><?php echo htmlspecialchars($cat['name']); ?></strong></td>
                                    <td><?php echo $cat['sort_order']; ?></td>
                                    <td>
                                        <span class="badge badge-blue"><?php echo $cat['total_services']; ?> total</span>
                                        <span class="badge badge-green"><?php echo $cat['active_services']; ?> active</span>
                                    </td>
                                    <td>
                                        <?php if ($cat['status'] === 'active'): ?>
                                        <span class="badge badge-green">Active</span>
                                        <?php else: ?>
                                        <span class="badge badge-red">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="action-btn edit" 
                                            onclick="editCategory(
                                                <?php echo $cat['id']; ?>, 
                                                '<?php echo htmlspecialchars(addslashes($cat['name'])); ?>', 
                                                <?php echo $cat['sort_order']; ?>, 
                                                '<?php echo $cat['status']; ?>',
                                                '<?php echo htmlspecialchars(addslashes($cat['icon'] ?? '')); ?>',
                                                '<?php echo htmlspecialchars($cat['icon_color'] ?? '#ffffff'); ?>'
                                            )" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="action-btn delete" onclick="deleteCategory(<?php echo $cat['id']; ?>, '<?php echo htmlspecialchars(addslashes($cat['name'])); ?>')" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </main>
    
    <!-- Edit Modal -->
    <div id="editModal" class="modal-overlay">
        <div class="modal-box">
            <h3 class="modal-title"><i class="fas fa-edit"></i> Edit Category</h3>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="editId">
                <input type="hidden" name="icon" id="editIconHidden" value="">
                <input type="hidden" name="icon_color" id="editIconColorHidden" value="#ffffff">
                
                <div class="form-group">
                    <label class="form-label">Name</label>
                    <input type="text" name="name" id="editName" class="form-control" required>
                </div>

                <!-- Icon Picker -->
                <div class="icon-picker-section">
                    <label class="icon-picker-label">Icon / Logo</label>
                    <div class="icon-preview-box">
                        <i id="editPreviewIcon" class="fas fa-folder" style="color:#9CA3AF;"></i>
                        <span id="editPreviewLabel">No icon selected</span>
                    </div>
                    <div class="preset-icons" id="editPresetGrid">
                        <?php foreach ($presetIcons as $pi): ?>
                        <button type="button" class="preset-icon-btn" 
                            data-icon="<?php echo $pi['icon']; ?>" 
                            data-color="<?php echo $pi['color']; ?>"
                            data-label="<?php echo $pi['label']; ?>"
                            onclick="selectPresetIcon(this, 'edit')"
                            title="<?php echo $pi['label']; ?>">
                            <i class="<?php echo $pi['icon']; ?>" style="color:<?php echo $pi['color']; ?>;"></i>
                            <span><?php echo $pi['label']; ?></span>
                        </button>
                        <?php endforeach; ?>
                    </div>
                    <label class="icon-picker-label">Or enter custom FontAwesome class + color:</label>
                    <div class="icon-inputs">
                        <input type="text" class="form-control" id="editCustomIcon" placeholder="fab fa-instagram" oninput="updateCustomIcon('edit')">
                        <input type="color" id="editCustomColor" value="#ffffff" oninput="updateCustomColor('edit')" title="Icon Color">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Sort Order</label>
                    <input type="number" name="sort_order" id="editOrder" class="form-control" min="0">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select name="status" id="editStatus" class="form-control">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
                
                <div style="display:flex;gap:0.5rem;margin-top:1rem;">
                    <button type="button" class="btn btn-navy" onclick="closeModal()" style="flex:1;">Cancel</button>
                    <button type="submit" class="btn btn-gold" style="flex:1;"><i class="fas fa-save"></i> Save</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Delete Form (hidden) -->
    <form method="POST" id="deleteForm" style="display:none;">
        <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="id" id="deleteId">
    </form>
    
    <script>
    // ---- Checkbox helpers ----
    function selectAll() {
        document.querySelectorAll('.cat-chk').forEach(c => c.checked = true);
        document.getElementById('checkAll').checked = true;
        updateCount();
    }
    function selectNone() {
        document.querySelectorAll('.cat-chk').forEach(c => c.checked = false);
        document.getElementById('checkAll').checked = false;
        updateCount();
    }
    function toggleAll(master) {
        document.querySelectorAll('.cat-chk').forEach(c => c.checked = master.checked);
        updateCount();
    }
    function updateCount() {
        document.getElementById('selectedCount').textContent = document.querySelectorAll('.cat-chk:checked').length;
    }
    function confirmBulkDelete() {
        var count = document.querySelectorAll('.cat-chk:checked').length;
        if (count === 0) { alert('Please select categories to delete'); return false; }
        if (confirm('Delete ' + count + ' categories? Services in these categories will be deactivated.')) {
            document.getElementById('formAction').value = 'bulk_delete';
            return true;
        }
        return false;
    }

    // ---- Icon picker ----
    function selectPresetIcon(btn, context) {
        var icon = btn.dataset.icon;
        var color = btn.dataset.color;
        var label = btn.dataset.label;

        // Deselect all in same grid
        btn.closest('.preset-icons').querySelectorAll('.preset-icon-btn').forEach(b => b.classList.remove('selected'));
        btn.classList.add('selected');

        applyIcon(context, icon, color, label);
    }

    function applyIcon(context, icon, color, label) {
        if (context === 'create') {
            document.getElementById('createIcon').value = icon;
            document.getElementById('createIconColor').value = color;
            document.getElementById('createPreviewIcon').className = icon;
            document.getElementById('createPreviewIcon').style.color = color;
            document.getElementById('createPreviewLabel').textContent = label || icon;
            document.getElementById('createCustomIcon').value = icon;
            document.getElementById('createCustomColor').value = colorToHex(color);
        } else {
            document.getElementById('editIconHidden').value = icon;
            document.getElementById('editIconColorHidden').value = color;
            document.getElementById('editPreviewIcon').className = icon;
            document.getElementById('editPreviewIcon').style.color = color;
            document.getElementById('editPreviewLabel').textContent = label || icon;
            document.getElementById('editCustomIcon').value = icon;
            document.getElementById('editCustomColor').value = colorToHex(color);
        }
    }

    function updateCustomIcon(context) {
        var iconInput = document.getElementById(context + 'CustomIcon');
        var colorInput = document.getElementById(context + 'CustomColor');
        var icon = iconInput.value.trim();
        var color = colorInput.value;

        if (context === 'create') {
            document.getElementById('createIcon').value = icon;
            document.getElementById('createPreviewIcon').className = icon || 'fas fa-folder';
            document.getElementById('createPreviewIcon').style.color = color;
            document.getElementById('createPreviewLabel').textContent = icon || 'No icon selected';
        } else {
            document.getElementById('editIconHidden').value = icon;
            document.getElementById('editPreviewIcon').className = icon || 'fas fa-folder';
            document.getElementById('editPreviewIcon').style.color = color;
            document.getElementById('editPreviewLabel').textContent = icon || 'No icon selected';
        }
        // Deselect presets
        document.getElementById(context + 'PresetGrid').querySelectorAll('.preset-icon-btn').forEach(b => b.classList.remove('selected'));
    }

    function updateCustomColor(context) {
        var colorInput = document.getElementById(context + 'CustomColor');
        var color = colorInput.value;

        if (context === 'create') {
            document.getElementById('createIconColor').value = color;
            document.getElementById('createPreviewIcon').style.color = color;
        } else {
            document.getElementById('editIconColorHidden').value = color;
            document.getElementById('editPreviewIcon').style.color = color;
        }
    }

    function colorToHex(color) {
        // If already hex return as-is
        if (color.startsWith('#')) return color;
        return '#ffffff';
    }

    // ---- Modal ----
    function editCategory(id, name, order, status, icon, iconColor) {
        document.getElementById('editId').value = id;
        document.getElementById('editName').value = name;
        document.getElementById('editOrder').value = order;
        document.getElementById('editStatus').value = status;

        // Reset preset selections
        document.getElementById('editPresetGrid').querySelectorAll('.preset-icon-btn').forEach(b => {
            b.classList.toggle('selected', b.dataset.icon === icon);
        });

        // Apply icon
        if (icon) {
            applyIcon('edit', icon, iconColor, icon);
        } else {
            document.getElementById('editIconHidden').value = '';
            document.getElementById('editIconColorHidden').value = '#ffffff';
            document.getElementById('editPreviewIcon').className = 'fas fa-folder';
            document.getElementById('editPreviewIcon').style.color = '#9CA3AF';
            document.getElementById('editPreviewLabel').textContent = 'No icon selected';
            document.getElementById('editCustomIcon').value = '';
            document.getElementById('editCustomColor').value = '#ffffff';
        }

        document.getElementById('editModal').classList.add('active');
    }

    function closeModal() {
        document.getElementById('editModal').classList.remove('active');
    }

    function deleteCategory(id, name) {
        if (confirm('Delete category "' + name + '"? Services in this category will be deactivated.')) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteForm').submit();
        }
    }

    document.getElementById('editModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });
    </script>
</body>
</html>