<?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_package', $returnPath);

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

try {
    $artifact = maintenance_deployment_write_archive($conn, $deploymentFilters);
    $filePath = (string) ($artifact['absolute_path'] ?? '');
    $fileName = (string) ($artifact['file_name'] ?? 'deployment_source_only_package');
    $contentType = (string) ($artifact['mime_type'] ?? maintenance_deployment_archive_content_type($fileName));

    if ($filePath === '' || !is_file($filePath)) {
        throw new RuntimeException('Deployment package file was not found after export.');
    }

    header('Content-Type: ' . $contentType);
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . (string) filesize($filePath));
    readfile($filePath);
    exit;
} catch (Throwable $exception) {
    redirect_with_flash(
        $returnPath,
        'error',
        $exception->getMessage() !== ''
            ? $exception->getMessage()
            : localized_flash_message(
                'ไม่สามารถสร้าง source-only package ได้',
                'Source-only package export failed.'
            )
    );
}
