<?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_player'])) {
        // [Keep existing add player code...]
    } 
    elseif(isset($_POST['update_player'])) {
        // [Keep existing update player code...]
    }
    elseif(isset($_POST['bulk_action'])) {
        // Handle bulk actions
        $bulk_action = $_POST['bulk_action'];
        $player_ids = $_POST['player_ids'] ?? [];
        
        if(!empty($player_ids) && $bulk_action) {
            $placeholders = str_repeat('?,', count($player_ids) - 1) . '?';
            
            switch($bulk_action) {
                case 'activate':
                    $stmt = $pdo->prepare("UPDATE players SET is_active = TRUE WHERE id IN ($placeholders)");
                    $stmt->execute($player_ids);
                    $_SESSION['success'] = count($player_ids) . " players activated successfully!";
                    break;
                    
                case 'deactivate':
                    $stmt = $pdo->prepare("UPDATE players SET is_active = FALSE WHERE id IN ($placeholders)");
                    $stmt->execute($player_ids);
                    $_SESSION['success'] = count($player_ids) . " players deactivated successfully!";
                    break;
                    
                case 'delete':
                    // First, check if any players have votes
                    $stmt = $pdo->prepare("
                        SELECT p.id, p.name, COUNT(v.id) as vote_count 
                        FROM players p 
                        LEFT JOIN votes v ON p.id = v.player_id 
                        WHERE p.id IN ($placeholders) 
                        GROUP BY p.id
                    ");
                    $stmt->execute($player_ids);
                    $players_with_votes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $can_delete = [];
                    $cannot_delete = [];
                    
                    foreach($players_with_votes as $player) {
                        if($player['vote_count'] > 0) {
                            $cannot_delete[] = $player['name'];
                        } else {
                            $can_delete[] = $player['id'];
                        }
                    }
                    
                    if(!empty($can_delete)) {
                        $placeholders_delete = str_repeat('?,', count($can_delete) - 1) . '?';
                        $stmt = $pdo->prepare("DELETE FROM players WHERE id IN ($placeholders_delete)");
                        $stmt->execute($can_delete);
                        $_SESSION['success'] = count($can_delete) . " players deleted successfully!";
                    }
                    
                    if(!empty($cannot_delete)) {
                        $_SESSION['error'] = "Cannot delete " . count($cannot_delete) . " players because they have votes: " . implode(', ', $cannot_delete);
                    }
                    break;
            }
        } else {
            $_SESSION['error'] = "No players selected for bulk action!";
        }
        
        header('Location: manage-players.php');
        exit;
    }
}

// Handle search and filters
$search = $_GET['search'] ?? '';
$game_week_filter = $_GET['game_week'] ?? '';
$position_filter = $_GET['position'] ?? '';
$status_filter = $_GET['status'] ?? '';

// Build query with filters
$sql = "
    SELECT p.*, pos.name as position_name, pos.code as position_code 
    FROM players p 
    JOIN positions pos ON p.position_id = pos.id 
    WHERE 1=1
";

$params = [];

if($search) {
    $sql .= " AND (p.name LIKE ? OR p.team LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if($game_week_filter) {
    $sql .= " AND p.game_week = ?";
    $params[] = $game_week_filter;
}

if($position_filter) {
    $sql .= " AND pos.code = ?";
    $params[] = $position_filter;
}

if($status_filter !== '') {
    $sql .= " AND p.is_active = ?";
    $params[] = ($status_filter === 'active') ? 1 : 0;
}

$sql .= " ORDER BY p.game_week DESC, p.name ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$players = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get positions for dropdown
$positions = $pdo->query("SELECT * FROM positions")->fetchAll(PDO::FETCH_ASSOC);

// Get unique game weeks for filter
$game_weeks = $pdo->query("SELECT DISTINCT game_week FROM players ORDER BY game_week DESC")->fetchAll(PDO::FETCH_COLUMN);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Players - Admin</title>
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .admin-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .admin-nav {
            background: var(--secondary);
            padding: 1rem 0;
        }
        
        .admin-nav-container {
            max-width: 1400px;
            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;
        }
        
        /* Search and Filter Styles */
        .search-filters {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 1fr auto;
            gap: 1rem;
            align-items: end;
        }
        
        .filter-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: var(--dark-blue);
            font-size: 0.9rem;
        }
        
        /* Bulk Actions */
        .bulk-actions {
            background: #e8f5e8;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border-left: 4px solid var(--accent-blue);
            display: none;
        }
        
        .bulk-actions.active {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .bulk-info {
            font-weight: 600;
            color: var(--dark-blue);
        }
        
        /* Players Grid with Checkboxes */
        .players-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }
        
        .player-admin-card {
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 1.5rem;
            position: relative;
            transition: all 0.3s ease;
        }
        
        .player-admin-card:hover {
            border-color: var(--primary-blue);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .player-admin-card.selected {
            border-color: var(--accent-blue);
            background: #f8fff8;
        }
        
        .player-checkbox {
            position: absolute;
            top: 10px;
            left: 10px;
            transform: scale(1.2);
        }
        
        .player-admin-card img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-bottom: 1rem;
        }
        
        .player-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            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;
        }
        
        .select-all-container {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 1rem;
            padding: 0.5rem;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .results-count {
            color: var(--gray);
            font-size: 0.9rem;
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .players-grid {
                grid-template-columns: 1fr;
            }
            
            .bulk-actions.active {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </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 Players</h1>
        
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['error'])): ?>
            <div class="alert error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
        <?php endif; ?>
        
        <!-- Add Player Form -->
        <section class="form-section">
            <h2>Add New Player</h2>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Player Name:</label>
                        <input type="text" name="name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Position:</label>
                        <select name="position_id" required>
                            <option value="">Select Position</option>
                            <?php foreach($positions as $position): ?>
                                <option value="<?php echo $position['id']; ?>">
                                    <?php echo $position['name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Team:</label>
                        <input type="text" name="team" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Game Week:</label>
                        <input type="number" name="game_week" min="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Player Photo:</label>
                        <input type="file" name="photo" accept="image/*">
                    </div>
                </div>
                
                <button type="submit" name="add_player" class="btn btn-primary">Add Player</button>
            </form>
        </section>
        
        <!-- Search and Filters -->
        <section class="list-section">
            <h2>Player Management</h2>
            
            <div class="search-filters">
                <form method="GET" id="searchForm">
                    <div class="filter-grid">
                        <div class="filter-group">
                            <label>Search Players:</label>
                            <input type="text" name="search" placeholder="Search by name or team..." 
                                   value="<?php echo htmlspecialchars($search); ?>" 
                                   class="live-search" data-search-type="players">
                        </div>
                        
                        <div class="filter-group">
                            <label>Game Week:</label>
                            <select name="game_week">
                                <option value="">All Weeks</option>
                                <?php foreach($game_weeks as $week): ?>
                                    <option value="<?php echo $week; ?>" <?php echo $game_week_filter == $week ? 'selected' : ''; ?>>
                                        Week <?php echo $week; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Position:</label>
                            <select name="position">
                                <option value="">All Positions</option>
                                <?php foreach($positions as $position): ?>
                                    <option value="<?php echo $position['code']; ?>" <?php echo $position_filter == $position['code'] ? 'selected' : ''; ?>>
                                        <?php echo $position['name']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Status:</label>
                            <select name="status">
                                <option value="">All Status</option>
                                <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <button type="submit" class="btn btn-primary">Apply Filters</button>
                            <a href="manage-players.php" class="btn btn-secondary">Clear</a>
                        </div>
                    </div>
                </form>
            </div>
            
            <!-- Bulk Actions -->
            <div class="bulk-actions" id="bulkActions">
                <div class="bulk-info" id="bulkSelectedCount">0 players selected</div>
                <select name="bulk_action" id="bulkActionSelect" class="form-control" style="flex: 1;">
                    <option value="">Choose action...</option>
                    <option value="activate">Activate Selected</option>
                    <option value="deactivate">Deactivate Selected</option>
                    <option value="delete">Delete Selected</option>
                </select>
                <button type="button" id="applyBulkAction" class="btn btn-primary">Apply</button>
                <button type="button" id="clearSelection" class="btn btn-secondary">Clear Selection</button>
            </div>
            
            <div class="select-all-container">
                <input type="checkbox" id="selectAllPlayers">
                <label for="selectAllPlayers">Select all <span id="resultsCount"><?php echo count($players); ?></span> players</label>
            </div>
            
            <div class="players-grid" id="playersGrid">
                <?php if(empty($players)): ?>
                    <div class="no-results" style="grid-column: 1 / -1; text-align: center; padding: 3rem; color: var(--gray);">
                        <i class="fas fa-search" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i>
                        <h3>No players found</h3>
                        <p>Try adjusting your search criteria or add new players.</p>
                    </div>
                <?php else: ?>
                    <?php foreach($players as $player): ?>
                    <div class="player-admin-card" data-player-id="<?php echo $player['id']; ?>">
                        <input type="checkbox" name="player_ids[]" value="<?php echo $player['id']; ?>" class="player-checkbox">
                        
                        <span class="status-badge <?php echo $player['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                            <?php echo $player['is_active'] ? 'Active' : 'Inactive'; ?>
                        </span>
                        
                        <img src="<?php echo $player['photo'] ? '../' . $player['photo'] : '../assets/default-player.jpg'; ?>" 
                             alt="<?php echo $player['name']; ?>"
                             onerror="this.src='../assets/default-player.jpg'">
                        
                        <h4><?php echo htmlspecialchars($player['name']); ?></h4>
                        <p><strong>Position:</strong> <?php echo $player['position_name']; ?></p>
                        <p><strong>Team:</strong> <?php echo htmlspecialchars($player['team']); ?></p>
                        <p><strong>Game Week:</strong> <?php echo $player['game_week']; ?></p>
                        
                        <div class="player-actions">
                            <button class="btn btn-secondary btn-small" 
                                    onclick="openEditModal(<?php echo htmlspecialchars(json_encode($player)); ?>)">
                                Edit
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
    </div>
    
    <!-- Edit Player Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h2>Edit Player</h2>
            <form method="POST" enctype="multipart/form-data" id="editForm">
                <input type="hidden" name="player_id" id="edit_player_id">
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Player Name:</label>
                        <input type="text" name="name" id="edit_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Position:</label>
                        <select name="position_id" id="edit_position_id" required>
                            <option value="">Select Position</option>
                            <?php foreach($positions as $position): ?>
                                <option value="<?php echo $position['id']; ?>">
                                    <?php echo $position['name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Team:</label>
                        <input type="text" name="team" id="edit_team" required>
                    </div>
                    
                    <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>Player Photo:</label>
                        <input type="file" name="photo" accept="image/*">
                        <small>Current: <span id="current_photo"></span></small>
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="is_active" id="edit_is_active" value="1">
                            Active Player
                        </label>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="update_player" class="btn btn-primary">Update Player</button>
                    <button type="button" class="btn btn-secondary" onclick="closeEditModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Bulk Action Form -->
    <form method="POST" id="bulkActionForm" style="display: none;">
        <input type="hidden" name="bulk_action" id="bulkActionInput">
        <div id="bulkPlayersContainer"></div>
    </form>
    
    <script src="../js/admin-actions.js"></script>
    <script>
    // Modal functions
    function openEditModal(player) {
        document.getElementById('edit_player_id').value = player.id;
        document.getElementById('edit_name').value = player.name;
        document.getElementById('edit_position_id').value = player.position_id;
        document.getElementById('edit_team').value = player.team;
        document.getElementById('edit_game_week').value = player.game_week;
        document.getElementById('edit_is_active').checked = player.is_active == 1;
        document.getElementById('current_photo').textContent = player.photo ? 'Uploaded' : 'No photo';
        
        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>