<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Manage Teams';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$clubManagerModel = new ClubManager();
$teamModel = new Team();
$userModel = new User();
$settingModel = new Setting();

// --- Fetch Data ---
$club = $clubManagerModel->getClubByManagerId($manager_id);

if (!$club) {
    echo "<div class='page-content'><p class='no-data-msg'>You are not currently assigned as a manager to any club.</p></div>";
    include 'includes/footer.php';
    exit();
}

$club_id = $club->id;
$teams = $teamModel->getAllByClub($club_id);
$available_managers = $userModel->getUsersByRole('team_manager') ?: [];

$settings = $settingModel->getAll();
$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';

?>

<div class="team-dashboard-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="team-identity">
                <img src="<?php echo htmlspecialchars($club->logo); ?>" alt="<?php echo htmlspecialchars($club->name); ?>" class="hero-team-logo">
                <div class="team-details">
                    <h1>Manage Teams</h1>
                    <span class="manager-badge"><?php echo htmlspecialchars($club->name); ?></span>
                </div>
            </div>
            <div class="hero-actions">
                <a href="my_club.php?tab=management" class="btn btn-hero-secondary"><i class="fa-solid fa-arrow-left"></i> Back</a>
                <button class="btn btn-hero-primary" onclick="openModal('add')"><i class="fa-solid fa-plus"></i> Add Team</button>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <!-- Display any success or error messages -->
    <?php if (isset($_GET['status'])): ?>
        <div class="status-message <?php echo $_GET['status'] === 'success' ? 'success' : 'error'; ?>">
            <?php
            if ($_GET['status'] === 'success') echo 'Operation completed successfully.';
            elseif (isset($_GET['error'])) echo 'Error: ' . htmlspecialchars($_GET['error']);
            ?>
        </div>
    <?php endif; ?>

    <div class="dashboard-section">
        <div class="table-wrapper">
            <?php if (!empty($teams)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Team Name</th>
                            <th>Manager</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($teams as $team): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($team->name); ?></td>
                                <td><?php echo htmlspecialchars($team->manager_name ?? 'Not Assigned'); ?></td>
                                <td>
                                    <button class="btn-sm btn-edit" onclick='openModal("edit", <?php echo json_encode($team); ?>)'>Edit</button>
                                    <form action="teams_process.php" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this team?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="team_id" value="<?php echo $team->id; ?>">
                                        <button type="submit" class="btn-sm btn-danger">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No teams found for this club.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add/Edit Team Modal -->
<div id="teamModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Add Team</h3>
            <button class="modal-close-btn" onclick="closeModal()">&times;</button>
        </div>
        <form action="teams_process.php" method="POST">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="team_id" id="teamId">
            <input type="hidden" name="club_id" value="<?php echo $club_id; ?>">

            <div class="form-group">
                <label for="teamName">Team Name</label>
                <input type="text" name="name" id="teamName" required placeholder="e.g. U21 Squad">
            </div>

            <div class="form-group">
                <label for="teamManager">Assign Manager</label>
                <select name="manager_id" id="teamManager">
                    <option value="">-- Select Manager --</option>
                    <?php foreach ($available_managers as $mgr): ?>
                        <option value="<?php echo $mgr->id; ?>"><?php echo htmlspecialchars($mgr->first_name . ' ' . $mgr->last_name); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <button type="submit" class="btn btn-block" id="modalSubmitBtn">Create Team</button>
        </form>
    </div>
</div>

<script>
    const modal = document.getElementById('teamModal');
    const modalTitle = document.getElementById('modalTitle');
    const formAction = document.getElementById('formAction');
    const teamIdInput = document.getElementById('teamId');
    const teamNameInput = document.getElementById('teamName');
    const teamManagerSelect = document.getElementById('teamManager');
    const modalSubmitBtn = document.getElementById('modalSubmitBtn');

    function openModal(mode, teamData = null) {
        if (mode === 'edit' && teamData) {
            modalTitle.textContent = 'Edit Team';
            formAction.value = 'update';
            teamIdInput.value = teamData.id;
            teamNameInput.value = teamData.name;
            teamManagerSelect.value = teamData.manager_id || '';
            modalSubmitBtn.textContent = 'Update Team';
        } else {
            modalTitle.textContent = 'Add Team';
            formAction.value = 'create';
            teamIdInput.value = '';
            teamNameInput.value = '';
            teamManagerSelect.value = '';
            modalSubmitBtn.textContent = 'Create Team';
        }
        modal.classList.add('show');
    }

    function closeModal() {
        modal.classList.remove('show');
    }

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

<style>
:root {
    --hero-gradient: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
}

/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

.team-dashboard-hero {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-top: 0;
}

.hero-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
}

.hero-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.team-identity {
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.hero-team-logo {
    width: 80px;
    height: 80px;
    object-fit: contain;
    background: white;
    border-radius: 50%;
    padding: 5px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.team-details h1 {
    margin: 0 0 5px 0;
    font-size: 2rem;
    font-weight: 700;
}

.manager-badge {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    backdrop-filter: blur(5px);
}

.hero-actions {
    display: flex;
    gap: 10px;
}

.btn-hero-secondary {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
}
.btn-hero-secondary:hover { background: rgba(255,255,255,0.3); }

.btn-hero-primary {
    background: white;
    color: var(--primary-color);
    border: none;
}
.btn-hero-primary:hover { background: #f0f0f0; }

@media (max-width: 768px) {
    .hero-header-row {
        flex-direction: column;
        text-align: center;
        gap: 1.5rem;
    }
    .team-identity {
        flex-direction: column;
    }
}
</style>

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