<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

require_admin();

$pageTitle = 'Backups';
$success = '';
$error = '';

$backupDir = __DIR__ . '/../storage/backups/';

if (!is_dir($backupDir)) {
    mkdir($backupDir, 0777, true);
}

function sql_value($value)
{
    if ($value === null) {
        return 'NULL';
    }

    return "'" . str_replace("'", "''", $value) . "'";
}

function generate_database_backup($pdo, $backupFile)
{
    $handle = fopen($backupFile, 'w');

    if (!$handle) {
        throw new Exception('Could not create backup file.');
    }

    fwrite($handle, "-- LOVE-U Essentials Database Backup\n");
    fwrite($handle, "-- Generated: " . date('Y-m-d H:i:s') . "\n\n");
    fwrite($handle, "SET FOREIGN_KEY_CHECKS=0;\n\n");

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

    foreach ($tables as $table) {
        fwrite($handle, "\n-- Table structure for `$table`\n");
        fwrite($handle, "DROP TABLE IF EXISTS `$table`;\n");

        $createStmt = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
        fwrite($handle, $createStmt['Create Table'] . ";\n\n");

        fwrite($handle, "-- Data for `$table`\n");

        $rows = $pdo->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);

        foreach ($rows as $row) {
            $columns = array_map(function ($column) {
                return "`$column`";
            }, array_keys($row));

            $values = array_map('sql_value', array_values($row));

            fwrite(
                $handle,
                "INSERT INTO `$table` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $values) . ");\n"
            );
        }

        fwrite($handle, "\n");
    }

    fwrite($handle, "SET FOREIGN_KEY_CHECKS=1;\n");
    fclose($handle);
}

if (isset($_GET['download'])) {
    $backupId = (int) $_GET['download'];

    $stmt = $pdo->prepare("SELECT * FROM backups WHERE id = ? LIMIT 1");
    $stmt->execute([$backupId]);
    $backup = $stmt->fetch();

    if (!$backup) {
        die('Backup not found.');
    }

    $filePath = __DIR__ . '/../' . $backup['backup_path'];

    if (!file_exists($filePath)) {
        die('Backup file missing.');
    }

    header('Content-Type: application/sql');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    header('Content-Length: ' . filesize($filePath));

    readfile($filePath);
    exit;
}

if (isset($_GET['delete'])) {
    $backupId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("SELECT * FROM backups WHERE id = ? LIMIT 1");
    $stmt->execute([$backupId]);
    $backup = $stmt->fetch();

    if ($backup) {
    $filePath = __DIR__ . '/../' . $backup['backup_path'];

    if (file_exists($filePath)) {
        unlink($filePath);
    }

    $stmt = $pdo->prepare("DELETE FROM backups WHERE id = ?");
    $stmt->execute([$backupId]);

    log_admin_activity(
        'backup_deleted',
        'Backup deleted: ' . ($backup['backup_name'] ?? 'Backup ID ' . $backupId)
    );
}

redirect(ADMIN_URL . '/backups.php?deleted=1');
}

if (isset($_GET['created'])) {
    $success = 'Database backup created successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'Backup deleted successfully.';
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        try {
            $currentAdmin = admin();

            $backupName = 'database-backup-' . date('Y-m-d-H-i-s');
            $fileName = $backupName . '.sql';
            $absolutePath = $backupDir . $fileName;
            $relativePath = 'storage/backups/' . $fileName;

            generate_database_backup($pdo, $absolutePath);

            $stmt = $pdo->prepare("
                INSERT INTO backups (
                    backup_name,
                    backup_path,
                    backup_type,
                    created_by
                ) VALUES (?, ?, 'database', ?)
            ");

            $stmt->execute([
    $backupName,
    $relativePath,
    $currentAdmin['id'] ?? null
]);

log_admin_activity(
    'backup_created',
    'Database backup created: ' . $backupName . ' | Path: ' . $relativePath
);

redirect(ADMIN_URL . '/backups.php?created=1');
        } catch (Exception $e) {
            $error = 'Backup could not be created: ' . $e->getMessage();
        }
    }
}

$backups = $pdo->query("
    SELECT b.*,
           a.full_name AS admin_name
    FROM backups b
    LEFT JOIN admin_users a ON b.created_by = a.id
    ORDER BY b.id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Backups</h1>
            <div class="admin-user">Create, download, and delete database backup files.</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Create Database Backup</h2>
        <p style="color:#666; line-height:1.7;">
            This will generate a full SQL backup of your current local database and save it inside
            <strong>storage/backups</strong>.
        </p>

        <form method="POST">
            <?= csrf_field(); ?>
            <button type="submit" class="admin-btn">Create Database Backup</button>
        </form>
    </section>

    <section class="admin-panel">
        <h2>Backup History</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Backup Name</th>
                    <th>Type</th>
                    <th>Path</th>
                    <th>Created By</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$backups): ?>
                    <tr>
                        <td colspan="6">No backups created yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($backups as $backup): ?>
                    <tr>
                        <td><strong><?= e($backup['backup_name']); ?></strong></td>
                        <td><?= e(ucfirst($backup['backup_type'])); ?></td>
                        <td><?= e($backup['backup_path']); ?></td>
                        <td><?= e($backup['admin_name'] ?? 'Admin'); ?></td>
                        <td><?= e(date('d M Y, h:i A', strtotime($backup['created_at']))); ?></td>
                        <td>
                            <a class="admin-btn" href="<?= e(ADMIN_URL); ?>/backups.php?download=<?= e($backup['id']); ?>">
                                Download
                            </a>

                            <a
                                class="admin-btn admin-btn-light"
                                href="<?= e(ADMIN_URL); ?>/backups.php?delete=<?= e($backup['id']); ?>"
                                onclick="return confirm('Delete this backup file and record?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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