<?php
/**
 * Database Backup Page
 * CMTC Shopping
 */
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/navbar.php';

require_login();
require_permission($db, 'system_settings');

$success = "";
$error = "";

// Handle export / backup download
if (isset($_GET['download']) && $_GET['download'] === 'sql') {
    try {
        $tables = $db->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        $return = "-- CMTC Shopping SQL Database Backup\n";
        $return .= "-- Generated: " . date("Y-m-d H:i:s") . "\n\n";
        $return .= "SET FOREIGN_KEY_CHECKS=0;\n\n";

        foreach ($tables as $table) {
            $row2 = $db->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_NUM);
            $return .= "\n\n" . $row2[1] . ";\n\n";

            $rows = $db->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_NUM);
            foreach ($rows as $row) {
                $return .= "INSERT INTO `$table` VALUES(";
                $vals = [];
                foreach ($row as $v) {
                    if ($v === null) {
                        $vals[] = "NULL";
                    } else {
                        $vals[] = "'" . addslashes($v) . "'";
                    }
                }
                $return .= implode(',', $vals) . ");\n";
            }
        }
        $return .= "\nSET FOREIGN_KEY_CHECKS=1;\n";

        $filename = "backup_shop_" . date('Ymd_His') . ".sql";
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header("Content-disposition: attachment; filename=\"" . $filename . "\"");
        echo $return;
        exit();
    } catch (Exception $e) {
        $error = "เกิดข้อผิดพลาดในการสำรองข้อมูล: " . $e->getMessage();
    }
}
?>

<div class="d-flex">
    <?php require_once __DIR__ . '/../includes/sidebar.php'; ?>

    <main class="flex-grow-1 p-4" style="background-color: var(--bs-body-bg);">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold mb-0"><i class="bi bi-database-down text-primary me-2"></i>สำรองข้อมูลระบบ (Database Backup)</h3>
                <p class="text-muted small mb-0">ดาวน์โหลดไฟล์สำรองฐานข้อมูล SQL เพื่อความปลอดภัยของข้อมูล</p>
            </div>
        </div>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger mb-4"><?php echo $error; ?></div>
        <?php endif; ?>

        <div class="card border-0 shadow-sm glass-card p-5 mx-auto text-center" style="max-width: 650px;">
            <i class="bi bi-database-check text-success mb-3" style="font-size: 4rem;"></i>
            <h4 class="fw-bold">ดาวน์โหลดไฟล์สำรองฐานข้อมูล</h4>
            <p class="text-muted mb-4">ระบบจะทำการ Dump โครงสร้างตารางและข้อมูลทั้งหมดออกเป็นไฟล์ <code>.sql</code></p>

            <div>
                <a href="<?php echo base_url('views/backup.php?download=sql'); ?>" class="btn btn-success btn-lg px-4 shadow">
                    <i class="bi bi-download me-2"></i> ดาวน์โหลด Backup SQL ตอนนี้
                </a>
            </div>
        </div>
    </main>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
