<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$transferModuleBoot = 'transfer_module_boot';
$findTransferOrAbort = 'find_transfer_or_abort';
$transferApprovalMap = 'transfer_approval_map';
$transferTimelineList = 'transfer_timeline_list';
$transferOfferList = 'transfer_offer_list';
$transferLatestOpenOffer = 'transfer_latest_open_offer';
$transferCanReviewInterest = 'transfer_can_review_interest';
$transferCanSubmitOffer = 'transfer_can_submit_offer';
$transferCanReviewOffer = 'transfer_can_review_offer';
$transferCanFinalizeBuyingClubApproval = 'transfer_can_finalize_buying_club_approval';
$transferCanConfirmLeagueApproval = 'transfer_can_confirm_league_approval';
$transferCanManageMedical = 'transfer_can_manage_medical';
$transferOfferBadgeClass = 'transfer_offer_badge_class';
$transferOfferStatusLabel = 'transfer_offer_status_label';
$transferMarkNotificationsRead = 'transfer_mark_notifications_read';
$transferStageLabel = 'transfer_stage_label';
$transferStageBadgeClass = 'transfer_stage_badge_class';

$transferModuleBoot();

$transferRecord = $findTransferOrAbort((int) ($_GET['id'] ?? 0));
$transferMarkNotificationsRead((int) $transferRecord['id'], (int) ($_SESSION['user_id'] ?? 0));
$approvalMap = $transferApprovalMap((int) $transferRecord['id']);
$timelineEvents = $transferTimelineList((int) $transferRecord['id']);
$offerHistory = $transferOfferList((int) $transferRecord['id']);
$latestOpenOffer = $transferLatestOpenOffer((int) $transferRecord['id']);
$canReviewInterest = $transferCanReviewInterest($transferRecord);
$canSubmitOffer = $transferCanSubmitOffer($transferRecord);
$canReviewOffer = $transferCanReviewOffer($transferRecord, $latestOpenOffer);
$canFinalizeBuyingClubApproval = $transferCanFinalizeBuyingClubApproval($transferRecord, $approvalMap);
$canConfirmLeagueApproval = $transferCanConfirmLeagueApproval($transferRecord, $approvalMap);
$canManageMedical = $transferCanManageMedical($transferRecord);
$pageTitle = 'View Transfer';
$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="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Transfer record</p>
            <h2 class="h4 mb-0"><?php echo e(trim($transferRecord['first_name'] . ' ' . $transferRecord['last_name'])); ?></h2>
        </div>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/transfers/index.php')); ?>">Back to transfers</a>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-buildings"></i>
                <div>
                    <h4>Route</h4>
                    <p><?php echo e($transferRecord['selling_club_name']); ?> <i class="bi bi-arrow-right mx-1"></i> <?php echo e($transferRecord['buying_club_name']); ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-signpost-split"></i>
                <div>
                    <h4>Stage</h4>
                    <p><span class="badge <?php echo e($transferStageBadgeClass((string) $transferRecord['current_stage'])); ?>"><?php echo e($transferStageLabel((string) $transferRecord['current_stage'])); ?></span></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-door-open"></i>
                <div>
                    <h4>Window</h4>
                    <p><?php echo e($transferRecord['window_name'] ?? 'Not assigned'); ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-person-badge"></i>
                <div>
                    <h4>Initiated by</h4>
                    <p><?php echo e($transferRecord['initiated_by_name']); ?></p>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="row g-4">
    <div class="col-12 col-xl-8">
        <?php if ($canReviewInterest): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Seller review</p>
                        <h3 class="h5 mb-0">Accept or reject this interest</h3>
                    </div>
                </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="review_interest">
                    <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">

                    <div class="mb-3">
                        <label class="form-label" for="decision_notes">Seller note</label>
                        <textarea class="form-control <?php echo validation_error($formErrors, 'decision_notes') ? 'is-invalid' : ''; ?>" id="decision_notes" name="decision_notes" rows="4" placeholder="Optional for accept, required for reject."><?php echo e((string) old('decision_notes')); ?></textarea>
                        <?php if (validation_error($formErrors, 'decision_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'decision_notes')); ?></div><?php endif; ?>
                    </div>

                    <div class="d-flex gap-2">
                        <button class="btn btn-jlfc" type="submit" name="decision" value="accept">Accept interest</button>
                        <button class="btn btn-outline-danger" type="submit" name="decision" value="reject">Reject interest</button>
                    </div>
                </form>
            </article>
        <?php endif; ?>

        <?php if ($canSubmitOffer): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Negotiation</p>
                        <h3 class="h5 mb-0">Submit buyer offer</h3>
                    </div>
                </div>
                <?php if ($latestOpenOffer !== null): ?>
                    <div class="alert alert-warning">A proposed offer is already waiting for seller response. You can submit a new one after that offer is accepted or rejected.</div>
                <?php else: ?>
                    <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="submit_offer">
                        <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label" for="offered_fee">Offered fee</label>
                                <input class="form-control <?php echo validation_error($formErrors, 'offered_fee') ? 'is-invalid' : ''; ?>" id="offered_fee" name="offered_fee" type="number" min="0" step="0.01" value="<?php echo e((string) old('offered_fee', (string) ($transferRecord['proposed_fee'] ?? ''))); ?>" required>
                                <?php if (validation_error($formErrors, 'offered_fee')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'offered_fee')); ?></div><?php endif; ?>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label" for="contract_years">Contract years</label>
                                <input class="form-control <?php echo validation_error($formErrors, 'contract_years') ? 'is-invalid' : ''; ?>" id="contract_years" name="contract_years" type="number" min="1" step="1" value="<?php echo e((string) old('contract_years', (string) ($transferRecord['contract_years'] ?? ''))); ?>" required>
                                <?php if (validation_error($formErrors, 'contract_years')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'contract_years')); ?></div><?php endif; ?>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label" for="release_date">Release date</label>
                                <input class="form-control <?php echo validation_error($formErrors, 'release_date') ? 'is-invalid' : ''; ?>" id="release_date" name="release_date" type="date" value="<?php echo e((string) old('release_date', (string) ($transferRecord['proposed_release_date'] ?? ''))); ?>">
                                <?php if (validation_error($formErrors, 'release_date')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'release_date')); ?></div><?php endif; ?>
                            </div>
                            <div class="col-12">
                                <label class="form-label" for="offer_notes">Offer note</label>
                                <textarea class="form-control <?php echo validation_error($formErrors, 'offer_notes') ? 'is-invalid' : ''; ?>" id="offer_notes" name="offer_notes" rows="4" placeholder="Optional buyer note for the selling club."><?php echo e((string) old('offer_notes')); ?></textarea>
                                <?php if (validation_error($formErrors, 'offer_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'offer_notes')); ?></div><?php endif; ?>
                            </div>
                        </div>
                        <div class="d-flex gap-2 mt-3">
                            <button class="btn btn-jlfc" type="submit">Submit offer</button>
                        </div>
                    </form>
                <?php endif; ?>
            </article>
        <?php endif; ?>

        <?php if ($canReviewOffer && $latestOpenOffer !== null): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Negotiation review</p>
                        <h3 class="h5 mb-0">Respond to current offer</h3>
                    </div>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <div class="feature-tile"><i class="bi bi-cash-stack"></i>
                            <div>
                                <h4>Fee</h4>
                                <p><?php echo e(number_format((float) $latestOpenOffer['offered_fee'], 2)); ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="feature-tile"><i class="bi bi-calendar2-week"></i>
                            <div>
                                <h4>Contract</h4>
                                <p><?php echo e((string) $latestOpenOffer['contract_years']); ?> years</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="feature-tile"><i class="bi bi-box-arrow-in-right"></i>
                            <div>
                                <h4>Release</h4>
                                <p><?php echo e($latestOpenOffer['release_date'] ?: 'Not set'); ?></p>
                            </div>
                        </div>
                    </div>
                </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="review_offer">
                    <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">
                    <input type="hidden" name="offer_id" value="<?php echo e((string) $latestOpenOffer['id']); ?>">
                    <div class="mb-3">
                        <label class="form-label" for="offer_decision_notes">Seller note</label>
                        <textarea class="form-control <?php echo validation_error($formErrors, 'decision_notes') ? 'is-invalid' : ''; ?>" id="offer_decision_notes" name="decision_notes" rows="4" placeholder="Optional for accept, required for reject."><?php echo e((string) old('decision_notes')); ?></textarea>
                        <?php if (validation_error($formErrors, 'decision_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'decision_notes')); ?></div><?php endif; ?>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-jlfc" type="submit" name="decision" value="accept">Accept offer</button>
                        <button class="btn btn-outline-danger" type="submit" name="decision" value="reject">Reject offer</button>
                    </div>
                </form>
            </article>
        <?php endif; ?>

        <?php if ($canFinalizeBuyingClubApproval): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Buying club approval</p>
                        <h3 class="h5 mb-0">Confirm agreed terms</h3>
                    </div>
                </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="review_approval">
                    <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">
                    <input type="hidden" name="approval_type" value="buying_club">
                    <div class="mb-3">
                        <label class="form-label" for="buying_approval_notes">Approval note</label>
                        <textarea class="form-control <?php echo validation_error($formErrors, 'decision_notes') ? 'is-invalid' : ''; ?>" id="buying_approval_notes" name="decision_notes" rows="4" placeholder="Optional for approve, required for reject."><?php echo e((string) old('decision_notes')); ?></textarea>
                        <?php if (validation_error($formErrors, 'decision_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'decision_notes')); ?></div><?php endif; ?>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-jlfc" type="submit" name="decision" value="accept">Approve agreement</button>
                        <button class="btn btn-outline-danger" type="submit" name="decision" value="reject">Reject and reopen negotiation</button>
                    </div>
                </form>
            </article>
        <?php endif; ?>

        <?php if ($canConfirmLeagueApproval): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">League approval</p>
                        <h3 class="h5 mb-0">Authorize or reject transfer</h3>
                    </div>
                </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="review_approval">
                    <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">
                    <input type="hidden" name="approval_type" value="league">
                    <div class="mb-3">
                        <label class="form-label" for="league_approval_notes">League note</label>
                        <textarea class="form-control <?php echo validation_error($formErrors, 'decision_notes') ? 'is-invalid' : ''; ?>" id="league_approval_notes" name="decision_notes" rows="4" placeholder="Optional for approve, required for reject."><?php echo e((string) old('decision_notes')); ?></textarea>
                        <?php if (validation_error($formErrors, 'decision_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'decision_notes')); ?></div><?php endif; ?>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-jlfc" type="submit" name="decision" value="accept">Grant league approval</button>
                        <button class="btn btn-outline-danger" type="submit" name="decision" value="reject">Reject approval</button>
                    </div>
                </form>
            </article>
        <?php endif; ?>

        <?php if ($canManageMedical): ?>
            <article class="panel-card mb-4">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Medical and completion</p>
                        <h3 class="h5 mb-0">Finalize the transfer</h3>
                    </div>
                </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="review_medical">
                    <input type="hidden" name="transfer_id" value="<?php echo e((string) $transferRecord['id']); ?>">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label" for="effective_date">Effective date</label>
                            <input class="form-control <?php echo validation_error($formErrors, 'effective_date') ? 'is-invalid' : ''; ?>" id="effective_date" name="effective_date" type="date" value="<?php echo e((string) old('effective_date', (string) ($transferRecord['effective_date'] ?? date('Y-m-d')))); ?>">
                            <?php if (validation_error($formErrors, 'effective_date')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'effective_date')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-12">
                            <label class="form-label" for="medical_notes">Medical note</label>
                            <textarea class="form-control <?php echo validation_error($formErrors, 'medical_notes') ? 'is-invalid' : ''; ?>" id="medical_notes" name="medical_notes" rows="4" placeholder="Optional for completion, required for failure."><?php echo e((string) old('medical_notes')); ?></textarea>
                            <?php if (validation_error($formErrors, 'medical_notes')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'medical_notes')); ?></div><?php endif; ?>
                        </div>
                    </div>
                    <div class="d-flex gap-2 mt-3">
                        <button class="btn btn-jlfc" type="submit" name="decision" value="complete">Complete medical</button>
                        <button class="btn btn-outline-danger" type="submit" name="decision" value="fail">Fail medical</button>
                    </div>
                </form>
            </article>
        <?php endif; ?>

        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Timeline</p>
                    <h3 class="h5 mb-0">Transfer desk updates</h3>
                </div>
            </div>
            <?php if ($timelineEvents === []): ?>
                <p class="text-muted mb-0">No timeline events have been recorded for this transfer yet.</p>
            <?php else: ?>
                <ul class="status-list mb-0">
                    <?php foreach ($timelineEvents as $timelineEvent): ?>
                        <li>
                            <span>
                                <strong><?php echo e($timelineEvent['headline']); ?></strong><br>
                                <small class="text-muted"><?php echo e($timelineEvent['body'] ?: 'No additional body text.'); ?></small><br>
                                <small class="text-muted"><?php echo e((string) $timelineEvent['created_at']); ?><?php echo $timelineEvent['created_by_name'] ? ' · ' . e($timelineEvent['created_by_name']) : ''; ?></small>
                            </span>
                            <span class="badge <?php echo e((int) $timelineEvent['publish_news'] === 1 ? 'badge-soft-success' : 'text-bg-light'); ?>"><?php echo (int) $timelineEvent['publish_news'] === 1 ? 'Published' : 'Internal'; ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?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">Transfer summary</p>
                    <h3 class="h5 mb-0">Deal state</h3>
                </div>
            </div>
            <ul class="status-list mb-0">
                <li>
                    <span>Player position</span>
                    <span class="badge text-bg-light"><?php echo e($transferRecord['position']); ?></span>
                </li>
                <li>
                    <span>Registration number</span>
                    <span class="badge text-bg-light"><?php echo e($transferRecord['registration_number']); ?></span>
                </li>
                <li>
                    <span>Interest note</span>
                    <span class="badge text-bg-light"><?php echo e($transferRecord['interest_message'] ?: 'None'); ?></span>
                </li>
                <li>
                    <span>Latest fee</span>
                    <span class="badge text-bg-light"><?php echo e($transferRecord['agreed_fee'] !== null ? number_format((float) $transferRecord['agreed_fee'], 2) : ($transferRecord['proposed_fee'] !== null ? number_format((float) $transferRecord['proposed_fee'], 2) : 'TBD')); ?></span>
                </li>
                <li>
                    <span>Medical status</span>
                    <span class="badge text-bg-light"><?php echo e(ucwords(str_replace('_', ' ', (string) $transferRecord['medical_status']))); ?></span>
                </li>
                <li>
                    <span>Rejection reason</span>
                    <span class="badge text-bg-light"><?php echo e($transferRecord['rejection_reason'] ?: 'Not rejected'); ?></span>
                </li>
            </ul>
        </article>

        <article class="panel-card h-100 mb-4">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Offers</p>
                    <h3 class="h5 mb-0">Negotiation history</h3>
                </div>
            </div>
            <?php if ($offerHistory === []): ?>
                <p class="text-muted mb-0">No offers have been submitted yet.</p>
            <?php else: ?>
                <ul class="status-list mb-0">
                    <?php foreach ($offerHistory as $offer): ?>
                        <li>
                            <span>
                                <strong><?php echo e($offer['offered_by_club_name']); ?></strong><br>
                                <small class="text-muted"><?php echo e(number_format((float) $offer['offered_fee'], 2)); ?> · <?php echo e((string) $offer['contract_years']); ?> years<?php echo $offer['release_date'] ? ' · ' . e($offer['release_date']) : ''; ?></small><br>
                                <small class="text-muted"><?php echo e((string) $offer['created_at']); ?><?php echo $offer['offered_by_name'] ? ' · ' . e($offer['offered_by_name']) : ''; ?></small>
                            </span>
                            <span class="badge <?php echo e($transferOfferBadgeClass((string) $offer['status'])); ?>"><?php echo e($transferOfferStatusLabel((string) $offer['status'])); ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </article>

        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Approvals</p>
                    <h3 class="h5 mb-0">Workflow checkpoints</h3>
                </div>
            </div>
            <ul class="status-list mb-0">
                <?php foreach (['selling_club' => 'Selling club', 'buying_club' => 'Buying club', 'league' => 'League'] as $approvalType => $approvalLabel): ?>
                    <?php $approvalRow = $approvalMap[$approvalType] ?? null; ?>
                    <li>
                        <span><?php echo e($approvalLabel); ?></span>
                        <span class="badge <?php echo e($approvalRow ? (($approvalRow['status'] ?? 'pending') === 'accepted' ? 'badge-soft-success' : (($approvalRow['status'] ?? 'pending') === 'rejected' ? 'badge-soft-danger' : 'text-bg-light')) : 'text-bg-light'); ?>"><?php echo e($approvalRow ? ucfirst((string) $approvalRow['status']) : 'Pending'); ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        </article>
    </div>
</section>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>