<?php
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();

$db       = Database::getInstance()->getConnection();
$backupDir = __DIR__ . '/../backups/';
if (!is_dir($backupDir)) @mkdir($backupDir, 0755, true);

$error = ''; $success = '';

// ساخت بک‌آپ
if (isset($_POST['create_backup'])) {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'خطای امنیتی.';
    } else {
        try {
            $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
            $filepath = $backupDir . $filename;

            $tables = $db->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
            $sql = "-- کیف‌لند | بک‌آپ دیتابیس\n-- تاریخ: " . date('Y-m-d H:i:s') . "\n\nSET FOREIGN_KEY_CHECKS=0;\nSET NAMES utf8mb4;\n\n";

            foreach ($tables as $table) {
                $create = $db->query("SHOW CREATE TABLE `$table`")->fetch();
                $sql .= "DROP TABLE IF EXISTS `$table`;\n" . $create['Create Table'] . ";\n\n";

                $rows = $db->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
                if (!empty($rows)) {
                    $cols = '`' . implode('`, `', array_keys($rows[0])) . '`';
                    $sql .= "INSERT INTO `$table` ($cols) VALUES\n";
                    $vals = [];
                    foreach ($rows as $row) {
                        $escaped = array_map(fn($v) => is_null($v) ? 'NULL' : $db->quote($v), $row);
                        $vals[] = '(' . implode(', ', $escaped) . ')';
                    }
                    $sql .= implode(",\n", $vals) . ";\n\n";
                }
            }

            $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";
            file_put_contents($filepath, $sql);
            Auth::logActivity('db_backup', 'بک‌آپ دیتابیس: ' . $filename);
            $success = 'بک‌آپ با موفقیت ساخته شد: ' . $filename;
        } catch (Exception $e) {
            $error = 'خطا در ساخت بک‌آپ: ' . $e->getMessage();
        }
    }
}

// دانلود
if (isset($_GET['download'])) {
    $file = basename($_GET['download']);
    $path = $backupDir . $file;
    if (file_exists($path) && pathinfo($file, PATHINFO_EXTENSION) === 'sql') {
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}

// حذف
if (isset($_POST['delete_backup'])) {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'خطای امنیتی.';
    } else {
        $file = basename($_POST['file']);
        $path = $backupDir . $file;
        if (file_exists($path) && pathinfo($file, PATHINFO_EXTENSION) === 'sql') {
            unlink($path);
            Auth::logActivity('db_backup_delete', 'حذف بک‌آپ: ' . $file);
            $success = 'بک‌آپ حذف شد.';
        }
    }
}

$files = glob($backupDir . '*.sql') ?: [];
usort($files, fn($a, $b) => filemtime($b) - filemtime($a));
$csrfToken = Auth::generateCSRFToken();

include 'includes/admin-header.php';
?>

<div class="backup-page">
    <div class="bp-header">
        <h1><i class="fas fa-database"></i> مدیریت بک‌آپ دیتابیس</h1>
        <p>ساخت، دانلود و مدیریت بک‌آپ‌های دیتابیس</p>
    </div>

    <?php if ($success): ?><div class="bp-alert bp-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bp-alert bp-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

    <?php
    $totalSize = !empty($files) ? array_sum(array_map('filesize', $files)) : 0;
    $lastBackup = !empty($files) ? date('Y/m/d H:i', filemtime($files[0])) : 'هیچ';
    ?>
    <div class="bp-stats">
        <div class="bp-stat-card">
            <div class="bp-stat-icon blue"><i class="fas fa-file-code"></i></div>
            <div class="bp-stat-num"><?= count($files) ?></div>
            <div class="bp-stat-label">بک‌آپ</div>
        </div>
        <div class="bp-stat-card">
            <div class="bp-stat-icon green"><i class="fas fa-hard-drive"></i></div>
            <div class="bp-stat-num"><?= number_format($totalSize / 1024 / 1024, 1) ?> MB</div>
            <div class="bp-stat-label">حجم کل</div>
        </div>
        <div class="bp-stat-card">
            <div class="bp-stat-icon orange"><i class="fas fa-clock"></i></div>
            <div class="bp-stat-num" style="font-size:14px;"><?= $lastBackup ?></div>
            <div class="bp-stat-label">آخرین بک‌آپ</div>
        </div>
    </div>

    <!-- ساخت بک‌آپ -->
    <div class="bp-card">
        <h3><i class="fas fa-plus-circle"></i> ساخت بک‌آپ جدید</h3>
        <p>یک نسخه کامل از تمام جداول دیتابیس ساخته می‌شود.</p>
        <form method="POST" onsubmit="this.querySelector('button').disabled=true;this.querySelector('button').innerHTML='<i class=\'fas fa-spinner fa-spin\'></i> در حال ساخت...';">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <button type="submit" name="create_backup" class="bp-btn bp-btn-primary">
                <i class="fas fa-database"></i> ساخت بک‌آپ الان
            </button>
        </form>
    </div>

    <!-- لیست بک‌آپ‌ها -->
    <div class="bp-card">
        <h3><i class="fas fa-list"></i> بک‌آپ‌های موجود</h3>
        <?php if (!empty($files)): ?>
        <div class="bp-table-wrap">
            <table class="bp-table">
                <thead>
                    <tr>
                        <th>نام فایل</th>
                        <th>تاریخ ساخت</th>
                        <th>حجم</th>
                        <th>عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($files as $i => $file): ?>
                    <tr>
                        <td>
                            <i class="fas fa-file-code" style="color:#8b5cf6;margin-left:8px;"></i>
                            <?= htmlspecialchars(basename($file)) ?>
                            <?php if ($i === 0): ?><span class="bp-newest">جدیدترین</span><?php endif; ?>
                        </td>
                        <td><?= date('Y/m/d H:i:s', filemtime($file)) ?></td>
                        <td><span class="bp-size"><?= number_format(filesize($file) / 1024, 1) ?> KB</span></td>
                        <td>
                            <div class="bp-actions">
                                <a href="?download=<?= urlencode(basename($file)) ?>" class="bp-btn bp-btn-sm bp-btn-ghost">
                                    <i class="fas fa-download"></i> دانلود
                                </a>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از حذف این بک‌آپ مطمئن هستید؟');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                                    <input type="hidden" name="file" value="<?= htmlspecialchars(basename($file)) ?>">
                                    <button type="submit" name="delete_backup" class="bp-btn bp-btn-sm bp-btn-danger">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="bp-empty">
            <i class="fas fa-database"></i>
            <p>هنوز بک‌آپی ساخته نشده.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<style>
.backup-page { max-width: 900px; margin: 0 auto; }
.bp-header { margin-bottom: 24px; }
.bp-header h1 { font-size: 22px; font-weight: 700; display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.bp-header h1 i { color: var(--admin-primary, #8b5cf6); }
.bp-header p { color: var(--admin-text-muted, #64748b); font-size: 13px; }

.bp-alert { padding: 12px 16px; border-radius: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; font-size: 13px; font-weight: 500; }
.bp-success { background: rgba(16,185,129,0.12); color: #10b981; border: 1px solid rgba(16,185,129,0.25); }
.bp-danger { background: rgba(239,68,68,0.12); color: #ef4444; border: 1px solid rgba(239,68,68,0.25); }

.bp-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; margin-bottom: 24px; }
.bp-stat-card { background: var(--admin-card-bg, rgba(255,255,255,0.04)); border: 1px solid var(--admin-card-border, rgba(255,255,255,0.08)); border-radius: 16px; padding: 20px; text-align: center; transition: all 0.25s; }
.bp-stat-card:hover { transform: translateY(-2px); border-color: rgba(139,92,246,0.3); }
.bp-stat-icon { width: 42px; height: 42px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1rem; margin: 0 auto 10px; }
.bp-stat-icon.blue { background: rgba(59,130,246,0.12); color: #3b82f6; }
.bp-stat-icon.green { background: rgba(16,185,129,0.12); color: #10b981; }
.bp-stat-icon.orange { background: rgba(245,158,11,0.12); color: #f59e0b; }
.bp-stat-num { font-size: 22px; font-weight: 800; color: var(--admin-text, #e2e8f0); }
.bp-stat-label { font-size: 12px; color: var(--admin-text-muted, #64748b); margin-top: 4px; }

.bp-card { background: var(--admin-card-bg, rgba(255,255,255,0.04)); border: 1px solid var(--admin-card-border, rgba(255,255,255,0.08)); border-radius: 16px; padding: 24px; margin-bottom: 20px; }
.bp-card h3 { font-size: 15px; font-weight: 700; margin: 0 0 10px; display: flex; align-items: center; gap: 8px; }
.bp-card h3 i { color: var(--admin-primary, #8b5cf6); }
.bp-card p { font-size: 13px; color: var(--admin-text-muted, #64748b); margin: 0 0 16px; }

.bp-btn { padding: 10px 18px; border-radius: 10px; border: none; font-weight: 600; font-size: 13px; cursor: pointer; transition: all 0.25s; display: inline-flex; align-items: center; gap: 6px; font-family: inherit; text-decoration: none; }
.bp-btn-primary { background: var(--admin-primary, #8b5cf6); color: #fff; box-shadow: 0 4px 12px rgba(139,92,246,0.3); }
.bp-btn-primary:hover { opacity: 0.9; transform: translateY(-1px); }
.bp-btn-ghost { background: transparent; border: 1px solid var(--admin-card-border, rgba(255,255,255,0.08)); color: var(--admin-text, #e2e8f0); }
.bp-btn-ghost:hover { background: rgba(255,255,255,0.06); border-color: var(--admin-primary, #8b5cf6); color: var(--admin-primary, #8b5cf6); }
.bp-btn-danger { background: rgba(239,68,68,0.12); color: #ef4444; border: 1px solid rgba(239,68,68,0.2); }
.bp-btn-danger:hover { background: #ef4444; color: #fff; }
.bp-btn-sm { padding: 6px 12px; font-size: 12px; }

.bp-table-wrap { overflow-x: auto; }
.bp-table { width: 100%; border-collapse: collapse; }
.bp-table th { text-align: right; padding: 12px 14px; font-size: 12px; font-weight: 600; color: var(--admin-text-muted, #64748b); border-bottom: 1px solid var(--admin-card-border, rgba(255,255,255,0.08)); }
.bp-table td { padding: 14px; font-size: 13px; border-bottom: 1px solid rgba(255,255,255,0.04); vertical-align: middle; color: var(--admin-text, #e2e8f0); }
.bp-table tr:hover td { background: rgba(255,255,255,0.03); }
.bp-newest { font-size: 10px; background: var(--admin-primary, #8b5cf6); color: #fff; padding: 2px 8px; border-radius: 12px; margin-right: 8px; font-weight: 700; }
.bp-size { font-size: 12px; background: rgba(255,255,255,0.06); padding: 3px 10px; border-radius: 20px; color: var(--admin-text-muted, #64748b); }
.bp-actions { display: flex; gap: 8px; align-items: center; }
.bp-empty { text-align: center; padding: 40px; color: var(--admin-text-muted, #64748b); }
.bp-empty i { font-size: 3rem; opacity: 0.15; display: block; margin-bottom: 12px; }

@media (max-width: 600px) {
    .bp-stats { grid-template-columns: 1fr; }
    .bp-table th:nth-child(3), .bp-table td:nth-child(3) { display: none; }
}
</style>

<?php include 'includes/admin-footer.php'; ?>
