<?php
/**
 * 炎酷CMS - 数据库备份
 * 导出全部 DB_PREFIX 前缀表结构与数据为 .sql 存 data/backup/，支持下载与删除
 */
define('YKCMS', 1);
require dirname(__DIR__) . '/inc/auth.php';

$page_title = '数据备份';
$active = 'backup';

$backupDir = SITE_PATH . '/data/backup';
if (!is_dir($backupDir)) @mkdir($backupDir, 0755, true);

// 文件名校验：防目录穿越
function yk_safe_backup_name($name) {
    $name = basename((string)$name);
    return preg_match('/^yk_backup_\d{8}_\d{6}\.sql$/', $name) ? $name : '';
}

// ---------- 下载 ----------
if (isset($_GET['act']) && $_GET['act'] === 'download') {
    $name = yk_safe_backup_name(isset($_GET['file']) ? $_GET['file'] : '');
    $file = $name !== '' ? $backupDir . '/' . $name : '';
    if ($file === '' || !is_file($file)) {
        exit('文件不存在');
    }
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $name . '"');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

// ---------- 写操作 ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $do = isset($_POST['do']) ? $_POST['do'] : '';

    if ($do === 'backup') {
        $pdo = db();
        $tables = array();
        $like = $pdo->quote(DB_PREFIX . '%');
        foreach ($pdo->query("SHOW TABLES LIKE $like")->fetchAll(PDO::FETCH_COLUMN) as $t) {
            $tables[] = $t;
        }
        $sql = "-- 炎酷CMS 数据库备份\n-- 时间：" . date('Y-m-d H:i:s') . "\n-- 表前缀：" . DB_PREFIX . "\n\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\n\n";
        foreach ($tables as $t) {
            $create = $pdo->query("SHOW CREATE TABLE `$t`")->fetch(PDO::FETCH_NUM);
            $sql .= "DROP TABLE IF EXISTS `$t`;\n" . $create[1] . ";\n\n";
            $rows = $pdo->query("SELECT * FROM `$t`")->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $r) {
                $vals = array();
                foreach ($r as $v) {
                    $vals[] = $v === null ? 'NULL' : $pdo->quote((string)$v);
                }
                $sql .= "INSERT INTO `$t` VALUES (" . implode(',', $vals) . ");\n";
            }
            $sql .= "\n";
        }
        $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";

        $name = 'yk_backup_' . date('Ymd_His') . '.sql';
        if (@file_put_contents($backupDir . '/' . $name, $sql) === false) {
            flash_set('备份失败：data/backup/ 目录不可写', 'err');
        } else {
            admin_log('数据备份', '生成备份 ' . $name . '（共 ' . count($tables) . ' 张表）');
            flash_set('备份成功：' . $name);
        }
        header('Location: backup.php');
        exit;
    }

    if ($do === 'delete') {
        $name = yk_safe_backup_name(isset($_POST['file']) ? $_POST['file'] : '');
        $file = $name !== '' ? $backupDir . '/' . $name : '';
        if ($file !== '' && is_file($file)) {
            @unlink($file);
            admin_log('删除备份', $name);
            flash_set('备份已删除');
        } else {
            flash_set('文件不存在', 'err');
        }
        header('Location: backup.php');
        exit;
    }
}

// ---------- 备份列表 ----------
$files = array();
foreach (glob($backupDir . '/yk_backup_*.sql') as $f) {
    $files[] = array('name' => basename($f), 'size' => filesize($f), 'mtime' => filemtime($f));
}
usort($files, function ($a, $b) { return $b['mtime'] - $a['mtime']; });

require dirname(__DIR__) . '/inc/header.php';
?>
<div class="yk-card">
  <h3>数据库备份</h3>
  <form method="post" action="backup.php" onsubmit="return confirm('确定立即备份数据库？');">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="do" value="backup">
    <button class="yk-btn" type="submit">立即备份</button>
    <span style="color:#999;font-size:12px;margin-left:10px">导出全部 <?php echo e(DB_PREFIX); ?> 前缀表的结构与数据，保存到 data/backup/</span>
  </form>
</div>

<div class="yk-card">
  <h3>已有备份</h3>
  <table class="yk-table">
    <tr><th>文件名</th><th width="110">大小</th><th width="150">备份时间</th><th width="130">操作</th></tr>
    <?php foreach ($files as $f): ?>
    <tr>
      <td><?php echo e($f['name']); ?></td>
      <td><?php echo e(number_format($f['size'] / 1024, 1)); ?> KB</td>
      <td><?php echo e(date('Y-m-d H:i:s', $f['mtime'])); ?></td>
      <td class="yk-actions">
        <a href="backup.php?act=download&amp;file=<?php echo urlencode($f['name']); ?>">下载</a>
        <form method="post" action="backup.php" style="display:inline" onsubmit="return confirm('确定删除该备份文件？');">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="do" value="delete">
          <input type="hidden" name="file" value="<?php echo e($f['name']); ?>">
          <button type="submit" style="background:none;border:none;color:#d93025;cursor:pointer;padding:0;font-size:13px">删除</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$files): ?><tr><td colspan="4" style="text-align:center;color:#999">暂无备份文件</td></tr><?php endif; ?>
  </table>
</div>
<?php require dirname(__DIR__) . '/inc/footer.php'; ?>
