<?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') {
    redirect('../pages/data_maintenance.php?section=structure_sync');
}

if (!can_access($conn, 'maintenance_compare_database_structure')) {
    redirect_with_flash('../pages/data_maintenance.php?section=structure_sync', 'error', localized_flash_message('คุณไม่มีสิทธิ์เปรียบเทียบโครงสร้างฐานข้อมูล', 'You do not have permission to compare database structure.'));
}

$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));

try {
    $preview = maintenance_structure_sync_preview($sourceInput, $targetInput, $conn);
} catch (Throwable $exception) {
    redirect_with_flash(
        '../pages/data_maintenance.php?section=structure_sync',
        'error',
        $exception->getMessage() !== '' ? $exception->getMessage() : 'Database Structure Sync preview failed.'
    );
}

$fileName = 'structure_compare_' . date('Ymd_His') . '.json';
$payload = json_encode($preview, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($payload === false) {
    redirect_with_flash('../pages/data_maintenance.php?section=structure_sync', 'error', localized_flash_message('ไม่สามารถสร้างไฟล์เปรียบเทียบ JSON ได้', 'Unable to build compare JSON.'));
}

header('Content-Type: application/json; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . strlen($payload));

echo $payload;
exit;
