<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/functions_backup.php';
require_once dirname(__DIR__) . '/includes/auth.php';
requirePermission('export_data');

$pdo = getDBConnection();
$stmt = $pdo->query("SELECT setting_key, setting_value, setting_group FROM settings ORDER BY setting_group, setting_key");
$rows = array_values(array_filter($stmt->fetchAll(), 'backupSettingRowIsExportable'));
$payload = [
    'app_name' => 'MelonLite',
    'export_version' => 2,
    'export_type' => 'settings',
    'generated_at' => date('c'),
    'sections' => ['settings'],
    'counts' => ['settings' => count($rows)],
    'data' => ['settings' => $rows],
    'settings' => $rows,
];
if (function_exists('writeAppLog')) writeAppLog('info', 'export', 'Settings export generated', ['count' => count($rows)]);
header('Content-Type: application/json; charset=utf-8');
header('Content-Disposition: attachment; filename="melonlite_settings_' . date('Y-m-d_His') . '.json"');
header('X-Content-Type-Options: nosniff');
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
