<?php
$pageTitle = 'Manage Rosters';
include 'includes/header.php';
include 'includes/sidebar.php';

// --- Authentication and Role Check ---
$admin_roles = ['super_admin', 'admin', 'league_manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], $admin_roles, true)) {
    header('Location: /smart_football/app/login.php');
    exit();
}

// --- Instantiate Models ---
$teamModel = new Team();
$leagueModel = new League();

// --- Fetch Data ---
$leagues = $leagueModel->getAll();
$selected_league_id = $_GET['league_id'] ?? ($leagues[0]->id ?? null);
$pending_teams = $selected_league_id ? $teamModel->getTeamsWithPendingRosters($selected_league_id) : [];

?>

<!-- Begin Page Content -->
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Manage Team Rosters</h1>
    </div>

    <!-- Filter Form -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <form action="manage_rosters.php" method="GET" class="form-inline">
                <div class="form-group mr-3 mb-2">
                    <label for="league_id" class="mr-2">Filter by League:</label>
                    <select name="league_id" id="league_id" class="form-control" onchange="this.form.submit()">
                        <?php foreach ($leagues as $league): ?>
                            <option value="<?php echo $league->id; ?>" <?php echo ($league->id == $selected_league_id) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($league->name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>
    </div>

    <!-- Pending Rosters Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Pending Roster Approvals</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <?php if (!empty($pending_teams)): ?>
                    <table class="table table-bordered" width="100%" cellspacing="0">
                        <thead><tr><th>Club</th><th>Team</th><th>Manager</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($pending_teams as $team): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($team->club_name); ?></td>
                                    <td><?php echo htmlspecialchars($team->team_name); ?></td>
                                    <td><?php echo htmlspecialchars($team->manager_name ?? 'N/A'); ?></td>
                                    <td>
                                        <button class="btn btn-info btn-sm" onclick="openReviewModal(<?php echo $team->id; ?>, '<?php echo htmlspecialchars($team->team_name, ENT_QUOTES); ?>')">Review Squad</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p class="text-center">No rosters are pending approval for this league.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

</div>
<!-- /.container-fluid -->

<!-- Review Roster Modal -->
<div id="reviewModal" class="modal">
    <div class="modal-content" style="max-width: 700px;">
        <div class="modal-header">
            <h3 id="reviewModalTitle">Review Roster</h3>
            <button class="modal-close-btn" onclick="closeReviewModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="rosterLoading" style="text-align: center; padding: 20px;"><i class="fa-solid fa-spinner fa-spin"></i> Loading players...</div>
            
            <div id="rosterContent" style="display: none;">
                <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-bordered table-striped">
                        <thead><tr><th>#</th><th>Player Name</th><th>Position</th></tr></thead>
                        <tbody id="rosterTableBody"></tbody>
                    </table>
                </div>
                
                <div id="actionButtons" style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end; border-top: 1px solid #eee; padding-top: 15px;">
                    <button class="btn btn-danger" onclick="showRejectForm()">Reject Squad</button>
                    <form action="manage_rosters_process.php" method="POST" style="display:inline;">
                        <input type="hidden" name="team_id" id="approveTeamId">
                        <button type="submit" name="action" value="approve" class="btn btn-success">Approve Squad</button>
                    </form>
                </div>

                <div id="rejectForm" style="display: none; margin-top: 20px; background: #fff3cd; padding: 15px; border-radius: 5px; border: 1px solid #ffeeba;">
                    <form action="manage_rosters_process.php" method="POST">
                        <input type="hidden" name="team_id" id="rejectTeamId">
                        <input type="hidden" name="action" value="reject">
                        <div class="form-group">
                            <label for="rejection_reason" style="font-weight: bold; color: #856404;">Reason for Rejection:</label>
                            <textarea name="rejection_reason" id="rejection_reason" class="form-control" rows="3" required placeholder="e.g., Squad size exceeds limit, invalid player registration..."></textarea>
                        </div>
                        <div style="text-align: right; margin-top: 10px;">
                            <button type="button" class="btn btn-secondary btn-sm" onclick="hideRejectForm()">Cancel</button>
                            <button type="submit" class="btn btn-danger btn-sm">Confirm Rejection</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Modal Styles (if not globally available) */
.modal { display: none; position: fixed; z-index: 1050; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); align-items: center; justify-content: center; }
.modal.show { display: flex; }
.modal-content { background-color: #fff; margin: auto; padding: 20px; border-radius: 8px; width: 90%; position: relative; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px; }
.modal-close-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #aaa; }
.modal-close-btn:hover { color: #333; }
</style>

<script>
const reviewModal = document.getElementById('reviewModal');
const rosterLoading = document.getElementById('rosterLoading');
const rosterContent = document.getElementById('rosterContent');
const rosterTableBody = document.getElementById('rosterTableBody');
const reviewModalTitle = document.getElementById('reviewModalTitle');
const approveTeamId = document.getElementById('approveTeamId');
const rejectTeamId = document.getElementById('rejectTeamId');
const actionButtons = document.getElementById('actionButtons');
const rejectForm = document.getElementById('rejectForm');

function openReviewModal(teamId, teamName) {
    reviewModalTitle.textContent = 'Review Roster: ' + teamName;
    approveTeamId.value = teamId;
    rejectTeamId.value = teamId;
    
    // Reset UI
    rosterLoading.style.display = 'block';
    rosterContent.style.display = 'none';
    hideRejectForm();
    rosterTableBody.innerHTML = '';
    
    reviewModal.classList.add('show');

    // Fetch Players
    fetch(`api/get_roster_details.php?team_id=${teamId}`)
        .then(response => response.json())
        .then(data => {
            rosterLoading.style.display = 'none';
            rosterContent.style.display = 'block';
            
            if (data.length > 0) {
                data.forEach(player => {
                    const row = `<tr>
                        <td>${player.squad_number}</td>
                        <td>${player.first_name} ${player.last_name}</td>
                        <td>${player.position}</td>
                    </tr>`;
                    rosterTableBody.insertAdjacentHTML('beforeend', row);
                });
            } else {
                rosterTableBody.innerHTML = '<tr><td colspan="3" class="text-center">No players found in this roster.</td></tr>';
            }
        })
        .catch(err => {
            console.error(err);
            rosterLoading.innerHTML = '<p class="text-danger">Error loading roster.</p>';
        });
}

function closeReviewModal() { reviewModal.classList.remove('show'); }
function showRejectForm() { actionButtons.style.display = 'none'; rejectForm.style.display = 'block'; }
function hideRejectForm() { rejectForm.style.display = 'none'; actionButtons.style.display = 'flex'; }

window.onclick = function(event) { if (event.target == reviewModal) closeReviewModal(); }
</script>

<?php include 'includes/footer.php'; ?>