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

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$clubManagerModel = new ClubManager();
$clubModel = new Club();
$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();
}

$settings = $settingModel->getAll();
$transfer_window_start = $settings['transfer_window_start'] ?? null;
$transfer_window_end = $settings['transfer_window_end'] ?? null;
$today = date('Y-m-d');
$is_window_open = ($today >= $transfer_window_start && $today <= $transfer_window_end);

$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';

// --- Fetch Ongoing Transfers ---
$db = new Database();
$db->query("
    SELECT 
        t.*,
        p.position,
        u.first_name, u.last_name,
        c_from.name as from_club_name,
        c_to.name as to_club_name
    FROM transfers t
    JOIN players p ON t.player_id = p.user_id
    JOIN users u ON p.user_id = u.id
    JOIN clubs c_from ON t.from_club_id = c_from.id
    JOIN clubs c_to ON t.to_club_id = c_to.id
    WHERE t.from_club_id = :club_id OR t.to_club_id = :club_id2
    ORDER BY t.created_at DESC
");
$db->bind(':club_id', $club->id);
$db->bind(':club_id2', $club->id);
$ongoing_transfers = $db->resultSet();

?>

<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>Club Transfers</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>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <!-- Transfer Window Status -->
    <div class="dashboard-section">
        <div class="transfer-window-status <?php echo $is_window_open ? 'open' : 'closed'; ?>">
            <i class="fa-solid fa-door-<?php echo $is_window_open ? 'open' : 'closed'; ?>"></i>
            <div>
                <span class="status-title">Transfer Window is currently <strong><?php echo $is_window_open ? 'OPEN' : 'CLOSED'; ?></strong></span>
                <span class="status-dates">
                    <?php if ($transfer_window_start && $transfer_window_end): ?>
                        <?php echo date('d M Y', strtotime($transfer_window_start)); ?> - <?php echo date('d M Y', strtotime($transfer_window_end)); ?>
                    <?php else: ?>
                        Dates not set by league manager.
                    <?php endif; ?>
                </span>
            </div>
        </div>
    </div>

    <!-- Initiate Transfer Section -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Initiate New Transfer</h2>
        <?php if ($is_window_open): ?>
            <form action="transfer_process.php" method="POST">
                <input type="hidden" name="action" value="initiate">
                <input type="hidden" name="player_id" id="transfer_player_id">
                <input type="hidden" name="from_club_id" id="transfer_from_club_id">
                <input type="hidden" name="to_club_id" value="<?php echo $club->id; ?>">

                <div class="form-group">
                    <label for="player_search">Search for a player to sign:</label>
                    <input type="text" id="player_search" class="player-search-input" placeholder="Start typing player name..." autocomplete="off">
                    <div id="player_search_results" class="search-results"></div>
                </div>

                <div class="form-group">
                    <label for="offer_amount">Offer Amount ($)</label>
                    <input type="number" name="offer_amount" id="offer_amount" step="1000" placeholder="e.g., 50000">
                </div>

                <button type="submit" class="btn" id="initiate_transfer_btn" disabled>Submit Offer</button>
            </form>
        <?php else: ?>
            <p class="no-data-msg">You can only initiate transfers when the transfer window is open.</p>
        <?php endif; ?>
    </div>

    <!-- Ongoing Transfers Section -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Ongoing & Past Transfers</h2>
        <div class="table-wrapper">
            <?php if (!empty($ongoing_transfers)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Player</th>
                            <th>From</th>
                            <th>To</th>
                            <th>Offer</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($ongoing_transfers as $transfer): 
                            $is_incoming = ($transfer->to_club_id == $club->id);
                            $status_class = 'status-' . $transfer->status;
                        ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($transfer->first_name . ' ' . $transfer->last_name); ?></strong><br>
                                    <small><?php echo htmlspecialchars($transfer->position); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($transfer->from_club_name); ?></td>
                                <td><?php echo htmlspecialchars($transfer->to_club_name); ?></td>
                                <td>$<?php echo number_format($transfer->offer_amount, 2); ?></td>
                                <td><span class="status-badge <?php echo $status_class; ?>"><?php echo ucfirst($transfer->status); ?></span></td>
                                <td>
                                    <?php if ($transfer->status === 'pending' && $is_incoming): ?>
                                        <form action="transfer_response_process.php" method="POST" style="display:inline;">
                                            <input type="hidden" name="transfer_id" value="<?php echo $transfer->id; ?>">
                                            <button type="submit" name="action" value="accept" class="btn-sm btn-success">Accept</button>
                                            <button type="submit" name="action" value="reject" class="btn-sm btn-danger">Reject</button>
                                        </form>
                                    <?php elseif ($transfer->status === 'pending' && !$is_incoming): ?>
                                        <span class="text-muted">Waiting for response</span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No transfer activity for your club yet.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const playerSearchInput = document.getElementById('player_search');
    const searchResults = document.getElementById('player_search_results');
    const playerIdInput = document.getElementById('transfer_player_id');
    const fromClubIdInput = document.getElementById('transfer_from_club_id');
    const initiateBtn = document.getElementById('initiate_transfer_btn');

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

            fetch(`api/search_players.php?q=${encodeURIComponent(query)}`)
                .then(res => res.json())
                .then(data => {
                    searchResults.innerHTML = '';
                    data.forEach(player => {
                        // Don't allow transfers from own club
                        if (player.club_id == <?php echo $club->id; ?>) return;

                        const div = document.createElement('div');
                        div.className = 'search-result-item';
                        div.innerHTML = `<img src="${player.club_logo}" alt=""> <div><div class="player-name">${player.first_name} ${player.last_name}</div><div class="club-name">${player.club_name}</div></div>`;
                        div.onclick = () => {
                            playerSearchInput.value = `${player.first_name} ${player.last_name}`;
                            playerIdInput.value = player.id;
                            fromClubIdInput.value = player.club_id;
                            searchResults.innerHTML = '';
                            initiateBtn.disabled = false;
                        };
                        searchResults.appendChild(div);
                    });
                });
        });
    }
});
</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'; ?>