<?php
session_start();

// 1. التحقق من الدخول (للأدمن فقط لخطورة العمليات)
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("<div style='font-family:Cairo; text-align:center; padding:100px;'><h2>Access Denied. Admins Only.</h2><a href='dashboard.php'>Back to Home</a></div>");
}

require_once 'db.php';

// إدارة اللغة بناءً على الجلسة (بدون زر تبديل)
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// نصوص الترجمة الاحترافية المحدثة
$texts = [
    'ar' => [
        'title' => 'مركز الأمان والبيانات | أسامة إلكتريك',
        'header' => 'إدارة الأرشفة والأمان',
        'sub_header' => 'تأمين البيانات عبر النسخ الاحتياطي والاستعادة المحمية',
        'home' => 'الرئيسية',
        'save_host' => 'الأرشفة السحابية',
        'save_host_desc' => 'إنشاء نسخة أمان فورية داخل السيرفر للرجوع إليها عند الطوارئ.',
        'copy_now' => 'تثبيت نسخة الآن',
        'download_sql' => 'تصدير خارجي',
        'download_sql_desc' => 'تحميل ملف SQL شامل لكافة البيانات على جهازك الشخصي.',
        'download_btn' => 'تحميل الملف الآمن',
        'excel_report' => 'جرد الأرصدة (Excel)',
        'excel_desc' => 'تصدير جدول المشتركين والديون والعلب بصيغة CSV.',
        'excel_btn' => 'تحميل التقرير',
        'restore_title' => 'استعادة النظام',
        'restore_desc' => 'استرجاع البيانات من ملف خارجي (يتطلب كلمة السر).',
        'choose_file' => 'اختر ملف SQL',
        'pass_confirm' => 'كلمة السر للتحقق',
        'restore_btn' => 'تأكيد الاستعادة',
        'host_history' => 'خزنة النسخ الاحتياطية (Host)',
        'file_date' => 'تاريخ الأرشفة',
        'file_name' => 'اسم النسخة',
        'actions' => 'العمليات',
        'restore_from_server' => 'استعادة فورية',
        'delete_file' => 'حذف النسخة',
        'pass_error' => 'خطأ: كلمة السر غير صحيحة.',
        'success_restore' => 'تمت استعادة البيانات بنجاح وتم تحديث النظام!',
        'success_host' => 'تمت عملية الأرشفة على السيرفر بنجاح.',
        'success_delete' => 'تم حذف ملف النسخة من الهوست بنجاح.',
        'warning_restore' => 'تحذير: سيتم استبدال البيانات الحالية كلياً بالنسخة المختارة.'
    ],
    'en' => [
        'title' => 'Security Center | Osama Electric',
        'header' => 'Archive & Security Management',
        'sub_header' => 'Secure data via backups and protected recovery points',
        'home' => 'Dashboard',
        'save_host' => 'Cloud Archiving',
        'save_host_desc' => 'Create an instant security point on the server for emergencies.',
        'copy_now' => 'Archive to Server',
        'download_sql' => 'External Export',
        'download_sql_desc' => 'Download a comprehensive SQL file of all data to your device.',
        'download_btn' => 'Download Secure File',
        'excel_report' => 'Balance Audit (Excel)',
        'excel_desc' => 'Export customers, debts, and boxes in CSV format.',
        'excel_btn' => 'Download Report',
        'restore_title' => 'System Restore',
        'restore_desc' => 'Recover data from an external file (Password required).',
        'choose_file' => 'Choose SQL File',
        'pass_confirm' => 'Password Verification',
        'restore_btn' => 'Confirm Restore',
        'host_history' => 'Server Backup Vault',
        'file_date' => 'Archive Date',
        'file_name' => 'Version Name',
        'actions' => 'Actions',
        'restore_from_server' => 'Quick Restore',
        'delete_file' => 'Delete Version',
        'pass_error' => 'Error: Invalid password.',
        'success_restore' => 'Data restored successfully! System updated.',
        'success_host' => 'Archiving to server completed successfully.',
        'success_delete' => 'Backup file deleted from host successfully.',
        'warning_restore' => 'Warning: Current data will be totally replaced by the chosen version.'
    ]
];

$message = '';
$error = '';
$backup_dir = 'backups';

if (!is_dir($backup_dir)) { mkdir($backup_dir, 0755, true); }

// دالة توليد محتوى الـ SQL
function generateBackupSQL($pdo) {
    $tables = [];
    $result = $pdo->query("SHOW TABLES");
    while ($row = $result->fetch(PDO::FETCH_NUM)) { $tables[] = $row[0]; }
    $sql_content = "-- Osama Electric System Backup\n-- Date: " . date('Y-m-d H:i:s') . "\nSET FOREIGN_KEY_CHECKS = 0;\n\n";
    foreach ($tables as $table) {
        $sql_content .= "DROP TABLE IF EXISTS `$table`;\n";
        $res = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
        $sql_content .= "\n\n" . $res[1] . ";\n\n";
        $rows = $pdo->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_NUM);
        foreach ($rows as $row) {
            $sql_content .= "INSERT INTO `$table` VALUES (";
            $values = array_map(function($val) use ($pdo) { return ($val === null) ? 'NULL' : $pdo->quote($val); }, $row);
            $sql_content .= implode(',', $values) . ");\n";
        }
    }
    $sql_content .= "\nSET FOREIGN_KEY_CHECKS = 1;";
    return $sql_content;
}

// --- معالجة الحذف من الهوست ---
if (isset($_GET['delete_file'])) {
    $filename = basename($_GET['delete_file']);
    $filepath = $backup_dir . '/' . $filename;
    if (file_exists($filepath) && strpos($filename, 'Osama_') === 0) {
        unlink($filepath);
        $message = $texts[$lang]['success_delete'];
    }
}

// --- معالجة الاستعادة ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $password = $_POST['confirm_password'];
    $stmt_auth = $pdo->prepare("SELECT password FROM users WHERE id = ?");
    $stmt_auth->execute([$_SESSION['user_id']]);
    $user_p = $stmt_auth->fetchColumn();

    if (!$user_p || !password_verify($password, $user_p)) {
        $error = $texts[$lang]['pass_error'];
    } else {
        if ($_POST['action'] == 'restore' && isset($_FILES['backup_file']) && $_FILES['backup_file']['error'] == 0) {
            try {
                $sql = file_get_contents($_FILES['backup_file']['tmp_name']);
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 0; " . $sql . " SET FOREIGN_KEY_CHECKS = 1;");
                $message = $texts[$lang]['success_restore'];
            } catch (Exception $e) { $error = $e->getMessage(); }
        } 
        elseif ($_POST['action'] == 'restore_from_server' && isset($_POST['server_filename'])) {
            try {
                $filepath = $backup_dir . '/' . basename($_POST['server_filename']);
                if (file_exists($filepath)) {
                    $sql = file_get_contents($filepath);
                    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0; " . $sql . " SET FOREIGN_KEY_CHECKS = 1;");
                    $message = $texts[$lang]['success_restore'];
                }
            } catch (Exception $e) { $error = $e->getMessage(); }
        }
    }
}

// أرشفة للهوست
if (isset($_GET['action']) && $_GET['action'] == 'save_to_host') {
    try {
        $sql = generateBackupSQL($pdo);
        $filename = "Osama_Backup_" . date('Y-m-d_H-i') . ".sql";
        file_put_contents($backup_dir . '/' . $filename, $sql);
        $message = $texts[$lang]['success_host'];
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// تحميل SQL
if (isset($_GET['export']) && $_GET['export'] == 'sql') {
    $sql_content = generateBackupSQL($pdo);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=Osama_Backup_'.date('Y-m-d').'.sql');
    echo $sql_content; exit;
}

// تحميل إكسل
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=Balances_Report_'.date('Y-m-d').'.csv');
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($output, ['Sub No', 'Name', 'Phone', 'Box', 'Total Balance ($)']);
    $query = "SELECT sub_no, name, phone, box_no, (old_balance + IFNULL((SELECT SUM(amount_usd) FROM bills WHERE customer_id = c.id AND status = 'unpaid'), 0)) as total FROM customers c ORDER BY name ASC";
    $stmt = $pdo->query($query);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { fputcsv($output, $row); }
    fclose($output); exit;
}

$server_files = glob($backup_dir . "/*.sql");
usort($server_files, function($a, $b) { return filemtime($b) - filemtime($a); });
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $texts[$lang]['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; }</style>
</head>
<body class="text-slate-800 pb-20">

    <div class="container mx-auto px-4 py-12 max-w-6xl">
        <!-- Header -->
        <div class="bg-white p-8 rounded-[3rem] shadow-sm mb-10 flex flex-col md:flex-row justify-between items-center gap-6 border border-slate-100">
            <div class="flex items-center gap-6">
                <div class="w-20 h-20 bg-slate-900 text-white rounded-[2.5rem] flex items-center justify-center text-4xl shadow-2xl">
                    <i class="fas fa-shield-halved"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800 italic"><?= $texts[$lang]['header'] ?></h1>
                    <p class="text-sm text-slate-400 font-bold uppercase"><?= $texts[$lang]['sub_header'] ?></p>
                </div>
            </div>
            <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-black hover:bg-slate-200 transition"><?= $texts[$lang]['home'] ?></a>
        </div>

        <?php if($message): ?>
            <div class="bg-emerald-500 text-white p-6 rounded-3xl mb-8 font-black shadow-lg flex items-center gap-4 italic animate-pulse">
                <i class="fas fa-check-circle text-2xl"></i> <?= $message ?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="bg-rose-500 text-white p-6 rounded-3xl mb-8 font-black shadow-lg flex items-center gap-4 italic">
                <i class="fas fa-exclamation-triangle text-2xl"></i> <?= $error ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Side Actions -->
            <div class="lg:col-span-1 space-y-6">
                <div class="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
                    <div class="w-14 h-14 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center text-xl mb-6 shadow-inner">
                        <i class="fas fa-server"></i>
                    </div>
                    <h3 class="text-lg font-black mb-2 italic"><?= $texts[$lang]['save_host'] ?></h3>
                    <p class="text-[10px] text-slate-400 font-bold mb-6 italic leading-relaxed"><?= $texts[$lang]['save_host_desc'] ?></p>
                    <a href="?action=save_to_host" class="w-full inline-flex items-center justify-center gap-3 bg-blue-600 text-white py-4 rounded-2xl font-black hover:bg-black transition-all shadow-lg italic">
                        <i class="fas fa-hdd"></i> <?= $texts[$lang]['copy_now'] ?>
                    </a>
                </div>

                <div class="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
                    <div class="w-14 h-14 bg-slate-900 text-white rounded-2xl flex items-center justify-center text-xl mb-6 shadow-inner">
                        <i class="fas fa-file-export"></i>
                    </div>
                    <h3 class="text-lg font-black mb-2 italic"><?= $texts[$lang]['download_sql'] ?></h3>
                    <p class="text-[10px] text-slate-400 font-bold mb-6 italic leading-relaxed"><?= $texts[$lang]['download_sql_desc'] ?></p>
                    <a href="?export=sql" class="w-full inline-flex items-center justify-center gap-3 bg-slate-900 text-white py-4 rounded-2xl font-black hover:bg-slate-600 transition-all shadow-lg italic">
                        <i class="fas fa-download"></i> <?= $texts[$lang]['download_btn'] ?>
                    </a>
                </div>

                <div class="bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
                    <div class="w-14 h-14 bg-emerald-50 text-emerald-600 rounded-2xl flex items-center justify-center text-xl mb-6 shadow-inner">
                        <i class="fas fa-file-csv"></i>
                    </div>
                    <h3 class="text-lg font-black mb-2 italic"><?= $texts[$lang]['excel_report'] ?></h3>
                    <p class="text-[10px] text-slate-400 font-bold mb-6 italic"><?= $texts[$lang]['excel_desc'] ?></p>
                    <a href="?export=excel" class="w-full inline-flex items-center justify-center gap-3 bg-emerald-600 text-white py-4 rounded-2xl font-black hover:bg-black transition-all shadow-lg italic">
                        <i class="fas fa-file-download"></i> <?= $texts[$lang]['excel_btn'] ?>
                    </a>
                </div>
            </div>

            <!-- Restore Section -->
            <div class="lg:col-span-2 space-y-8">
                <!-- Upload Restore -->
                <div class="bg-white p-10 rounded-[3.5rem] shadow-xl border-4 border-slate-50 relative overflow-hidden">
                    <h3 class="text-xl font-black mb-6 text-rose-600 italic flex items-center gap-3">
                        <i class="fas fa-history"></i> <?= $texts[$lang]['restore_title'] ?>
                    </h3>
                    <p class="text-xs text-slate-400 font-bold mb-6 italic"><?= $texts[$lang]['warning_restore'] ?></p>

                    <form method="POST" enctype="multipart/form-data" class="space-y-6">
                        <input type="hidden" name="action" value="restore">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 italic font-bold">
                            <div>
                                <label class="block text-[10px] text-slate-400 mb-2 mr-2 uppercase"><?= $texts[$lang]['choose_file'] ?></label>
                                <input type="file" name="backup_file" accept=".sql" required class="w-full p-4 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200 text-sm cursor-pointer hover:border-blue-400 transition">
                            </div>
                            <div>
                                <label class="block text-[10px] text-rose-600 mb-2 mr-2 uppercase"><?= $texts[$lang]['pass_confirm'] ?></label>
                                <input type="password" name="confirm_password" placeholder="******" required class="w-full p-4 bg-rose-50/50 rounded-2xl border-none focus:ring-2 focus:ring-rose-500 outline-none">
                            </div>
                        </div>
                        <button type="submit" class="w-full bg-slate-900 text-white py-5 rounded-3xl font-black text-lg shadow-2xl hover:bg-rose-600 transition-all transform active:scale-95 italic">
                            <?= $texts[$lang]['restore_btn'] ?>
                        </button>
                    </form>
                </div>

                <!-- Server Side Points List -->
                <div class="bg-white rounded-[3.5rem] shadow-sm border border-slate-100 overflow-hidden">
                    <div class="p-8 bg-slate-50 border-b border-slate-100 flex justify-between items-center">
                        <h3 class="font-black text-slate-800 italic uppercase tracking-tighter"><?= $texts[$lang]['host_history'] ?></h3>
                        <span class="bg-blue-600 text-white px-4 py-1 rounded-full text-[10px] font-black italic"><?= count($server_files) ?> Points</span>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-right font-bold italic text-sm">
                            <thead class="bg-white border-b text-slate-400 text-[10px] uppercase">
                                <tr>
                                    <th class="p-6"><?= $texts[$lang]['file_date'] ?></th>
                                    <th class="p-6"><?= $texts[$lang]['file_name'] ?></th>
                                    <th class="p-6 text-center"><?= $texts[$lang]['actions'] ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <?php foreach($server_files as $file): 
                                    $fname = basename($file);
                                    $ftime = date("Y-m-d H:i", filemtime($file));
                                ?>
                                <tr class="hover:bg-slate-50 transition group">
                                    <td class="p-6 text-slate-400 font-mono text-xs"><?= $ftime ?></td>
                                    <td class="p-6 text-slate-700 font-black"><?= $fname ?></td>
                                    <td class="p-6 text-center">
                                        <div class="flex justify-center gap-2">
                                            <a href="<?= $file ?>" download class="w-9 h-9 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center hover:bg-blue-600 hover:text-white transition shadow-sm" title="Download"><i class="fas fa-download"></i></a>
                                            
                                            <button onclick="promptServerRestore('<?= $fname ?>')" class="h-9 px-4 bg-emerald-50 text-emerald-600 rounded-xl flex items-center gap-2 hover:bg-emerald-600 hover:text-white transition text-[10px] font-black shadow-sm" title="<?= $texts[$lang]['restore_from_server'] ?>">
                                                <i class="fas fa-rotate-left"></i> <?= $texts[$lang]['restore_from_server'] ?>
                                            </button>

                                            <!-- زر حذف النسخة الجديد -->
                                            <a href="?delete_file=<?= $fname ?>" onclick="return confirm('<?= $texts[$lang]['warning_restore'] ?> - Permanent Delete?')" class="w-9 h-9 bg-rose-50 text-rose-500 rounded-xl flex items-center justify-center hover:bg-rose-600 hover:text-white transition shadow-sm" title="<?= $texts[$lang]['delete_file'] ?>">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($server_files)): ?>
                                    <tr><td colspan="3" class="p-20 text-center text-slate-300 italic font-black">No Archived Points Found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Hidden Server Restore Modal -->
    <div id="serverModal" class="fixed inset-0 bg-slate-900/90 hidden items-center justify-center z-[100] p-4 backdrop-blur-md">
        <div class="bg-white rounded-[3rem] w-full max-w-md p-10 text-center shadow-2xl animate-in zoom-in duration-300">
            <div class="w-20 h-20 bg-emerald-50 text-emerald-600 rounded-full flex items-center justify-center text-3xl mx-auto mb-6 shadow-inner">
                <i class="fas fa-shield-check"></i>
            </div>
            <h3 class="text-xl font-black mb-2 italic"><?= $texts[$lang]['restore_from_server'] ?></h3>
            <p id="targetFileName" class="text-xs text-slate-400 font-bold mb-8 italic"></p>
            
            <form method="POST" class="space-y-6">
                <input type="hidden" name="action" value="restore_from_server">
                <input type="hidden" name="server_filename" id="serverFileNameInput">
                <input type="password" name="confirm_password" placeholder="<?= $texts[$lang]['pass_confirm'] ?>" required 
                       class="w-full p-5 bg-slate-50 rounded-2xl border-none focus:ring-2 focus:ring-emerald-500 text-center font-black outline-none italic shadow-inner">
                
                <div class="flex gap-3">
                    <button type="submit" class="flex-grow bg-emerald-600 text-white p-5 rounded-2xl font-black hover:bg-black transition transform active:scale-95 italic shadow-lg">
                        <?= $texts[$lang]['restore_btn'] ?>
                    </button>
                    <button type="button" onclick="closeServerModal()" class="px-8 bg-slate-100 text-slate-500 rounded-2xl font-black italic"><?= $is_ar ? 'إلغاء' : 'Cancel' ?></button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function promptServerRestore(fname) {
            document.getElementById('targetFileName').innerText = fname;
            document.getElementById('serverFileNameInput').value = fname;
            document.getElementById('serverModal').classList.replace('hidden', 'flex');
        }
        function closeServerModal() {
            document.getElementById('serverModal').classList.replace('flex', 'hidden');
        }
    </script>
</body>
</html>