<?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'] ?? ''), 'services.php');
$serviceId = filter_input(INPUT_POST, 'service_id', FILTER_VALIDATE_INT);
$returnCategoryId = filter_input(INPUT_POST, 'return_category_id', FILTER_VALIDATE_INT);

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

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

$serviceStmt = db_prepare($conn, "
    SELECT
        s.service_id,
        s.service_name,
        s.service_type,
        s.category_id,
        s.main_service_id,
        s.group_id,
        s.package_vehicle_scope,
        s.is_quick_service,
        s.price,
        s.description,
        s.is_active,
        COUNT(DISTINCT od.detail_id) AS usage_count,
        COUNT(DISTINCT child.service_id) AS child_service_count,
        COUNT(DISTINCT sg.group_id) AS group_count,
        COUNT(DISTINCT spi_as_package.package_item_id) AS package_item_count,
        COUNT(DISTINCT spi_as_sub.package_item_id) AS package_reference_count,
        COUNT(DISTINCT cpi.customer_package_item_id) AS customer_package_reference_count
    FROM services s
    LEFT JOIN order_details od ON od.service_id = s.service_id
    LEFT JOIN services child ON child.main_service_id = s.service_id
    LEFT JOIN service_groups sg ON sg.main_service_id = s.service_id
    LEFT JOIN service_package_items spi_as_package ON spi_as_package.package_service_id = s.service_id
    LEFT JOIN service_package_items spi_as_sub ON spi_as_sub.sub_service_id = s.service_id
    LEFT JOIN customer_package_items cpi ON cpi.sub_service_id = s.service_id
    WHERE s.service_id = ?
    GROUP BY s.service_id, s.service_name, s.service_type
    LIMIT 1
");
$serviceStmt->bind_param('i', $serviceId);
$serviceStmt->execute();
$service = $serviceStmt->get_result()->fetch_assoc();
$serviceStmt->close();

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

if ((int) ($service['usage_count'] ?? 0) > 0) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('บริการนี้มีประวัติการใช้งานแล้ว จึงไม่สามารถลบได้ กรุณาปิดใช้งานแทน', 'This service is already used in history and cannot be deleted. Set it inactive instead.'));
}

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

if ((int) ($service['package_reference_count'] ?? 0) > 0 || (int) ($service['customer_package_reference_count'] ?? 0) > 0) {
    $packageBlockers = service_sub_service_package_blockers($conn, $serviceId);
    redirect_with_flash($redirectPath, 'error', service_sub_service_package_blocker_flash($packageBlockers, 'delete'));
}

try {
    $beforeSnapshot = array(
        'service_name' => (string) ($service['service_name'] ?? ''),
        'service_type' => (string) ($service['service_type'] ?? ''),
        'category_id' => (int) ($service['category_id'] ?? 0),
        'main_service_id' => (int) ($service['main_service_id'] ?? 0),
        'group_id' => (int) ($service['group_id'] ?? 0),
        'package_vehicle_scope' => (string) ($service['package_vehicle_scope'] ?? ''),
        'is_quick_service' => (int) ($service['is_quick_service'] ?? 0),
        'price' => (float) ($service['price'] ?? 0),
        'description' => (string) ($service['description'] ?? ''),
        'is_active' => (int) ($service['is_active'] ?? 0),
        'package_items' => service_package_purchase_snapshot($conn, $serviceId),
    );

    if ((string) ($service['service_type'] ?? 'sub_service') === 'package' || (int) ($service['package_item_count'] ?? 0) > 0) {
        $deletePackageItemsStmt = db_prepare($conn, "
            DELETE FROM service_package_items
            WHERE package_service_id = ?
        ");
        $deletePackageItemsStmt->bind_param('i', $serviceId);
        $deletePackageItemsStmt->execute();
        $deletePackageItemsStmt->close();
    }

    $deleteStmt = db_prepare($conn, "
        DELETE FROM services
        WHERE service_id = ?
        LIMIT 1
    ");
    $deleteStmt->bind_param('i', $serviceId);
    $deleteStmt->execute();
    $deleteStmt->close();

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

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