<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_permission($conn, 'services');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../pages/services.php');
}

$returnTo = safe_page_return((string) ($_POST['return_to'] ?? ''), 'service_categories.php');
$categoryId = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);
$returnServiceId = filter_input(INPUT_POST, 'return_service_id', FILTER_VALIDATE_INT);

$redirectPath = '../pages/' . $returnTo;

if (!$categoryId) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ไม่พบหมวดหมู่', 'Category was not found.'));
}

$categoryStmt = db_prepare($conn, "
    SELECT
        sc.category_id,
        sc.category_name,
        COUNT(DISTINCT s.service_id) AS service_count,
        COUNT(DISTINCT sg.group_id) AS group_count
    FROM service_categories sc
    LEFT JOIN services s ON s.category_id = sc.category_id
    LEFT JOIN service_groups sg ON sg.category_id = sc.category_id
    WHERE sc.category_id = ?
    GROUP BY sc.category_id, sc.category_name
    LIMIT 1
");
$categoryStmt->bind_param('i', $categoryId);
$categoryStmt->execute();
$category = $categoryStmt->get_result()->fetch_assoc();
$categoryStmt->close();

if (!$category) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ไม่พบหมวดหมู่', 'Category was not found.'));
}

if ((int) ($category['service_count'] ?? 0) > 0) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('หมวดหมู่นี้ยังมีบริการผูกอยู่ จึงไม่สามารถลบได้', 'This category still has services assigned and cannot be deleted.'));
}

if ((int) ($category['group_count'] ?? 0) > 0) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('หมวดหมู่นี้ยังมีกลุ่มบริการผูกอยู่ จึงไม่สามารถลบได้', 'This category still has service groups assigned and cannot be deleted.'));
}

try {
    $beforeSnapshot = array(
        'category_name' => (string) ($category['category_name'] ?? ''),
    );

    $deleteStmt = db_prepare($conn, "
        DELETE FROM service_categories
        WHERE category_id = ?
        LIMIT 1
    ");
    $deleteStmt->bind_param('i', $categoryId);
    $deleteStmt->execute();
    $deleteStmt->close();

    audit_log($conn, array(
        'module_key' => 'category',
        'action_key' => 'delete',
        'entity_type' => 'service_category',
        'entity_id' => $categoryId,
        'message' => 'Service category deleted.',
        'before' => $beforeSnapshot,
    ));

    redirect_with_flash($redirectPath, 'success', localized_flash_message('ลบหมวดหมู่เรียบร้อยแล้ว', 'Category deleted.'));
} catch (Throwable $exception) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ลบหมวดหมู่ไม่สำเร็จ', 'Category could not be deleted.'));
}
