<?php

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

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

$dbPath    = QDB_PATH;
$backupDir = QDB_UPLOADS_DIR . '/backups';

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

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