<?php
require_once __DIR__ . '/../config/db.php';

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

$today = date('Y-m-d');
$stmt = $pdo->query("SELECT MAX(created_at) as last_backup FROM backups_log");
$lastBackup = $stmt->fetchColumn();

if(!$lastBackup || strtotime($lastBackup) < strtotime('-1 day')){
    $fileName = "backup_" . date('Y-m-d_H-i') . ".sql";
    $filePath = $backupDir . $fileName;

    $dbHost = $DB_HOST;
    $dbUser = $DB_USER;
    $dbPass = $DB_PASS;
    $dbName = $DB_NAME;

    // إنشاء النسخة
    $command = "mysqldump --user={$dbUser} --password=\"{$dbPass}\" --host={$dbHost} {$dbName} > {$filePath}";
    system($command);

    // حفظ السجل في قاعدة البيانات
    $stmt = $pdo->prepare("INSERT INTO backups_log (file_name) VALUES (?)");
    $stmt->execute([$fileName]);

    // حذف النسخ القديمة (احتفظ بآخر 7)
    $files = glob($backupDir . 'backup_*.sql');
    usort($files, function($a, $b){ return filemtime($b) - filemtime($a); });
    foreach(array_slice($files, 7) as $oldFile){ unlink($oldFile); }
}
?>
