<?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'];

// Get profit margin
$profitMargin = 20;
try {
    $stmt = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'smm_profit_margin'");
    $profitMargin = floatval($stmt->fetchColumn() ?: 20);
} catch (PDOException $e) {}

$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 'update_field':
                $id = (int)($_POST['id'] ?? 0);
                $field = $_POST['field'] ?? '';
                $value = $_POST['value'] ?? '';
                
                $allowedFields = ['custom_name', 'custom_rate', 'custom_min', 'custom_max', 'status', 'category_id'];
                if ($id && in_array($field, $allowedFields)) {
                    if ($field === 'category_id') {
                        $value = $value ? (int)$value : null;
                    } elseif ($field === 'custom_rate') {
                        $value = (float)$value;
                    } elseif (in_array($field, ['custom_min', 'custom_max'])) {
                        $value = (int)$value;
                    }
                    
                    $stmt = $pdo->prepare("UPDATE smm_services SET {$field} = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$value, $id]);
                    
                    // For AJAX
                    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['success' => true]);
                        exit;
                    }
                    $message = "Service updated!";
                    $messageType = 'success';
                }
                break;

            case 'save_all':
                $ids = $_POST['service_ids'] ?? [];
                $names = $_POST['custom_name'] ?? [];
                $rates = $_POST['custom_rate'] ?? [];
                $mins = $_POST['custom_min'] ?? [];
                $maxs = $_POST['custom_max'] ?? [];
                $statuses = $_POST['status'] ?? [];
                $categoryIds = $_POST['row_category_id'] ?? [];

                $count = 0;
                foreach ($ids as $i => $id) {
                    $id = (int)$id;
                    if (!$id) continue;
                    $stmt = $pdo->prepare("UPDATE smm_services SET 
                        custom_name = ?,
                        custom_rate = ?,
                        custom_min = ?,
                        custom_max = ?,
                        status = ?,
                        category_id = ?,
                        updated_at = NOW()
                        WHERE id = ?");
                    $catId = isset($categoryIds[$i]) && $categoryIds[$i] !== '' ? (int)$categoryIds[$i] : null;
                    $stmt->execute([
                        trim($names[$i] ?? ''),
                        (float)($rates[$i] ?? 0),
                        (int)($mins[$i] ?? 0),
                        (int)($maxs[$i] ?? 0),
                        in_array($statuses[$i] ?? '', ['active', 'inactive']) ? $statuses[$i] : 'inactive',
                        $catId,
                        $id
                    ]);
                    $count++;
                }
                $message = "Saved $count services!";
                $messageType = 'success';
                break;
                
            case 'bulk_move':
                $ids = $_POST['service_ids'] ?? [];
                $categoryId = (int)($_POST['category_id'] ?? 0);
                
                if (!empty($ids) && $categoryId) {
                    $ids = array_map('intval', $ids);
                    $placeholders = implode(',', array_fill(0, count($ids), '?'));
                    $multiplier = 1 + ($profitMargin / 100);
                    
                    $stmt = $pdo->prepare("UPDATE smm_services SET category_id = ?, custom_rate = api_rate * ?, status = 'active', updated_at = NOW() WHERE id IN ($placeholders)");
                    $stmt->execute(array_merge([$categoryId, $multiplier], $ids));
                    $message = "Moved " . count($ids) . " services with {$profitMargin}% margin applied!";
                    $messageType = 'success';
                } else {
                    $message = "Please select services and a category";
                    $messageType = 'error';
                }
                break;
                
            case 'apply_margin':
                $ids = $_POST['service_ids'] ?? [];
                if (!empty($ids)) {
                    $ids = array_map('intval', $ids);
                    $placeholders = implode(',', array_fill(0, count($ids), '?'));
                    $multiplier = 1 + ($profitMargin / 100);
                    $stmt = $pdo->prepare("UPDATE smm_services SET custom_rate = api_rate * ? WHERE id IN ($placeholders)");
                    $stmt->execute(array_merge([$multiplier], $ids));
                    $message = "Applied {$profitMargin}% margin to " . count($ids) . " services!";
                    $messageType = 'success';
                }
                break;
                
            case 'create_category':
                $name = trim($_POST['cat_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 {
                        $stmt = $pdo->prepare("INSERT INTO smm_categories (name, sort_order, status, created_at) VALUES (?, 0, 'active', NOW())");
                        $stmt->execute([$name]);
                        $message = "Category '$name' created!";
                        $messageType = 'success';
                    }
                }
                break;
                
            case 'delete_category':
                $id = (int)($_POST['cat_id'] ?? 0);
                if ($id) {
                    $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 deleted!";
                    $messageType = 'success';
                }
                break;
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = 'error';
    }
    
    // Redirect to prevent form resubmission
    $redirectUrl = 'smm-services.php';
    if (isset($_POST['api_cat']) && $_POST['api_cat']) {
        $redirectUrl .= '?api_cat=' . urlencode($_POST['api_cat']);
    } elseif (isset($_POST['my_cat']) && $_POST['my_cat']) {
        $redirectUrl .= '?my_cat=' . urlencode($_POST['my_cat']);
    }
    
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = $messageType;
    header("Location: $redirectUrl");
    exit;
}

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

// Fetch categories
$myCategories = $pdo->query("
    SELECT c.*, (SELECT COUNT(*) FROM smm_services WHERE category_id = c.id) as service_count 
    FROM smm_categories c ORDER BY c.sort_order ASC, c.name ASC
")->fetchAll();

$apiCategories = $pdo->query("
    SELECT api_category, COUNT(*) as count FROM smm_services 
    WHERE api_category IS NOT NULL AND api_category != '' 
    GROUP BY api_category ORDER BY api_category
")->fetchAll();

// Get selected category
$selectedApiCat = $_GET['api_cat'] ?? '';
$selectedMyCat = $_GET['my_cat'] ?? '';

// Fetch services
$services = [];
$currentCatName = '';

if ($selectedApiCat) {
    $stmt = $pdo->prepare("SELECT s.*, c.name as my_cat_name FROM smm_services s LEFT JOIN smm_categories c ON s.category_id = c.id WHERE s.api_category = ? ORDER BY s.api_name");
    $stmt->execute([$selectedApiCat]);
    $services = $stmt->fetchAll();
    $currentCatName = $selectedApiCat;
} elseif ($selectedMyCat) {
    $stmt = $pdo->prepare("SELECT s.*, c.name as my_cat_name FROM smm_services s LEFT JOIN smm_categories c ON s.category_id = c.id WHERE s.category_id = ? ORDER BY s.custom_name");
    $stmt->execute([(int)$selectedMyCat]);
    $services = $stmt->fetchAll();
    $catStmt = $pdo->prepare("SELECT name FROM smm_categories WHERE id = ?");
    $catStmt->execute([(int)$selectedMyCat]);
    $currentCatName = $catStmt->fetchColumn() ?: 'My Category';
}

// Stats
$stats = $pdo->query("SELECT COUNT(*) as total, SUM(status = 'active') as active FROM smm_services")->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMM Services - <?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; }
        
        .top-bar { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; align-items: center; }
        .stat { background: #0F2744; padding: 0.75rem 1.25rem; border-radius: 8px; text-align: center; }
        .stat-val { font-size: 1.25rem; font-weight: 700; color: #F5A623; }
        .stat-lbl { font-size: 0.7rem; color: #9CA3AF; }
        .margin-box { background: rgba(245,166,35,0.1); border: 1px solid #F5A623; border-radius: 8px; padding: 0.75rem 1.25rem; }
        .margin-box span { color: #F5A623; font-weight: 700; }
        .cat-mgmt-btn { background: #F5A623; color: #0A1628; border-radius: 8px; padding: 0.75rem 1.25rem; text-decoration: none; font-weight: 600; display: inline-flex; align-items: center; gap: 0.5rem; }
        .cat-mgmt-btn:hover { background: #e5951c; }
        
        .grid { display: grid; grid-template-columns: 300px 1fr; gap: 1.5rem; }
        
        .panel { background: #0F2744; border-radius: 10px; overflow: hidden; margin-bottom: 1rem; }
        .panel-header { padding: 1rem; background: #0A1628; border-bottom: 1px solid #1E3A5F; cursor: pointer; display: flex; justify-content: space-between; align-items: center; }
        .panel-header:hover { background: #1E3A5F; }
        .panel-title { color: #F5A623; font-size: 0.9rem; font-weight: 600; }
        .panel-body { max-height: 0; overflow: hidden; transition: max-height 0.3s; }
        .panel-body.open { max-height: 500px; overflow-y: auto; }
        
        .cat-item { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem; border-bottom: 1px solid #1E3A5F; text-decoration: none; color: #fff; }
        .cat-item:hover { background: #1E3A5F; }
        .cat-item.active { background: rgba(245,166,35,0.15); border-left: 3px solid #F5A623; }
        .cat-item .count { background: #0A1628; padding: 0.2rem 0.5rem; border-radius: 10px; font-size: 0.75rem; color: #F5A623; }
        
        .del-btn { background: none; border: none; color: #EF4444; cursor: pointer; padding: 0.25rem; opacity: 0.7; }
        .del-btn:hover { opacity: 1; }
        
        .add-form { display: flex; gap: 0.5rem; padding: 0.75rem 1rem; background: #0A1628; }
        .add-form input { flex: 1; padding: 0.5rem; background: #0F2744; border: 1px solid #1E3A5F; border-radius: 6px; color: #fff; }
        .add-form input:focus { outline: none; border-color: #F5A623; }
        .add-form button { padding: 0.5rem 1rem; background: #F5A623; border: none; border-radius: 6px; color: #0A1628; cursor: pointer; font-weight: 600; }
        
        .services-panel { background: #0F2744; border-radius: 10px; }
        .services-header { padding: 1rem; border-bottom: 1px solid #1E3A5F; display: flex; justify-content: space-between; align-items: center; }
        .services-title { color: #F5A623; font-size: 1rem; }
        
        .toolbar { display: flex; gap: 0.5rem; padding: 1rem; background: #0A1628; border-bottom: 1px solid #1E3A5F; flex-wrap: wrap; align-items: center; }
        .toolbar select, .toolbar button { padding: 0.5rem 0.75rem; border-radius: 6px; font-size: 0.85rem; cursor: pointer; border: none; }
        .toolbar select { background: #0F2744; border: 1px solid #1E3A5F; color: #fff; }
        .btn-gold { background: #F5A623; color: #0A1628; font-weight: 600; }
        .btn-green { background: #10B981; color: #fff; font-weight: 600; }
        .btn-navy { background: #1E3A5F; color: #fff; }
        
        .table-wrap { max-height: 500px; overflow: auto; }
        table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
        th, td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #1E3A5F; }
        th { background: #1E3A5F; color: #F5A623; position: sticky; top: 0; }
        tr:hover { background: rgba(255,255,255,0.02); }
        
        .chk { width: 40px; text-align: center; }
        .chk input { width: 16px; height: 16px; accent-color: #F5A623; }
        
        .inline-input, .inline-select { background: #0A1628; border: 1px solid #1E3A5F; border-radius: 4px; color: #fff; padding: 0.4rem 0.5rem; font-size: 0.85rem; }
        .inline-input:focus, .inline-select:focus { outline: none; border-color: #F5A623; }
        .inline-input.name-input { width: 200px; }
        .inline-input.rate-input { width: 90px; color: #F5A623; }
        .inline-input.num-input { width: 80px; }
        .inline-select { min-width: 100px; }
        
        .empty { text-align: center; padding: 3rem; color: #6B7280; }
        .empty i { font-size: 3rem; margin-bottom: 1rem; display: block; }
        
        @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 active"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="smm-categories.php" class="nav-link"><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-rocket" style="color:#F5A623;"></i> SMM Services</h1>
        </header>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <div class="top-bar">
            <div class="stat"><div class="stat-val"><?php echo number_format($stats['total'] ?? 0); ?></div><div class="stat-lbl">Total</div></div>
            <div class="stat"><div class="stat-val"><?php echo number_format($stats['active'] ?? 0); ?></div><div class="stat-lbl">Active</div></div>
            <div class="stat"><div class="stat-val"><?php echo count($myCategories); ?></div><div class="stat-lbl">My Categories</div></div>
            <div class="margin-box"><span><?php echo $profitMargin; ?>%</span> Profit Margin</div>
            <a href="smm-categories.php" class="cat-mgmt-btn"><i class="fas fa-folder-plus"></i> Category Management</a>
        </div>
        
        <div class="grid">
            <!-- Left: Categories -->
            <div>
                <!-- API Categories -->
                <div class="panel">
                    <div class="panel-header" onclick="togglePanel(this)">
                        <span class="panel-title"><i class="fas fa-cloud"></i> API Categories</span>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                    <div class="panel-body<?php echo $selectedApiCat ? ' open' : ''; ?>">
                        <?php foreach ($apiCategories as $cat): ?>
                        <a href="?api_cat=<?php echo urlencode($cat['api_category']); ?>" class="cat-item<?php echo $selectedApiCat === $cat['api_category'] ? ' active' : ''; ?>">
                            <span><?php echo htmlspecialchars($cat['api_category']); ?></span>
                            <span class="count"><?php echo $cat['count']; ?></span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- My Categories -->
                <div class="panel">
                    <div class="panel-header" onclick="togglePanel(this)">
                        <span class="panel-title"><i class="fas fa-folder"></i> My Categories</span>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                    <div class="panel-body<?php echo $selectedMyCat ? ' open' : ''; ?>">
                        <?php foreach ($myCategories as $cat): ?>
                        <div class="cat-item<?php echo $selectedMyCat == $cat['id'] ? ' active' : ''; ?>">
                            <a href="?my_cat=<?php echo $cat['id']; ?>" style="flex:1;text-decoration:none;color:#fff;">
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </a>
                            <span class="count"><?php echo $cat['service_count']; ?></span>
                            <form method="POST" style="display:inline;margin-left:0.5rem;" onsubmit="return confirm('Delete this category? Services will be deactivated.')">
                                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                                <input type="hidden" name="action" value="delete_category">
                                <input type="hidden" name="cat_id" value="<?php echo $cat['id']; ?>">
                                <button type="submit" class="del-btn"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                        <form method="POST" class="add-form">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                            <input type="hidden" name="action" value="create_category">
                            <input type="text" name="cat_name" placeholder="New category..." required>
                            <button type="submit"><i class="fas fa-plus"></i></button>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Right: Services -->
            <div class="services-panel">
                <div class="services-header">
                    <span class="services-title"><i class="fas fa-list"></i> <?php echo $currentCatName ?: 'Services'; ?></span>
                    <span style="color:#9CA3AF;"><?php echo count($services); ?> services</span>
                </div>
                
                <?php if (!empty($services)): ?>
                <form method="POST" id="servicesForm">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" id="formAction" value="">
                    <?php if ($selectedApiCat): ?>
                    <input type="hidden" name="api_cat" value="<?php echo htmlspecialchars($selectedApiCat); ?>">
                    <?php elseif ($selectedMyCat): ?>
                    <input type="hidden" name="my_cat" value="<?php echo htmlspecialchars($selectedMyCat); ?>">
                    <?php endif; ?>
                    
                    <div class="toolbar">
                        <button type="button" class="btn-navy" onclick="selectAll()"><i class="fas fa-check-square"></i> All</button>
                        <button type="button" class="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>
                        
                        <select name="category_id" id="categorySelect">
                            <option value="">Move to...</option>
                            <?php foreach ($myCategories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" class="btn-gold" onclick="document.getElementById('formAction').value='bulk_move'"><i class="fas fa-arrow-right"></i> Move</button>
                        <button type="submit" class="btn-navy" onclick="document.getElementById('formAction').value='apply_margin'"><i class="fas fa-percent"></i> Apply <?php echo $profitMargin; ?>%</button>
                        <button type="submit" class="btn-green" onclick="document.getElementById('formAction').value='save_all'"><i class="fas fa-save"></i> Save Changes</button>
                    </div>
                    
                    <div class="table-wrap">
                        <table>
                            <thead>
                                <tr>
                                    <th class="chk"><input type="checkbox" id="checkAll" onchange="toggleAll(this)"></th>
                                    <th>ID</th>
                                    <th>Service Name</th>
                                    <th>API Rate</th>
                                    <th>Your Rate</th>
                                    <th>Min</th>
                                    <th>Max</th>
                                    <th>Status</th>
                                    <th>Category</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($services as $i => $s): ?>
                                <tr data-id="<?php echo $s['id']; ?>">
                                    <td class="chk"><input type="checkbox" name="service_ids[]" value="<?php echo $s['id']; ?>" class="srv-chk" onchange="updateCount()"></td>
                                    <td style="color:#6B7280;font-size:0.8rem;"><?php echo htmlspecialchars($s['api_service_id']); ?></td>
                                    <td><input type="text" name="custom_name[]" class="inline-input name-input" value="<?php echo htmlspecialchars($s['custom_name'] ?: $s['api_name']); ?>"></td>
                                    <td style="color:#6B7280;">$<?php echo number_format($s['api_rate'], 4); ?></td>
                                    <td><input type="number" step="0.0001" name="custom_rate[]" class="inline-input rate-input" value="<?php echo $s['custom_rate']; ?>"></td>
                                    <td><input type="number" name="custom_min[]" class="inline-input num-input" value="<?php echo $s['custom_min']; ?>"></td>
                                    <td><input type="number" name="custom_max[]" class="inline-input num-input" value="<?php echo $s['custom_max']; ?>"></td>
                                    <td>
                                        <select name="status[]" class="inline-select">
                                            <option value="active" <?php echo $s['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="inactive" <?php echo $s['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                        </select>
                                    </td>
                                    <td>
                                        <select name="row_category_id[]" class="inline-select">
                                            <option value="">-- None --</option>
                                            <?php foreach ($myCategories as $cat): ?>
                                            <option value="<?php echo $cat['id']; ?>" <?php echo $s['category_id'] == $cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <!-- Hidden row IDs in order matching the table rows -->
                    <?php foreach ($services as $s): ?>
                    <input type="hidden" name="service_ids_all[]" value="<?php echo $s['id']; ?>">
                    <?php endforeach; ?>
                </form>
                <?php else: ?>
                <div class="empty">
                    <i class="fas fa-arrow-left"></i>
                    <p>Select a category from the left to view services</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
    
    <script>
    function togglePanel(header) {
        header.nextElementSibling.classList.toggle('open');
    }
    
    function selectAll() {
        document.querySelectorAll('.srv-chk').forEach(c => c.checked = true);
        document.getElementById('checkAll').checked = true;
        updateCount();
    }
    
    function selectNone() {
        document.querySelectorAll('.srv-chk').forEach(c => c.checked = false);
        document.getElementById('checkAll').checked = false;
        updateCount();
    }
    
    function toggleAll(master) {
        document.querySelectorAll('.srv-chk').forEach(c => c.checked = master.checked);
        updateCount();
    }
    
    function updateCount() {
        document.getElementById('selectedCount').textContent = document.querySelectorAll('.srv-chk:checked').length;
    }

    // Override Save Changes to submit ALL rows (not just checked)
    document.getElementById('servicesForm').addEventListener('submit', function(e) {
        var action = document.getElementById('formAction').value;
        if (action === 'save_all') {
            // Check all checkboxes temporarily so all row data is included
            document.querySelectorAll('.srv-chk').forEach(c => c.checked = true);
        }
    });
    </script>
</body>
</html>