<?php
declare(strict_types=1);

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

$items = load_json(DATA_DIR . '/items.json', []);
$votes = (array) load_json(DATA_DIR . '/votes.json', []);
$email = current_user_email();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    
    $itemId = $_POST['item_id'] ?? '';
    $score = (int) ($_POST['score'] ?? 0);
    
    // Verify item exists
    $itemExists = false;
    foreach ($items as $item) {
        if ($item['id'] === $itemId) {
            $itemExists = true;
            break;
        }
    }
    
    if ($itemExists && $score >= 1 && $score <= 5) {
        if (!isset($votes[$email])) {
            $votes[$email] = [];
        }
        
        $votes[$email][$itemId] = ['score' => $score];
        save_json(DATA_DIR . '/votes.json', $votes);
        $success = 'O seu voto foi registado com sucesso!';
    } else {
        $error = 'Voto invÃ¡lido. Por favor tente novamente.';
    }
}

// Get current user's votes to pre-fill
$userVotes = $votes[$email] ?? [];

?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VotaÃ§Ã£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;
            --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;
            position: relative;
            overflow-x: hidden;
        }

        /* Animated Background Elements */
        .bg-shapes {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            overflow: hidden;
            pointer-events: none;
        }

        .blob {
            position: absolute;
            filter: blur(60px);
            z-index: 0;
            opacity: 0.6;
            animation: float 10s infinite ease-in-out;
        }

        .blob-1 {
            width: 400px;
            height: 400px;
            background: var(--primary-color);
            top: -100px;
            left: -100px;
            border-radius: 50%;
        }

        .blob-2 {
            width: 300px;
            height: 300px;
            background: var(--accent-color);
            bottom: -50px;
            right: -50px;
            border-radius: 50%;
            animation-delay: -3s;
        }
        
        .blob-3 {
            width: 250px;
            height: 250px;
            background: #ffaf55;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border-radius: 50%;
            animation-delay: -5s;
        }

        @keyframes float {
            0%, 100% { transform: translate(0, 0) scale(1); }
            33% { transform: translate(30px, -50px) scale(1.1); }
            66% { transform: translate(-20px, 20px) scale(0.9); }
        }

        /* Floating Easter Eggs */
        .floating-egg {
            position: fixed;
            z-index: 1;
            animation: float-egg 15s infinite ease-in-out;
            opacity: 0.8;
            filter: drop-shadow(0 10px 15px rgba(0,0,0,0.1));
            pointer-events: none;
        }

        @keyframes float-egg {
            0%, 100% { transform: translateY(0) rotate(0deg); }
            50% { transform: translateY(-30px) rotate(10deg); }
        }

        .egg-1 { top: 12%; left: calc(50% - 650px); width: 220px; animation-delay: 0s; }
        .egg-2 { top: 22%; right: calc(50% - 650px); width: 280px; animation-delay: -2s; }
        .egg-3 { bottom: 15%; left: calc(50% - 600px); width: 240px; animation-delay: -5s; }
        .egg-4 { bottom: 10%; right: calc(50% - 600px); width: 190px; animation-delay: -7s; }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            position: relative;
            z-index: 10;
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            padding: 1.5rem 2rem;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header-title {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--accent-color);
        }

        .user-info {
            font-size: 1rem;
            font-weight: 600;
        }

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

        .nav-link {
            text-decoration: none;
            color: var(--primary-color);
            font-weight: 600;
            padding: 0.5rem 1rem;
            border-radius: 10px;
            transition: all 0.3s ease;
            background: rgba(253, 139, 43, 0.1);
        }

        .nav-link:hover {
            background: var(--primary-color);
            color: white;
            transform: translateY(-2px);
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: linear-gradient(135deg, rgba(92, 58, 33, 0.95), rgba(58, 34, 17, 0.95));
            backdrop-filter: blur(20px);
            padding: 1rem 2rem;
            border-radius: 25px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.2);
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 15px;
            border: 1px solid rgba(255,255,255,0.1);
            position: relative;
            overflow: visible;
        }

        .header::after {
            content: '';
            position: absolute;
            bottom: -15px;
            right: 20px;
            width: 80px;
            height: 80px;
            background: url('imagens/Coelho-01.png') no-repeat center center;
            background-size: contain;
            z-index: 5;
            filter: drop-shadow(0 5px 10px rgba(0,0,0,0.3));
        }

        .header-title {
            font-size: 1.6rem;
            font-weight: 800;
            color: #ffffff;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .user-info {
            font-size: 0.9rem;
            font-weight: 400;
            color: rgba(255,255,255,0.8);
        }

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

        .message {
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            font-weight: 600;
            text-align: center;
            position: relative;
            z-index: 20;
        }
        .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); }

        .posts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 2.5rem;
        }

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

        .post-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 25px;
            padding: 2.5rem;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            border: 2px solid rgba(253, 139, 43, 0.1);
            position: relative;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .post-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.1);
            border: 2px solid rgba(253, 139, 43, 0.3);
        }

        .egg-bg-1 { top: -5%; left: -5%; width: 350px; }
        .egg-bg-2 { top: 5%; right: -5%; width: 400px; }
        .egg-bg-3 { bottom: -5%; left: -5%; width: 320px; }
        .egg-bg-4 { bottom: -2%; right: -2%; width: 300px; }
        .egg-bg-5 { top: 35%; left: 5%; width: 220px; opacity: 0.6; }
        .egg-bg-6 { top: 40%; right: 5%; width: 200px; opacity: 0.6; }
        .egg-bg-7 { top: 12%; left: 35%; width: 160px; opacity: 0.4; }
        .egg-bg-8 { bottom: 15%; right: 38%; width: 180px; opacity: 0.4; }
        .egg-bg-9 { bottom: 30%; left: 40%; width: 150px; opacity: 0.4; }

        .post-image-container {
            height: 450px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
            cursor: zoom-in;
        }

        /* Modal Lightbox */
        .modal {
            display: none; 
            position: fixed; 
            z-index: 1000; 
            left: 0;
            top: 0;
            width: 100%; 
            height: 100%; 
            overflow: auto; 
            background-color: rgba(0,0,0,0.85); 
            backdrop-filter: blur(10px);
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

        .modal-content {
            margin: auto;
            display: block;
            max-width: 90%;
            max-height: 90vh;
            object-fit: contain;
            animation: zoom 0.3s ease;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            border-radius: 10px;
        }
        
        @keyframes zoom {
            from {transform:scale(0)} 
            to {transform:scale(1)}
        }

        .close-modal {
            position: absolute;
            top: 30px;
            right: 40px;
            color: #f1f1f1;
            font-size: 50px;
            font-weight: bold;
            transition: 0.3s;
            cursor: pointer;
        }

        .close-modal:hover,
        .close-modal:focus {
            color: var(--primary-color);
            text-decoration: none;
            cursor: pointer;
        }

        .post-card img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            filter: drop-shadow(0 15px 25px rgba(0,0,0,0.15));
            transition: transform 0.3s ease;
        }
        
        .post-card:hover img {
            transform: scale(1.05);
        }

        .rating-group {
            display: flex;
            justify-content: center;
            flex-direction: row-reverse;
            gap: 5px;
            margin-bottom: 1.5rem;
        }

        /* Star styling / Egg styling for rating */
        .rating-group input {
            display: none;
        }

        .rating-group label {
            cursor: pointer;
            width: 35px;
            height: 35px;
            background: #eee;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 800;
            color: #ccc;
            transition: all 0.2s ease;
            font-size: 1.1rem;
        }

        .rating-group label:hover,
        .rating-group label:hover ~ label,
        .rating-group input:checked ~ label {
            background: var(--primary-color);
            color: white;
            box-shadow: 0 5px 15px rgba(253, 139, 43, 0.3);
        }

        .btn {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
            color: white;
            border: none;
            padding: 0.8rem 1.5rem;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
            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);
        }

        .voted-badge {
            position: absolute;
            top: -10px;
            right: -10px;
            background: var(--success-color);
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(42, 157, 143, 0.3);
            z-index: 10;
        }
    </style>
</head>
<body>

    <div class="bg-shapes">
        <div class="blob blob-1"></div>
        <div class="blob blob-2"></div>
        <div class="blob blob-3"></div>
    </div>

    <!-- Floating Background Images -->
    <img src="imagens/Ovo_1-01.png" alt="" class="floating-egg egg-bg-1">
    <img src="imagens/Ovo_2-01.png" alt="" class="floating-egg egg-bg-2">
    <img src="imagens/Ovo_3-01.png" alt="" class="floating-egg egg-bg-3">
    <img src="imagens/Ovo_4-01.png" alt="" class="floating-egg egg-4">
    <img src="imagens/Ovo_5-01.png" alt="" class="floating-egg egg-bg-5">
    <img src="imagens/Ovo_6-01.png" alt="" class="floating-egg egg-bg-6">
    <img src="imagens/Ovo_7-01.png" alt="" class="floating-egg egg-bg-7">
    <img src="imagens/Ovo_1-01.png" alt="" class="floating-egg egg-bg-8">
    <img src="imagens/Ovo_2-01.png" alt="" class="floating-egg egg-bg-9">

<div class="container">
    <div class="header">
        <div class="header-title">FÃ¡brica dos Ovos - VotaÃ§Ã£o</div>
        <div class="user-info">A votar como: <?= escape($email ?? '') ?></div>
        <div class="nav-links">
            <?php if (is_admin()): ?>
                <a href="admin.php" class="nav-link">AdministraÃ§Ã£o</a>
            <?php endif; ?>
            <a href="logout.php" class="nav-link" style="background: rgba(230, 57, 70, 0.1); color: var(--error-color);">Sair</a>
        </div>
    </div>

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

    $unvotedItems = [];

    foreach ($items as $item) {

        if (!isset($userVotes[$item['id']])) {

            $unvotedItems[] = $item;

        }

    }

    $currentItem = count($unvotedItems) > 0 ? $unvotedItems[0] : null;

    ?>



    <?php if (count($items) === 0): ?>

        <div style="background: rgba(255,255,255,0.8); border-radius: 20px; padding: 4rem; text-align: center;">

            <h2 style="color: var(--accent-color); margin-bottom: 1rem;">Nenhuma imagem disponÃ­vel</h2>

            <p style="color: #666;">De momento nÃ£o hÃ¡ imagens a votaÃ§Ã£o. Volte mais tarde!</p>

        </div>

    <?php elseif ($currentItem !== null): ?>

        <div style="text-align: center; margin-bottom: 2rem;">

            <h2 style="color: var(--accent-color);">Progresso: <?= count($items) - count($unvotedItems) + 1 ?> de <?= count($items) ?></h2>

        </div>

        <div style="max-width: 800px; margin: 0 auto;">

            <?php $item = $currentItem; $userScore = 0; ?>

            <div class="post-card">

                <div class="post-image-container" onclick="openModal('<?= escape($item['image']) ?>')">

                    <img src="<?= escape($item['image']) ?>" alt="Imagem a votaÃ§Ã£o">

                </div>

                

                <form method="post" action="vote.php" id="voteForm">

                    <input type="hidden" name="csrf_token" value="<?= escape(csrf_token()) ?>">

                    <input type="hidden" name="item_id" value="<?= escape($item['id']) ?>">

                    

                    <div class="rating-group">

                        <input type="radio" id="star5_<?= $item['id'] ?>" name="score" value="5" onchange="document.getElementById('voteForm').submit();" required />

                        <label for="star5_<?= $item['id'] ?>">5</label>

                        

                        <input type="radio" id="star4_<?= $item['id'] ?>" name="score" value="4" onchange="document.getElementById('voteForm').submit();" />

                        <label for="star4_<?= $item['id'] ?>">4</label>

                        

                        <input type="radio" id="star3_<?= $item['id'] ?>" name="score" value="3" onchange="document.getElementById('voteForm').submit();" />

                        <label for="star3_<?= $item['id'] ?>">3</label>

                        

                        <input type="radio" id="star2_<?= $item['id'] ?>" name="score" value="2" onchange="document.getElementById('voteForm').submit();" />

                        <label for="star2_<?= $item['id'] ?>">2</label>

                        

                        <input type="radio" id="star1_<?= $item['id'] ?>" name="score" value="1" onchange="document.getElementById('voteForm').submit();" />

                        <label for="star1_<?= $item['id'] ?>">1</label>

                    </div>

                    

                    <button type="submit" class="btn">Votar</button>

                </form>

            </div>

        </div>

    <?php else: ?>

        <div style="text-align: center; margin-bottom: 2rem;">

            <h2 style="color: var(--success-color);">VotaÃ§Ã£o concluÃ­da! Obrigado pela participaÃ§Ã£o.</h2>

            <p style="color: #666; margin-top: 0.5rem;">Abaixo podes rever os teus votos.</p>

        </div>

        <div class="posts-grid">

            <?php foreach ($items as $item): ?>

                <?php 

                    $userScore = $userVotes[$item['id']]['score'] ?? 0;

                ?>

                <div class="post-card">

                    <div class="voted-badge">âœ“</div>

                    

                    <div class="post-image-container" onclick="openModal('<?= escape($item['image']) ?>')">

                        <img src="<?= escape($item['image']) ?>" alt="Imagem a votaÃ§Ã£o">

                    </div>

                    

                    <form method="post" action="vote.php" id="form_<?= $item['id'] ?>">

                        <input type="hidden" name="csrf_token" value="<?= escape(csrf_token()) ?>">

                        <input type="hidden" name="item_id" value="<?= escape($item['id']) ?>">

                        

                        <div class="rating-group">

                            <input type="radio" id="star5_<?= $item['id'] ?>" name="score" value="5" <?= $userScore === 5 ? 'checked' : '' ?> onchange="document.getElementById('form_<?= $item['id'] ?>').submit();" required />

                            <label for="star5_<?= $item['id'] ?>">5</label>

                            

                            <input type="radio" id="star4_<?= $item['id'] ?>" name="score" value="4" <?= $userScore === 4 ? 'checked' : '' ?> onchange="document.getElementById('form_<?= $item['id'] ?>').submit();" />

                            <label for="star4_<?= $item['id'] ?>">4</label>

                            

                            <input type="radio" id="star3_<?= $item['id'] ?>" name="score" value="3" <?= $userScore === 3 ? 'checked' : '' ?> onchange="document.getElementById('form_<?= $item['id'] ?>').submit();" />

                            <label for="star3_<?= $item['id'] ?>">3</label>

                            

                            <input type="radio" id="star2_<?= $item['id'] ?>" name="score" value="2" <?= $userScore === 2 ? 'checked' : '' ?> onchange="document.getElementById('form_<?= $item['id'] ?>').submit();" />

                            <label for="star2_<?= $item['id'] ?>">2</label>

                            

                            <input type="radio" id="star1_<?= $item['id'] ?>" name="score" value="1" <?= $userScore === 1 ? 'checked' : '' ?> onchange="document.getElementById('form_<?= $item['id'] ?>').submit();" />

                            <label for="star1_<?= $item['id'] ?>">1</label>

                        </div>

                        

                        <button type="submit" class="btn">Atualizar Voto</button>

                    </form>

                </div>

            <?php endforeach; ?>

        </div>

    <?php endif; ?>
</div>

<!-- Lightbox Modal -->
<div id="imageModal" class="modal" onclick="closeModal()">
    <span class="close-modal">&times;</span>
    <img class="modal-content" id="modalImg">
</div>

<script>
    function openModal(src) {
        document.getElementById('modalImg').src = src;
        document.getElementById('imageModal').style.display = 'flex';
    }
    
    function closeModal() {
        document.getElementById('imageModal').style.display = 'none';
        document.getElementById('modalImg').src = '';
    }
</script>

</body>
</html>
