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

<?= $this->section('content') ?>
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">
            <i class="bi bi-list-ul me-2"></i>Manage Tips
            <span class="badge bg-secondary ms-2"><?= count($tips) ?> total</span>
        </h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <div class="btn-group me-2">
                <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#filterModal">
                    <i class="bi bi-funnel"></i> Filter
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="exportTips()">
                    <i class="bi bi-download"></i> Export
                </button>
                <button type="button" class="btn btn-success" onclick="extractAllPredictions()">
                    <i class="bi bi-gear"></i> Extract All Predictions
                </button>
            </div>
            <div class="btn-group">
                <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#importTipsModal">
                    <i class="bi bi-upload"></i> Import Tips
                </button>
                <a href="<?= site_url('admin/addTip') ?>" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> Add New Tip
                </a>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Total Tips</h6>
                            <h3 class="mb-0"><?= count($tips) ?></h3>
                        </div>
                        <i class="bi bi-list-ul fs-2 opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Free Tips</h6>
                            <h3 class="mb-0"><?= count(array_filter($tips, function($tip) { return $tip['tag'] == 'free'; })) ?></h3>
                        </div>
                        <i class="bi bi-gift fs-2 opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Paid Tips</h6>
                            <h3 class="mb-0"><?= count(array_filter($tips, function($tip) { return $tip['tag'] == 'paid'; })) ?></h3>
                        </div>
                        <i class="bi bi-cash-coin fs-2 opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-dark">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-0">Subscriber Only</h6>
                            <h3 class="mb-0"><?= count(array_filter($tips, function($tip) { return !empty($tip['is_subscriber_only']); })) ?></h3>
                        </div>
                        <i class="bi bi-person-check fs-2 opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Search and Filter Bar -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" id="searchTips" placeholder="Search tips by title, author, or category...">
                    </div>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="filterTag">
                        <option value="">All Tags</option>
                        <option value="free">Free</option>
                        <option value="paid">Paid</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="filterCategory">
                        <option value="">All Categories</option>
                        <?php 
                        $categories = array_unique(array_column($tips, 'category'));
                        foreach ($categories as $category): ?>
                            <option value="<?= $category ?>"><?= $category ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="filterAuthor">
                        <option value="">All Authors</option>
                        <?php 
                        $authors = array_unique(array_column($tips, 'author'));
                        foreach ($authors as $author): ?>
                            <option value="<?= $author ?>"><?= $author ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-outline-secondary w-100" onclick="clearFilters()">
                        <i class="bi bi-x-circle"></i> Clear
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Tips Table -->
    <div class="card">
        <div class="card-header bg-light">
            <div class="d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="bi bi-table me-2"></i>Tips List</h6>
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-outline-secondary" onclick="selectAll()">
                        <i class="bi bi-check-all"></i> Select All
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="bulkDelete()" disabled id="bulkDeleteBtn">
                        <i class="bi bi-trash"></i> Delete Selected
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body p-0" style="overflow: visible;">
            <div class="table-responsive" style="overflow-x: auto; overflow-y: visible;">
                <table class="table table-hover align-middle mb-0" id="tipsTable">
                    <thead class="table-light">
                        <tr>
                            <th width="40">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="selectAllCheckbox">
                                </div>
                            </th>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Tag</th>
                            <th>Category</th>
                            <th>Author</th>
                            <th>Amount</th>
                            <th>Matches</th>
                            <th>Match Time</th>
                            <th>Status</th>
                            <th>Today's Hits</th>
                            <th>Created</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($tips)): ?>
                            <tr>
                                <td colspan="12" class="text-center py-5">
                                    <div class="text-muted">
                                        <i class="bi bi-info-circle-fill fs-1 mb-3 d-block"></i>
                                        <h5>No tips found</h5>
                                        <p class="mb-0">Start by adding your first tip or importing from CSV</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($tips as $tip):
                                // Decode matches if it's a JSON string
                                $matches = is_string($tip['matches']) ? json_decode($tip['matches'], true) : $tip['matches'];
                                $matchesCount = is_array($matches) ? count($matches) : 0;
                                $isStarted = !empty($tip['match_time']) && strtotime($tip['match_time']) < time();
                            ?>
                                <tr data-tip-id="<?= $tip['id'] ?>">
                                    <td>
                                        <div class="form-check">
                                            <input class="form-check-input row-checkbox" type="checkbox" value="<?= $tip['id'] ?>">
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-light text-dark border">#<?= $tip['id'] ?></span>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column">
                                            <span class="fw-medium text-truncate" style="max-width: 200px;" title="<?= $tip['title'] ?>">
                                                <?= $tip['title'] ?>
                                            </span>
                                            <?php if ($tip['odds_source']): ?>
                                                <small class="text-muted">
                                                    <i class="bi bi-link-45deg"></i> <?= $tip['odds_source'] ?>
                                                </small>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($tip['tag'] == 'free'): ?>
                                            <span class="badge bg-success rounded-pill">
                                                <i class="bi bi-gift me-1"></i>Free
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-info rounded-pill">
                                                <i class="bi bi-cash-coin me-1"></i>Paid
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary rounded-pill"><?= $tip['category'] ?></span>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-sm bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 32px; height: 32px;">
                                                <?= strtoupper(substr($tip['author'], 0, 1)) ?>
                                            </div>
                                            <span class="text-truncate" style="max-width: 100px;" title="<?= $tip['author'] ?>">
                                                <?= $tip['author'] ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="fw-medium text-success">
                                            <?= number_format($tip['amount']) ?> <small class="text-muted">UGX</small>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-trophy me-2 text-warning"></i>
                                            <span class="badge bg-primary rounded-pill">
                                                <?= $matchesCount ?> match<?= $matchesCount !== 1 ? 'es' : '' ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if (!empty($tip['match_time'])): ?>
                                            <div class="d-flex flex-column">
                                                <span class="fw-medium"><?= date('M d, Y', strtotime($tip['match_time'])) ?></span>
                                                <small class="text-muted">
                                                    <i class="bi bi-clock"></i> <?= date('H:i', strtotime($tip['match_time'])) ?>
                                                </small>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted">
                                                <i class="bi bi-question-circle"></i> Not set
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-column gap-1">
                                            <?php if ($isStarted): ?>
                                                <span class="badge bg-danger">
                                                    <i class="bi bi-play-fill"></i> Started
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-success">
                                                    <i class="bi bi-clock"></i> Upcoming
                                                </span>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($tip['is_subscriber_only'])): ?>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="bi bi-star-fill"></i> Subscribers
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td><?= number_format($tip['daily_hits'] ?? 0) ?></td>
                                    <td>
                                        <div class="d-flex flex-column">
                                            <span class="fw-medium"><?= date('M d, Y', strtotime($tip['created_at'])) ?></span>
                                            <small class="text-muted">
                                                <i class="bi bi-clock"></i> <?= date('H:i', strtotime($tip['created_at'])) ?>
                                            </small>
                                        </div>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-primary" title="Process Matches" onclick="processTip(<?= $tip['id'] ?>)">
                                                <i class="bi bi-gear"></i>
                                            </button>
                                            <a href="<?= site_url('admin/edit/' . $tip['id']) ?>" class="btn btn-outline-info" title="Edit">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#tipModal<?= $tip['id'] ?>" title="View Details">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            <div class="btn-group" role="group" style="position: relative;">
                                                <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <i class="bi bi-three-dots"></i>
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end" style="z-index: 1050;">
                                                    <li><a class="dropdown-item text-primary" href="#" onclick="sendNotification(<?= $tip['id'] ?>)">
                                                        <i class="bi bi-bell"></i> Send Notification
                                                    </a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><a class="dropdown-item text-danger" href="#" onclick="deleteTip(<?= $tip['id'] ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Pagination would go here if needed -->
    
    <!-- Modal container for tip details -->
    <?php if (!empty($tips)): ?>
        <?php foreach ($tips as $tip):
            $matches = is_string($tip['matches']) ? json_decode($tip['matches'], true) : $tip['matches'];
        ?>
            <!-- Enhanced Modal for Tip Details -->
            <div class="modal fade" id="tipModal<?= $tip['id'] ?>" tabindex="-1" aria-labelledby="tipModalLabel<?= $tip['id'] ?>" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="tipModalLabel<?= $tip['id'] ?>">
                                <i class="bi bi-info-circle me-2"></i>Tip Details - <?= $tip['title'] ?>
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="card h-100">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0"><i class="bi bi-card-text me-2"></i>Basic Information</h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Tip ID</label>
                                                <div class="fw-bold">#<?= $tip['id'] ?></div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Title</label>
                                                <div class="fw-bold"><?= $tip['title'] ?></div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Category</label>
                                                <div><span class="badge bg-secondary"><?= $tip['category'] ?></span></div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Tag</label>
                                                <div>
                                                    <?php if ($tip['tag'] == 'free'): ?>
                                                        <span class="badge bg-success">Free</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-info">Paid</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Amount</label>
                                                <div class="fw-bold text-success"><?= number_format($tip['amount']) ?> UGX</div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Author</label>
                                                <div class="d-flex align-items-center">
                                                    <div class="avatar-sm bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 32px; height: 32px;">
                                                        <?= strtoupper(substr($tip['author'], 0, 1)) ?>
                                                    </div>
                                                    <?= $tip['author'] ?>
                                                </div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Odds Source</label>
                                                <div><?= $tip['odds_source'] ?? 'Not specified' ?></div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Created</label>
                                                <div>
                                                    <?= date('M d, Y', strtotime($tip['created_at'])) ?>
                                                    <small class="text-muted d-block"><?= date('H:i', strtotime($tip['created_at'])) ?></small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-8">
                                    <div class="card h-100">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0"><i class="bi bi-trophy me-2"></i>Matches (<?= is_array($matches) ? count($matches) : 0 ?>)</h6>
                                        </div>
                                        <div class="card-body">
                                            <?php if (is_array($matches) && !empty($matches)): ?>
                                                <div class="table-responsive">
                                                    <table class="table table-hover">
                                                        <thead class="table-light">
                                                            <tr>
                                                                <th>Match</th>
                                                                <th>League</th>
                                                                <th>Prediction</th>
                                                                <th>Odds</th>
                                                                <th>Status</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($matches as $match): ?>
                                                                <tr>
                                                                    <td>
                                                                        <div class="fw-medium"><?= $match['team1'] ?> vs <?= $match['team2'] ?></div>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-light text-dark"><?= $match['league'] ?? 'N/A' ?></span>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-primary"><?= $match['prediction'] ?></span>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-success"><?= $match['odds'] ?></span>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-secondary">Pending</span>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            <?php else: ?>
                                                <div class="text-center text-muted py-5">
                                                    <i class="bi bi-info-circle-fill fs-1 mb-3 d-block"></i>
                                                    <h5>No match data available</h5>
                                                    <p class="mb-0">This tip doesn't have any match information yet.</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="bi bi-x-circle"></i> Close
                            </button>
                            <a href="<?= site_url('admin/edit/' . $tip['id']) ?>" class="btn btn-primary">
                                <i class="bi bi-pencil"></i> Edit Tip
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- Import Tips Modal -->
    <div class="modal fade" id="importTipsModal" tabindex="-1" aria-labelledby="importTipsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-secondary text-white">
                    <h5 class="modal-title" id="importTipsModalLabel">
                        <i class="bi bi-upload me-2"></i>Import Tips from CSV
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="<?= site_url('admin/tips/import') ?>" method="post" enctype="multipart/form-data">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            <strong>Before you start:</strong> Make sure your CSV file follows the correct format. Download our template to get started.
                        </div>
                        
                        <div class="mb-4">
                            <a href="<?= site_url('admin/tips/template') ?>" class="btn btn-info">
                                <i class="bi bi-download"></i> Download CSV Template
                            </a>
                        </div>
                        
                        <div class="mb-3">
                            <label for="import_file" class="form-label">Select CSV File</label>
                            <input class="form-control" type="file" id="import_file" name="import_file" accept=".csv" required>
                            <div class="form-text">Maximum file size: 10MB</div>
                        </div>
                        
                        <div class="alert alert-warning">
                            <strong>Important:</strong> The 'matches' column should be formatted as follows:
                            <br><br>
                            <code>Team A vs Team B;League Name;Prediction;1.85|Team C vs Team D;League Name;Prediction;2.10</code>
                            <br><br>
                            <small>Multiple matches are separated by pipe (|) and each match has 4 parts separated by semicolons (;)</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="bi bi-x-circle"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-upload"></i> Upload and Import
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Enhanced JavaScript functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize search functionality
    const searchInput = document.getElementById('searchTips');
    const filterTag = document.getElementById('filterTag');
    const filterCategory = document.getElementById('filterCategory');
    const filterAuthor = document.getElementById('filterAuthor');
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
    
    // Search functionality
    searchInput.addEventListener('input', filterTable);
    filterTag.addEventListener('change', filterTable);
    filterCategory.addEventListener('change', filterTable);
    filterAuthor.addEventListener('change', filterTable);
    
    // Select all functionality
    selectAllCheckbox.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.row-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBulkDeleteButton();
    });
    
    // Individual checkbox functionality
    document.querySelectorAll('.row-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkDeleteButton);
    });
    
    function filterTable() {
        const searchTerm = searchInput.value.toLowerCase();
        const tagFilter = filterTag.value;
        const categoryFilter = filterCategory.value;
        const authorFilter = filterAuthor.value;
        
        const rows = document.querySelectorAll('#tipsTable tbody tr[data-tip-id]');
        
        rows.forEach(row => {
            const title = row.cells[2].textContent.toLowerCase();
            const tag = row.cells[3].textContent.toLowerCase();
            const category = row.cells[4].textContent.toLowerCase();
            const author = row.cells[5].textContent.toLowerCase();
            
            const matchesSearch = searchTerm === '' || title.includes(searchTerm) || 
                                 category.includes(searchTerm) || author.includes(searchTerm);
            const matchesTag = tagFilter === '' || tag.includes(tagFilter);
            const matchesCategory = categoryFilter === '' || category.includes(categoryFilter.toLowerCase());
            const matchesAuthor = authorFilter === '' || author.includes(authorFilter.toLowerCase());
            
            if (matchesSearch && matchesTag && matchesCategory && matchesAuthor) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
    
    function updateBulkDeleteButton() {
        const checkedBoxes = document.querySelectorAll('.row-checkbox:checked');
        bulkDeleteBtn.disabled = checkedBoxes.length === 0;
        bulkDeleteBtn.textContent = checkedBoxes.length > 0 ? 
            `Delete Selected (${checkedBoxes.length})` : 'Delete Selected';
    }
});

function clearFilters() {
    document.getElementById('searchTips').value = '';
    document.getElementById('filterTag').value = '';
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterAuthor').value = '';
    
    // Show all rows
    const rows = document.querySelectorAll('#tipsTable tbody tr[data-tip-id]');
    rows.forEach(row => row.style.display = '');
}

function processTip(tipId) {
    if (confirm('Are you sure you want to process this tip?')) {
        // Create and submit form
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `<?= site_url('admin/process-tip/') ?>${tipId}`;
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '<?= csrf_token() ?>';
        csrfInput.value = '<?= csrf_hash() ?>';
        form.appendChild(csrfInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

function deleteTip(tipId) {
    if (confirm('Are you sure you want to delete this tip? This action cannot be undone.')) {
        // Create and submit form
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `<?= site_url('admin/delete/') ?>${tipId}`;
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '<?= csrf_token() ?>';
        csrfInput.value = '<?= csrf_hash() ?>';
        form.appendChild(csrfInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

function sendNotification(tipId) {
    if (!confirm('Are you sure you want to send a push notification for this tip to all users?')) {
        return;
    }
    
    // Show loading state
    const button = event.target.closest('.dropdown-item');
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i> Sending...';
    button.style.pointerEvents = 'none';
    button.style.opacity = '0.6';
    
    // Close dropdown menu if open
    const dropdown = button.closest('.dropdown-menu');
    if (dropdown) {
        const bsDropdown = bootstrap.Dropdown.getInstance(button.closest('.dropdown-toggle'));
        if (bsDropdown) {
            bsDropdown.hide();
        }
    }
    
    // Send AJAX request
    fetch(`<?= site_url('admin/send-notification/') ?>${tipId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({})
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error(data.message || 'Request failed');
            });
        }
        return response.json();
    })
    .then(data => {
        // Reset button state
        button.innerHTML = originalText;
        button.style.pointerEvents = '';
        button.style.opacity = '1';
        
        // Show result message
        if (data.status === 'success') {
            showNotificationAlert('success', data.message);
        } else {
            showNotificationAlert('error', data.message || 'Failed to send notification');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        
        // Reset button state
        button.innerHTML = originalText;
        button.style.pointerEvents = '';
        button.style.opacity = '1';
        
        showNotificationAlert('error', error.message || 'An error occurred while sending the notification. Please try again.');
    });
}

function showNotificationAlert(type, message) {
    // Remove existing alerts
    const existingAlerts = document.querySelectorAll('.notification-alert');
    existingAlerts.forEach(alert => alert.remove());
    
    // Create alert element
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertIcon = type === 'success' ? 'bi-check-circle' : 'bi-exclamation-triangle';
    
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert ${alertClass} alert-dismissible fade show notification-alert`;
    alertDiv.setAttribute('role', 'alert');
    alertDiv.style.position = 'fixed';
    alertDiv.style.top = '80px';
    alertDiv.style.right = '20px';
    alertDiv.style.zIndex = '9999';
    alertDiv.style.minWidth = '300px';
    alertDiv.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
    alertDiv.innerHTML = `
        <i class="bi ${alertIcon} me-2"></i>${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // Auto-dismiss after 5 seconds
    setTimeout(() => {
        if (alertDiv.parentNode) {
            const bsAlert = new bootstrap.Alert(alertDiv);
            bsAlert.close();
        }
    }, 5000);
}

function extractAllPredictions() {
    if (confirm('Are you sure you want to extract predictions from all tips? This will process all matches in all tips.')) {
        fetch('<?= base_url('api/predictions/extract-all') ?>', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert(`Success! ${data.message}`);
                // Redirect to predictions page with tip_id filter
                window.location.href = `<?= base_url('admin/predictions') ?>`;
            } else {
                alert(data.message || 'Error extracting all predictions.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while extracting all predictions.');
        });
    }
}

function bulkDelete() {
    const checkedBoxes = document.querySelectorAll('.row-checkbox:checked');
    const tipIds = Array.from(checkedBoxes).map(cb => cb.value);
    
    if (tipIds.length === 0) {
        alert('Please select at least one tip to delete.');
        return;
    }
    
    if (confirm(`Are you sure you want to delete ${tipIds.length} selected tip(s)? This action cannot be undone.`)) {
        // Create and submit form
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?= site_url('admin/bulk-delete') ?>';
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '<?= csrf_token() ?>';
        csrfInput.value = '<?= csrf_hash() ?>';
        form.appendChild(csrfInput);
        
        // Add tip IDs
        tipIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'tip_ids[]';
            input.value = id;
            form.appendChild(input);
        });
        
        document.body.appendChild(form);
        form.submit();
    }
}

function duplicateTip(tipId) {
    if (confirm('Are you sure you want to duplicate this tip?')) {
        // Create and submit form
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `<?= site_url('admin/duplicate/') ?>${tipId}`;
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '<?= csrf_token() ?>';
        csrfInput.value = '<?= csrf_hash() ?>';
        form.appendChild(csrfInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

function exportTip(tipId) {
    window.location.href = `<?= site_url('admin/export-tip/') ?>${tipId}`;
}

function exportTips() {
    const checkedBoxes = document.querySelectorAll('.row-checkbox:checked');
    const tipIds = Array.from(checkedBoxes).map(cb => cb.value);
    
    if (tipIds.length === 0) {
        // Export all tips
        window.location.href = '<?= site_url('admin/export-tips') ?>';
    } else {
        // Export selected tips
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?= site_url('admin/export-selected-tips') ?>';
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '<?= csrf_token() ?>';
        csrfInput.value = '<?= csrf_hash() ?>';
        form.appendChild(csrfInput);
        
        // Add tip IDs
        tipIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'tip_ids[]';
            input.value = id;
            form.appendChild(input);
        });
        
        document.body.appendChild(form);
        form.submit();
    }
}

function selectAll() {
    const selectAllCheckbox = document.getElementById('selectAllCheckbox');
    selectAllCheckbox.checked = !selectAllCheckbox.checked;
    selectAllCheckbox.dispatchEvent(new Event('change'));
}

// Auto-refresh functionality (optional)
function autoRefresh() {
    const refreshInterval = 300000; // 5 minutes
    setTimeout(() => {
        location.reload();
    }, refreshInterval);
}

// Uncomment the line below to enable auto-refresh
// autoRefresh();
</script>

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