<?php
/**
 * Admin - Delete Service Category
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Invalid security token');
}

$category_id = intval($_POST['category_id'] ?? 0);

if (!$category_id) {
    redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Invalid category ID');
}

try {
    // Check if category exists
    $stmt = db()->prepare("SELECT name FROM service_categories WHERE id = ?");
    $stmt->execute([$category_id]);
    $category = $stmt->fetch();
    
    if (!$category) {
        redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Category not found');
    }
    
    // Check if category has services
    $stmt = db()->prepare("SELECT COUNT(*) as count FROM services WHERE category_id = ?");
    $stmt->execute([$category_id]);
    $services_count = $stmt->fetch()['count'];
    
    if ($services_count > 0) {
        redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Cannot delete category with services. Move or delete services first.');
    }
    
    // Delete category
    $stmt = db()->prepare("DELETE FROM service_categories WHERE id = ?");
    $stmt->execute([$category_id]);
    
    // Log activity
    log_activity('service_category_deleted', "Deleted service category: {$category['name']}", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/service-categories.php', 'success', 'Service category deleted successfully');
    
} catch (PDOException $e) {
    error_log("Delete service category error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/service-categories.php', 'error', 'Failed to delete service category');
}
