<?= $this->extend('admin/layout') ?>

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

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>Manage Predictions</h1>
        <div class="btn-group">
            <button type="button" class="btn btn-info" onclick="recalculateStats()">
                <i class="bi bi-calculator"></i> Recalculate Stats
            </button>
        </div>
    </div>

    <?php if (session()->has('message')): ?>
        <div class="alert alert-success"><?= session('message') ?></div>
    <?php endif; ?>

    <?php if (session()->has('error')): ?>
        <div class="alert alert-danger"><?= session('error') ?></div>
    <?php endif; ?>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-header">Filters</div>
        <div class="card-body">
            <form method="get" action="<?= site_url('admin/predictions') ?>" class="row g-3">
                <div class="col-md-4">
                    <label for="author" class="form-label">Author</label>
                    <select name="author" id="author" class="form-select">
                        <option value="">All Authors</option>
                        <?php foreach ($authors as $a): ?>
                            <option value="<?= $a['author'] ?>" <?= $currentAuthor == $a['author'] ? 'selected' : '' ?>>
                                <?= $a['author'] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-4">
                    <label for="outcome" class="form-label">Outcome</label>
                    <select name="outcome" id="outcome" class="form-select">
                        <option value="">All Outcomes</option>
                        <option value="pending" <?= $currentOutcome == 'pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="correct" <?= $currentOutcome == 'correct' ? 'selected' : '' ?>>Correct</option>
                        <option value="wrong" <?= $currentOutcome == 'wrong' ? 'selected' : '' ?>>Wrong</option>
                    </select>
                </div>

                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                    <a href="<?= site_url('admin/predictions') ?>" class="btn btn-secondary ms-2">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Grouped by Tipster / Ticket (W, L, TBD, %) -->
    <?php if (!empty($groupedTickets)): ?>
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Predictions by Tipster & Ticket</h5>
        </div>
        <div class="card-body">
            <div class="accordion" id="tipsterTicketsAccordion">
                <?php $tipsterIndex = 0; ?>
                <?php foreach ($groupedTickets as $tipsterName => $tickets): ?>
                    <?php
                        $tipsterIndex++;
                        $latestTickets = array_slice($tickets, 0, 5);
                        $headingId = 'tipsterHeading' . $tipsterIndex;
                        $collapseId = 'tipsterCollapse' . $tipsterIndex;
                    ?>
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="<?= $headingId ?>">
                            <button class="accordion-button collapsed" type="button"
                                data-bs-toggle="collapse"
                                data-bs-target="#<?= $collapseId ?>"
                                aria-expanded="false"
                                aria-controls="<?= $collapseId ?>">
                                <?= esc($tipsterName) ?> (<?= count($latestTickets) ?> of <?= count($tickets) ?>)
                            </button>
                        </h2>
                        <div id="<?= $collapseId ?>" class="accordion-collapse collapse"
                            aria-labelledby="<?= $headingId ?>"
                            data-bs-parent="#tipsterTicketsAccordion">
                            <div class="accordion-body">
                                <div class="table-responsive mb-2">
                                    <table class="table table-sm table-bordered">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Ticket</th>
                                                <th>Picks</th>
                                                <th>W</th>
                                                <th>L</th>
                                                <th>TBD</th>
                                                <th>%</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($latestTickets as $t): ?>
                                                <tr>
                                                    <td>
                                                        <a href="<?= site_url('admin/ticket-predictions/' . (int)$t['tip_id']) ?>"><?= esc($t['title'] ?? 'Tip #' . $t['tip_id']) ?></a>
                                                    </td>
                                                    <td><?= (int)($t['total_picks'] ?? 0) ?></td>
                                                    <td><span class="badge bg-success"><?= (int)($t['correct'] ?? 0) ?></span></td>
                                                    <td><span class="badge bg-danger"><?= (int)($t['wrong'] ?? 0) ?></span></td>
                                                    <td><span class="badge bg-warning text-dark"><?= (int)($t['pending'] ?? 0) ?></span></td>
                                                    <td><?= $t['success_pct'] !== null ? $t['success_pct'] . '%' : '-' ?></td>
                                                    <td>
                                                        <a href="<?= site_url('admin/ticket-predictions/' . (int)$t['tip_id']) ?>" class="btn btn-sm btn-outline-primary me-1">Manage</a>
                                                        <button type="button" class="btn btn-sm btn-info send-ticket-notification" data-tip-id="<?= (int)$t['tip_id'] ?>" data-tip-title="<?= esc($t['title'] ?? '') ?>">Push</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Predictions Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">Predictions</h5>
        </div>
        <div class="card-body">
            <!-- Filters -->
            <!-- <div class="row mb-3">
                <div class="col-md-4">
                    <select class="form-select" id="authorFilter">
                        <option value="">All Authors</option>
                        <?php foreach ($authors as $author): ?>
                            <option value="<?= $author['author'] ?>" <?= ($currentAuthor === $author['author']) ? 'selected' : '' ?>>
                                <?= $author['author'] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <select class="form-select" id="outcomeFilter">
                        <option value="">All Outcomes</option>
                        <option value="pending" <?= ($currentOutcome === 'pending') ? 'selected' : '' ?>>Pending</option>
                        <option value="correct" <?= ($currentOutcome === 'correct') ? 'selected' : '' ?>>Correct</option>
                        <option value="wrong" <?= ($currentOutcome === 'wrong') ? 'selected' : '' ?>>Wrong</option>
                    </select>
                </div>
            </div> -->

            <!-- Predictions Table -->
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Author</th>
                            <th>Match</th>
                            <th>Prediction</th>
                            <th>Odds</th>
                            <th>Outcome</th>
                            <th>Match Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($predictions)): ?>
                            <tr>
                                <td colspan="8" class="text-center">No predictions found</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($predictions as $prediction): ?>
                                <tr>
                                    <td><?= $prediction['id'] ?></td>
                                    <td>
                                        <a href="#" class="tipster-link" data-author="<?= $prediction['author'] ?>">
                                            <?= $prediction['author'] ?>
                                        </a>
                                    </td>
                                    <td>
                                        <?php
                                        $matchData = is_array($prediction['match_data'])
                                            ? $prediction['match_data']
                                            : json_decode($prediction['match_data'], true);
                                        echo $matchData['team1'] . ' vs ' . $matchData['team2'];
                                        if (isset($prediction['actual_score'])) {
                                            echo '<br><small>Result: ' . $prediction['actual_score'] . '</small>';
                                        }
                                        ?>
                                    </td>
                                    <td><?= $matchData['prediction'] ?></td>
                                    <td><?= $matchData['odds'] ?></td>
                                    <td>
                                        <span
                                            class="badge bg-<?= $prediction['prediction_outcome'] === 'correct' ? 'success' : ($prediction['prediction_outcome'] === 'wrong' ? 'danger' : 'warning') ?>">
                                            <?= ucfirst($prediction['prediction_outcome']) ?>
                                        </span>
                                    </td>
                                    <td><?= $prediction['match_date'] ?></td>
                                    <td>
                                        <div class="btn-group-vertical" role="group">
                                            <?php if ($prediction['prediction_outcome'] === 'pending'): ?>
                                                <div class="btn-group mb-1">
                                                    <button class="btn btn-sm btn-success mark-outcome"
                                                        data-id="<?= $prediction['id'] ?>" data-outcome="correct">Correct</button>
                                                    <button class="btn btn-sm btn-danger mark-outcome"
                                                        data-id="<?= $prediction['id'] ?>" data-outcome="wrong">Wrong</button>
                                                </div>
                                            <?php endif; ?>

                                            <!-- Edit button for all predictions -->
                                            <button class="btn btn-sm btn-primary edit-prediction"
                                                data-id="<?= $prediction['id'] ?>"
                                                data-outcome="<?= esc($prediction['prediction_outcome']) ?>"
                                                data-actual-score="<?= esc($prediction['actual_score'] ?? '') ?>"
                                                data-ht-score="<?= esc($prediction['ht_score'] ?? '') ?>"
                                                data-ft-score="<?= esc($prediction['ft_score'] ?? '') ?>"
                                                data-team1="<?= esc($matchData['team1'] ?? '') ?>"
                                                data-team2="<?= esc($matchData['team2'] ?? '') ?>"
                                                data-prediction="<?= esc($matchData['prediction'] ?? '') ?>"
                                                data-odds="<?= esc($matchData['odds'] ?? '') ?>"
                                                data-match-date="<?= esc($prediction['match_date']) ?>">
                                                <i class="bi bi-pencil"></i> Edit
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div class="mt-4">
                <?= $pager->links() ?>
            </div>
        </div>
    </div>
</div>

<!-- Score Modal -->
<div class="modal fade" id="scoreModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enter Match Result</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="scoreForm">
                    <div class="mb-3">
                        <label for="actualScore" class="form-label">Final Score *</label>
                        <input type="text" class="form-control" id="actualScore" placeholder="e.g. 2-1" required
                            pattern="\d+-\d+">
                        <div class="invalid-feedback">Please enter a valid score (e.g. 2-1)</div>
                    </div>
                    <div class="mb-3">
                        <label for="htScore" class="form-label">Half Time Score (optional)</label>
                        <input type="text" class="form-control" id="htScore" placeholder="e.g. 1-0" pattern="\d+-\d+">
                        <div class="invalid-feedback">Please enter a valid score (e.g. 1-0)</div>
                    </div>
                    <div class="mb-3">
                        <label for="ftScore" class="form-label">Full Time Score (optional)</label>
                        <input type="text" class="form-control" id="ftScore" placeholder="e.g. 2-1" pattern="\d+-\d+">
                        <div class="invalid-feedback">Please enter a valid score (e.g. 2-1)</div>
                    </div>
                </form>
            </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="submitScore">Save Result</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Prediction Modal -->
<div class="modal fade" id="editPredictionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Prediction</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editPredictionForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="editTeam1" class="form-label">Team 1 *</label>
                            <input type="text" class="form-control" id="editTeam1" required>
                            <div class="invalid-feedback">Please enter team 1 name</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="editTeam2" class="form-label">Team 2 *</label>
                            <input type="text" class="form-control" id="editTeam2" required>
                            <div class="invalid-feedback">Please enter team 2 name</div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="editPredictionType" class="form-label">Prediction *</label>
                            <input type="text" class="form-control" id="editPredictionType" placeholder="e.g. 1, X, 2, 1X, X2, 12" required>
                            <div class="invalid-feedback">Please enter prediction type</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="editOdds" class="form-label">Odds *</label>
                            <input type="text" class="form-control" id="editOdds" placeholder="e.g. 1.50" required>
                            <div class="invalid-feedback">Please enter odds</div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editMatchDate" class="form-label">Match Date *</label>
                        <input type="date" class="form-control" id="editMatchDate" required>
                        <div class="invalid-feedback">Please select match date</div>
                    </div>
                    <div class="mb-3">
                        <label for="editPredictionOutcome" class="form-label">Prediction Outcome *</label>
                        <select class="form-select" id="editPredictionOutcome" required>
                            <option value="pending">Pending</option>
                            <option value="correct">Correct</option>
                            <option value="wrong">Wrong</option>
                        </select>
                        <div class="invalid-feedback">Please select an outcome</div>
                    </div>
                    <div class="mb-3">
                        <label for="editActualScore" class="form-label">Final Score</label>
                        <input type="text" class="form-control" id="editActualScore" placeholder="e.g. 2-1"
                            pattern="\d+-\d+">
                        <small class="form-text text-muted">Required if outcome is not pending</small>
                        <div class="invalid-feedback">Please enter a valid score (e.g. 2-1)</div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="editHtScore" class="form-label">Half Time Score (optional)</label>
                            <input type="text" class="form-control" id="editHtScore" placeholder="e.g. 1-0"
                                pattern="\d+-\d+">
                            <div class="invalid-feedback">Please enter a valid score (e.g. 1-0)</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="editFtScore" class="form-label">Full Time Score (optional)</label>
                            <input type="text" class="form-control" id="editFtScore" placeholder="e.g. 2-1"
                                pattern="\d+-\d+">
                            <div class="invalid-feedback">Please enter a valid score (e.g. 2-1)</div>
                        </div>
                    </div>
                </form>
            </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="submitEdit">Save Changes</button>
            </div>
        </div>
    </div>
</div>

<!-- Send Ticket Notification Modal -->
<div class="modal fade" id="sendTicketNotificationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Push (Ticket Won)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted small">Sends FCM to users who purchased this ticket. Add a custom message (e.g. "Go for collections, #Ticket No. Won").</p>
                <input type="hidden" id="sendTicketTipId" value="">
                <div class="mb-3">
                    <label for="sendTicketMessage" class="form-label">Custom message (optional)</label>
                    <textarea class="form-control" id="sendTicketMessage" rows="3" placeholder="e.g. Go for collections, #Ticket No. Won"></textarea>
                </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="submitSendTicketNotification">Send</button>
            </div>
        </div>
    </div>
</div>

<!-- Tipster History Modal -->
<div class="modal fade" id="tipsterHistoryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tipster History</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="tipster-stats mb-3">
                    <h6>Statistics</h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6>Success Rate</h6>
                                    <h3 class="success-rate">0%</h3>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6>Total Predictions</h6>
                                    <h3 class="total-predictions">0</h3>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6>Correct Predictions</h6>
                                    <h3 class="correct-predictions">0</h3>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="match-history">
                    <h6>Recent Matches (Last 2 Days)</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Match</th>
                                    <th>Prediction</th>
                                    <th>Odds</th>
                                    <th>Outcome</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody class="history-table-body">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Send ticket notification (Push)
        document.querySelectorAll('.send-ticket-notification').forEach(btn => {
            btn.addEventListener('click', function () {
                const tipId = this.dataset.tipId;
                const tipTitle = this.dataset.tipTitle || '';
                document.getElementById('sendTicketTipId').value = tipId;
                document.getElementById('submitSendTicketNotification').dataset.tipTitle = tipTitle;
                document.getElementById('sendTicketMessage').value = '';
                document.getElementById('sendTicketMessage').placeholder = 'e.g. Go for collections, #Ticket No. Won';
                const modal = new bootstrap.Modal(document.getElementById('sendTicketNotificationModal'));
                modal.show();
            });
        });
        document.getElementById('submitSendTicketNotification').addEventListener('click', function () {
            const tipId = document.getElementById('sendTicketTipId').value;
            const message = document.getElementById('sendTicketMessage').value.trim();
            const btn = this;
            const tipTitle = btn.dataset.tipTitle || '';
            btn.disabled = true;
            btn.textContent = 'Sending...';
            fetch('<?= site_url('admin/send-ticket-notification/') ?>' + tipId, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                body: JSON.stringify({ message: message, tip_title: tipTitle })
            })
                .then(r => r.json())
                .then(data => {
                    btn.disabled = false;
                    btn.textContent = 'Send';
                    bootstrap.Modal.getInstance(document.getElementById('sendTicketNotificationModal')).hide();
                    alert(data.status === 'success' ? data.message : (data.message || 'Failed to send'));
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.textContent = 'Send';
                    alert('Error: ' + (err.message || 'Request failed'));
                });
        });

        // Handle tipster link clicks
        document.querySelectorAll('.tipster-link').forEach(link => {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                const author = this.dataset.author;
                loadTipsterHistory(author);
            });
        });

        // Function to load tipster history
        function loadTipsterHistory(author) {
            fetch(`/api/author-stats/${author}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        const stats = data.data;

                        // Update stats
                        document.querySelector('.success-rate').textContent = stats.success_rate + '%';
                        document.querySelector('.total-predictions').textContent = stats.total_predictions;
                        document.querySelector('.correct-predictions').textContent = stats.correct_predictions;

                        // Update match history
                        const tbody = document.querySelector('.history-table-body');
                        tbody.innerHTML = '';

                        stats.match_history.forEach(match => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                            <td>${match.match}</td>
                            <td>${match.prediction}</td>
                            <td>${match.odds}</td>
                            <td>
                                <span class="badge bg-${match.outcome === 'correct' ? 'success' : (match.outcome === 'wrong' ? 'danger' : 'warning')}">
                                    ${match.outcome}
                                </span>
                            </td>
                            <td>${match.match_date}</td>
                        `;
                            tbody.appendChild(row);
                        });

                        // Show modal
                        const modal = new bootstrap.Modal(document.getElementById('tipsterHistoryModal'));
                        modal.show();
                    }
                })
                .catch(error => console.error('Error loading tipster history:', error));
        }

        // Handle outcome marking with new modal
        const scoreModalEl = document.getElementById('scoreModal');
        let scoreModal = bootstrap.Modal.getInstance(scoreModalEl) || new bootstrap.Modal(scoreModalEl);

        // In your .mark-outcome click handler:
        document.querySelectorAll('.mark-outcome').forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();

                // Store prediction info
                window.currentPrediction = {
                    id: this.dataset.id,
                    outcome: this.dataset.outcome
                };

                // Reset form
                const form = document.getElementById('scoreForm');
                form.reset();
                form.classList.remove('was-validated');

                // Set modal title based on outcome
                document.querySelector('.modal-title').textContent =
                    `Mark as ${this.dataset.outcome.toUpperCase()}`;

                // Show the modal using the single instance
                scoreModal.show();
            });
        });

        // Update the score form submission handler:
        document.getElementById('submitScore').addEventListener('click', function () {
            const form = document.getElementById('scoreForm');
            const actualScore = document.getElementById('actualScore').value;

            form.classList.add('was-validated');

            if (!form.checkValidity()) {
                return;
            }

            const formData = {
                outcome: window.currentPrediction.outcome,
                actual_score: actualScore,
                ht_score: document.getElementById('htScore').value,
                ft_score: document.getElementById('ftScore').value
            };

            fetch(`<?= base_url('api/predictions/update-score/') ?>${window.currentPrediction.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    prediction_outcome: formData.outcome,
                    actual_score: formData.actual_score,
                    ht_score: formData.ht_score,
                    ft_score: formData.ft_score
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert(data.message || 'Error updating prediction');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred. Please try again.');
                });
        });



        // Handle filters (only if elements exist)
        const authorFilter = document.getElementById('authorFilter');
        const outcomeFilter = document.getElementById('outcomeFilter');
        
        if (authorFilter) {
            authorFilter.addEventListener('change', applyFilters);
        }
        if (outcomeFilter) {
            outcomeFilter.addEventListener('change', applyFilters);
        }

        function applyFilters() {
            const author = authorFilter ? authorFilter.value : '';
            const outcome = outcomeFilter ? outcomeFilter.value : '';

            let url = '/admin/predictions?';
            if (author) url += `author=${author}&`;
            if (outcome) url += `outcome=${outcome}`;

            window.location.href = url;
        }

        // Handle edit prediction buttons
        document.addEventListener('click', function (e) {
            const editBtn = e.target.closest('.edit-prediction');
            if (editBtn) {
                e.preventDefault();
                console.log('Edit button clicked:', editBtn.dataset);

                const predictionId = editBtn.dataset.id;
                const actualScore = editBtn.dataset.actualScore || '';
                const htScore = editBtn.dataset.htScore || '';
                const ftScore = editBtn.dataset.ftScore || '';
                const currentOutcome = editBtn.dataset.outcome || '';
                const team1 = editBtn.dataset.team1 || '';
                const team2 = editBtn.dataset.team2 || '';
                const prediction = editBtn.dataset.prediction || '';
                const odds = editBtn.dataset.odds || '';
                const matchDate = editBtn.dataset.matchDate || '';

                // Populate the edit form
                const team1El = document.getElementById('editTeam1');
                const team2El = document.getElementById('editTeam2');
                const predictionTypeEl = document.getElementById('editPredictionType');
                const oddsEl = document.getElementById('editOdds');
                const matchDateEl = document.getElementById('editMatchDate');
                const outcomeEl = document.getElementById('editPredictionOutcome');
                const actualScoreEl = document.getElementById('editActualScore');
                const htScoreEl = document.getElementById('editHtScore');
                const ftScoreEl = document.getElementById('editFtScore');
                
                if (!team1El || !team2El || !predictionTypeEl || !oddsEl || !matchDateEl || 
                    !outcomeEl || !actualScoreEl || !htScoreEl || !ftScoreEl) {
                    console.error('Form elements not found');
                    alert('Form elements not found. Please refresh the page.');
                    return;
                }
                
                team1El.value = team1;
                team2El.value = team2;
                predictionTypeEl.value = prediction;
                oddsEl.value = odds;
                matchDateEl.value = matchDate;
                outcomeEl.value = currentOutcome;
                actualScoreEl.value = actualScore;
                htScoreEl.value = htScore;
                ftScoreEl.value = ftScore;

                // Store the prediction ID for the submit handler
                window.currentEditPredictionId = predictionId;

                console.log('Opening edit modal for prediction:', predictionId);

                // Show the modal
                const editModalEl = document.getElementById('editPredictionModal');
                if (!editModalEl) {
                    console.error('Edit modal element not found');
                    alert('Modal not found. Please refresh the page.');
                    return;
                }
                const editModal = new bootstrap.Modal(editModalEl);
                editModal.show();
            }
        });

        // Handle edit prediction form submission
        const submitEditBtn = document.getElementById('submitEdit');
        if (!submitEditBtn) {
            console.error('Submit edit button not found');
            return;
        }
        
        submitEditBtn.addEventListener('click', function () {
            const form = document.getElementById('editPredictionForm');
            const team1 = document.getElementById('editTeam1').value.trim();
            const team2 = document.getElementById('editTeam2').value.trim();
            const predictionType = document.getElementById('editPredictionType').value.trim();
            const odds = document.getElementById('editOdds').value.trim();
            const matchDate = document.getElementById('editMatchDate').value;
            const outcome = document.getElementById('editPredictionOutcome').value;
            const actualScore = document.getElementById('editActualScore').value.trim();
            const htScore = document.getElementById('editHtScore').value.trim();
            const ftScore = document.getElementById('editFtScore').value.trim();

            if (!form) {
                console.error('Edit form not found');
                alert('Form not found. Please refresh the page.');
                return;
            }

            // Validate required fields
            if (!team1 || !team2 || !predictionType || !odds || !matchDate || !outcome) {
                alert('Please fill in all required fields');
                form.classList.add('was-validated');
                return;
            }

            // If outcome is not pending, actual_score is required
            if (outcome !== 'pending' && !actualScore) {
                alert('Final score is required when outcome is not pending');
                form.classList.add('was-validated');
                return;
            }

            // Validate score format if provided
            if (actualScore && !/^\d+-\d+$/.test(actualScore)) {
                alert('Invalid final score format. Use format like 2-1');
                form.classList.add('was-validated');
                return;
            }

            if (htScore && !/^\d+-\d+$/.test(htScore)) {
                alert('Invalid half-time score format. Use format like 1-0');
                form.classList.add('was-validated');
                return;
            }

            if (ftScore && !/^\d+-\d+$/.test(ftScore)) {
                alert('Invalid full-time score format. Use format like 2-1');
                form.classList.add('was-validated');
                return;
            }

            form.classList.add('was-validated');

            if (!form.checkValidity()) {
                return;
            }

            // Prepare match_data
            const matchData = {
                team1: team1,
                team2: team2,
                prediction: predictionType,
                odds: odds
            };

            const updateData = {
                match_data: matchData,
                match_date: matchDate,
                prediction_outcome: outcome,
                actual_score: actualScore || null,
                ht_score: htScore || null,
                ft_score: ftScore || null
            };

            console.log('Submitting edit prediction:', window.currentEditPredictionId, updateData);

            fetch(`<?= base_url('api/predictions/update-full/') ?>${window.currentEditPredictionId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(updateData)
            })
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.status === 'success') {
                        alert('Prediction updated successfully!');
                        location.reload();
                    } else {
                        alert(data.message || 'Error updating prediction');
                        if (data.errors) {
                            console.error('Validation errors:', data.errors);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    console.error('Error details:', {
                        message: error.message,
                        stack: error.stack
                    });
                    alert('An error occurred while updating the prediction. Check console for details.');
                });
        });

        // Recalculate stats
        function recalculateStats() {
            if (confirm('Are you sure you want to recalculate all tipster statistics? This may take a moment.')) {
                fetch('<?= base_url('admin/recalculate-stats') ?>', {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            alert('Statistics recalculated successfully!');
                            location.reload();
                        } else {
                            alert(data.message || 'Error recalculating statistics');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred while recalculating statistics.');
                    });
            }
        }
    });
</script>

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