<?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_groups.php');
$serviceGroupId = filter_input(INPUT_POST, 'service_group_id', FILTER_VALIDATE_INT);
$returnServiceId = filter_input(INPUT_POST, 'return_service_id', FILTER_VALIDATE_INT);

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

if (!$serviceGroupId) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ไม่พบกลุ่มบริการ', 'Service group was not found.'));
}

$groupStmt = db_prepare($conn, "
    SELECT sg.group_id, sg.category_id, sg.main_service_id, sg.group_name, sg.show_window_film_details, COUNT(s.service_id) AS service_count
    FROM service_groups sg
    LEFT JOIN services s ON s.group_id = sg.group_id
    WHERE sg.group_id = ?
    GROUP BY sg.group_id, sg.group_name
    LIMIT 1
");
$groupStmt->bind_param('i', $serviceGroupId);
$groupStmt->execute();
$group = $groupStmt->get_result()->fetch_assoc();
$groupStmt->close();

if (!$group) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ไม่พบกลุ่มบริการ', 'Service group was not found.'));
}

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

try {
    $beforeSnapshot = array(
        'category_id' => (int) ($group['category_id'] ?? 0),
        'main_service_id' => (int) ($group['main_service_id'] ?? 0),
        'group_name' => (string) ($group['group_name'] ?? ''),
        'show_window_film_details' => (int) ($group['show_window_film_details'] ?? 0),
    );

    $deleteStmt = db_prepare($conn, "
        DELETE FROM service_groups
        WHERE group_id = ?
        LIMIT 1
    ");
    $deleteStmt->bind_param('i', $serviceGroupId);
    $deleteStmt->execute();
    $deleteStmt->close();

    audit_log($conn, array(
        'module_key' => 'group',
        'action_key' => 'delete',
        'entity_type' => 'service_group',
        'entity_id' => $serviceGroupId,
        'message' => localized_flash_message('ลบกลุ่มบริการเรียบร้อยแล้ว', 'Service group deleted.'),
        'before' => $beforeSnapshot,
    ));

    redirect_with_flash($redirectPath, 'success', localized_flash_message('ลบกลุ่มบริการเรียบร้อยแล้ว', 'Service group deleted.'));
} catch (Throwable $exception) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ลบกลุ่มบริการไม่สำเร็จ', 'Service group could not be deleted.'));
}
