<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

if (!admin_is_authenticated()) {
    admin_redirect('/admin/?route=login');
}

$state = admin_refresh_state();
$config = $state['config'];
$errors = [];
$notice = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfToken = (string) ($_POST['csrf_token'] ?? '');
    if (!admin_verify_csrf($csrfToken)) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } elseif (!isset($_FILES['media_file'])) {
        $errors[] = 'Please select a file.';
    } else {
        $result = cms_save_media_upload($_FILES['media_file']);
        if (!empty($result['ok'])) {
            $notice = (string) $result['message'];
        } else {
            $errors[] = (string) ($result['message'] ?? 'Upload failed.');
        }
    }
}

$mediaItems = cms_get_media_items();
$siteTitle = admin_site_title($config);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo admin_escape($siteTitle); ?> Media</title>
    <?php echo admin_shared_styles(); ?>
</head>
<body>
<div class="app">
    <?php admin_render_sidebar('media'); ?>
    <main class="content">
        <div class="page-header"><div><h1 class="page-title">Media Manager</h1><div class="page-subtitle">Upload and open media from a lighter mobile-friendly library screen.</div></div></div>
        <?php if ($notice !== ''): ?><div class="message success"><?php echo admin_escape($notice); ?></div><?php endif; ?>
        <?php foreach ($errors as $error): ?><div class="message error"><?php echo admin_escape($error); ?></div><?php endforeach; ?>
        <div class="panel">
            <form method="post" action="/admin/media.php" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                <input type="file" name="media_file" required>
                <button class="btn" type="submit">Upload</button>
            </form>
        </div>
        <div class="panel">
            <div class="grid">
                <?php foreach ($mediaItems as $media): ?>
                    <div class="card">
                        <strong><?php echo admin_escape((string) $media['file_name']); ?></strong>
                        <p style="color:#746655; word-break:break-all;"><?php echo admin_escape((string) $media['file_path']); ?></p>
                        <p style="color:#746655;"><?php echo admin_escape((string) $media['mime_type']); ?> | <?php echo number_format((int) $media['file_size']); ?> bytes</p>
                        <a href="<?php echo admin_escape((string) $media['file_path']); ?>" target="_blank" rel="noopener">Open</a>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </main>
</div>
</body>
</html>
