<?php
declare(strict_types=1);

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

require_login($conn);

$returnPage = safe_page_return(trim((string) ($_POST['return_page'] ?? '')), '');
$returnPath = $returnPage !== ''
    ? '../pages/' . $returnPage
    : '../pages/data_maintenance.php?section=structure_sync';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect($returnPath);
}

if (!can_access($conn, 'maintenance_compare_database_structure')) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message(
            'คุณไม่มีสิทธิ์ดาวน์โหลด structure patch',
            'You do not have permission to download structure patches.'
        )
    );
}

$sourceInput = maintenance_structure_sync_input($_POST['source'] ?? array(), maintenance_structure_sync_current_config($conn));
$targetInput = maintenance_structure_sync_input($_POST['target'] ?? array(), maintenance_structure_sync_custom_defaults($conn));
$scope = strtolower(trim((string) ($_POST['patch_scope'] ?? 'combined')));
if (!in_array($scope, array('safe', 'manual', 'combined'), true)) {
    $scope = 'combined';
}

try {
    $preview = maintenance_structure_sync_preview($sourceInput, $targetInput, $conn);
    $sql = maintenance_structure_sync_build_patch_sql($preview, $scope);
    $fileName = 'structure_sync_' . $scope . '_' . date('Ymd_His') . '.sql';

    header('Content-Type: application/sql; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . strlen($sql));
    echo $sql;
    exit;
} catch (Throwable $exception) {
    redirect_with_flash(
        $returnPath,
        'error',
        $exception->getMessage() !== ''
            ? $exception->getMessage()
            : localized_flash_message(
                'ไม่สามารถสร้าง structure patch ได้',
                'Structure patch could not be generated.'
            )
    );
}
