<?php
declare(strict_types=1);

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

require_login($conn);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method not allowed');
}

if (!can_access($conn, 'maintenance_compare_database_structure')) {
    http_response_code(403);
    exit('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) {
    $message = $exception->getMessage() !== '' ? $exception->getMessage() : 'Structure patch could not be generated.';
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo $message;
    exit;
}
