<section class="analytics-dashboard">
    <div class="title-wrapper">
        <h1 class="title">Add/Scratch Request</h1>
    </div>

    <div class="user-page">
        <div class="events-page">

            <!-- Top Bar with Tabs + Filter -->
            <div class="top-bar">
                <div class="tab-buttons" style="margin-bottom: 2px;">
                    <button class="tab-btn active" data-tab="add">Add</button>
                    <button class="tab-btn" data-tab="scratch">Scratch</button>
                </div>

                <div class="filter-wrapper d-flex align-items-center" style="gap: 10px;">
                    <select id="eventFilter" class="form-select filter-select" style="min-width: 200px;">
                        <option value="all">All Events</option>
                        <?php foreach ($event_names as $name): ?>
                            <option value="<?= htmlspecialchars($name); ?>"><?= htmlspecialchars($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- ADD SCRATCH SECTION (scratchType = 'Add') -->
            <div class="events-wrapper section" id="addSection">
                <div class="d-flex justify-content-between align-items-center mb-3 events-header">
                    <h2 class="title">Add Scratch</h2>
                </div>

                <div class="table-responsive table-wrapper">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Rider Name</th>
                                <th>Horse Name</th>
                                <th>Class Number</th>
                                <th>Back Number</th>
                                <th>Event Name</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>

                        <tbody id="addTableBody">
                            <?php if (!empty($add_scratch)): ?>
                                <?php foreach ($add_scratch as $id => $item): ?>
                                    <?php
                                    $formattedDate = isset($item['createdDate']) ? date('M d, Y H:i', $item['createdDate'] / 1000) : 'N/A';
                                    $status = $item['scratchStatus'] ?? 'New';
                                    ?>
                                    <tr class="scratch-row clickable-row"
                                        data-event="<?= htmlspecialchars($item['event_name'] ?? 'N/A'); ?>"
                                        onclick="viewScratchDetails(
                                        '<?= addslashes($item['riderName']); ?>', 
                                        '<?= addslashes($item['horseName']); ?>', 
                                        '<?= addslashes($item['classNumber']); ?>', 
                                        '<?= addslashes($item['backNumber']); ?>', 
                                        'Add', 
                                        '<?= addslashes($item['event_name'] ?? 'N/A'); ?>', 
                                        '<?= $status; ?>', 
                                        '<?= $formattedDate; ?>', 
                                        '<?= addslashes($item['comment'] ?? ''); ?>'
                                    )">
                                        <td>
                                            <div class="user-info">
                                                <img src="<?= base_url('public/admin_assets/images/users-profile.png'); ?>" alt="">
                                                <span><?= htmlspecialchars($item['riderName']); ?></span>
                                            </div>
                                        </td>
                                        <td><?= htmlspecialchars($item['horseName']); ?></td>
                                        <td class="text-truncate" style="max-width: 150px;">
                                            <?= htmlspecialchars($item['classNumber']); ?>
                                        </td>
                                        <td><?= htmlspecialchars($item['backNumber']); ?></td>
                                        <td><strong><?= htmlspecialchars($item['event_name'] ?? 'N/A'); ?></strong></td>
                                        <td>
                                            <span class="badge <?= $status === 'Active' ? 'bg-success' : ($status === 'Approved' ? 'bg-info' : 'bg-secondary') ?>">
                                                <?= htmlspecialchars($status); ?>
                                            </span>
                                        </td>
                                        <td class="date"><?= $formattedDate; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center">No Add scratch requests found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div class="pagination-wrapper" id="addPagination" style="margin-top:10px; text-align:center;"></div>

            </div>

            <!-- SCRATCH SECTION (scratchType = 'Scratch') -->
            <div class="events-schedule section" id="scratchSection" style="display:none;">
                <div class="events-header">
                    <h2 class="title">Scratch</h2>
                </div>

                <div class="table-responsive table-wrapper">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Rider Name</th>
                                <th>Horse Name</th>
                                <th>Class Number</th>
                                <th>Back Number</th>
                                <th>Event Name</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>

                        <tbody id="scratchTableBody">
                            <?php if (!empty($scratch_items)): ?>
                                <?php foreach ($scratch_items as $id => $item): ?>
                                    <?php
                                    $formattedDate = isset($item['createdDate']) ? date('M d, Y H:i', $item['createdDate'] / 1000) : 'N/A';
                                    $status = $item['scratchStatus'] ?? 'New';
                                    ?>
                                    <tr class="scratch-row clickable-row"
                                        data-event="<?= htmlspecialchars($item['event_name'] ?? 'N/A'); ?>"
                                        onclick="viewScratchDetails(
                                        '<?= addslashes($item['riderName']); ?>', 
                                        '<?= addslashes($item['horseName']); ?>', 
                                        '<?= addslashes($item['classNumber']); ?>', 
                                        '<?= addslashes($item['backNumber']); ?>', 
                                        'Scratch', 
                                        '<?= addslashes($item['event_name'] ?? 'N/A'); ?>', 
                                        '<?= $status; ?>', 
                                        '<?= $formattedDate; ?>', 
                                        '<?= addslashes($item['comment'] ?? ''); ?>'
                                    )">
                                        <td>
                                            <div class="user-info">
                                                <img src="<?= base_url('public/admin_assets/images/users-profile.png'); ?>" alt="">
                                                <span><?= htmlspecialchars($item['riderName']); ?></span>
                                            </div>
                                        </td>
                                        <td><?= htmlspecialchars($item['horseName']); ?></td>
                                        <td class="text-truncate" style="max-width: 150px;">
                                            <?= htmlspecialchars($item['classNumber']); ?>
                                        </td>
                                        <td><?= htmlspecialchars($item['backNumber']); ?></td>
                                        <td><strong><?= htmlspecialchars($item['event_name'] ?? 'N/A'); ?></strong></td>
                                        <td>
                                            <span class="badge <?= $status === 'Active' ? 'bg-success' : ($status === 'Approved' ? 'bg-info' : 'bg-secondary') ?>">
                                                <?= htmlspecialchars($status); ?>
                                            </span>
                                        </td>
                                        <td class="date"><?= $formattedDate; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center">No Scratch requests found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div class="pagination-wrapper" id="scratchPagination" style="margin-top:10px; text-align:center;"></div>

            </div>

        </div>
    </div>
</section>

<!-- Scratch Details Modal (Single modal for both types) -->
<div id="scratchDetailsModal" class="custom-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="title">Scratch Details</h3>
            <span class="close-modal" onclick="closeScratchModal()">&times;</span>
        </div>
        <div class="modal-body">
            <div class="modal-grid">
                <div class="detail-group">
                    <label>Type:</label>
                    <p id="scratchType" class="type-badge"></p>
                </div>
                <div class="detail-group">
                    <label>Rider Name:</label>
                    <p id="scratchRiderName"></p>
                </div>
                <div class="detail-group">
                    <label>Horse Name:</label>
                    <p id="scratchHorseName"></p>
                </div>
                <div class="detail-group">
                    <label>Class Number:</label>
                    <p id="scratchClassNumber"></p>
                </div>
                <div class="detail-group">
                    <label>Back Number:</label>
                    <p id="scratchBackNumber"></p>
                </div>
                <div class="detail-group">
                    <label>Event Name:</label>
                    <p id="scratchEventName"></p>
                </div>
                <div class="detail-group">
                    <label>Status:</label>
                    <p id="scratchStatus"></p>
                </div>
                <div class="detail-group">
                    <label>Date & Time:</label>
                    <p id="scratchDateTime"></p>
                </div>
            </div>
            <hr>
            <div class="detail-group">
                <label>Comment:</label>
                <div class="scrollable-message" id="scratchComment"></div>
            </div>
        </div>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', () => {
        // -------------------- DATA --------------------
        let addScratchData = <?php echo json_encode($add_scratch ?? []); ?>;
        let scratchData = <?php echo json_encode($scratch_items ?? []); ?>;
        let selectedFilter = "all";

        // -------------------- TAB SWITCH --------------------
        document.querySelectorAll(".tab-btn").forEach(btn => {
            btn.addEventListener("click", () => {
                document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active"));
                btn.classList.add("active");

                document.getElementById("addSection").style.display = btn.dataset.tab === "add" ? "block" : "none";
                document.getElementById("scratchSection").style.display = btn.dataset.tab === "scratch" ? "block" : "none";
            });
        });

        // -------------------- FILTER --------------------
        const eventFilter = document.getElementById('eventFilter');

        eventFilter.addEventListener('change', () => {
            currentAddPage = 1;
            currentScratchPage = 1;

            renderTableWithPagination('addTableBody', 'addPagination', currentAddPage);
            renderTableWithPagination('scratchTableBody', 'scratchPagination', currentScratchPage);
        });


        function applyFilters() {
            filterAddScratch();
            filterScratchItems();
        }

        function filterAddScratch() {
            const rows = document.querySelectorAll('#addTableBody .scratch-row');

            rows.forEach(row => {
                const eventName = row.getAttribute('data-event');
                const matchesFilter = (selectedFilter === 'all' || eventName === selectedFilter);
                row.style.display = matchesFilter ? '' : 'none';
            });
        }

        function filterScratchItems() {
            const rows = document.querySelectorAll('#scratchTableBody .scratch-row');

            rows.forEach(row => {
                const eventName = row.getAttribute('data-event');
                const matchesFilter = (selectedFilter === 'all' || eventName === selectedFilter);
                row.style.display = matchesFilter ? '' : 'none';
            });
        }
        const itemsPerPage = 10;

        let currentAddPage = 1;
        let currentScratchPage = 1;

        function renderTableWithPagination(tbodyId, paginationId, currentPage) {
            if (!currentPage || currentPage < 1) currentPage = 1;

            const tbody = document.getElementById(tbodyId);
            const pagination = document.getElementById(paginationId);

            const allRows = Array.from(tbody.querySelectorAll('.scratch-row'));
            const filteredRows = allRows.filter(row => {
                const eventName = row.getAttribute('data-event');
                return selectedFilter === 'all' || eventName === selectedFilter;
            });

            const totalPages = Math.ceil(filteredRows.length / itemsPerPage);
            if (currentPage > totalPages) currentPage = totalPages || 1; // fallback if no rows

            // hide all rows
            allRows.forEach(row => row.style.display = 'none');

            // show rows for current page
            const start = (currentPage - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            filteredRows.slice(start, end).forEach(row => row.style.display = '');

            // build pagination buttons
            pagination.innerHTML = `
                    <button class="btn-primary" style="background-color:#000" ${currentPage === 1 ? 'disabled' : ''}
                        onclick="goToPage('${tbodyId}', ${currentPage - 1})">Previous</button>
                    <button class="btn-primary active" style="background-color:#000" disabled>${currentPage}</button>
                    <button class="btn-primary" style="background-color:#000" ${currentPage === totalPages ? 'disabled' : ''}
                        onclick="goToPage('${tbodyId}', ${currentPage + 1})">Next</button>
                `;
        }



        window.goToPage = function(tbodyId, page) {
            if (tbodyId === 'addTableBody') currentAddPage = page;
            if (tbodyId === 'scratchTableBody') currentScratchPage = page;

            renderTableWithPagination(
                tbodyId,
                tbodyId === 'addTableBody' ? 'addPagination' : 'scratchPagination',
                tbodyId === 'addTableBody' ? currentAddPage : currentScratchPage
            );
        };


        // Initial render
        // Initial render
        renderTableWithPagination('addTableBody', 'addPagination', currentAddPage);
        renderTableWithPagination('scratchTableBody', 'scratchPagination', currentScratchPage);

        // Re-render on filter change
        const filterSelect = document.getElementById('eventFilter');
        filterSelect.addEventListener('change', () => {
            currentAddPage = 1;
            currentScratchPage = 1;
            // Initial render
            renderTableWithPagination('addTableBody', 'addPagination', currentAddPage);
            renderTableWithPagination('scratchTableBody', 'scratchPagination', currentScratchPage);

        });
    });

    // View Scratch Details Modal
    function viewScratchDetails(riderName, horseName, classNumber, backNumber, type, eventName, status, dateTime, comment) {
        // Set the type with badge styling
        const typeElement = document.getElementById('scratchType');
        typeElement.textContent = type;
        typeElement.setAttribute('data-type', type);

        // Set other details
        document.getElementById('scratchRiderName').textContent = riderName || 'N/A';
        document.getElementById('scratchHorseName').textContent = horseName || 'N/A';
        document.getElementById('scratchClassNumber').textContent = classNumber || 'N/A';
        document.getElementById('scratchBackNumber').textContent = backNumber || 'N/A';
        document.getElementById('scratchEventName').textContent = eventName || 'N/A';
        document.getElementById('scratchStatus').textContent = status || 'New';
        document.getElementById('scratchDateTime').textContent = dateTime || 'N/A';
        document.getElementById('scratchComment').textContent = comment || 'No comment';

        document.getElementById('scratchDetailsModal').style.display = 'block';
    }

    function closeScratchModal() {
        document.getElementById('scratchDetailsModal').style.display = 'none';
    }

    // Close modal if user clicks outside
    window.onclick = function(event) {
        const scratchModal = document.getElementById('scratchDetailsModal');
        if (event.target == scratchModal) {
            scratchModal.style.display = 'none';
        }
    }
</script>
<style>
    .pagination-wrapper button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .clickable-row {
        cursor: pointer;
        transition: background-color 0.2s ease;
    }

    .clickable-row:hover {
        background-color: rgba(0, 0, 0, 0.05) !important;
    }

    /* Two-column grid inside modal for Scratch */
    .modal-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px 20px;
    }

    /* Type badge styling */
    .type-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-weight: 600;
        font-size: 14px;
    }

    .type-badge[data-type="Add"] {
        background: rgba(40, 167, 69, 0.2);
        color: #155724;
        border: 1px solid rgba(40, 167, 69, 0.3);
    }

    .type-badge[data-type="Scratch"] {
        background: rgba(220, 53, 69, 0.2);
        color: #721c24;
        border: 1px solid rgba(220, 53, 69, 0.3);
    }

    /* Modal Styling */
    .custom-modal {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(5px);
    }

    .modal-content {
        background: linear-gradient(90deg, #ead97c 0%, #d2b767 47%, #c3a259 100%);
        margin: 5% auto;
        padding: 20px;
        border-radius: 20px;
        width: 60%;
        max-width: 600px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        animation: slideIn 0.3s ease-out;
    }

    @keyframes slideIn {
        from {
            transform: translateY(-50px);
            opacity: 0;
        }

        to {
            transform: translateY(0);
            opacity: 1;
        }
    }

    /* Modal Header */
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ddd;
        padding-bottom: 15px;
        margin-bottom: 20px;
    }

    .modal-header .title {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
        color: #5D5D5D;
    }

    .close-modal {
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        color: #5D5D5D;
        transition: color 0.2s;
    }

    .close-modal:hover {
        color: #D2B767;
    }

    /* Detail Groups */
    .detail-group {
        margin-bottom: 15px;
    }

    .detail-group label {
        display: block;
        font-weight: 600;
        color: #5D5D5D;
        font-size: 14px;
        margin-bottom: 5px;
    }

    .detail-group p {
        font-size: 16px;
        color: #222;
        margin: 0;
    }

    .detail-group hr {
        border: none;
        border-top: 1px solid #ddd;
        margin: 15px 0;
    }

    /* Scrollable Message Box */
    .scrollable-message {
        background: rgba(255, 255, 255, 0.3);
        padding: 20px;
        border-radius: 12px;
        max-height: 300px;
        overflow-y: auto;
        font-size: 16px;
        line-height: 1.6;
        white-space: pre-wrap;
        color: #000;
    }

    /* Custom Scrollbar */
    .scrollable-message::-webkit-scrollbar {
        width: 6px;
    }

    .scrollable-message::-webkit-scrollbar-thumb {
        background: #D2B767;
        border-radius: 10px;
    }
</style>