<?php
declare(strict_types=1);

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

require_login($conn);

$deploymentFilters = maintenance_deployment_filters($_POST);
$returnPage = safe_page_return(trim((string) ($_POST['return_page'] ?? '')), '');
$returnPath = $returnPage !== ''
    ? '../pages/' . $returnPage
    : '../pages/data_maintenance.php?section=production_export';
process_post_only_or_redirect($returnPath);
ensure_post_csrf_or_redirect('deployment_folder', $returnPath);

if (!can_access($conn, 'maintenance_prepare_deployment_package')) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message(
            'คุณไม่มีสิทธิ์สร้าง source-only folder',
            'You do not have permission to create a source-only folder.'
        )
    );
}

try {
    $artifact = maintenance_deployment_copy_source_folder($conn, $deploymentFilters);
    redirect_with_flash(
        $returnPath,
        'success',
        localized_flash_message(
            'สร้าง source-only folder เรียบร้อยแล้วที่ {folder_path}',
            'Source-only folder created at {folder_path}',
            array(
                'folder_path' => (string) ($artifact['relative_path'] ?? ''),
            )
        )
    );
} catch (Throwable $exception) {
    redirect_with_flash(
        $returnPath,
        'error',
        $exception->getMessage() !== ''
            ? $exception->getMessage()
            : localized_flash_message(
                'สร้าง source-only folder ไม่สำเร็จ',
                'Source-only folder export failed.'
            )
    );
}
