<?php
// File: admin/backup.php
// One-click export database sebagai file SQL

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once '../includes/db_connect.php';
require_once '../includes/security.php';

secureSessionStart();
if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    header("Location: login.php"); exit;
}

// Verifikasi CSRF untuk action download
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'download') {
    verifyCsrf();

    try {
        $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);

        // AUDIT FIX: Whitelist tabel yang diizinkan — cegah injeksi via nama tabel tak terduga
        $allowedTables = [
            'admin_users', 'artikel', 'config_cabang', 'kredit_tenor', 'kredit_umum',
            'leads_log', 'produk', 'promo', 'rate_asuransi', 'sales_profile', 'testimoni',
        ];
        $tables = array_filter($tables, fn($t) => in_array($t, $allowedTables, true));

        $sql  = "-- Backup Database\n";
        $sql .= "-- Tanggal: " . date('Y-m-d H:i:s') . "\n";
        $sql .= "-- Generator: Admin Panel Dealer System\n\n";
        $sql .= "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
        $sql .= "START TRANSACTION;\n";
        $sql .= "SET time_zone = \"+00:00\";\n\n";

        // AUDIT FIX: Tambah header peringatan tentang data sensitif di backup
        $sql .= "-- PERINGATAN: File backup ini mengandung data sensitif.\n";
        $sql .= "-- Simpan dengan aman dan JANGAN dibagikan.\n\n";

        foreach ($tables as $table) {
            // Skip tabel cache/log jika tidak diperlukan
            if (in_array($table, ['leads_log'])) {
                // Tetap backup struktur tapi skip data leads (bisa besar)
                $create = $pdo->query("SHOW CREATE TABLE `$table`")->fetch();
                $sql .= "\n-- Struktur: $table\nDROP TABLE IF EXISTS `$table`;\n" . $create[1] . ";\n";
                continue;
            }

            // Struktur tabel
            $create = $pdo->query("SHOW CREATE TABLE `$table`")->fetch();
            $sql .= "\n-- Struktur: $table\nDROP TABLE IF EXISTS `$table`;\n" . $create[1] . ";\n";

            // Data tabel
            $rows = $pdo->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
            // AUDIT FIX: Redact API keys sensitif dari output backup
            if ($table === 'config_cabang') {
                $rows = array_map(function($row) {
                    $row['gemini_api_key']        = '[REDACTED - isi manual setelah restore]';
                    $row['google_places_api_key'] = '[REDACTED - isi manual setelah restore]';
                    return $row;
                }, $rows);
            }
            if ($rows) {
                $cols = '`' . implode('`, `', array_keys($rows[0])) . '`';
                $sql .= "\n-- Data: $table\n";
                foreach ($rows as $row) {
                    $vals = array_map(function($v) use ($pdo) {
                        return $v === null ? 'NULL' : $pdo->quote($v);
                    }, array_values($row));
                    $sql .= "INSERT INTO `$table` ($cols) VALUES (" . implode(', ', $vals) . ");\n";
                }
            }
        }

        $sql .= "\nCOMMIT;\n";

        $filename = 'backup_' . date('Y-m-d_His') . '.sql';
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($sql));
        echo $sql;
        exit;

    } catch (Exception $e) {
        error_log("Backup error: " . $e->getMessage());
        $error = "Gagal membuat backup: " . $e->getMessage();
    }
}

$page_title = 'Backup Database';
require 'includes/header.php';

// Ambil info tabel
$tableInfo = [];
try {
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($tables as $t) {
        $count = $pdo->query("SELECT COUNT(*) FROM `$t`")->fetchColumn();
        $tableInfo[] = ['name' => $t, 'rows' => $count];
    }
} catch (Exception $e) {}
?>

<main class="flex-1 overflow-y-auto p-6 md:p-10 bg-gray-50 w-full">
    <div class="max-w-2xl">
        <h2 class="text-3xl font-bold text-gray-800 mb-2">Backup Database</h2>
        <p class="text-gray-500 mb-8">Export seluruh data website sebagai file SQL. Simpan di tempat aman secara berkala.</p>

        <?php if (!empty($error)): ?>
        <div class="bg-red-100 text-red-700 p-4 rounded-lg mb-6">
            <i class="fa-solid fa-triangle-exclamation mr-2"></i><?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <!-- Info Tabel -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <h3 class="font-bold text-gray-700 mb-4 flex items-center gap-2">
                <i class="fa-solid fa-database text-blue-500"></i> Isi Database Saat Ini
            </h3>
            <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                <?php foreach ($tableInfo as $t): ?>
                <div class="bg-gray-50 rounded-lg p-3 border border-gray-100">
                    <div class="text-xs text-gray-500 uppercase tracking-wide"><?= htmlspecialchars($t['name']) ?></div>
                    <div class="text-2xl font-bold text-gray-800"><?= number_format($t['rows']) ?></div>
                    <div class="text-xs text-gray-400">baris data</div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Tombol Download -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h3 class="font-bold text-gray-700 mb-2">Download Backup SQL</h3>
            <p class="text-sm text-gray-500 mb-5">File backup berisi semua tabel dan data (kecuali riwayat leads yang bisa sangat besar).</p>
            <form method="POST">
                <?= csrfInput() ?>
                <input type="hidden" name="action" value="download">
                <button type="submit"
                        class="bg-blue-600 text-white font-bold py-3 px-8 rounded-lg hover:bg-blue-700 transition flex items-center gap-2 shadow">
                    <i class="fa-solid fa-download"></i> Download Backup Sekarang
                </button>
            </form>
            <p class="text-xs text-gray-400 mt-4">
                <i class="fa-solid fa-circle-info mr-1"></i>
                Disarankan backup rutin setiap minggu, terutama sebelum melakukan perubahan besar.
            </p>
        </div>
    </div>
</main>
<?php require 'includes/footer.php'; ?>
