<?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_coach'])) {
        // Add new coach
        $name = $_POST['name'];
        $team = $_POST['team'];
        $game_week = $_POST['game_week'];
        
        $photo_path = null;
        if(isset($_FILES['photo']) && $_FILES['photo']['error'] === 0) {
            $upload_dir = '../assets/uploads/coaches/';
            if(!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if(in_array(strtolower($file_extension), $allowed_extensions)) {
                $new_filename = 'coach_' . time() . '_' . uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if(move_uploaded_file($_FILES['photo']['tmp_name'], $upload_path)) {
                    $photo_path = 'assets/uploads/coaches/' . $new_filename;
                }
            }
        }
        
        $stmt = $pdo->prepare("INSERT INTO coaches (name, team, photo, game_week) VALUES (?, ?, ?, ?)");
        $stmt->execute([$name, $team, $photo_path, $game_week]);
        
        $_SESSION['success'] = "Coach added successfully!";
        
    } elseif(isset($_POST['update_coach'])) {
        // Update coach
        $coach_id = $_POST['coach_id'];
        $name = $_POST['name'];
        $team = $_POST['team'];
        $game_week = $_POST['game_week'];
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Get current photo
        $stmt = $pdo->prepare("SELECT photo FROM coaches WHERE id = ?");
        $stmt->execute([$coach_id]);
        $current_coach = $stmt->fetch(PDO::FETCH_ASSOC);
        $photo_path = $current_coach['photo'];
        
        // Handle photo upload
        if(isset($_FILES['photo']) && $_FILES['photo']['error'] === 0) {
            $upload_dir = '../assets/uploads/coaches/';
            if(!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if(in_array(strtolower($file_extension), $allowed_extensions)) {
                $new_filename = 'coach_' . time() . '_' . uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if(move_uploaded_file($_FILES['photo']['tmp_name'], $upload_path)) {
                    // Delete old photo if exists
                    if($photo_path && file_exists('../' . $photo_path)) {
                        unlink('../' . $photo_path);
                    }
                    $photo_path = 'assets/uploads/coaches/' . $new_filename;
                }
            }
        }
        
        $stmt = $pdo->prepare("UPDATE coaches SET name = ?, team = ?, photo = ?, game_week = ?, is_active = ? WHERE id = ?");
        $stmt->execute([$name, $team, $photo_path, $game_week, $is_active, $coach_id]);
        
        $_SESSION['success'] = "Coach updated successfully!";
    }
    elseif(isset($_POST['bulk_action'])) {
        // Handle bulk actions
        $bulk_action = $_POST['bulk_action'];
        $coach_ids = $_POST['coach_ids'] ?? [];
        
        if(!empty($coach_ids) && $bulk_action) {
            $placeholders = str_repeat('?,', count($coach_ids) - 1) . '?';
            
            switch($bulk_action) {
                case 'activate':
                    $stmt = $pdo->prepare("UPDATE coaches SET is_active = TRUE WHERE id IN ($placeholders)");
                    $stmt->execute($coach_ids);
                    $_SESSION['success'] = count($coach_ids) . " coaches activated successfully!";
                    break;
                    
                case 'deactivate':
                    $stmt = $pdo->prepare("UPDATE coaches SET is_active = FALSE WHERE id IN ($placeholders)");
                    $stmt->execute($coach_ids);
                    $_SESSION['success'] = count($coach_ids) . " coaches deactivated successfully!";
                    break;
                    
                case 'delete':
                    // First, check if any coaches have votes
                    $stmt = $pdo->prepare("
                        SELECT c.id, c.name, COUNT(v.id) as vote_count 
                        FROM coaches c 
                        LEFT JOIN votes v ON c.id = v.coach_id 
                        WHERE c.id IN ($placeholders) 
                        GROUP BY c.id
                    ");
                    $stmt->execute($coach_ids);
                    $coaches_with_votes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    $can_delete = [];
                    $cannot_delete = [];
                    
                    foreach($coaches_with_votes as $coach) {
                        if($coach['vote_count'] > 0) {
                            $cannot_delete[] = $coach['name'];
                        } else {
                            $can_delete[] = $coach['id'];
                        }
                    }
                    
                    if(!empty($can_delete)) {
                        $placeholders_delete = str_repeat('?,', count($can_delete) - 1) . '?';
                        $stmt = $pdo->prepare("DELETE FROM coaches WHERE id IN ($placeholders_delete)");
                        $stmt->execute($can_delete);
                        $_SESSION['success'] = count($can_delete) . " coaches deleted successfully!";
                    }
                    
                    if(!empty($cannot_delete)) {
                        $_SESSION['error'] = "Cannot delete " . count($cannot_delete) . " coaches because they have votes: " . implode(', ', $cannot_delete);
                    }
                    break;
            }
        } else {
            $_SESSION['error'] = "No coaches selected for bulk action!";
        }
        
        header('Location: manage-coaches.php');
        exit;
    }
}

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

// Build query with filters
$sql = "SELECT * FROM coaches WHERE 1=1";
$params = [];

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

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

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

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

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

// Get unique game weeks for filter
$game_weeks = $pdo->query("SELECT DISTINCT game_week FROM coaches 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 Coaches - 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 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);
        }
        
        /* Coaches Grid with Checkboxes */
        .players-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }
        
        .coach-admin-card {
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 1.5rem;
            position: relative;
            transition: all 0.3s ease;
        }
        
        .coach-admin-card:hover {
            border-color: var(--primary-blue);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .coach-admin-card.selected {
            border-color: var(--accent-blue);
            background: #f8fff8;
        }
        
        .coach-checkbox {
            position: absolute;
            top: 10px;
            left: 10px;
            transform: scale(1.2);
        }
        
        .coach-admin-card img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-bottom: 1rem;
        }
        
        .coach-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;
        }
        
        .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;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .btn-warning {
            background: var(--warning);
            color: white;
        }
        
        .btn-warning:hover {
            background: #e67e22;
        }
        
        @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 Coaches</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 Coach Form -->
        <section class="form-section">
            <h2>Add New Coach</h2>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Coach Name:</label>
                        <input type="text" name="name" required>
                    </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>Coach Photo:</label>
                        <input type="file" name="photo" accept="image/*">
                    </div>
                </div>
                
                <button type="submit" name="add_coach" class="btn btn-primary">Add Coach</button>
            </form>
        </section>
        
        <!-- Search and Filters -->
        <section class="list-section">
            <h2>Coach Management</h2>
            
            <div class="search-filters">
                <form method="GET" id="searchForm">
                    <div class="filter-grid">
                        <div class="filter-group">
                            <label>Search Coaches:</label>
                            <input type="text" name="search" placeholder="Search by name or team..." 
                                   value="<?php echo htmlspecialchars($search); ?>" 
                                   class="live-search" data-search-type="coaches">
                        </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>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-coaches.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 coaches 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="selectAllCoaches">
                <label for="selectAllCoaches">Select all <span id="resultsCount"><?php echo count($coaches); ?></span> coaches</label>
            </div>
            
            <div class="players-grid" id="coachesGrid">
                <?php if(empty($coaches)): ?>
                    <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 coaches found</h3>
                        <p>Try adjusting your search criteria or add new coaches.</p>
                    </div>
                <?php else: ?>
                    <?php foreach($coaches as $coach): ?>
                    <div class="coach-admin-card" data-coach-id="<?php echo $coach['id']; ?>">
                        <input type="checkbox" name="coach_ids[]" value="<?php echo $coach['id']; ?>" class="coach-checkbox">
                        
                        <span class="status-badge <?php echo $coach['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                            <?php echo $coach['is_active'] ? 'Active' : 'Inactive'; ?>
                        </span>
                        
                        <img src="<?php echo $coach['photo'] ? '../' . $coach['photo'] : '../assets/default-coach.jpg'; ?>" 
                             alt="<?php echo $coach['name']; ?>"
                             onerror="this.src='../assets/default-coach.jpg'">
                        
                        <h4><?php echo htmlspecialchars($coach['name']); ?></h4>
                        <p><strong>Team:</strong> <?php echo htmlspecialchars($coach['team']); ?></p>
                        <p><strong>Game Week:</strong> <?php echo $coach['game_week']; ?></p>
                        
                        <div class="coach-actions">
                            <button class="btn btn-secondary btn-small" 
                                    onclick="openEditModal(<?php echo htmlspecialchars(json_encode($coach)); ?>)">
                                Edit
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
    </div>
    
    <!-- Edit Coach Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h2>Edit Coach</h2>
            <form method="POST" enctype="multipart/form-data" id="editForm">
                <input type="hidden" name="coach_id" id="edit_coach_id">
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Coach Name:</label>
                        <input type="text" name="name" id="edit_name" required>
                    </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>Coach 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 Coach
                        </label>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="update_coach" class="btn btn-primary">Update Coach</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="bulkCoachesContainer"></div>
    </form>
    
    <script src="../js/admin-actions.js"></script>
    <script>
    // Modal functions
    function openEditModal(coach) {
        document.getElementById('edit_coach_id').value = coach.id;
        document.getElementById('edit_name').value = coach.name;
        document.getElementById('edit_team').value = coach.team;
        document.getElementById('edit_game_week').value = coach.game_week;
        document.getElementById('edit_is_active').checked = coach.is_active == 1;
        document.getElementById('current_photo').textContent = coach.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>