<?php
/**
 * backup_manager.php
 * نظام إدارة النسخ الاحتياطية (شامل: إنشاء، استعادة، تحميل، حذف)
 * يدعم اللغتين العربية والإنجليزية
 */

// تعديل المسارات لتناسب وجود الملف داخل مجلد admin
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../src/auth.php';

require_login(); // التحقق من الدخول

// --- إعداد اللغة (Language Setup) ---
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
$lang = in_array($lang, ['en','ar']) ? $lang : 'en';
$dir = $lang === 'ar' ? 'rtl' : 'ltr';

// القاموس (Translations)
$T = [
    'en' => [
        'title' => 'Backup Manager',
        'back' => 'Dashboard',
        'create' => 'Create Backup',
        'filename' => 'Filename',
        'size' => 'Size',
        'date' => 'Date',
        'actions' => 'Actions',
        'download' => 'Download',
        'restore' => 'Restore',
        'delete' => 'Delete',
        'empty' => 'No backups found.',
        'msg_create' => 'Backup created successfully.',
        'msg_delete' => 'File deleted successfully.',
        'msg_restore' => 'Database restored successfully!',
        'err_create' => 'Error creating backup.',
        'err_restore' => 'Failed to restore database.',
        'err_file' => 'File not found.',
        'confirm_restore' => 'WARNING: This will overwrite your current database! Are you sure?',
        'confirm_delete' => 'Delete this backup file?',
        'note' => 'Backups are stored safely in admin/backups/'
    ],
    'ar' => [
        'title' => 'إدارة النسخ الاحتياطية',
        'back' => 'لوحة التحكم',
        'create' => 'نسخة جديدة',
        'filename' => 'اسم الملف',
        'size' => 'الحجم',
        'date' => 'التاريخ',
        'actions' => 'إجراءات',
        'download' => 'تحميل',
        'restore' => 'استعادة',
        'delete' => 'حذف',
        'empty' => 'لا توجد نسخ احتياطية.',
        'msg_create' => 'تم إنشاء النسخة الاحتياطية بنجاح.',
        'msg_delete' => 'تم حذف الملف بنجاح.',
        'msg_restore' => 'تم استعادة قاعدة البيانات بنجاح!',
        'err_create' => 'حدث خطأ أثناء إنشاء النسخة.',
        'err_restore' => 'فشل في استعادة قاعدة البيانات.',
        'err_file' => 'الملف غير موجود.',
        'confirm_restore' => 'تحذير: سيتم حذف البيانات الحالية واستبدالها بهذه النسخة! هل أنت متأكد؟',
        'confirm_delete' => 'هل أنت متأكد من حذف هذا الملف؟',
        'note' => 'يتم حفظ النسخ بشكل آمن في مجلد admin/backups/'
    ]
];
$t = $T[$lang];

// --- إعداد المجلد ---
$backupDir = __DIR__ . '/backups/';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
    file_put_contents($backupDir . '.htaccess', 'Deny from all'); 
}

$message = '';
$error = '';

// --- الدوال (Functions) ---

function createBackup($pdo, $backupDir) {
    try {
        $tables = [];
        $query = $pdo->query('SHOW TABLES');
        while ($row = $query->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }
        
        // بداية السكربت: تعطيل فحص المفاتيح الأجنبية لتجنب مشاكل الترتيب
        $sqlScript = "SET FOREIGN_KEY_CHECKS=0;\n";
        
        foreach ($tables as $table) {
            // هيكل الجدول
            $query = $pdo->query('SHOW CREATE TABLE ' . $table);
            $row = $query->fetch(PDO::FETCH_NUM);
            $sqlScript .= "\n\n" . "DROP TABLE IF EXISTS `$table`;\n";
            $sqlScript .= $row[1] . ";\n\n";
            
            // البيانات
            $query = $pdo->query('SELECT * FROM ' . $table);
            $columnCount = $query->columnCount();
            while ($row = $query->fetch(PDO::FETCH_NUM)) {
                $sqlScript .= "INSERT INTO `$table` VALUES(";
                for ($j = 0; $j < $columnCount; $j++) {
                    $row[$j] = addslashes($row[$j] ?? '');
                    $row[$j] = preg_replace("/\n/", "\\n", $row[$j]);
                    if (isset($row[$j])) { $sqlScript .= '"' . $row[$j] . '"'; } else { $sqlScript .= '""'; }
                    if ($j < ($columnCount - 1)) { $sqlScript .= ','; }
                }
                $sqlScript .= ");\n";
            }
        }
        
        // نهاية السكربت: إعادة تفعيل فحص المفاتيح الأجنبية
        $sqlScript .= "\nSET FOREIGN_KEY_CHECKS=1;";
        
        $filename = 'db_backup_' . date('Y-m-d_H-i-s') . '.sql';
        file_put_contents($backupDir . $filename, $sqlScript);
        return true;
    } catch (Exception $e) { return false; }
}

function restoreBackup($pdo, $filePath) {
    try {
        // قراءة الملف بالكامل وتنفيذه
        $sql = file_get_contents($filePath);
        $pdo->exec($sql);
        return true;
    } catch (Exception $e) { return false; }
}

// --- المعالجة (Actions) ---

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    
    if ($action === 'create') {
        if (createBackup($pdo, $backupDir)) {
            $message = $t['msg_create'];
        } else {
            $error = $t['err_create'];
        }
    }
    
    if ($action === 'download' && isset($_GET['file'])) {
        $file = basename($_GET['file']);
        $filePath = $backupDir . $file;
        if (file_exists($filePath)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        } else {
            $error = $t['err_file'];
        }
    }

    if ($action === 'delete' && isset($_GET['file'])) {
        $file = basename($_GET['file']);
        $filePath = $backupDir . $file;
        if (file_exists($filePath)) {
            unlink($filePath);
            $message = $t['msg_delete'];
        }
    }

    if ($action === 'restore' && isset($_GET['file'])) {
        $file = basename($_GET['file']);
        $filePath = $backupDir . $file;
        if (file_exists($filePath)) {
            set_time_limit(600); 
            ini_set('memory_limit', '512M');
            if (restoreBackup($pdo, $filePath)) {
                $message = $t['msg_restore'];
            } else {
                $error = $t['err_restore'];
            }
        }
    }
}

// قائمة الملفات
$files = array_diff(scandir($backupDir), array('.', '..', '.htaccess'));
rsort($files);
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $t['title'] ?></title>
    <!-- Fonts & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: #f8fafc; font-family: 'Poppins', 'Cairo', sans-serif; color: #334155; }
        .main-card { border: none; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); border-radius: 16px; overflow: hidden; }
        .card-header { background: #fff; border-bottom: 1px solid #e2e8f0; padding: 1.5rem; }
        .table th { background: #f1f5f9; color: #475569; font-weight: 600; text-transform: uppercase; font-size: 0.85rem; letter-spacing: 0.05em; border:none; padding: 1rem; }
        .table td { vertical-align: middle; padding: 1rem; border-bottom: 1px solid #f1f5f9; }
        .table tr:last-child td { border-bottom: none; }
        .btn-action { width: 32px; height: 32px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; margin: 0 4px; transition: all 0.2s; }
        .btn-action:hover { transform: translateY(-2px); }
        .badge-size { background: #e0f2fe; color: #0284c7; font-weight: 500; font-size: 0.8rem; padding: 4px 8px; border-radius: 6px; }
        .file-icon { color: #475569; margin-inline-end: 8px; font-size: 1.1rem; }
    </style>
</head>
<body>

<div class="container py-5">
    
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1"><?= $t['title'] ?></h3>
            <p class="text-muted small mb-0"><?= $t['note'] ?></p>
        </div>
        <div class="d-flex gap-2">
            <a href="/index.php" class="btn btn-white border shadow-sm fw-medium">
                <i class="fa fa-arrow-<?= $dir=='rtl'?'right':'left' ?>"></i> <?= $t['back'] ?>
            </a>
            <a href="?action=create&lang=<?= $lang ?>" class="btn btn-primary shadow-sm fw-medium">
                <i class="fa fa-plus-circle me-1"></i> <?= $t['create'] ?>
            </a>
        </div>
    </div>

    <!-- Alerts -->
    <?php if ($message): ?>
        <div class="alert alert-success border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center">
            <i class="fa fa-check-circle fs-5 me-2 ms-2"></i> <?= htmlspecialchars($message) ?>
        </div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger border-0 shadow-sm rounded-3 mb-4 d-flex align-items-center">
            <i class="fa fa-exclamation-circle fs-5 me-2 ms-2"></i> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <!-- Files List -->
    <div class="card main-card">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th class="ps-4"><?= $t['filename'] ?></th>
                        <th width="15%"><?= $t['size'] ?></th>
                        <th width="20%"><?= $t['date'] ?></th>
                        <th width="15%" class="text-center"><?= $t['actions'] ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($files)): ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted fw-medium"><?= $t['empty'] ?></td></tr>
                    <?php else: ?>
                        <?php foreach ($files as $file): 
                            $fullPath = $backupDir . $file;
                            $size = round(filesize($fullPath) / 1024, 2);
                            $sizeStr = $size > 1024 ? round($size/1024, 2) . ' MB' : $size . ' KB';
                            $date = date("Y-m-d h:i A", filemtime($fullPath));
                        ?>
                        <tr>
                            <td class="ps-4">
                                <div class="d-flex align-items-center">
                                    <i class="fa fa-file-code file-icon"></i>
                                    <span class="fw-medium text-dark" dir="ltr"><?= $file ?></span>
                                </div>
                            </td>
                            <td><span class="badge-size"><?= $sizeStr ?></span></td>
                            <td class="text-muted small"><?= $date ?></td>
                            <td class="text-center">
                                <a href="?action=download&file=<?= $file ?>&lang=<?= $lang ?>" class="btn btn-light border btn-action text-primary" title="<?= $t['download'] ?>">
                                    <i class="fa fa-download"></i>
                                </a>
                                <a href="?action=restore&file=<?= $file ?>&lang=<?= $lang ?>" class="btn btn-light border btn-action text-warning" onclick="return confirm('<?= $t['confirm_restore'] ?>')" title="<?= $t['restore'] ?>">
                                    <i class="fa fa-clock-rotate-left"></i>
                                </a>
                                <a href="?action=delete&file=<?= $file ?>&lang=<?= $lang ?>" class="btn btn-light border btn-action text-danger" onclick="return confirm('<?= $t['confirm_delete'] ?>')" title="<?= $t['delete'] ?>">
                                    <i class="fa fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>