<?php
declare(strict_types=1);

require __DIR__ . '/src/bootstrap.php';
require_admin();

$items = load_json(DATA_DIR . '/items.json', []);
$images = get_available_images();

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    
    $action = $_POST['action'] ?? '';
    
    if ($action === 'upload') {
        $file = $_FILES['upload_image'] ?? null;
        if ($file && $file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (in_array($ext, $allowed, true)) {
                $filename = 'Upload_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                $dest = BASE_DIR . '/imagens/' . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $dest)) {
                    $imagePath = 'imagens/' . $filename;
                    
                    $newItem = [
                        'id' => generate_id(),
                        'title' => pathinfo($file['name'], PATHINFO_FILENAME),
                        'description' => '',
                        'image' => $imagePath,
                        'created_at' => date('c'),
                    ];
                    
                    $items[] = $newItem;
                    save_json(DATA_DIR . '/items.json', $items);
                    $success = 'A imagem foi carregada e partilhada com sucesso!';
                } else {
                    $error = 'Erro ao guardar a imagem. Verifique as permissões.';
                }
            } else {
                $error = 'Formato inválido. Use JPG, PNG, GIF ou WEBP.';
            }
        } else {
            $error = 'Por favor, selecione um ficheiro válido e que não exceda o limite do servidor.';
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? '';
        $items = array_filter($items, static fn($item) => $item['id'] !== $id);
        $items = array_values($items); // Reindex array
        save_json(DATA_DIR . '/items.json', $items);
        
        // Optionally clean up votes for deleted item
        $votes = load_json(DATA_DIR . '/votes.json', []);
        $votesChanged = false;
        foreach ($votes as $email => &$userVotes) {
            if (isset($userVotes[$id])) {
                unset($userVotes[$id]);
                $votesChanged = true;
            }
        }
        if ($votesChanged) {
            save_json(DATA_DIR . '/votes.json', $votes);
        }
        
        $success = 'A imagem foi removida da votação.';
    } elseif ($action === 'reset_votos') {
        $resetEmail = normalize_email($_POST['email'] ?? '');
        $votes = load_json(DATA_DIR . '/votes.json', []);
        
        if (isset($votes[$resetEmail])) {
            unset($votes[$resetEmail]);
            save_json(DATA_DIR . '/votes.json', $votes);
            $success = "Todos os votos do utilizador $resetEmail foram removidos.";
        } else {
            $error = "Não foram encontrados votos para o utilizador $resetEmail.";
        }
    }
}

// Carregar estatísticas
$allVotes = load_json(DATA_DIR . '/votes.json', []);
$stats = build_item_stats($items, $allVotes);
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administração - Fábrica dos Ovos</title>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #fd8b2b;
            --secondary-color: #ffc273;
            --accent-color: #e56b10;
            --chocolate-bg: #5c3a21;
            --bg-color: #fdfbfb;
            --text-main: #4a4a4a;
            --error-color: #e63946;
            --success-color: #2a9d8f;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Outfit', sans-serif;
        }

        body {
            min-height: 100vh;
            background: linear-gradient(135deg, #fce0cd 0%, #ffead4 100%);
            color: var(--text-main);
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Modern Header */
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: var(--chocolate-bg);
            padding: 1rem 2rem;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.2);
            margin-bottom: 2rem;
            color: white;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header-logo {
            height: 70px;
            width: auto;
        }

        .header-info-group {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        @media (max-width: 600px) {
            body { padding: 10px; }
            .header { padding: 1.2rem; flex-direction: column; text-align: center; border-radius: 15px; }
            .header-info-group { flex-direction: column; gap: 5px; }
            .nav-links { width: 100%; justify-content: center; margin-top: 10px; }
            .main-grid { grid-template-columns: 1fr; }
            .panel { padding: 1.5rem 1rem; border-radius: 15px; }
            .stats-table thead { display: none; }
            .stats-table tr { display: block; margin-bottom: 1.5rem; padding: 1rem; border: 1px solid #eee; border-radius: 12px; background: #fff; }
            .stats-table td { display: flex; justify-content: space-between; align-items: center; padding: 0.8rem 0; border-bottom: 1px solid #f9f9f9; text-align: right; }
            .stats-table td:last-child { border-bottom: none; }
            .stats-table td::before { content: attr(data-label); font-weight: 800; color: #999; text-transform: uppercase; font-size: 0.7rem; }
            .post-image-box { height: 140px; }
        }

        .nav-links {
            display: flex;
            gap: 15px;
        }

        .nav-link {
            text-decoration: none;
            color: white;
            font-weight: 600;
            padding: 0.7rem 1.2rem;
            border-radius: 12px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255,255,255,0.1);
        }

        .nav-link:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        /* Main Grid Layout */
        .main-grid {
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 2rem;
        }

        @media (max-width: 900px) {
            .main-grid { grid-template-columns: 1fr; }
        }

        .panel {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 25px;
            padding: 2.5rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            border: 1px solid white;
            height: fit-content;
        }

        .panel-title {
            font-size: 1.4rem;
            margin-bottom: 1.5rem;
            font-weight: 700;
            color: var(--chocolate-bg);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .message {
            padding: 1.2rem;
            border-radius: 15px;
            margin-bottom: 1.5rem;
            font-weight: 600;
            text-align: center;
            animation: slideIn 0.3s ease-out;
        }
        @keyframes slideIn { from { transform: translateY(-10px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        
        .message.success { background: rgba(42, 157, 143, 0.1); color: var(--success-color); border: 1px solid rgba(42, 157, 143, 0.2); }
        .message.error { background: rgba(230, 57, 70, 0.1); color: var(--error-color); border: 1px solid rgba(230, 57, 70, 0.2); }

        /* Forms */
        .form-label {
            display: block;
            font-weight: 700;
            margin-bottom: 0.8rem;
            color: var(--text-main);
            font-size: 0.9rem;
        }

        .input-field {
            width: 100%;
            padding: 1rem;
            border: 2px solid #eee;
            border-radius: 12px;
            font-family: inherit;
            transition: all 0.3s ease;
            margin-bottom: 1rem;
        }

        .input-field:focus {
            outline: none;
            border-color: var(--primary-color);
            background: rgba(253, 139, 43, 0.02);
        }

        .upload-area {
            display: block;
            width: 100%;
            border: 2px dashed #ccc;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fff;
            color: #666;
            margin-top: 5px;
        }

        .upload-area:hover {
            border-color: var(--primary-color);
            background: rgba(253, 139, 43, 0.05);
            color: var(--primary-color);
        }

        .btn {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
            color: white;
            border: none;
            padding: 1rem 1.5rem;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            box-shadow: 0 10px 20px rgba(229, 107, 16, 0.2);
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 25px rgba(229, 107, 16, 0.3);
        }

        .btn-secondary {
            background: var(--chocolate-bg);
            margin-top: 0.5rem;
        }

        /* Active Items Grid */
        .posts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 1.5rem;
        }

        .post-card {
            background: #fff;
            border-radius: 20px;
            padding: 1.2rem;
            text-align: center;
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
            border: 1px solid rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
        }

        .post-image-box {
            background: #fdfbfb;
            border-radius: 15px;
            padding: 1rem;
            margin-bottom: 1rem;
            height: 160px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .post-card img {
            max-width: 100%;
            max-height: 140px;
            object-fit: contain;
            filter: drop-shadow(0 5px 10px rgba(0,0,0,0.1));
        }

          .login-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 50px rgba(0, 0, 0, 0.3),
                        inset 0 0 0 1px rgba(255, 255, 255, 0.2);
        }

        .logo-container {
            margin-top: -2rem;
            margin-bottom: 1.5rem;
            position: relative;
            display: flex;
            align-items: flex-end;
            justify-content: center;
        }

        .logo {
            width: 100%;
            max-width: 500px;
            height: auto;
            position: relative;
            z-index: 1;
            animation: bounce-in 1s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            filter: drop-shadow(0 15px 25px rgba(0,0,0,0.3));
        }

        @media (max-width: 600px) {
            body { 
                overflow-y: auto !important; 
                padding: 40px 15px !important;
                display: block !important;
                height: auto !important;
            }
            .login-wrapper { padding: 0 !important; margin: 0 auto; }
            .login-card { padding: 2rem 1.5rem 3rem 1.5rem !important; border-radius: 20px !important; }
            .hanging-pascoa { width: 220px !important; bottom: -60px !important; }
            .logo { max-width: 280px !important; }
            .floating-egg { display: none !important; } /* Hide eggs to prevent horizontal scroll */
            .title { font-size: 1.4rem !important; }
        }

        .post-info {
            margin-bottom: 1rem;
        }

        .post-date {
            font-size: 0.75rem;
            color: #aaa;
            font-weight: 600;
        }

        .btn-delete {
            background: #fff1f1;
            color: var(--error-color);
            border: 1px solid #ffe3e3;
            padding: 0.6rem;
            border-radius: 10px;
            font-size: 0.85rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
            width: 100%;
        }

        .btn-delete:hover {
            background: var(--error-color);
            color: white;
            border-color: var(--error-color);
        }

        /* Stats Table */
        .stats-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .stats-table th {
            text-align: left;
            padding: 1rem;
            color: #888;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            border-bottom: 2px solid #f0f0f0;
        }

        .stats-table td {
            padding: 1.2rem 1rem;
            border-bottom: 1px solid #f9f9f9;
            vertical-align: middle;
        }

        .avg-badge {
            background: var(--chocolate-bg);
            color: white;
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
            font-weight: 800;
            display: inline-block;
        }

        .dist-bar {
            height: 8px;
            background: #eee;
            border-radius: 4px;
            overflow: hidden;
            width: 100px;
            display: inline-flex;
        }

        .dist-fill {
            height: 100%;
        }
    </style>
</head>
<body>

<div class="container">
    <header class="header">
        <img src="imagens/Fabrica_dos_Ovos__Coelho-01.png" alt="Logo" class="header-logo">
        <div class="nav-links">
            <a href="vote.php" class="nav-link">Página de Voto</a>
            <a href="logout.php" class="nav-link" style="color: #ff9999;">Sair</a>
        </div>
    </header>

    <?php if ($success !== ''): ?>
        <div class="message success"><?= escape($success) ?></div>
    <?php endif; ?>
    <?php if ($error !== ''): ?>
        <div class="message error"><?= escape($error) ?></div>
    <?php endif; ?>

    <main class="main-grid">
        <!-- Sidebar: Forms -->
        <aside class="sidebar-actions">
            <div class="panel" style="margin-bottom: 1.5rem;">
                <h2 class="panel-title">📸 Publicar</h2>
                <form method="post" action="admin.php" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= escape(csrf_token()) ?>">
                    <input type="hidden" name="action" value="upload">
                    
                    <label class="form-label">Nova Imagem para Votação</label>
                    <input type="file" name="upload_image" id="upload_image" accept="image/*" required style="display: none;" onchange="updateFileName(this)">
                    <label for="upload_image" class="upload-area" id="file-label">
                        <span style="font-size: 2rem; display: block; margin-bottom: 0.5rem;">＋</span>
                        Clique para escolher ficheiro
                    </label>
                    <div id="file-name" style="margin-top: 0.5rem; font-size: 0.8rem; color: var(--success-color); font-weight: 600; display: none;"></div>
                    
                    <button type="submit" class="btn" style="margin-top: 1.5rem;">Publicar Agora</button>
                </form>
            </div>

            <div class="panel">
                <h2 class="panel-title">🔄 Reset Votos</h2>
                <form method="post" action="admin.php">
                    <input type="hidden" name="csrf_token" value="<?= escape(csrf_token()) ?>">
                    <input type="hidden" name="action" value="reset_votos">
                    
                    <label class="form-label">E-mail do Utilizador</label>
                    <input type="email" name="email" class="input-field" placeholder="exemplo@grupo.com" required>
                    
                    <button type="submit" class="btn btn-secondary">Limpar Votos</button>
                </form>
            </div>

            <div class="panel" style="margin-top: 1.5rem; background: #fffcf5; border: 1px solid #ffead4;">
                <h2 class="panel-title">📊 Resumo Geral</h2>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div style="background: white; padding: 1rem; border-radius: 12px; text-align: center;">
                        <span style="font-size: 1.5rem; font-weight: 800; color: var(--accent-color);"><?= count($items) ?></span>
                        <p style="font-size: 0.7rem; color: #999;">Imagens</p>
                    </div>
                    <div style="background: white; padding: 1rem; border-radius: 12px; text-align: center;">
                        <span style="font-size: 1.5rem; font-weight: 800; color: var(--success-color);"><?= count($allVotes) ?></span>
                        <p style="font-size: 0.7rem; color: #999;">Votantes</p>
                    </div>
                </div>
            </div>
        </aside>

        <!-- Main Content: Active Items -->
        <section class="active-content">
            <div class="panel">
                <h2 class="panel-title" style="justify-content: space-between;">
                    <span>📦 Imagens Ativas</span>
                    <span style="font-size: 0.9rem; font-weight: 400; color: #888;"><?= count($items) ?> itens</span>
                </h2>
                
                <?php if (count($items) === 0): ?>
                    <div style="text-align: center; padding: 4rem 2rem;">
                        <span style="font-size: 3rem; display: block; filter: grayscale(1);">🥚</span>
                        <p style="color: #999; margin-top: 1rem;">Ainda não existem imagens publicadas.</p>
                    </div>
                <?php else: ?>
                    <div class="posts-grid">
                        <?php foreach (array_reverse($items) as $item): ?>
                            <div class="post-card">
                                <div>
                                    <div class="post-image-box">
                                        <img src="<?= escape($item['image']) ?>" alt="Ovo">
                                    </div>
                                    <div class="post-info">
                                        <div class="post-date"><?= escape(format_datetime($item['created_at'])) ?></div>
                                    </div>
                                </div>
                                
                                <form method="post" action="admin.php" onsubmit="return confirm('Tem a certeza que deseja apagar esta imagem? Os votos associados também serão apagados.');">
                                    <input type="hidden" name="csrf_token" value="<?= escape(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= escape($item['id']) ?>">
                                    <button type="submit" class="btn-delete">Eliminar</button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <div class="panel" style="margin-top: 2rem;">
                <h2 class="panel-title">📈 Estatísticas de Votos</h2>
                
                <?php if (count($stats) === 0): ?>
                    <p style="color: #999; text-align: center; padding: 2rem;">Sem dados para exibir.</p>
                <?php else: ?>
                    <table class="stats-table">
                        <thead>
                            <tr>
                                <th>Imagem</th>
                                <th>Votos</th>
                                <th>Média</th>
                                <th>Distribuição (1-5★)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($stats as $s): ?>
                                <tr>
                                    <td data-label="Imagem">
                                        <div style="display: flex; justify-content: flex-end;">
                                            <img src="<?= escape($s['image']) ?>" style="width: 50px; height: 50px; object-fit: contain; border-radius: 8px; background: #f9f9f9; padding: 4px; border: 1px solid #eee;">
                                        </div>
                                    </td>
                                    <td data-label="Votos" style="font-weight: 600;"><?= $s['count'] ?></td>
                                    <td data-label="Média"><span class="avg-badge"><?= number_format($s['average'], 1) ?> ★</span></td>
                                    <td data-label="Distribuição">
                                        <div style="display: flex; align-items: center; gap: 5px;">
                                            <?php 
                                            $colors = ['#ff4d4d', '#ff944d', '#ffdb4d', '#c2f02b', '#2a9d8f'];
                                            for($i=1; $i<=5; $i++): 
                                                $pct = $s['count'] > 0 ? ($s['distribution'][$i] / $s['count']) * 100 : 0;
                                            ?>
                                                <div style="flex: 1; height: 15px; background: #eee; border-radius: 3px; overflow: hidden; position: relative;" title="<?= $i ?>★: <?= $s['distribution'][$i] ?> votos">
                                                    <div style="width: <?= $pct ?>%; height: 100%; background: <?= $colors[$i-1] ?>;"></div>
                                                </div>
                                            <?php endfor; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </section>
    </main>
</div>

<script>
    function updateFileName(input) {
        const nameDiv = document.getElementById('file-name');
        const labelText = document.querySelector('#file-label').childNodes[2];
        if (input.files && input.files[0]) {
            nameDiv.textContent = 'Ficheiro selecionado: ' + input.files[0].name;
            nameDiv.style.display = 'block';
        }
    }
    document.addEventListener("contextmenu", e => e.preventDefault());
</script>
<?php disable_inspect(); ?>
</body>
</html>
