<?php
session_start();
require_once '../includes/database.php';

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

// Handle form submissions
if($_POST) {
    if(isset($_POST['add_voting_period'])) {
        $game_week = $_POST['game_week'];
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        
        // Deactivate all other voting periods
        $pdo->exec("UPDATE voting_periods SET is_active = FALSE");
        
        // Add new voting period
        $stmt = $pdo->prepare("INSERT INTO voting_periods (game_week, start_date, end_date, is_active) VALUES (?, ?, ?, TRUE)");
        $stmt->execute([$game_week, $start_date, $end_date]);
        
        $_SESSION['success'] = "Voting period added successfully!";
        
    } elseif(isset($_POST['update_voting_period'])) {
        $period_id = $_POST['period_id'];
        $game_week = $_POST['game_week'];
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // If activating this period, deactivate all others
        if($is_active) {
            $pdo->exec("UPDATE voting_periods SET is_active = FALSE");
        }
        
        $stmt = $pdo->prepare("UPDATE voting_periods SET game_week = ?, start_date = ?, end_date = ?, is_active = ? WHERE id = ?");
        $stmt->execute([$game_week, $start_date, $end_date, $is_active, $period_id]);
        
        $_SESSION['success'] = "Voting period updated successfully!";
    }
    
    header('Location: manage-voting.php');
    exit;
}

// Get all voting periods
$voting_periods = $pdo->query("SELECT * FROM voting_periods ORDER BY game_week DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Voting Periods - Admin</title>
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .admin-nav {
            background: var(--secondary);
            padding: 1rem 0;
        }
        
        .admin-nav-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 2rem;
        }
        
        .admin-menu a {
            color: white;
            text-decoration: none;
            margin-left: 1.5rem;
        }
        
        .form-section, .list-section {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }
        
        .voting-periods-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-top: 1.5rem;
        }
        
        .voting-periods-table th,
        .voting-periods-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .voting-periods-table th {
            background: var(--secondary);
            color: white;
        }
        
        .status-badge {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
        }
    </style>
</head>
<body>
    <nav class="admin-nav">
        <div class="admin-nav-container">
            <div class="nav-logo">
                <a href="index.php" style="color: white;">FantasyVote Admin</a>
            </div>
            <div class="admin-menu">
                <a href="index.php">Dashboard</a>
                <a href="manage-players.php">Manage Players</a>
                <a href="manage-coaches.php">Manage Coaches</a>
                <a href="manage-voting.php">Voting Periods</a>
                <a href="../logout.php">Logout</a>
            </div>
        </div>
    </nav>
    
    <div class="admin-container">
        <h1>Manage Voting Periods</h1>
        
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
        <?php endif; ?>
        
        <!-- Add Voting Period Form -->
        <section class="form-section">
            <h2>Add New Voting Period</h2>
            <form method="POST">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Game Week:</label>
                        <input type="number" name="game_week" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Start Date:</label>
                        <input type="datetime-local" name="start_date" required>
                    </div>
                    
                    <div class="form-group">
                        <label>End Date:</label>
                        <input type="datetime-local" name="end_date" required>
                    </div>
                </div>
                
                <button type="submit" name="add_voting_period" class="btn btn-primary">Add Voting Period</button>
            </form>
        </section>
        
        <!-- Voting Periods List -->
        <section class="list-section">
            <h2>All Voting Periods</h2>
            
            <table class="voting-periods-table">
                <thead>
                    <tr>
                        <th>Game Week</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($voting_periods as $period): ?>
                    <tr>
                        <td><?php echo $period['game_week']; ?></td>
                        <td><?php echo date('M j, Y g:i A', strtotime($period['start_date'])); ?></td>
                        <td><?php echo date('M j, Y g:i A', strtotime($period['end_date'])); ?></td>
                        <td>
                            <span class="status-badge <?php echo $period['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                <?php echo $period['is_active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-secondary btn-small" 
                                    onclick="openEditModal(<?php echo htmlspecialchars(json_encode($period)); ?>)">
                                Edit
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </section>
    </div>
    
    <!-- Edit Voting Period Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h2>Edit Voting Period</h2>
            <form method="POST" id="editForm">
                <input type="hidden" name="period_id" id="edit_period_id">
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Game Week:</label>
                        <input type="number" name="game_week" id="edit_game_week" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Start Date:</label>
                        <input type="datetime-local" name="start_date" id="edit_start_date" required>
                    </div>
                    
                    <div class="form-group">
                        <label>End Date:</label>
                        <input type="datetime-local" name="end_date" id="edit_end_date" required>
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="is_active" id="edit_is_active" value="1">
                            Active Voting Period
                        </label>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="update_voting_period" class="btn btn-primary">Update Period</button>
                    <button type="button" class="btn btn-secondary" onclick="closeEditModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
    function openEditModal(period) {
        document.getElementById('edit_period_id').value = period.id;
        document.getElementById('edit_game_week').value = period.game_week;
        
        // Format dates for datetime-local input
        const startDate = new Date(period.start_date);
        const endDate = new Date(period.end_date);
        
        document.getElementById('edit_start_date').value = startDate.toISOString().slice(0, 16);
        document.getElementById('edit_end_date').value = endDate.toISOString().slice(0, 16);
        document.getElementById('edit_is_active').checked = period.is_active == 1;
        
        document.getElementById('editModal').style.display = 'block';
    }
    
    function closeEditModal() {
        document.getElementById('editModal').style.display = 'none';
    }
    
    // Close modal when clicking outside
    window.onclick = function(event) {
        const modal = document.getElementById('editModal');
        if (event.target == modal) {
            closeEditModal();
        }
    }
    </script>
</body>
</html>