<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Respaldo BD', 'backup');
?>
<style>
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-track{background:#1e293b;border-radius:8px}
::-webkit-scrollbar-thumb{background:#475569;border-radius:8px}
.glass{background:var(--card-bg);backdrop-filter:blur(20px);border:1px solid var(--border-color)}
</style>

<div class="relative z-10 max-w-[98%] mx-auto px-4 py-6" style="background:var(--card-bg); color:var(--text-primary); border-radius:var(--radius-lg); min-height:80vh;">
    <header class="glass rounded-2xl p-6 mb-6 flex justify-between items-center flex-wrap gap-3">
        <div><h1 class="text-2xl font-bold text-white m-0">Respaldo de Base de Datos</h1><p class="text-slate-400 text-sm mt-1 m-0">Descargar copia de seguridad de la base de datos MySQL</p></div>
        <button onclick="descargarSQL()" id="btnDescargar" class="py-2.5 px-5 font-bold text-white rounded-xl bg-gradient-to-r from-cyan-600 to-blue-600 hover:from-cyan-500 hover:to-blue-500 border-0 cursor-pointer text-sm transition-all"><i class="bi bi-download me-1"></i> Descargar Backup (.sql)</button>
    </header>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="glass rounded-2xl p-5">
            <div class="flex items-center gap-3">
                <div class="p-3 rounded-xl bg-blue-500/20 text-blue-400"><i class="bi bi-database text-xl"></i></div>
                <div><p class="text-xs text-slate-400 m-0">Base de Datos</p><p class="text-lg font-bold text-white m-0" id="dbName"><?=DB_NAME?></p></div>
            </div>
        </div>
        <div class="glass rounded-2xl p-5">
            <div class="flex items-center gap-3">
                <div class="p-3 rounded-xl bg-emerald-500/20 text-emerald-400"><i class="bi bi-table text-xl"></i></div>
                <div><p class="text-xs text-slate-400 m-0">Tablas</p><p class="text-lg font-bold text-white m-0" id="totalTables">...</p></div>
            </div>
        </div>
        <div class="glass rounded-2xl p-5">
            <div class="flex items-center gap-3">
                <div class="p-3 rounded-xl bg-purple-500/20 text-purple-400"><i class="bi bi-hdd-stack text-xl"></i></div>
                <div><p class="text-xs text-slate-400 m-0">Tamaño</p><p class="text-lg font-bold text-white m-0" id="dbSize">...</p></div>
            </div>
        </div>
    </div>

    <div class="glass rounded-2xl p-5 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-sm font-bold text-white m-0"><i class="bi bi-layers me-1 text-slate-400"></i> Tablas con datos</h3>
            <span class="text-xs text-slate-500" id="tablesCount"></span>
        </div>
        <div id="tablesList" class="overflow-x-auto max-h-80 overflow-y-auto"></div>
    </div>

    <div class="glass rounded-2xl p-5">
        <div class="flex items-center gap-2 mb-3">
            <i class="bi bi-info-circle text-slate-400"></i>
            <p class="text-xs text-slate-400 m-0">El backup contiene todas las tablas, procedimientos, triggers y datos. El archivo se descargará en formato <code class="text-cyan-400 bg-slate-800 px-1.5 py-0.5 rounded">.sql</code>.</p>
        </div>
        <div id="dumpStatus" class="hidden text-xs text-emerald-400 mt-2"><i class="bi bi-check-circle me-1"></i> mysqldump disponible — backup optimizado</div>
    </div>
</div>

<script src="assets/js/sweetalert2.min.js"></script>
<script>
async function cargarInfo() {
    try {
        const r = await fetch('api/backup/descargar.php?action=info');
        const d = await r.json();
        if (!d.success) return;
        const data = d.data;
        document.getElementById('totalTables').textContent = data.total_tables;
        document.getElementById('dbSize').textContent = data.size_mb + ' MB';
        document.getElementById('tablesCount').textContent = (data.tables_with_data||[]).length + ' tablas con datos';

        if (data.mysqldump_available) {
            document.getElementById('dumpStatus').classList.remove('hidden');
        }

        let html = '<table class="w-full text-xs"><thead><tr class="text-slate-400 border-b border-slate-700"><th class="text-left py-2">Tabla</th><th class="text-right py-2">Filas</th></tr></thead><tbody>';
        (data.tables_with_data||[]).forEach(t => {
            const icon = t.table.match(/^(asientos|categoria|cuenta|plan_|libro_)/) ? '📒' :
                        t.table.match(/^(venta|compra|gasto|promo|descuento)/) ? '💰' :
                        t.table.match(/^(usuario|cliente|proveedor|lugar|empleado)/) ? '👤' :
                        t.table.match(/^(producto|inventario|lote|movimiento)/) ? '📦' : '📋';
            html += `<tr class="border-b border-slate-700/20 hover:bg-slate-700/20"><td class="py-1.5"><span class="me-1">${icon}</span><span class="font-mono text-slate-300">${t.table}</span></td><td class="py-1.5 text-right text-slate-400">${t.rows.toLocaleString()}</td></tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('tablesList').innerHTML = html;
    } catch(e) { console.error(e); }
}

function descargarSQL() {
    Swal.fire({
        title: 'Descargar Backup',
        html: '<p class="text-slate-300 text-sm">Se generará un archivo <strong>.sql</strong> con toda la base de datos.</p><p class="text-slate-400 text-xs mt-2">¿Desea continuar?</p>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#06b6d4',
        cancelButtonColor: '#475569',
        confirmButtonText: '<i class="bi bi-download me-1"></i> Descargar',
        cancelButtonText: 'Cancelar'
    }).then(r => {
        if (r.isConfirmed) {
            window.location.href = 'api/backup/descargar.php?action=descargar';
        }
    });
}

cargarInfo();
</script>
<?php renderFooter(); ?>

