<?php
/**
 * Daily database backup — run via cron at 03:00
 * 0 3 * * * php /path/cron/backup_db.php
 */
require_once __DIR__ . '/../config.php';

$backupDir = __DIR__ . '/../backups';
if (!is_dir($backupDir)) @mkdir($backupDir, 0750, true);

$date = date('Ymd_His');
$file = "$backupDir/sudanna_$date.sql.gz";

$cmd = sprintf(
    'mysqldump --single-transaction --quick --skip-lock-tables -h%s -u%s -p%s %s | gzip > %s',
    escapeshellarg(DB_HOST),
    escapeshellarg(DB_USER),
    escapeshellarg(DB_PASS),
    escapeshellarg(DB_NAME),
    escapeshellarg($file)
);

exec($cmd, $out, $rc);

if ($rc === 0) {
    error_log("[backup_db] success: $file (" . filesize($file) . ' bytes)');
    // Retain last 14 days
    $cutoff = time() - (14 * 86400);
    foreach (glob("$backupDir/sudanna_*.sql.gz") as $old) {
        if (filemtime($old) < $cutoff) @unlink($old);
    }
} else {
    error_log("[backup_db] FAILED rc=$rc cmd=$cmd");
    // Optionally email admin
}
