<?php

namespace Core\App\Controllers;

use Core\App\Models\SystemBackup;
use Core\System\Response;

class SystemBackupController
{
    public function index()
    {
        $model = new SystemBackup();

        $tables  = $model->getTables();
        $backups = $model->listBackups();

        extract([
            'tables'  => $tables,
            'backups' => $backups
        ]);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/system/backup.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function run()
{
    $model = new SystemBackup();

    $type       = trim((string)($_POST['backup_type'] ?? 'db'));
    $compress   = (int)($_POST['compress'] ?? 1) === 1;

    $tablesMode = trim((string)($_POST['tables_mode'] ?? 'all'));
    $tables     = $_POST['tables'] ?? [];

    if (!in_array($type, ['db', 'script', 'full'], true)) {
        Response::redirect('/admin/system/backup?error=1');
    }

    // only validate tables if DB or FULL
    if ($type === 'db' || $type === 'full') {
        if ($tablesMode === 'selected') {
            if (!is_array($tables) || empty($tables)) {
                Response::redirect('/admin/system/backup?error=1');
            }
        } else {
            $tables = [];
        }
    } else {
        $tables = [];
    }

    $file = null;

    // DB only
    if ($type === 'db') {
        $file = $model->createDatabaseBackup($tables, $compress);
    }

    // Script only
    if ($type === 'script') {
        $file = $model->createScriptBackupZip();
    }

    // Full backup (DB + Script)
    if ($type === 'full') {
        $file = $model->createFullBackupScriptAndDbZip($tables, $compress);
    }

    if (!$file) {
        Response::redirect('/admin/system/backup?error=1');
    }

    Response::redirect('/admin/system/backup?done=1&file=' . urlencode($file));
}

    public function download()
    {
        $model = new SystemBackup();

        $file = trim((string)($_GET['file'] ?? ''));

        if ($file === '') {
            http_response_code(404);
            exit;
        }

        $model->downloadBackup($file);
        exit;
    }

    public function delete()
    {
        $model = new SystemBackup();

        $file = trim((string)($_POST['file'] ?? ''));

        if ($file === '') {
            Response::redirect('/admin/system/backup?error=1');
        }

        $ok = $model->deleteBackup($file);

        Response::redirect('/admin/system/backup?' . ($ok ? 'deleted=1' : 'error=1'));
    }

    public function clean()
    {
        $model = new SystemBackup();

        // delete backups older than 30 days by default
        $model->cleanupOldBackups(30);

        Response::redirect('/admin/system/backup?deleted=1');
    }
}
