<?php
/**
 * Scheduled database backup (local + optional FTP).
 * Add to crontab, e.g. every night:
 *   0 3 * * * /usr/bin/php /path/to/project/cron/db_backup.php >> /path/to/project/backups/cron.log 2>&1
 *
 * Remote FTP is append-only: this script never deletes files on the FTP server.
 */
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/scheduled_db_backup.php';

$out = scheduled_db_backup_run($pdo, 50);
$ts = date('c');

if (empty($out['ok'])) {
    echo $ts . ' BACKUP FAIL: ' . ($out['local_error'] ?? '') . "\n";
    exit(1);
}

echo $ts . ' BACKUP OK: ' . basename((string) $out['local_file']) . "\n";
if ($out['ftp_ok'] !== null) {
    echo $ts . ' FTP: ' . ($out['ftp_ok'] ? 'OK' : 'FAIL') . ' — ' . ($out['ftp_message'] ?? '') . "\n";
    if ($out['ftp_ok'] === false) {
        exit(2);
    }
}

require_once __DIR__ . '/../includes/scheduled_files_backup.php';
$f = scheduled_files_backup_run($pdo, false);
if (empty($f['skipped'])) {
    echo $ts . ' FILES_FTP: ' . ($f['ok'] ? 'OK' : 'FAIL') . ' — ' . ($f['message'] ?? '') . "\n";
    if ($f['ftp_message'] !== null && $f['ftp_message'] !== '') {
        echo $ts . ' FILES_FTP detail: ' . $f['ftp_message'] . "\n";
    }
}
