<style>
.backup-card {
    border-radius: 16px;
    border: none;
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
}
.backup-card:hover { transform: translateY(-3px); box-shadow: 0 12px 30px rgba(0,0,0,0.1) !important; }
.backup-export-card { border-top: 4px solid #0d6efd; }
.backup-import-card { border-top: 4px solid #8b5cf6; }
.backup-info-card  { border-top: 4px solid #10b981; }
.action-btn {
    padding: 14px 28px;
    border-radius: 999px;
    font-weight: 700;
    font-size: 15px;
    border: none;
    cursor: pointer;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
}
.btn-export { background: linear-gradient(135deg, #0d6efd, #0ea5e9); color: #fff; }
.btn-export:hover { box-shadow: 0 6px 20px rgba(13,110,253,0.4); transform: scale(1.03); color: #fff; }
.btn-restore { background: linear-gradient(135deg, #8b5cf6, #6366f1); color: #fff; }
.btn-restore:hover { box-shadow: 0 6px 20px rgba(139,92,246,0.4); transform: scale(1.03); color: #fff; }
.danger-notice {
    background: rgba(220,53,69,0.08);
    border: 1px solid rgba(220,53,69,0.25);
    border-radius: 12px;
    padding: 14px 18px;
    color: #dc3545;
    font-size: 13px;
    font-weight: 600;
}
.file-drop-zone {
    border: 2px dashed #6366f1;
    border-radius: 12px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    background: rgba(99,102,241,0.04);
}
.file-drop-zone:hover, .file-drop-zone.drag-over {
    background: rgba(99,102,241,0.1);
    border-color: #8b5cf6;
}
.file-drop-zone input[type="file"] { display: none; }
.table-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 8px;
    max-height: 250px;
    overflow-y: auto;
}
.table-badge {
    background: rgba(13,110,253,0.08);
    border: 1px solid rgba(13,110,253,0.15);
    border-radius: 8px;
    padding: 6px 10px;
    font-size: 11px;
    color: #0d6efd;
    font-weight: 600;
}
</style>

<!-- Header -->
<div class="row mb-4">
    <div class="col">
        <h1 class="h2 fw-bold mb-1">
            <i class="fa-solid fa-database text-primary me-2"></i>النسخ الاحتياطي والاستعادة
        </h1>
        <p class="text-muted">صدّر بياناتك بالكامل أو استعدها من نسخة سابقة بأمان تام.</p>
    </div>
</div>

<?= isset($flash) ? '' : '' ?>
<?php if(isset($_SESSION['flash']['backup'])): ?>
    <?php $f = $_SESSION['flash']['backup']; unset($_SESSION['flash']['backup']); ?>
    <div class="alert alert-<?= $f['type'] ?> alert-dismissible fade show rounded-4 mb-4" role="alert">
        <?= $f['message'] ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">

    <!-- EXPORT CARD -->
    <div class="col-md-6">
        <div class="card backup-card backup-export-card h-100 p-4 shadow-sm">
            <div class="d-flex align-items-center gap-3 mb-4">
                <div style="width:52px;height:52px;background:rgba(13,110,253,0.1);border-radius:14px;display:flex;align-items:center;justify-content:center;">
                    <i class="fa-solid fa-file-export fa-lg text-primary"></i>
                </div>
                <div>
                    <h5 class="fw-bold mb-0">تصدير البيانات</h5>
                    <small class="text-muted">Export All Data</small>
                </div>
            </div>

            <p class="text-secondary mb-4">
                يُصدِّر <strong>جميع بياناتك</strong> في ملف JSON واحد يحتوي على:
                كل سجلات الصحة، المالية، العادات، السلوكيات، اليومية، التقويم، التعليم، والخزنة.
            </p>

            <div class="mb-4">
                <div class="d-flex flex-wrap gap-2 mb-2">
                    <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill">🏥 الصحة</span>
                    <span class="badge bg-warning bg-opacity-10 text-warning rounded-pill">💰 المالية</span>
                    <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill">🔥 العادات</span>
                    <span class="badge bg-purple bg-opacity-10 rounded-pill" style="background:rgba(139,92,246,0.1);color:#8b5cf6;">🧠 السلوكيات</span>
                    <span class="badge bg-info bg-opacity-10 text-info rounded-pill">📖 اليومية</span>
                    <span class="badge bg-success bg-opacity-10 text-success rounded-pill">+ المزيد</span>
                </div>
            </div>

            <div class="mt-auto">
                <a href="<?= BASE_URL ?>/system/backup/export" class="action-btn btn-export w-100 justify-content-center" id="exportBtn" onclick="startExport(this)">
                    <i class="fa-solid fa-download" id="exportIcon"></i>
                    تحميل النسخة الاحتياطية
                </a>
                <p class="text-muted text-center mt-3 mb-0" style="font-size:12px;">
                    <i class="fa-solid fa-shield-halved text-success me-1"></i>
                    الملف مشفر بصيغة JSON • يحتوي تاريخ التصدير
                </p>
            </div>
        </div>
    </div>

    <!-- IMPORT CARD -->
    <div class="col-md-6">
        <div class="card backup-card backup-import-card h-100 p-4 shadow-sm">
            <div class="d-flex align-items-center gap-3 mb-4">
                <div style="width:52px;height:52px;background:rgba(139,92,246,0.1);border-radius:14px;display:flex;align-items:center;justify-content:center;">
                    <i class="fa-solid fa-file-import fa-lg" style="color:#8b5cf6;"></i>
                </div>
                <div>
                    <h5 class="fw-bold mb-0">استعادة البيانات</h5>
                    <small class="text-muted">Restore from Backup</small>
                </div>
            </div>

            <div class="danger-notice mb-4">
                <i class="fa-solid fa-triangle-exclamation me-2"></i>
                <strong>تحذير:</strong> الاستعادة ستحذف جميع بياناتك الحالية وتستبدلها بمحتوى الملف. هذا الإجراء لا يمكن التراجع عنه.
            </div>

            <form action="<?= BASE_URL ?>/system/backup/import" method="POST" enctype="multipart/form-data" id="restoreForm" data-no-pjax>
                <?= csrf_field() ?>

                <!-- File Drop Zone -->
                <div class="file-drop-zone mb-3" id="dropZone" onclick="document.getElementById('backupFile').click()">
                    <input type="file" name="backup_file" id="backupFile" accept=".json,application/json" required onchange="showFileName(this)">
                    <i class="fa-solid fa-cloud-arrow-up fa-2x mb-2" style="color:#8b5cf6;"></i>
                    <p class="mb-0 fw-bold">اسحب الملف هنا أو انقر للاختيار</p>
                    <small class="text-muted">يُقبل ملفات .json فقط</small>
                    <div id="fileNameDisplay" class="mt-2 text-success fw-bold d-none"></div>
                </div>

                <!-- Password Confirmation -->
                <div class="mb-3">
                    <label class="form-label fw-bold text-dark">
                        <i class="fa-solid fa-lock me-2 text-danger"></i>كلمة المرور للتأكيد
                    </label>
                    <input type="password" name="restore_password" class="form-control bg-light border-0 shadow-sm" placeholder="أدخل كلمة مرورك الحالية" required autocomplete="current-password">
                </div>

                <!-- Confirm checkbox -->
                <div class="form-check mb-4">
                    <input class="form-check-input" type="checkbox" id="confirmRestore" required>
                    <label class="form-check-label fw-bold text-danger" for="confirmRestore">
                        أفهم أن هذا الإجراء سيحذف بياناتي الحالية بشكل غير قابل للتراجع
                    </label>
                </div>

                <button type="submit" class="action-btn btn-restore w-100 justify-content-center" id="restoreBtn" onclick="return confirmRestore()">
                    <i class="fa-solid fa-rotate-left"></i>
                    استعادة البيانات
                </button>
            </form>
        </div>
    </div>
</div>

<!-- INFO CARD: Tables included -->
<div class="card backup-card backup-info-card p-4 shadow-sm">
    <h6 class="fw-bold mb-3">
        <i class="fa-solid fa-table-list text-success me-2"></i>
        الجداول المشمولة في النسخة الاحتياطية (38 جدول)
    </h6>
    <div class="table-list">
        <?php
        $tables = [
            'health_profile','health_weight_logs','health_blood_sugar','health_fasts','health_meals',
            'health_medications','health_med_logs','health_water_logs','health_activities','health_labs','health_goals',
            'finance_incomes','finance_expenses','finance_saving_goals','finance_installments','finance_debts','finance_investments',
            'habits','habit_logs','behavior_habits','behavior_logs',
            'daily_journal','todo_tasks','todo_daily_logs',
            'calendar_events','calendar_time_blocks',
            'edu_programs','edu_courses','edu_skills',
            'spiritual_prayers','spiritual_quran','spiritual_goals',
            'monthly_plans','vault_items','user_settings',
            'notifications','advisor_memory','smart_reminders'
        ];
        foreach($tables as $t): ?>
        <div class="table-badge"><i class="fa-solid fa-table fa-xs me-1"></i><?= $t ?></div>
        <?php endforeach; ?>
    </div>
    <p class="text-muted mt-3 mb-0" style="font-size:12px;">
        <i class="fa-solid fa-shield-halved text-success me-1"></i>
        جداول النظام الأساسية محمية ولن تُمس أثناء الاستعادة: <code>users</code>, <code>action_logs</code>
    </p>
</div>

<script>
function startExport(el) {
    const icon = document.getElementById('exportIcon');
    icon.className = 'fa-solid fa-spinner fa-spin';
    el.style.opacity = '0.7';
    el.style.pointerEvents = 'none';
    setTimeout(() => {
        icon.className = 'fa-solid fa-download';
        el.style.opacity = '';
        el.style.pointerEvents = '';
    }, 3000);
}

function showFileName(input) {
    const display = document.getElementById('fileNameDisplay');
    if (input.files[0]) {
        display.textContent = '✅ ' + input.files[0].name;
        display.classList.remove('d-none');
    }
}

function confirmRestore() {
    const confirm1 = document.getElementById('confirmRestore').checked;
    if (!confirm1) { alert('يجب تأكيد الموافقة أولاً'); return false; }
    return confirm('⚠️ تأكيد أخير: هل أنت متأكد من استعادة البيانات وحذف جميع البيانات الحالية؟');
}

// Drag & drop zone
const dropZone = document.getElementById('dropZone');
if (dropZone) {
    dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
    dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('drag-over');
        const file = e.dataTransfer.files[0];
        if (file && file.type === 'application/json') {
            const input = document.getElementById('backupFile');
            const dt = new DataTransfer();
            dt.items.add(file);
            input.files = dt.files;
            showFileName(input);
        } else {
            alert('يُقبل ملفات JSON فقط');
        }
    });
}
</script>
