<?php
// session_start();
// require_once 'auth_check.php';
require_once '../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// Create backups directory if not exists
$backupDir = '../backups';
if (!file_exists($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$message = '';
$messageType = '';

// Handle full backup creation (Database + Files)
if (isset($_POST['create_full_backup'])) {
    try {
        $timestamp = date('Y-m-d_H-i-s');
        $backupName = "full_backup_{$timestamp}";
        $backupFolder = $backupDir . '/' . $backupName;
        
        // Create backup folder
        if (!file_exists($backupFolder)) {
            mkdir($backupFolder, 0755, true);
        }
        
        // 1. Backup Database
        $sqlFilename = "database.sql";
        $sqlFilepath = $backupFolder . '/' . $sqlFilename;
        
        // Get all tables
        $tables = [];
        $result = $conn->query("SHOW TABLES");
        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }
        
        $output = "-- Roz Skin Database Backup/n";
        $output .= "-- Generated: " . date('Y-m-d H:i:s') . "/n";
        $output .= "-- Tables: " . count($tables) . "/n/n";
        $output .= "SET FOREIGN_KEY_CHECKS=0;/n/n";
        
        // Loop through tables
        foreach ($tables as $table) {
            // Get CREATE TABLE statement
            $createTable = $conn->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
            $output .= "/n-- Table: $table/n";
            $output .= "DROP TABLE IF EXISTS `$table`;/n";
            $output .= $createTable['Create Table'] . ";/n/n";
            
            // Get table data
            $rows = $conn->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($rows)) {
                $output .= "-- Data for table: $table/n";
                
                foreach ($rows as $row) {
                    $values = array_map(function($value) use ($conn) {
                        if ($value === null) return 'NULL';
                        return $conn->quote($value);
                    }, array_values($row));
                    
                    $columns = array_map(function($col) {
                        return "`$col`";
                    }, array_keys($row));
                    
                    $output .= "INSERT INTO `$table` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ");/n";
                }
                $output .= "/n";
            }
        }
        
        $output .= "SET FOREIGN_KEY_CHECKS=1;/n";
        
        // Save database to file
        file_put_contents($sqlFilepath, $output);
        
        // 2. Copy important folders
        $foldersToBackup = [
            '../uploads' => 'uploads',
            '../assets/images' => 'assets/images',
            '../public/uploads' => 'public/uploads'
        ];
        
        $totalFiles = 0;
        $totalSize = filesize($sqlFilepath);
        
        foreach ($foldersToBackup as $source => $dest) {
            if (is_dir($source)) {
                $destPath = $backupFolder . '/' . $dest;
                $result = recursiveCopy($source, $destPath);
                $totalFiles += $result['files'];
                $totalSize += $result['size'];
            }
        }
        
        // 3. Create ZIP archive
        $zipFilename = $backupName . '.zip';
        $zipFilepath = $backupDir . '/' . $zipFilename;
        
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive();
            if ($zip->open($zipFilepath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                addFolderToZip($backupFolder, $zip, strlen($backupFolder) + 1);
                $zip->close();
                
                // Delete temporary folder
                deleteDirectory($backupFolder);
                
                $finalSize = filesize($zipFilepath);
            } else {
                throw new Exception('فشل إنشاء ملف ZIP');
            }
        } else {
            // If ZipArchive not available, keep folder
            $zipFilepath = $backupFolder;
            $finalSize = $totalSize;
        }
        
        // Create metadata file
        $metadata = [
            'filename' => basename($zipFilepath),
            'type' => 'full',
            'created_at' => date('Y-m-d H:i:s'),
            'size' => $finalSize,
            'tables' => count($tables),
            'files' => $totalFiles,
            'created_by' => 'Admin'
        ];
        file_put_contents($zipFilepath . '.meta', json_encode($metadata, JSON_PRETTY_PRINT));
        
        $message = "تم إنشاء النسخة الاحتياطية الكاملة بنجاح! ✅<br>الجداول: " . count($tables) . " | الملفات: $totalFiles";
        $messageType = 'success';
        
    } catch (Exception $e) {
        $message = 'خطأ في إنشاء النسخة الاحتياطية: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Handle database-only backup
if (isset($_POST['create_backup'])) {
    try {
        $timestamp = date('Y-m-d_H-i-s');
        $filename = "backup_{$timestamp}.sql";
        $filepath = $backupDir . '/' . $filename;
        
        // Get all tables
        $tables = [];
        $result = $conn->query("SHOW TABLES");
        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }
        
        $output = "-- Roz Skin Database Backup/n";
        $output .= "-- Generated: " . date('Y-m-d H:i:s') . "/n";
        $output .= "-- Tables: " . count($tables) . "/n/n";
        $output .= "SET FOREIGN_KEY_CHECKS=0;/n/n";
        
        // Loop through tables
        foreach ($tables as $table) {
            $createTable = $conn->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
            $output .= "/n-- Table: $table/n";
            $output .= "DROP TABLE IF EXISTS `$table`;/n";
            $output .= $createTable['Create Table'] . ";/n/n";
            
            $rows = $conn->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($rows)) {
                $output .= "-- Data for table: $table/n";
                
                foreach ($rows as $row) {
                    $values = array_map(function($value) use ($conn) {
                        if ($value === null) return 'NULL';
                        return $conn->quote($value);
                    }, array_values($row));
                    
                    $columns = array_map(function($col) {
                        return "`$col`";
                    }, array_keys($row));
                    
                    $output .= "INSERT INTO `$table` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ");/n";
                }
                $output .= "/n";
            }
        }
        
        $output .= "SET FOREIGN_KEY_CHECKS=1;/n";
        
        file_put_contents($filepath, $output);
        
        $metadata = [
            'filename' => $filename,
            'type' => 'database',
            'created_at' => date('Y-m-d H:i:s'),
            'size' => filesize($filepath),
            'tables' => count($tables),
            'created_by' => 'Admin'
        ];
        file_put_contents($filepath . '.meta', json_encode($metadata, JSON_PRETTY_PRINT));
        
        $message = 'تم إنشاء نسخة احتياطية لقاعدة البيانات بنجاح! ✅';
        $messageType = 'success';
        
    } catch (Exception $e) {
        $message = 'خطأ في إنشاء النسخة الاحتياطية: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Helper functions
function recursiveCopy($src, $dst) {
    $files = 0;
    $size = 0;
    
    if (!file_exists($dst)) {
        mkdir($dst, 0755, true);
    }
    
    $dir = opendir($src);
    while (($file = readdir($dir)) !== false) {
        if ($file != '.' && $file != '..') {
            $srcPath = $src . '/' . $file;
            $dstPath = $dst . '/' . $file;
            
            if (is_dir($srcPath)) {
                $result = recursiveCopy($srcPath, $dstPath);
                $files += $result['files'];
                $size += $result['size'];
            } else {
                copy($srcPath, $dstPath);
                $files++;
                $size += filesize($srcPath);
            }
        }
    }
    closedir($dir);
    
    return ['files' => $files, 'size' => $size];
}

function addFolderToZip($folder, $zip, $baseLen) {
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($folder),
        RecursiveIteratorIterator::LEAVES_ONLY
    );
    
    foreach ($files as $file) {
        if (!$file->isDir()) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, $baseLen);
            $zip->addFile($filePath, $relativePath);
        }
    }
}

function deleteDirectory($dir) {
    if (!file_exists($dir)) return;
    
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    
    foreach ($files as $file) {
        if ($file->isDir()) {
            rmdir($file->getRealPath());
        } else {
            unlink($file->getRealPath());
        }
    }
    
    rmdir($dir);
}

// Handle backup restore
if (isset($_POST['restore_backup'])) {
    $filename = $_POST['backup_file'];
    $filepath = $backupDir . '/' . $filename;
    
    if (file_exists($filepath)) {
        try {
            $sql = file_get_contents($filepath);
            
            // Split by semicolon and execute
            $statements = array_filter(
                array_map('trim', explode(';', $sql)),
                function($stmt) {
                    return !empty($stmt) && 
                           !preg_match('/^--/', $stmt) && 
                           !preg_match('/^///*/', $stmt);
                }
            );
            
            $executed = 0;
            foreach ($statements as $statement) {
                if (!empty(trim($statement))) {
                    $conn->exec($statement);
                    $executed++;
                }
            }
            
            $message = "تم استعادة النسخة الاحتياطية بنجاح! تم تنفيذ $executed استعلام ✅";
            $messageType = 'success';
            
        } catch (Exception $e) {
            $message = 'خطأ في استعادة النسخة الاحتياطية: ' . $e->getMessage();
            $messageType = 'error';
        }
    } else {
        $message = 'الملف غير موجود!';
        $messageType = 'error';
    }
}

// Handle backup deletion
if (isset($_POST['delete_backup'])) {
    $filename = $_POST['backup_file'];
    $filepath = $backupDir . '/' . $filename;
    
    if (file_exists($filepath)) {
        unlink($filepath);
        if (file_exists($filepath . '.meta')) {
            unlink($filepath . '.meta');
        }
        $message = 'تم حذف النسخة الاحتياطية بنجاح! ✅';
        $messageType = 'success';
    }
}

// Handle backup download
if (isset($_GET['download'])) {
    $filename = $_GET['download'];
    $filepath = $backupDir . '/' . $filename;
    
    if (file_exists($filepath)) {
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    }
}

// Get all backups
$backups = [];
if (is_dir($backupDir)) {
    $files = scandir($backupDir);
    foreach ($files as $file) {
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        
        // Check for SQL files or ZIP files
        if ($ext === 'sql' || $ext === 'zip' || is_dir($backupDir . '/' . $file)) {
            if ($file === '.' || $file === '..') continue;
            
            $filepath = $backupDir . '/' . $file;
            $metafile = $filepath . '.meta';
            
            $backup = [
                'filename' => $file,
                'type' => 'database',
                'size' => is_dir($filepath) ? 0 : filesize($filepath),
                'created_at' => date('Y-m-d H:i:s', filemtime($filepath)),
                'tables' => 0,
                'files' => 0,
                'created_by' => 'Unknown'
            ];
            
            if (file_exists($metafile)) {
                $meta = json_decode(file_get_contents($metafile), true);
                $backup = array_merge($backup, $meta);
            }
            
            // Determine type from filename if not in meta
            if (strpos($file, 'full_backup') !== false) {
                $backup['type'] = 'full';
            }
            
            $backups[] = $backup;
        }
    }
}

// Sort by date (newest first)
usort($backups, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Get database info
$dbInfo = [
    'tables' => 0,
    'size' => 0
];

try {
    $result = $conn->query("SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()");
    $dbInfo['tables'] = $result->fetch(PDO::FETCH_ASSOC)['count'];
    
    $result = $conn->query("SELECT SUM(data_length + index_length) as size FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()");
    $dbInfo['size'] = $result->fetch(PDO::FETCH_ASSOC)['size'];
} catch (Exception $e) {
    // Ignore
}

function formatBytes($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' Bytes';
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>النسخ الاحتياطية - Roz Skin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f5f5; }
        
        .header {
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 5px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        
        .stat-icon.blue { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; }
        .stat-icon.green { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; }
        .stat-icon.purple { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; }
        
        .stat-info h3 {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        
        .stat-info p {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 30px;
            margin-bottom: 30px;
        }
        
        .card h2 {
            font-size: 20px;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-right: 4px solid #10b981;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-right: 4px solid #ef4444;
        }
        
        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-right: 4px solid #3b82f6;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(229, 115, 147, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }
        
        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
        }
        
        .btn-secondary {
            background: #f3f4f6;
            color: #374151;
        }
        
        .btn-secondary:hover {
            background: #e5e7eb;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 15px;
            text-align: right;
            border-bottom: 1px solid #e5e7eb;
        }
        
        th {
            background: #f9fafb;
            font-weight: 600;
            color: #374151;
        }
        
        tr:hover {
            background: #f9fafb;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-success {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-info {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #9ca3af;
        }
        
        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: white;
            text-decoration: none;
            margin-bottom: 20px;
            opacity: 0.9;
            transition: opacity 0.3s;
        }
        
        .back-link:hover {
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="header">
        <a href="dashboard.php" class="back-link">
            <i class="fas fa-arrow-right"></i> العودة للوحة التحكم
        </a>
        <h1><i class="fas fa-database"></i> النسخ الاحتياطية</h1>
        <p>إدارة النسخ الاحتياطية لقاعدة البيانات</p>
    </div>
    
    <div class="container">
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <!-- Statistics -->
        <div class="stats">
            <div class="stat-card">
                <div class="stat-icon blue">
                    <i class="fas fa-database"></i>
                </div>
                <div class="stat-info">
                    <h3>عدد الجداول</h3>
                    <p><?php echo $dbInfo['tables']; ?></p>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon green">
                    <i class="fas fa-hdd"></i>
                </div>
                <div class="stat-info">
                    <h3>حجم قاعدة البيانات</h3>
                    <p><?php echo formatBytes($dbInfo['size']); ?></p>
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon purple">
                    <i class="fas fa-copy"></i>
                </div>
                <div class="stat-info">
                    <h3>عدد النسخ الاحتياطية</h3>
                    <p><?php echo count($backups); ?></p>
                </div>
            </div>
        </div>
        
        <!-- Create Backup -->
        <div class="card">
            <h2><i class="fas fa-plus-circle"></i> إنشاء نسخة احتياطية جديدة</h2>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px;">
                <!-- Full Backup -->
                <div style="border: 2px solid #10b981; border-radius: 12px; padding: 20px; background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);">
                    <h3 style="color: #065f46; margin-bottom: 10px; display: flex; align-items: center; gap: 10px;">
                        <i class="fas fa-archive"></i> نسخة كاملة (موصى بها)
                    </h3>
                    <p style="color: #047857; font-size: 14px; margin-bottom: 15px; line-height: 1.6;">
                        تشمل قاعدة البيانات + جميع الملفات والصور
                    </p>
                    <ul style="color: #065f46; font-size: 13px; margin-bottom: 15px; padding-right: 20px;">
                        <li>✅ جميع الجداول والبيانات</li>
                        <li>✅ مجلد uploads (الصور)</li>
                        <li>✅ مجلد assets</li>
                        <li>✅ ملف ZIP مضغوط</li>
                    </ul>
                    <form method="POST" onsubmit="return confirm('سيتم إنشاء نسخة كاملة (قد يستغرق وقتاً). هل تريد المتابعة؟')">
                        <button type="submit" name="create_full_backup" class="btn btn-success" style="width: 100%;">
                            <i class="fas fa-archive"></i> إنشاء نسخة كاملة
                        </button>
                    </form>
                </div>
                
                <!-- Database Only -->
                <div style="border: 2px solid #3b82f6; border-radius: 12px; padding: 20px; background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);">
                    <h3 style="color: #1e40af; margin-bottom: 10px; display: flex; align-items: center; gap: 10px;">
                        <i class="fas fa-database"></i> قاعدة البيانات فقط
                    </h3>
                    <p style="color: #1e3a8a; font-size: 14px; margin-bottom: 15px; line-height: 1.6;">
                        نسخة سريعة لقاعدة البيانات فقط
                    </p>
                    <ul style="color: #1e40af; font-size: 13px; margin-bottom: 15px; padding-right: 20px;">
                        <li>✅ جميع الجداول والبيانات</li>
                        <li>⚠️ بدون الملفات والصور</li>
                        <li>✅ ملف SQL صغير</li>
                        <li>✅ سريع جداً</li>
                    </ul>
                    <form method="POST" onsubmit="return confirm('سيتم إنشاء نسخة لقاعدة البيانات فقط. هل تريد المتابعة؟')">
                        <button type="submit" name="create_backup" class="btn btn-primary" style="width: 100%;">
                            <i class="fas fa-database"></i> إنشاء نسخة قاعدة البيانات
                        </button>
                    </form>
                </div>
            </div>
            
            <div class="alert alert-info">
                <i class="fas fa-lightbulb"></i>
                <strong>نصيحة:</strong> استخدم النسخة الكاملة للحصول على نسخة شاملة تشمل جميع البيانات والملفات. 
                استخدم نسخة قاعدة البيانات فقط للنسخ السريعة اليومية.
            </div>
        </div>
        
        <!-- Backups List -->
        <div class="card">
            <h2><i class="fas fa-list"></i> النسخ الاحتياطية المتوفرة (<?php echo count($backups); ?>)</h2>
            
            <?php if (empty($backups)): ?>
                <div class="empty-state">
                    <i class="fas fa-folder-open"></i>
                    <h3>لا توجد نسخ احتياطية</h3>
                    <p>قم بإنشاء نسخة احتياطية أولاً</p>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>اسم الملف</th>
                            <th>النوع</th>
                            <th>التاريخ</th>
                            <th>الحجم</th>
                            <th>المحتوى</th>
                            <th>بواسطة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($backups as $backup): ?>
                            <tr>
                                <td>
                                    <?php if ($backup['type'] === 'full'): ?>
                                        <i class="fas fa-archive" style="color: #10b981;"></i>
                                    <?php else: ?>
                                        <i class="fas fa-database" style="color: #3b82f6;"></i>
                                    <?php endif; ?>
                                    <?php echo htmlspecialchars($backup['filename']); ?>
                                </td>
                                <td>
                                    <?php if ($backup['type'] === 'full'): ?>
                                        <span class="badge badge-success">نسخة كاملة</span>
                                    <?php else: ?>
                                        <span class="badge badge-info">قاعدة بيانات</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo date('Y-m-d H:i', strtotime($backup['created_at'])); ?></td>
                                <td><?php echo formatBytes($backup['size']); ?></td>
                                <td>
                                    <div style="font-size: 12px;">
                                        <div><i class="fas fa-table"></i> <?php echo $backup['tables']; ?> جدول</div>
                                        <?php if ($backup['type'] === 'full' && isset($backup['files'])): ?>
                                            <div><i class="fas fa-file"></i> <?php echo $backup['files']; ?> ملف</div>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($backup['created_by']); ?></td>
                                <td>
                                    <div class="actions">
                                        <a href="?download=<?php echo urlencode($backup['filename']); ?>" class="btn btn-secondary" title="تحميل">
                                            <i class="fas fa-download"></i>
                                        </a>
                                        
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('هل أنت متأكد من استعادة هذه النسخة؟ سيتم استبدال البيانات الحالية!')">
                                            <input type="hidden" name="backup_file" value="<?php echo htmlspecialchars($backup['filename']); ?>">
                                            <button type="submit" name="restore_backup" class="btn btn-success" title="استعادة">
                                                <i class="fas fa-undo"></i>
                                            </button>
                                        </form>
                                        
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('هل أنت متأكد من حذف هذه النسخة؟')">
                                            <input type="hidden" name="backup_file" value="<?php echo htmlspecialchars($backup['filename']); ?>">
                                            <button type="submit" name="delete_backup" class="btn btn-danger" title="حذف">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Tips -->
        <div class="card">
            <h2><i class="fas fa-lightbulb"></i> نصائح مهمة</h2>
            <ul style="line-height: 2; color: #666; padding-right: 20px;">
                <li>قم بإنشاء نسخة احتياطية قبل أي تحديث أو تعديل كبير</li>
                <li>احتفظ بنسخ احتياطية متعددة في أماكن مختلفة</li>
                <li>قم بتحميل النسخ الاحتياطية على جهازك أو خدمة تخزين سحابية</li>
                <li>تأكد من اختبار النسخ الاحتياطية بشكل دوري</li>
                <li>احذف النسخ القديمة لتوفير المساحة</li>
            </ul>
        </div>
    </div>
</body>
</html>
