<?php
/**
 * Automated Database Backup Script
 * Recommended Cron Job: 0 0 * * * /usr/bin/php /path/to/project/cron_backup.php
 */

require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/db/BackupService.php';

// Check if auto-backup is enabled
$stmt = db()->prepare("SELECT `key`, `value` FROM settings WHERE `key` IN ('backup_auto_enabled', 'backup_limit', 'backup_time')");
$stmt->execute();
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$enabled = $settings['backup_auto_enabled'] ?? '0';

if ($enabled === '1') {
    $scheduledTime = $settings['backup_time'] ?? '00:00';
    $currentTime = date('H:i');

    if ($currentTime !== $scheduledTime) {
        die("[" . date('Y-m-d H:i:s') . "] Not the scheduled time ($scheduledTime). Current time: $currentTime\n");
    }

    $limit = $settings['backup_limit'] ?? 5;

    echo "[" . date('Y-m-d H:i:s') . "] Starting automated backup...\n";
    $res = BackupService::createBackup();
    
    if ($res['success']) {
        echo "[" . date('Y-m-d H:i:s') . "] Backup created successfully: " . $res['file'] . "\n";
    } else {
        echo "[" . date('Y-m-d H:i:s') . "] Error creating backup: " . $res['error'] . "\n";
    }
} else {
    echo "[" . date('Y-m-d H:i:s') . "] Automated backup is disabled in settings.\n";
}
