<?php
session_start();
require_once '../config/database.php';

// Check admin authentication
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$database = new Database();
$conn = $database->getConnection();

$message = '';
$error = '';

// Handle backup download
if (isset($_GET['action']) && $_GET['action'] === 'download' && isset($_GET['file'])) {
    $filename = basename($_GET['file']);
    $filepath = __DIR__ . '/../backups/' . $filename;
    
    if (file_exists($filepath)) {
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    } else {
        $error = 'الملف غير موجود';
    }
}

// Handle backup deletion
if (isset($_POST['delete_backup'])) {
    $filename = basename($_POST['filename']);
    $filepath = __DIR__ . '/../backups/' . $filename;
    
    if (file_exists($filepath) && unlink($filepath)) {
        $message = 'تم حذف النسخة الاحتياطية بنجاح';
    } else {
        $error = 'فشل حذف النسخة الاحتياطية';
    }
}

// Handle backup creation
if (isset($_POST['create_backup'])) {
    try {
        $backupDir = __DIR__ . '/../backups/';
        if (!file_exists($backupDir)) {
            mkdir($backupDir, 0755, true);
        }
        
        $filename = 'backup_' . date('Y-m-d_H-i-s') . '.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";
        $output .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n";
        $output .= "SET time_zone = \"+00:00\";\n\n";
        
        foreach ($tables as $table) {
            $output .= "\n-- Table: $table\n";
            // Drop table
            $output .= "DROP TABLE IF EXISTS `$table`;\n";
            
            // Create table
            $createTable = $conn->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
            $output .= $createTable['Create Table'] . ";\n";
            
            // Insert data
            $rows = $conn->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
            if (!empty($rows)) {
                foreach ($rows as $row) {
                    $values = array_map(function($value) use ($conn) {
                        return $value === null ? 'NULL' : $conn->quote($value);
                    }, array_values($row));
                    
                    $output .= "INSERT INTO `$table` VALUES (" . implode(', ', $values) . ");\n";
                }
                $output .= "\n";
            }
        }
        
        $output .= "SET FOREIGN_KEY_CHECKS=1;\n";
        
        file_put_contents($filepath, $output);
        $message = 'تم إنشاء النسخة الاحتياطية بنجاح: ' . $filename;
        
    } catch (Exception $e) {
        $error = 'خطأ في إنشاء النسخة الاحتياطية: ' . $e->getMessage();
    }
}

// Handle backup restore
if (isset($_POST['restore_backup']) && isset($_FILES['backup_file'])) {
    try {
        $file = $_FILES['backup_file'];
        
        if ($file['error'] === UPLOAD_ERR_OK) {
            $sql = file_get_contents($file['tmp_name']);
            
            // Fix /n to proper newlines (common issue in some exports)
            $sql = str_replace('/n', "\n", $sql);
            
            // Remove comments and split into statements
            $sql = preg_replace('/^--.*$/m', '', $sql); // Remove single-line comments
            $sql = preg_replace('/\/\*.*?\*\//s', '', $sql); // Remove multi-line comments
            
            // Split by semicolon but keep them for execution
            $statements = array_filter(
                array_map('trim', preg_split('/;[\r\n]+/', $sql)),
                function($stmt) {
                    return !empty($stmt) && strlen($stmt) > 5;
                }
            );
            
            // Disable foreign key checks for MariaDB/MySQL
            $conn->exec('SET FOREIGN_KEY_CHECKS=0');
            $conn->exec('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"');
            $conn->exec('SET time_zone = "+00:00"');
            
            // Execute each statement separately
            $executed = 0;
            foreach ($statements as $statement) {
                $statement = trim($statement);
                if (!empty($statement)) {
                    try {
                        $conn->exec($statement);
                        $executed++;
                    } catch (PDOException $e) {
                        // Log but continue with other statements
                        error_log("SQL Error: " . $e->getMessage() . " in statement: " . substr($statement, 0, 100));
                    }
                }
            }
            
            // Re-enable foreign key checks
            $conn->exec('SET FOREIGN_KEY_CHECKS=1');
            
            $message = "تم استعادة النسخة الاحتياطية بنجاح ($executed استعلام تم تنفيذه)";
        } else {
            $error = 'خطأ في رفع الملف';
        }
    } catch (Exception $e) {
        $error = 'خطأ في استعادة النسخة الاحتياطية: ' . $e->getMessage();
    }
}

// Get existing backups
$backups = [];
$backupDir = __DIR__ . '/../backups/';
if (file_exists($backupDir)) {
    $files = scandir($backupDir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) === 'sql') {
            $backups[] = [
                'name' => $file,
                'size' => filesize($backupDir . $file),
                'date' => filemtime($backupDir . $file)
            ];
        }
    }
    // Sort by date descending
    usort($backups, function($a, $b) {
        return $b['date'] - $a['date'];
    });
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>النسخ الاحتياطية - لوحة التحكم</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Tajawal', sans-serif;
        }
        
        body {
            background: #f5f5f5;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 28px;
        }
        
        .subtitle {
            color: #7f8c8d;
            margin-bottom: 24px;
        }
        
        .alert {
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background: #2980b9;
        }
        
        .btn-success {
            background: #27ae60;
            color: white;
        }
        
        .btn-success:hover {
            background: #229954;
        }
        
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .btn-secondary {
            background: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .actions {
            display: flex;
            gap: 12px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: right;
            border-bottom: 1px solid #ecf0f1;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }
        
        tr:hover {
            background: #f8f9fa;
        }
        
        .file-input {
            display: none;
        }
        
        .file-label {
            padding: 12px 24px;
            background: #3498db;
            color: white;
            border-radius: 8px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .file-label:hover {
            background: #2980b9;
        }
        
        .empty-state {
            text-align: center;
            padding: 48px;
            color: #7f8c8d;
        }
        
        .empty-state i {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.3;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1><i class="fas fa-database"></i> إدارة النسخ الاحتياطية</h1>
            <p class="subtitle">إنشاء واستعادة نسخ احتياطية من قاعدة البيانات</p>
            
            <?php if ($message): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <div class="actions">
                <form method="POST" style="display: inline;">
                    <button type="submit" name="create_backup" class="btn btn-primary">
                        <i class="fas fa-plus"></i>
                        إنشاء نسخة احتياطية جديدة
                    </button>
                </form>
                
                <a href="sql-import.php" class="btn btn-success">
                    <i class="fas fa-file-import"></i>
                    استيراد ملف SQL
                </a>
                
                <a href="dashboard.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-right"></i>
                    العودة للوحة التحكم
                </a>
            </div>
        </div>
        
        <div class="card">
            <h2 style="margin-bottom: 20px;"><i class="fas fa-upload"></i> رفع واستعادة نسخة احتياطية</h2>
            <p style="color: #7f8c8d; margin-bottom: 20px;">قم برفع ملف SQL من جهازك لاستعادة قاعدة البيانات</p>
            
            <form method="POST" enctype="multipart/form-data" id="restore-form">
                <div style="border: 2px dashed #3498db; border-radius: 12px; padding: 40px; text-align: center; background: #f8f9fa; margin-bottom: 20px;">
                    <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #3498db; margin-bottom: 16px;"></i>
                    <p style="font-size: 18px; font-weight: 500; margin-bottom: 8px;">اختر ملف SQL للاستعادة</p>
                    <p style="color: #7f8c8d; font-size: 14px; margin-bottom: 20px;">يدعم ملفات .sql فقط</p>
                    
                    <input type="file" name="backup_file" id="backup_file_input" class="file-input" accept=".sql" required>
                    <label for="backup_file_input" class="file-label" style="font-size: 16px;">
                        <i class="fas fa-folder-open"></i>
                        اختر ملف SQL
                    </label>
                    
                    <div id="file-name" style="margin-top: 16px; color: #27ae60; font-weight: 500;"></div>
                </div>
                
                <input type="hidden" name="restore_backup" value="1">
                
                <div style="display: flex; gap: 12px; justify-content: center;">
                    <button type="submit" class="btn btn-success" id="restore-btn" disabled>
                        <i class="fas fa-database"></i>
                        استعادة النسخة الاحتياطية
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="document.getElementById('restore-form').reset(); document.getElementById('file-name').textContent = ''; document.getElementById('restore-btn').disabled = true;">
                        <i class="fas fa-times"></i>
                        إلغاء
                    </button>
                </div>
                
                <div style="margin-top: 20px; padding: 16px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; color: #856404;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>تحذير:</strong> استعادة النسخة الاحتياطية سيؤدي إلى استبدال جميع البيانات الحالية في قاعدة البيانات.
                </div>
            </form>
            
            <script>
                document.getElementById('backup_file_input').addEventListener('change', function(e) {
                    const fileName = e.target.files[0]?.name;
                    if (fileName) {
                        document.getElementById('file-name').textContent = '✓ تم اختيار: ' + fileName;
                        document.getElementById('restore-btn').disabled = false;
                    }
                });
                
                document.getElementById('restore-form').addEventListener('submit', function(e) {
                    if (!confirm('هل أنت متأكد من استعادة هذه النسخة الاحتياطية؟ سيتم استبدال جميع البيانات الحالية!')) {
                        e.preventDefault();
                    }
                });
            </script>
        </div>
        
        <div class="card">
            <h2 style="margin-bottom: 20px;"><i class="fas fa-history"></i> النسخ الاحتياطية المتاحة</h2>
            
            <?php if (empty($backups)): ?>
                <div class="empty-state">
                    <i class="fas fa-folder-open"></i>
                    <p>لا توجد نسخ احتياطية حالياً</p>
                    <p style="font-size: 14px; margin-top: 8px;">قم بإنشاء نسخة احتياطية جديدة للبدء</p>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>اسم الملف</th>
                            <th>الحجم</th>
                            <th>التاريخ</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($backups as $backup): ?>
                            <tr>
                                <td>
                                    <i class="fas fa-file-archive" style="color: #3498db; margin-left: 8px;"></i>
                                    <?php echo htmlspecialchars($backup['name']); ?>
                                </td>
                                <td><?php echo number_format($backup['size'] / 1024, 2); ?> KB</td>
                                <td><?php echo date('Y-m-d H:i:s', $backup['date']); ?></td>
                                <td>
                                    <a href="?action=download&file=<?php echo urlencode($backup['name']); ?>" class="btn btn-success" style="padding: 8px 16px; font-size: 14px;">
                                        <i class="fas fa-download"></i>
                                        تنزيل
                                    </a>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('هل أنت متأكد من حذف هذه النسخة الاحتياطية؟');">
                                        <input type="hidden" name="filename" value="<?php echo htmlspecialchars($backup['name']); ?>">
                                        <button type="submit" name="delete_backup" class="btn btn-danger" style="padding: 8px 16px; font-size: 14px;">
                                            <i class="fas fa-trash"></i>
                                            حذف
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
