<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$transferModuleBoot = 'transfer_module_boot';
$transferSummaryCards = 'transfer_summary_cards';
$transferRecentList = 'transfer_recent_list';
$transferWindowList = 'transfer_window_list';
$transferWindowReportSummary = 'transfer_window_report_summary';
$transferSeasonOptions = 'transfer_season_options';
$transferActiveWindowSnapshot = 'transfer_active_window_snapshot';
$transferWindowStatusBadgeClass = 'transfer_window_status_badge_class';
$transferMarketFiltersFromRequest = 'transfer_market_filters_from_request';
$transferMarketPlayerList = 'transfer_market_player_list';
$transferNotificationList = 'transfer_notification_list';
$transferBuyerClubOptions = 'transfer_buyer_club_options';
$transferCanReviewInterest = 'transfer_can_review_interest';
$transferStageLabel = 'transfer_stage_label';
$transferStageBadgeClass = 'transfer_stage_badge_class';

$transferModuleBoot();

$pageTitle = 'Transfers';
$summary = $transferSummaryCards();
$windowSnapshot = $transferActiveWindowSnapshot();
$openWindow = $windowSnapshot['window'];
$windowCountdown = $windowSnapshot['countdown'];
$marketFilters = $transferMarketFiltersFromRequest();
$marketPlayers = $transferMarketPlayerList($marketFilters);
$recentTransfers = $transferRecentList();
$notifications = $transferNotificationList();
$buyerClubOptions = $transferBuyerClubOptions();
$seasonOptions = $transferSeasonOptions();
$windows = $transferWindowList();
$windowSummary = $transferWindowReportSummary();
$formErrors = flash('errors') ?? [];

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="hero-banner mb-4">
    <div>
        <p class="eyebrow mb-2">Transfer centre</p>
        <h2>Manage the live transfer market</h2>
        <p class="mb-0 text-muted">Open and close windows, monitor active deals, and review transfer activity from one workspace.</p>
    </div>
    <div class="hero-banner-meta">
        <span class="hero-pill"><i class="bi bi-arrow-left-right"></i> Transfers</span>
        <span class="hero-pill"><i class="bi bi-hourglass-split"></i> Window countdown live</span>
    </div>
</section>

<?php if ($openWindow !== null && $windowCountdown !== null): ?>
    <section class="alert alert-success border-0 shadow-sm d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4" data-transfer-countdown data-deadline="<?php echo e($windowCountdown['deadline_iso']); ?>">
        <div>
            <strong><?php echo e($openWindow['name']); ?></strong> is open until <?php echo e($openWindow['end_date']); ?>.
            <div class="small text-muted">The transfer market stays available until the deadline closes this window automatically.</div>
        </div>
        <div class="text-lg-end">
            <div class="small text-uppercase text-muted">Time remaining</div>
            <div class="h4 mb-0" data-transfer-countdown-value><?php echo e((string) $windowCountdown['days_remaining']); ?>d 00h 00m 00s</div>
        </div>
    </section>
<?php else: ?>
    <section class="alert alert-warning border-0 shadow-sm mb-4">
        <strong>No transfer window is open.</strong> Coaches can browse the market, but only league management can open a transfer window before any club can register interest.
    </section>
<?php endif; ?>

<?php if (can_manage_transfer_windows()): ?>
    <section class="panel-card mb-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">League controls</p>
                <h3 class="h5 mb-0">Create transfer window</h3>
            </div>
            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/transfers/windows-report.php')); ?>">
                <i class="bi bi-file-earmark-bar-graph"></i>
                Window report
            </a>
        </div>
        <form method="post" action="<?php echo e(base_url('app/modules/transfers/actions.php')); ?>" novalidate>
            <?php echo csrf_input(); ?>
            <input type="hidden" name="action" value="create_window">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label" for="window_name">Window name</label>
                    <input class="form-control <?php echo validation_error($formErrors, 'name') ? 'is-invalid' : ''; ?>" id="window_name" name="name" value="<?php echo e((string) old('name')); ?>" required>
                    <?php if (validation_error($formErrors, 'name')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'name')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="season_id">Season</label>
                    <select class="form-select <?php echo validation_error($formErrors, 'season_id') ? 'is-invalid' : ''; ?>" id="season_id" name="season_id">
                        <option value="0">All seasons</option>
                        <?php foreach ($seasonOptions as $season): ?>
                            <option value="<?php echo e((string) $season['id']); ?>" <?php echo (string) old('season_id') === (string) $season['id'] ? 'selected' : ''; ?>><?php echo e($season['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (validation_error($formErrors, 'season_id')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'season_id')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="start_date">Start date</label>
                    <input class="form-control <?php echo validation_error($formErrors, 'start_date') ? 'is-invalid' : ''; ?>" id="start_date" name="start_date" type="date" value="<?php echo e((string) old('start_date')); ?>" required>
                    <?php if (validation_error($formErrors, 'start_date')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'start_date')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="end_date">Deadline</label>
                    <input class="form-control <?php echo validation_error($formErrors, 'end_date') ? 'is-invalid' : ''; ?>" id="end_date" name="end_date" type="date" value="<?php echo e((string) old('end_date')); ?>" required>
                    <?php if (validation_error($formErrors, 'end_date')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'end_date')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="window_status">Initial status</label>
                    <select class="form-select <?php echo validation_error($formErrors, 'status') ? 'is-invalid' : ''; ?>" id="window_status" name="status">
                        <option value="draft" <?php echo old('status', 'draft') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                        <option value="open" <?php echo old('status') === 'open' ? 'selected' : ''; ?>>Open now</option>
                    </select>
                    <?php if (validation_error($formErrors, 'status')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'status')); ?></div><?php endif; ?>
                </div>
            </div>
            <div class="d-flex gap-2 mt-3">
                <button class="btn btn-jlfc" type="submit">Save window</button>
            </div>
        </form>
    </section>
<?php endif; ?>

<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Market</p>
            <h3 class="h5 mb-0">Transfer market</h3>
        </div>
        <?php if ($openWindow !== null): ?>
            <span class="badge badge-soft-success"><?php echo e($openWindow['name']); ?> open</span>
        <?php else: ?>
            <span class="badge badge-soft-danger">No open window</span>
        <?php endif; ?>
    </div>

    <form method="get" action="<?php echo e(base_url('app/modules/transfers/index.php')); ?>" class="row g-3 mb-3">
        <div class="col-md-5">
            <label class="form-label" for="q">Search</label>
            <input class="form-control" id="q" name="q" value="<?php echo e($marketFilters['q']); ?>" placeholder="Player, club, or registration number">
        </div>
        <div class="col-md-3">
            <label class="form-label" for="position">Position</label>
            <select class="form-select" id="position" name="position">
                <option value="">All positions</option>
                <?php foreach (player_position_options() as $position): ?>
                    <option value="<?php echo e($position); ?>" <?php echo $marketFilters['position'] === $position ? 'selected' : ''; ?>><?php echo e($position); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if (!is_club_admin()): ?>
            <div class="col-md-3">
                <label class="form-label" for="club_id">Selling club</label>
                <select class="form-select" id="club_id" name="club_id">
                    <option value="0">All clubs</option>
                    <?php foreach ($buyerClubOptions as $club): ?>
                        <option value="<?php echo e((string) $club['id']); ?>" <?php echo (int) $marketFilters['club_id'] === (int) $club['id'] ? 'selected' : ''; ?>><?php echo e($club['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>
        <div class="col-md-1 d-flex align-items-end">
            <button class="btn btn-outline-jlfc w-100" type="submit">Filter</button>
        </div>
    </form>

    <?php if ($openWindow === null): ?>
        <div class="alert alert-warning mb-0">No open transfer window exists yet. Coaches can browse the market, but interest cannot be registered until a window is opened.</div>
    <?php endif; ?>

    <div class="table-responsive mt-3">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Player</th>
                    <th>Club</th>
                    <th>Position</th>
                    <th>Registration</th>
                    <th>Market</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($marketPlayers === []): ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted py-4">No players are currently available in the transfer market view.</td>
                    </tr>
                <?php endif; ?>
                <?php foreach ($marketPlayers as $player): ?>
                    <tr>
                        <td>
                            <strong><?php echo e(trim($player['first_name'] . ' ' . $player['last_name'])); ?></strong>
                            <div class="small text-muted">Jersey <?php echo e((string) ($player['jersey_number'] ?? '-')); ?> · <?php echo e(ucfirst((string) $player['transfer_status'])); ?></div>
                        </td>
                        <td><?php echo e($player['club_name']); ?></td>
                        <td><?php echo e($player['position']); ?></td>
                        <td><?php echo e($player['registration_number']); ?></td>
                        <td>
                            <?php if ((int) $player['active_interest_count'] > 0): ?>
                                <span class="badge text-bg-light">Interest already registered</span>
                            <?php else: ?>
                                <span class="badge badge-soft-success">Available</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/transfers/create-interest.php?player_id=' . (int) $player['id'])); ?>" <?php echo $openWindow === null || (int) $player['active_interest_count'] > 0 ? 'aria-disabled="true" tabindex="-1"' : ''; ?>>Register interest</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="row g-4 mb-4">
    <div class="col-12 col-md-6 col-xl-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-door-open"></i></div>
            <span class="metric-label">Open windows</span>
            <strong class="metric-value"><?php echo e((string) $summary['open_windows']); ?></strong>
            <small class="text-muted">Transfer windows currently available for business</small>
        </article>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-arrow-left-right"></i></div>
            <span class="metric-label">Active deals</span>
            <strong class="metric-value"><?php echo e((string) $summary['active_deals']); ?></strong>
            <small class="text-muted">Transfers not yet completed, rejected, or cancelled</small>
        </article>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-check2-square"></i></div>
            <span class="metric-label">Pending approvals</span>
            <strong class="metric-value"><?php echo e((string) $summary['pending_approvals']); ?></strong>
            <small class="text-muted">Deals awaiting club or league sign-off</small>
        </article>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-bell"></i></div>
            <span class="metric-label">Unread transfer notifications</span>
            <strong class="metric-value"><?php echo e((string) $summary['unread_notifications']); ?></strong>
            <small class="text-muted">Alerts waiting for user attention</small>
        </article>
    </div>
</section>

<section class="row g-4">
    <div class="col-12 col-xl-8">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Pipeline</p>
                    <h3 class="h5 mb-0">Recent transfer records</h3>
                </div>
            </div>
            <?php if ($recentTransfers === []): ?>
                <p class="text-muted mb-0">No transfer records exist yet. Once clubs register interest, seller review decisions will appear here for negotiation handoff.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Player</th>
                                <th>Route</th>
                                <th>Stage</th>
                                <th>Fee</th>
                                <th>Updated</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentTransfers as $transfer): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo e(trim($transfer['first_name'] . ' ' . $transfer['last_name'])); ?></strong>
                                        <div class="small text-muted">Started by <?php echo e($transfer['initiated_by_name']); ?></div>
                                    </td>
                                    <td>
                                        <?php echo e($transfer['selling_club_name']); ?>
                                        <i class="bi bi-arrow-right mx-1"></i>
                                        <?php echo e($transfer['buying_club_name']); ?>
                                    </td>
                                    <td><span class="badge <?php echo e($transferStageBadgeClass((string) $transfer['current_stage'])); ?>"><?php echo e($transferStageLabel((string) $transfer['current_stage'])); ?></span></td>
                                    <td><?php echo e($transfer['agreed_fee'] !== null ? number_format((float) $transfer['agreed_fee'], 2) : ($transfer['proposed_fee'] !== null ? number_format((float) $transfer['proposed_fee'], 2) : 'TBD')); ?></td>
                                    <td><?php echo e((string) $transfer['updated_at']); ?></td>
                                    <td class="text-end">
                                        <a class="btn btn-outline-secondary btn-sm" href="<?php echo e(base_url('app/modules/transfers/view.php?id=' . (int) $transfer['id'])); ?>"><?php echo $transferCanReviewInterest($transfer) ? 'Review' : 'View'; ?></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </article>
    </div>
    <div class="col-12 col-xl-4">
        <article class="panel-card h-100 mb-4">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Notifications</p>
                    <h3 class="h5 mb-0">Your transfer alerts</h3>
                </div>
            </div>
            <?php if ($notifications === []): ?>
                <p class="text-muted mb-0">No transfer notifications yet.</p>
            <?php else: ?>
                <ul class="status-list mb-0">
                    <?php foreach ($notifications as $notification): ?>
                        <li>
                            <span>
                                <strong><?php echo e($notification['title']); ?></strong><br>
                                <small class="text-muted"><?php echo e(trim($notification['first_name'] . ' ' . $notification['last_name']) . ' · ' . $notification['selling_club_name'] . ' to ' . $notification['buying_club_name']); ?></small>
                            </span>
                            <span class="d-inline-flex gap-2 align-items-center">
                                <a class="btn btn-outline-secondary btn-sm" href="<?php echo e(base_url('app/modules/transfers/view.php?id=' . (int) $notification['transfer_id'])); ?>">Open</a>
                                <span class="badge <?php echo e((int) $notification['is_read'] === 0 ? 'badge-soft-success' : 'text-bg-light'); ?>"><?php echo (int) $notification['is_read'] === 0 ? 'New' : 'Seen'; ?></span>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </article>

        <article class="panel-card h-100 mb-4">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Windows</p>
                    <h3 class="h5 mb-0">Configured transfer windows</h3>
                </div>
                <?php if (can_manage_transfer_windows()): ?>
                    <span class="badge text-bg-light"><?php echo e((string) $windowSummary['total_windows']); ?> total</span>
                <?php endif; ?>
            </div>
            <?php if ($windows === []): ?>
                <p class="text-muted mb-0">No transfer windows have been configured yet.</p>
            <?php else: ?>
                <ul class="status-list mb-0">
                    <?php foreach ($windows as $window): ?>
                        <li>
                            <span>
                                <strong><?php echo e($window['name']); ?></strong><br>
                                <small class="text-muted"><?php echo e(($window['season_name'] ?? 'All seasons') . ' · ' . $window['start_date'] . ' to ' . $window['end_date']); ?></small>
                            </span>
                            <span class="d-inline-flex gap-2 align-items-center">
                                <?php if (can_manage_transfer_windows()): ?>
                                    <form method="post" action="<?php echo e(base_url('app/modules/transfers/actions.php')); ?>">
                                        <?php echo csrf_input(); ?>
                                        <input type="hidden" name="action" value="set_window_status">
                                        <input type="hidden" name="window_id" value="<?php echo e((string) $window['id']); ?>">
                                        <input type="hidden" name="status" value="<?php echo e($window['status'] === 'open' ? 'closed' : 'open'); ?>">
                                        <button class="btn btn-outline-secondary btn-sm" type="submit"><?php echo $window['status'] === 'open' ? 'Close' : 'Open'; ?></button>
                                    </form>
                                <?php endif; ?>
                                <span class="badge <?php echo e($transferWindowStatusBadgeClass((string) $window['status'])); ?>"><?php echo e(ucfirst((string) $window['status'])); ?></span>
                            </span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </article>

    </div>
</section>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>