<?php /** @var array $matches */
/** @var array $tiers */
/** @var string $tab */
/** @var \CodeIgniter\Pager\Pager $pager */
/** @var int $upcomingCount */
/** @var int $settledCount */
$isSettledTab = ($tab ?? 'upcoming') === 'settled';
$tabBaseUrl = site_url('admin/bet-builder/matches');
?>
<?= $this->extend('admin/layout') ?>

<?= $this->section('content') ?>

<?php if (session()->has('message')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= esc(session('message')) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if (session()->has('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?= esc(session('error')) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-0">Bet Builder Matches</h1>
        <p class="text-muted">Admin-curated pool of selectable legs. Odds are public; predictions are hidden until a ticket is paid.</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#bulkMatchModal">
            <i class="bi bi-collection"></i> Bulk Add Fixtures
        </button>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#matchModal">
            <i class="bi bi-plus-circle"></i> Add Match
        </button>
    </div>
</div>

<div class="card shadow-sm mb-4">
    <div class="card-header bg-light">
        <h6 class="mb-0"><i class="bi bi-cash-coin"></i> Pricing tiers (combined odds &rarr; UGX)</h6>
    </div>
    <div class="card-body p-3">
        <div class="d-flex flex-wrap gap-2">
            <?php foreach ($tiers as $t): ?>
                <span class="badge bg-light text-dark border">
                    <?= esc($t['label']) ?> &rarr; <strong><?= number_format($t['price']) ?> UGX</strong>
                </span>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-light">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
            <h5 class="card-title mb-0"><i class="bi bi-list-ul"></i> Matches</h5>
            <ul class="nav nav-pills mb-0" role="tablist">
                <li class="nav-item" role="presentation">
                    <a class="nav-link <?= !$isSettledTab ? 'active' : '' ?>"
                       href="<?= $tabBaseUrl ?>?tab=upcoming">
                        <i class="bi bi-calendar-event"></i> Upcoming
                        <span class="badge bg-<?= !$isSettledTab ? 'light text-dark' : 'secondary' ?> ms-1"><?= (int) $upcomingCount ?></span>
                    </a>
                </li>
                <li class="nav-item" role="presentation">
                    <a class="nav-link <?= $isSettledTab ? 'active' : '' ?>"
                       href="<?= $tabBaseUrl ?>?tab=settled">
                        <i class="bi bi-clock-history"></i> Settled / History
                        <span class="badge bg-<?= $isSettledTab ? 'light text-dark' : 'secondary' ?> ms-1"><?= (int) $settledCount ?></span>
                    </a>
                </li>
            </ul>
        </div>
        <?php if ($isSettledTab): ?>
            <p class="text-muted small mb-0 mt-2">Settled and void fixtures — archived results, hidden from the live builder pool.</p>
        <?php else: ?>
            <p class="text-muted small mb-0 mt-2">Upcoming legs available for users to build tickets.</p>
        <?php endif; ?>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="px-3 py-3">#</th>
                        <th class="px-3 py-3">Match</th>
                        <th class="px-3 py-3">League</th>
                        <th class="px-3 py-3">Kickoff</th>
                        <th class="px-3 py-3">Odds</th>
                        <th class="px-3 py-3">Prediction</th>
                        <th class="px-3 py-3">Status</th>
                        <th class="px-3 py-3">Outcome</th>
                        <th class="px-3 py-3">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($matches)): ?>
                        <tr>
                            <td colspan="9" class="text-center py-5 text-muted">
                                <i class="bi bi-inbox display-4 d-block mb-3"></i>
                                <?php if ($isSettledTab): ?>
                                    <h5>No settled fixtures yet</h5>
                                    <p>Settled and void matches will appear here as history.</p>
                                <?php else: ?>
                                    <h5>No upcoming matches</h5>
                                    <p>Add matches so users can build tickets.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($matches as $i => $m): ?>
                            <tr class="align-middle">
                                <td class="px-3 py-3"><?= $m['id'] ?></td>
                                <td class="px-3 py-3">
                                    <strong><?= esc($m['team1']) ?></strong>
                                    <span class="text-muted">vs</span>
                                    <strong><?= esc($m['team2']) ?></strong>
                                    <?php if (!empty($m['is_archived'])): ?>
                                        <span class="badge bg-secondary ms-2">Archived</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-3 py-3"><?= esc($m['league'] ?? '') ?></td>
                                <td class="px-3 py-3">
                                    <?php if (!empty($m['match_time'])): ?>
                                        <small><?= date('M j, Y H:i', strtotime($m['match_time'])) ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-3 py-3">
                                    <span class="badge bg-primary fs-6"><?= number_format((float) $m['odds'], 2) ?></span>
                                </td>
                                <td class="px-3 py-3">
                                    <code class="small"><?= esc($m['our_prediction'] ?? '—') ?></code>
                                </td>
                                <td class="px-3 py-3">
                                    <span class="badge bg-<?= $m['status'] === 'upcoming' ? 'info' : ($m['status'] === 'settled' ? 'success' : 'warning') ?>">
                                        <?= esc($m['status']) ?>
                                    </span>
                                </td>
                                <td class="px-3 py-3">
                                    <span class="badge bg-<?= $m['result_outcome'] === 'correct' ? 'success' : ($m['result_outcome'] === 'wrong' ? 'danger' : 'secondary') ?>">
                                        <?= esc($m['result_outcome']) ?>
                                    </span>
                                </td>
                                <td class="px-3 py-3">
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-outline-primary edit-match-btn"
                                                data-id="<?= $m['id'] ?>"
                                                data-team1="<?= esc($m['team1']) ?>"
                                                data-team2="<?= esc($m['team2']) ?>"
                                                data-league="<?= esc($m['league'] ?? '') ?>"
                                                data-match_time="<?= !empty($m['match_time']) ? date('Y-m-d\TH:i', strtotime($m['match_time'])) : '' ?>"
                                                data-odds="<?= esc($m['odds']) ?>"
                                                data-our_prediction="<?= esc($m['our_prediction'] ?? '') ?>"
                                                data-status="<?= esc($m['status']) ?>"
                                                data-result_outcome="<?= esc($m['result_outcome']) ?>"
                                                data-is_archived="<?= (int)($m['is_archived'] ?? 0) ?>"
                                                title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <form method="post" action="<?= site_url('admin/bet-builder/matches/archive/' . $m['id']) ?>" class="d-inline">
                                            <input type="hidden" name="return_tab" value="<?= esc($tab) ?>">
                                            <button class="btn btn-sm btn-outline-secondary" title="Toggle archive">
                                                <i class="bi bi-archive"></i>
                                            </button>
                                        </form>
                                        <?php if (!$isSettledTab): ?>
                                        <button type="button" class="btn btn-sm btn-outline-success"
                                                data-bs-toggle="modal"
                                                data-bs-target="#settleModal"
                                                data-id="<?= $m['id'] ?>"
                                                data-current="<?= esc($m['result_outcome']) ?>"
                                                title="Settle outcome">
                                            <i class="bi bi-check2-circle"></i>
                                        </button>
                                        <?php endif; ?>
                                        <form method="post" action="<?= site_url('admin/bet-builder/matches/delete/' . $m['id']) ?>" class="d-inline"
                                              onsubmit="return confirm('Delete this match permanently?')">
                                            <input type="hidden" name="return_tab" value="<?= esc($tab) ?>">
                                            <button class="btn btn-sm btn-outline-danger" title="Delete">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php if (isset($pager) && $pager->getPageCount() > 1):
            $bbCurrentPage = (int) $pager->getCurrentPage();
            $bbLastPage = (int) $pager->getPageCount();
            $bbPageStart = max(1, $bbCurrentPage - 2);
            $bbPageEnd = min($bbLastPage, $bbCurrentPage + 2);
        ?>
            <div class="card-footer bg-light d-flex flex-wrap justify-content-between align-items-center gap-2">
                <span class="text-muted small mb-0">
                    Page <?= $bbCurrentPage ?> of <?= $bbLastPage ?>
                    &middot; <?= (int) $pager->getTotal() ?> matches
                </span>
                <nav aria-label="Bet builder pagination">
                    <ul class="pagination pagination-sm mb-0">
                        <?php if ($bbCurrentPage > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?= $tabBaseUrl ?>?tab=<?= esc($tab) ?>&page=<?= $bbCurrentPage - 1 ?>">Previous</a>
                            </li>
                        <?php endif; ?>
                        <?php for ($p = $bbPageStart; $p <= $bbPageEnd; $p++): ?>
                            <li class="page-item <?= $p === $bbCurrentPage ? 'active' : '' ?>">
                                <a class="page-link" href="<?= $tabBaseUrl ?>?tab=<?= esc($tab) ?>&page=<?= $p ?>"><?= $p ?></a>
                            </li>
                        <?php endfor; ?>
                        <?php if ($bbCurrentPage < $bbLastPage): ?>
                            <li class="page-item">
                                <a class="page-link" href="<?= $tabBaseUrl ?>?tab=<?= esc($tab) ?>&page=<?= $bbCurrentPage + 1 ?>">Next</a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Match Modal -->
<div class="modal fade" id="matchModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle"></i> Add / Edit Match</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post" action="<?= site_url('admin/bet-builder/matches/save') ?>">
                <div class="modal-body">
                    <?= view('partials/football_match_picker') ?>
                    <input type="hidden" name="return_tab" value="<?= esc($tab) ?>">
                    <input type="hidden" name="id" id="match-id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Team 1</label>
                            <input type="text" name="team1" id="team1" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Team 2</label>
                            <input type="text" name="team2" id="team2" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">League</label>
                            <input type="text" name="league" id="league" class="form-control" placeholder="Premier League">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Kickoff</label>
                            <input type="datetime-local" name="match_time" id="match_time" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Odds</label>
                            <input type="number" step="0.01" min="1.01" name="odds" id="odds" class="form-control" required>
                        </div>
                        <div class="col-md-8 mb-3">
                            <label class="form-label">Our Prediction (hidden from users until paid)</label>
                            <input type="text" name="our_prediction" id="our_prediction" class="form-control" placeholder="e.g. Over 2.5, Home Win">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" id="status" class="form-select">
                                <option value="upcoming">upcoming</option>
                                <option value="settled">settled</option>
                                <option value="void">void</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Outcome</label>
                            <select name="result_outcome" id="result_outcome" class="form-select">
                                <option value="pending">pending</option>
                                <option value="correct">correct</option>
                                <option value="wrong">wrong</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label d-block">&nbsp;</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_archived" id="is_archived" value="1">
                                <label class="form-check-label" for="is_archived">Archived (hide from app)</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle"></i> Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk import modal -->
<div class="modal fade" id="bulkMatchModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-collection"></i> Bulk Add Fixtures</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted small mb-3">
                    Select a country and league, then import fixtures from the daily cache window.
                    Enter <strong>prediction</strong> and <strong>odds</strong> for each row you want to add.
                </p>
                <link rel="stylesheet" href="<?= base_url('assets/css/football-picker.css') ?>">
                <div id="bb-bulk-picker" class="fp-match-picker border rounded p-3 mb-3 bg-light" data-bb-bulk-picker>
                    <label class="form-label small text-muted mb-2">
                        <i class="bi bi-calendar-event"></i> League (from fixture cache)
                    </label>
                    <div class="row g-2 align-items-end">
                        <div class="col-md-6">
                            <label class="form-label small mb-1">Country</label>
                            <div class="fp-search-wrap" data-fp-role="country">
                                <input type="text" class="form-control form-control-sm fp-search-input" placeholder="Search country…" autocomplete="off" spellcheck="false">
                                <i class="bi bi-search fp-search-icon"></i>
                                <ul class="fp-search-menu list-group"></ul>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small mb-1">League</label>
                            <div class="fp-search-wrap is-disabled" data-fp-role="league">
                                <input type="text" class="form-control form-control-sm fp-search-input" placeholder="Select country first" autocomplete="off" spellcheck="false" disabled>
                                <i class="bi bi-search fp-search-icon"></i>
                                <ul class="fp-search-menu list-group"></ul>
                            </div>
                        </div>
                    </div>
                    <div id="bb-bulk-hint" class="fp-picker-hint small text-muted mt-2 d-none"></div>
                </div>

                <div id="bb-bulk-loading" class="text-center py-4 d-none">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="text-muted small mt-2 mb-0">Loading fixtures…</p>
                </div>

                <div id="bb-bulk-errors" class="alert alert-danger d-none" role="alert"></div>

                <div id="bb-bulk-table-wrap" class="d-none">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small text-muted" id="bb-bulk-count"></span>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="bb-bulk-select-all" checked>
                            <label class="form-check-label small" for="bb-bulk-select-all">Select all</label>
                        </div>
                    </div>
                    <div class="table-responsive" style="max-height: 400px;">
                        <table class="table table-sm table-hover align-middle mb-0">
                            <thead class="table-light sticky-top">
                                <tr>
                                    <th style="width: 40px;"></th>
                                    <th>Match</th>
                                    <th style="width: 140px;">Kickoff</th>
                                    <th style="width: 200px;">Prediction *</th>
                                    <th style="width: 90px;">Odds *</th>
                                </tr>
                            </thead>
                            <tbody id="bb-bulk-tbody"></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="bb-bulk-submit" disabled>
                    <i class="bi bi-cloud-upload"></i> Import selected (0)
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Settle Modal -->
<div class="modal fade" id="settleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Settle Match</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="settle-form" method="post" action="">
                <div class="modal-body">
                    <input type="hidden" name="return_tab" id="settle-return-tab" value="<?= esc($tab) ?>">
                    <div class="mb-3">
                        <label class="form-label">Outcome</label>
                        <select name="result_outcome" id="settle-outcome" class="form-select">
                            <option value="pending">pending</option>
                            <option value="correct">correct</option>
                            <option value="wrong">wrong</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success"><i class="bi bi-check-circle"></i> Settle</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const bbAdminTab = <?= json_encode($tab) ?>;

document.querySelectorAll('.edit-match-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
        document.getElementById('match-id').value = btn.dataset.id;
        document.getElementById('team1').value = btn.dataset.team1;
        document.getElementById('team2').value = btn.dataset.team2;
        document.getElementById('league').value = btn.dataset.league;
        document.getElementById('match_time').value = btn.dataset.match_time;
        document.getElementById('odds').value = btn.dataset.odds;
        document.getElementById('our_prediction').value = btn.dataset.our_prediction;
        document.getElementById('status').value = btn.dataset.status;
        document.getElementById('result_outcome').value = btn.dataset.result_outcome;
        document.getElementById('is_archived').checked = btn.dataset.is_archived === '1';
        new bootstrap.Modal(document.getElementById('matchModal')).show();
    });
});

document.getElementById('matchModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('match-id').value = '';
    ['team1', 'team2', 'league', 'match_time', 'odds', 'our_prediction'].forEach(function (id) {
        document.getElementById(id).value = '';
    });
    document.getElementById('status').value = 'upcoming';
    document.getElementById('result_outcome').value = 'pending';
    document.getElementById('is_archived').checked = false;
});

const settleModal = document.getElementById('settleModal');
settleModal.addEventListener('show.bs.modal', function (event) {
    const btn = event.relatedTarget;
    const id = btn.getAttribute('data-id');
    const current = btn.getAttribute('data-current') || 'pending';
    document.getElementById('settle-form').action = '<?= site_url('admin/bet-builder/matches/settle/') ?>' + id;
    document.getElementById('settle-outcome').value = current;
});
</script>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/js/football-fixture-picker.js') ?>"></script>
<script src="<?= base_url('assets/js/bet-builder-bulk-import.js') ?>"></script>
<script>
    FootballMatchPicker.init({
        baseUrl: '<?= site_url('admin/football') ?>',
        mode: 'builder'
    });
    BetBuilderBulkImport.init({
        baseUrl: '<?= site_url('admin/football') ?>',
        bulkSaveUrl: '<?= site_url('admin/bet-builder/matches/bulk-save') ?>',
        footballSettingsUrl: '<?= site_url('admin/football/settings') ?>'
    });
</script>
<?= $this->endSection() ?>
