<?php
require_once __DIR__ . "/../../src/Core/Auth.php";
require_once __DIR__ . "/../../src/Core/Model.php";
require_once __DIR__ . "/../../src/Core/MultiTenancy.php";

if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

$tenantId = \Core\MultiTenancy::getTenantId();
define('DB_PATH', \Core\MultiTenancy::getDatabasePath($tenantId));

$message = '';
if (isset($_POST['action']) && $_POST['action'] === 'backup') {
    $zip = new ZipArchive();
    $zipName = 'backup_' . date('Y-m-d_H-i-s') . '.zip';
    $zipPath = __DIR__ . '/../' . $zipName;

    if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
        $zip->addFile(DB_PATH, 'database.sqlite');

        // Add uploads
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(__DIR__ . '/../uploads/'),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($files as $name => $file) {
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                $relativePath = 'uploads/' . substr($filePath, strlen(__DIR__ . '/../uploads/'));
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        $message = "Backup created: <a href='/$zipName'>$zipName</a>";
    } else {
        $message = "Failed to create backup.";
    }
}

// Health Check
$health = [
    'PHP Version' => phpversion(),
    'SQLite Writeable' => is_writable(DB_PATH) ? 'Yes' : 'No',
    'Uploads Writeable' => is_writable(__DIR__ . '/../uploads/') ? 'Yes' : 'No',
    'Memory Limit' => ini_get('memory_limit'),
];

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Maintenance - AI-Native CMS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
    <style>
        body {
            padding: 1rem;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>Maintenance & Health</h1>
        <a href="/admin/" role="button">← Back to Dashboard</a>

        <?php if ($message): ?><ins><?= $message ?></ins><?php endif; ?>

        <section>
            <h2>System Health</h2>
            <table>
                <?php foreach ($health as $key => $value): ?>
                    <tr>
                        <td><strong><?= $key ?></strong></td>
                        <td><?= $value ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </section>

        <section>
            <h2>Backups</h2>
            <form method="POST">
                <input type="hidden" name="action" value="backup">
                <button type="submit">Create Full Backup (.zip)</button>
            </form>
        </section>
    </div>
</body>

</html>