<?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 = 'Staff Members';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

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

// --- Fetch Data ---
// Get the club managed by the logged-in user
$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;
$staff_members = $clubManagerModel->getStaffByClubId($club_id);
$club_teams = $teamModel->getAllByClub($club_id);

// --- Get Colors from Settings ---
$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>Staff Members</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="openHireModal()"><i class="fa-solid fa-user-plus"></i> Hire Staff</button>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <div class="dashboard-section">
        <div class="table-wrapper">
            <?php if (!empty($staff_members)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Role</th>
                            <th>Team</th>
                            <th>Email</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($staff_members as $staff): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($staff->first_name . ' ' . $staff->last_name); ?></td>
                                <td><?php echo htmlspecialchars($staff->role_title); ?></td>
                                <td><?php echo htmlspecialchars($staff->team_name ?? 'N/A'); ?></td>
                                <td><a href="mailto:<?php echo htmlspecialchars($staff->email); ?>"><?php echo htmlspecialchars($staff->email); ?></a></td>
                                <td>
                                    <?php if ($staff->id != $manager_id): // Prevent sacking self ?>
                                        <form action="staff_process.php" method="POST" onsubmit="return confirm('Are you sure you want to sack this staff member? They will become a free agent.');">
                                            <input type="hidden" name="action" value="sack">
                                            <input type="hidden" name="user_id" value="<?php echo $staff->id; ?>">
                                            <button type="submit" class="btn-sm btn-danger">Sack</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No staff members found for this club.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Hire Staff Modal -->
<div id="hireModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Hire Staff Member</h3>
            <button class="modal-close-btn" onclick="closeHireModal()">&times;</button>
        </div>
        <form action="staff_process.php" method="POST">
            <input type="hidden" name="action" value="hire">
            <input type="hidden" name="user_id" id="selected_user_id">

            <div class="form-group">
                <label for="user_search">Search User (Free Agent)</label>
                <input type="text" id="user_search" placeholder="Type name or email..." autocomplete="off">
                <div id="user_search_results" class="search-results"></div>
            </div>

            <div class="form-group">
                <label for="role_type">Role Type</label>
                <select name="role_type" id="role_type" required onchange="toggleTeamSelect()">
                    <option value="">-- Select Role --</option>
                    <option value="team_manager">Team Manager</option>
                    <option value="other">Other Staff</option>
                </select>
            </div>

            <div class="form-group" id="team_select_group" style="display:none;">
                <label for="team_id">Assign to Team</label>
                <select name="team_id" id="team_id">
                    <option value="">-- Select Team --</option>
                    <?php foreach ($club_teams as $team): ?>
                        <option value="<?php echo $team->id; ?>"><?php echo htmlspecialchars($team->name); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group" id="position_input_group" style="display:none;">
                <label for="position">Position Title</label>
                <input type="text" name="position" id="position" placeholder="e.g. Assistant Coach, Physio">
            </div>

            <button type="submit" class="btn btn-block" id="hireBtn" disabled>Hire Selected User</button>
        </form>
    </div>
</div>

<script>
    const hireModal = document.getElementById('hireModal');
    const userSearch = document.getElementById('user_search');
    const searchResults = document.getElementById('user_search_results');
    const selectedUserIdInput = document.getElementById('selected_user_id');
    const hireBtn = document.getElementById('hireBtn');

    function openHireModal() { hireModal.classList.add('show'); }
    function closeHireModal() { hireModal.classList.remove('show'); }

    function toggleTeamSelect() {
        const roleType = document.getElementById('role_type').value;
        const teamGroup = document.getElementById('team_select_group');
        const posGroup = document.getElementById('position_input_group');
        
        if (roleType === 'team_manager') {
            teamGroup.style.display = 'block';
            posGroup.style.display = 'none';
        } else {
            teamGroup.style.display = 'none';
            posGroup.style.display = 'block';
        }
    }

    userSearch.addEventListener('input', function() {
        const query = this.value;
        if (query.length < 2) { searchResults.innerHTML = ''; return; }

        fetch(`api/search_users.php?q=${encodeURIComponent(query)}`)
            .then(res => res.json())
            .then(data => {
                searchResults.innerHTML = '';
                data.forEach(user => {
                    const div = document.createElement('div');
                    div.className = 'search-result-item';
                    div.textContent = `${user.first_name} ${user.last_name} (${user.email})`;
                    div.onclick = () => {
                        userSearch.value = `${user.first_name} ${user.last_name}`;
                        selectedUserIdInput.value = user.id;
                        searchResults.innerHTML = '';
                        hireBtn.disabled = false;
                    };
                    searchResults.appendChild(div);
                });
            });
    });

    window.onclick = (e) => { if (e.target === hireModal) closeHireModal(); };
</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'; ?>