<?php

$tokenRec = require_valid_token_web();
require_role(['admin'], $tokenRec);

if ($method !== 'POST') {
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}

$backupDir = QDB_UPLOADS_DIR . '/backups';
if (!is_dir($backupDir)) {
    if (!mkdir($backupDir, 0755, true) && !is_dir($backupDir)) {
        json_error('SERVER_ERROR', 'Could not create backups directory', 500);
    }
}

$timestamp = date('Y-m-d_H-i-s');

if (qdb_is_mysql()) {
    [$host, $port] = [qdb_env_get('QDB_MYSQL_HOST') ?: '127.0.0.1', qdb_env_get('QDB_MYSQL_PORT') ?: '3306'];
    [$user, $pass] = qdb_mysql_credentials();
    $db = qdb_env_get('QDB_MYSQL_DATABASE') ?: 'nat-as-db';
    $filename = "questionnaire_mysql_{$timestamp}.sql";
    $backupFile = "$backupDir/$filename";
    if (!function_exists('proc_open')) {
        json_error('SERVER_ERROR', 'MySQL backup is unavailable: proc_open is disabled', 500);
    }

    $command = [
        'mysqldump',
        '--single-transaction',
        '--routines',
        '--triggers',
        "--host={$host}",
        "--port={$port}",
        "--user={$user}",
        $db,
    ];
    $environment = getenv();
    if (!is_array($environment)) {
        $environment = [];
    }
    if ($pass !== '') {
        $environment['MYSQL_PWD'] = $pass;
    }
    $descriptors = [
        0 => ['file', '/dev/null', 'r'],
        1 => ['file', $backupFile, 'wb'],
        2 => ['pipe', 'w'],
    ];
    $process = @proc_open($command, $descriptors, $pipes, null, $environment);
    if (!is_resource($process)) {
        @unlink($backupFile);
        json_error('SERVER_ERROR', 'MySQL backup failed to start mysqldump', 500);
    }
    $errorOutput = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    $code = proc_close($process);
    if ($code !== 0 || !is_file($backupFile) || filesize($backupFile) === 0) {
        @unlink($backupFile);
        $detail = trim((string)$errorOutput);
        json_error('SERVER_ERROR', 'MySQL backup failed' . ($detail !== '' ? ": {$detail}" : ''), 500);
    }
    @chmod($backupFile, 0600);
    json_success(['filename' => $filename]);
}

$dbPath = QDB_PATH;
if (!file_exists($dbPath)) {
    json_error('NOT_FOUND', 'No database to back up', 404);
}

$filename = "questionnaire_database.$timestamp";
$backupFile = "$backupDir/$filename";

if (!copy($dbPath, $backupFile)) {
    json_error('SERVER_ERROR', 'Backup copy failed', 500);
}

@chmod($backupFile, 0644);

json_success(['filename' => $filename]);
