<?php
/**
 * نسخ احتياطي تلقائي - للتشغيل من Cron
 * Windows: schtasks
 * Linux: 0 2 * * * php /path/to/scripts/backup_cron.php
 */
$baseDir = dirname(__DIR__);
$config = require $baseDir . '/config/config.php';
$backupConfig = $config['backup'] ?? [];

if (!($backupConfig['enabled'] ?? true)) {
    echo "Backup disabled in config.\n";
    exit(0);
}

$db = $config['db'];
$backupDir = $baseDir . '/backups';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$date = date('Y-m-d_H-i-s');
$filename = 'backup_' . $date . '.sql';
$filepath = $backupDir . '/' . $filename;

$host = $db['host'] ?? 'localhost';
$port = (int)($db['port'] ?? 3306);
$name = $db['name'] ?? 'lab_lims';
$user = $db['user'] ?? 'root';
$pass = $db['pass'] ?? '';

$passArg = $pass !== '' ? '-p' . escapeshellarg($pass) : '';
$cmd = sprintf(
    'mysqldump -h %s -P %d -u %s %s %s > %s 2>&1',
    escapeshellarg($host),
    $port,
    escapeshellarg($user),
    $passArg,
    escapeshellarg($name),
    escapeshellarg($filepath)
);

exec($cmd, $output, $ret);
if ($ret !== 0) {
    fwrite(STDERR, "Backup failed: " . implode("\n", $output) . "\n");
    exit(1);
}

echo "Backup done: $filepath\n";

$retentionDays = (int)($backupConfig['retention_days'] ?? 7);
$maxAge = $retentionDays * 86400;
foreach (glob($backupDir . '/backup_*.sql') ?: [] as $f) {
    if (filemtime($f) < time() - $maxAge) {
        unlink($f);
        echo "Deleted old: $f\n";
    }
}
