<?php

declare(strict_types=1);

require_once __DIR__ . '/db_backup_export.php';
require_once __DIR__ . '/backup_ftp.php';

/**
 * Create a local .sql backup, rotate old local files, optionally upload the new file to FTP (append-only on remote).
 *
 * @return array{
 *   ok:bool,
 *   local_file:?string,
 *   local_error:?string,
 *   ftp_ok:?bool,
 *   ftp_message:?string
 * }
 */
function scheduled_db_backup_run(PDO $pdo, int $keepLocal = 50): array
{
    $root = realpath(__DIR__ . '/..');
    if ($root === false) {
        $root = dirname(__DIR__);
    }
    $backupDir = $root . DIRECTORY_SEPARATOR . 'backups' . DIRECTORY_SEPARATOR;
    if (!is_dir($backupDir) && !@mkdir($backupDir, 0755, true)) {
        return [
            'ok' => false,
            'local_file' => null,
            'local_error' => 'ایجاد پوشه backups ممکن نیست',
            'ftp_ok' => null,
            'ftp_message' => null,
        ];
    }

    db_backup_cleanup_stale_part_files($backupDir);
    $backupFile = db_backup_alloc_filepath($backupDir);
    $result = db_backup_export_sql($pdo, $backupFile);
    if (empty($result['ok'])) {
        return [
            'ok' => false,
            'local_file' => null,
            'local_error' => $result['error'] ?? 'نامشخص',
            'ftp_ok' => null,
            'ftp_message' => null,
        ];
    }

    db_backup_rotate_files($backupDir, $keepLocal);

    $cfg = backup_ftp_load_config($pdo);
    $ftpOk = null;
    $ftpMsg = null;
    if (!empty($cfg['enabled'])) {
        $up = backup_ftp_upload_file($backupFile, $cfg);
        $ftpOk = $up['ok'];
        $ftpMsg = $up['message'];
    }

    return [
        'ok' => true,
        'local_file' => $backupFile,
        'local_error' => null,
        'ftp_ok' => $ftpOk,
        'ftp_message' => $ftpMsg,
    ];
}
