<?php
declare(strict_types=1);

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

require_permission($conn, 'services');

process_post_only_or_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);
$categoryId = filter_input(INPUT_POST, 'group_category_id', FILTER_VALIDATE_INT);
$mainServiceId = filter_input(INPUT_POST, 'group_main_service_id', FILTER_VALIDATE_INT);
$groupName = trim((string) ($_POST['group_name'] ?? ''));
$showWindowFilmDetails = isset($_POST['show_window_film_details']) ? 1 : 0;

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

$oldInput = array(
    'group_category_id' => (string) ($categoryId ?: ''),
    'group_main_service_id' => (string) ($mainServiceId ?: ''),
    'group_name' => $groupName,
    'show_window_film_details' => (string) $showWindowFilmDetails,
);

if (!$categoryId || !$mainServiceId || $groupName === '') {
    redirect_with_flash(
        $redirectPath,
        'error',
        localized_flash_message('กรุณาระบุหมวดหมู่ บริการหลัก และชื่อกลุ่มบริการ', 'Category, main service and group name are required.'),
        $oldInput
    );
}

$mainServiceStmt = db_prepare($conn, "
    SELECT service_id, category_id
    FROM services
    WHERE service_id = ?
        AND service_type = 'main_service'
    LIMIT 1
");
$mainServiceStmt->bind_param('i', $mainServiceId);
$mainServiceStmt->execute();
$mainService = $mainServiceStmt->get_result()->fetch_assoc();
$mainServiceStmt->close();

if (!$mainService) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('ไม่พบบริการหลักที่เลือก', 'Selected main service is not available.'), $oldInput);
}

$resolvedCategoryId = (int) ($mainService['category_id'] ?? 0);
if ($resolvedCategoryId <= 0 || $resolvedCategoryId !== $categoryId) {
    redirect_with_flash($redirectPath, 'error', localized_flash_message('หมวดหมู่ที่เลือกไม่ตรงกับบริการหลัก', 'Selected category does not match the chosen main service.'), $oldInput);
}

$currentGroup = null;
$beforeGroupSnapshot = array();
if ($serviceGroupId) {
    $groupStmt = db_prepare($conn, "
        SELECT group_id, category_id, main_service_id, group_name, show_window_film_details
        FROM service_groups
        WHERE group_id = ?
        LIMIT 1
    ");
    $groupStmt->bind_param('i', $serviceGroupId);
    $groupStmt->execute();
    $currentGroup = $groupStmt->get_result()->fetch_assoc();
    $groupStmt->close();

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

    $beforeGroupSnapshot = array(
        'category_id' => (int) ($currentGroup['category_id'] ?? 0),
        'main_service_id' => (int) ($currentGroup['main_service_id'] ?? 0),
        'group_name' => (string) ($currentGroup['group_name'] ?? ''),
        'show_window_film_details' => (int) ($currentGroup['show_window_film_details'] ?? 0),
    );
}

$conn->begin_transaction();

try {
    if ($serviceGroupId) {
        $stmt = db_prepare($conn, "
            UPDATE service_groups
            SET category_id = ?,
                main_service_id = ?,
                group_name = ?,
                show_window_film_details = ?
            WHERE group_id = ?
        ");
        $stmt->bind_param('iisii', $resolvedCategoryId, $mainServiceId, $groupName, $showWindowFilmDetails, $serviceGroupId);
        $stmt->execute();
        $stmt->close();

        $groupDiff = audit_diff_assoc($beforeGroupSnapshot, array(
            'category_id' => $resolvedCategoryId,
            'main_service_id' => $mainServiceId,
            'group_name' => $groupName,
            'show_window_film_details' => $showWindowFilmDetails,
        ));
        if (!empty($groupDiff['after'])) {
            audit_log($conn, array(
                'module_key' => 'group',
                'action_key' => 'update',
                'entity_type' => 'service_group',
                'entity_id' => $serviceGroupId,
                'message' => 'Service group updated.',
                'before' => $groupDiff['before'],
                'after' => $groupDiff['after'],
            ));
        }

        $conn->commit();
        redirect_with_flash($successPath, 'success', localized_flash_message('อัปเดตกลุ่มบริการเรียบร้อยแล้ว', 'Service group updated.'));
    }

    $stmt = db_prepare($conn, "
        INSERT INTO service_groups (category_id, main_service_id, group_name, show_window_film_details)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->bind_param('iisi', $resolvedCategoryId, $mainServiceId, $groupName, $showWindowFilmDetails);
    $stmt->execute();
    $serviceGroupId = (int) $conn->insert_id;
    $stmt->close();

    audit_log($conn, array(
        'module_key' => 'group',
        'action_key' => 'create',
        'entity_type' => 'service_group',
        'entity_id' => $serviceGroupId,
        'message' => 'Service group created.',
        'after' => array(
            'category_id' => $resolvedCategoryId,
            'main_service_id' => $mainServiceId,
            'group_name' => $groupName,
            'show_window_film_details' => $showWindowFilmDetails,
        ),
    ));

    $conn->commit();
    redirect_with_flash($successPath, 'success', localized_flash_message('เพิ่มกลุ่มบริการเรียบร้อยแล้ว', 'Service group added.'));
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'save_service_group',
        $redirectPath,
        localized_flash_message('บันทึกกลุ่มบริการไม่สำเร็จ ชื่อนี้อาจถูกใช้งานแล้ว', 'Service group was not saved. The name may already be in use.'),
        array(
            'service_group_id' => (int) ($serviceGroupId ?: 0),
            'category_id' => (int) ($categoryId ?: 0),
            'main_service_id' => (int) ($mainServiceId ?: 0),
            'return_to' => $returnTo,
            'return_service_id' => (int) ($returnServiceId ?: 0),
        ),
        $oldInput
    );
}
