<section class="analytics-dashboard">
    <div class="title-wrapper">
        <h1 class="title">Add New Sponsor</h1>
    </div>

    <div class="user-page mx-2">
        <!-- --------- ADD SPONSOR FORM --------- -->
        <div class="ringside events-modal" id="sponsorModal">
            <form id="sponsorForm" enctype="multipart/form-data">
                <div class="form-wrapper">
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="sponsorName">Sponsor Name</label>
                                <input type="text" name="name" id="sponsorName" class="form-control" placeholder="Sponsor Name" required />
                            </div>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="sponsorUrl">Sponsor URL</label>
                                <input type="url" name="url" id="sponsorUrl" class="form-control" placeholder="https://example.com" required />
                            </div>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="sponsorImage">Sponsor Image/Icon</label>
                                <input type="file" name="image" id="sponsorImage" class="form-control" accept="image/*" required />
                            </div>
                        </div>
                    </div>

                    <div class="modal-buttons mt-3">
                        <button type="submit" class="btn btn-upload">Add Sponsor</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- --------- SPONSORS TABLE --------- -->
        <div class="recent-notification mt-4">
            <div class="events-header">
                <h2 class="title">Sponsors List</h2>
            </div>

            <div class="table-responsive table-wrapper">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Icon</th>
                            <th>Name</th>
                            <th>URL</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="sponsorsTableBody">
                        <?php if (!empty($sponsors)): ?>
                            <?php foreach ($sponsors as $id => $s): ?>
                                <tr class="table-data">
                                    <td><img src="<?= $s['imageurl'] ?>" style="height:50px; width:auto;" /></td>
                                    <td><?= htmlspecialchars($s['name']) ?></td>
                                    <td><a href="<?= htmlspecialchars($s['url']) ?>" target="_blank"><?= htmlspecialchars($s['url']) ?></a></td>
                                    <td><?= date('d M Y, H:i', $s['createdDate'] / 1000) ?></td>
                                    <td>
                                        <button class="btn-secondary btn-delete" onclick="deleteSponsor('<?= $s['id'] ?>')">
                                            <img src="<?= base_url('public/admin_assets/images/delete.png'); ?>" style="width:16px;" />
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" class="text-center">No sponsors found</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="pagination-wrapper" id="sponsorsPagination"
                style="margin-top:10px; text-align:center;"></div>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const tableBody = document.getElementById("sponsorsTableBody");
        const pagination = document.getElementById("sponsorsPagination");

        const rowsPerPage = 10;
        let currentPage = 1;

        function getRows() {
            return Array.from(tableBody.querySelectorAll("tr"))
                .filter(row => !row.innerText.includes("No sponsors found"));
        }

        function renderSponsors() {
            const rows = getRows();
            pagination.innerHTML = "";

            // Hide all rows
            rows.forEach(r => r.style.display = "none");

            if (!rows.length) return;

            const totalPages = Math.ceil(rows.length / rowsPerPage);
            if (currentPage > totalPages) currentPage = 1;

            const start = (currentPage - 1) * rowsPerPage;
            const paginatedRows = rows.slice(start, start + rowsPerPage);

            paginatedRows.forEach(r => r.style.display = "");

            // -------- PREVIOUS --------
            pagination.innerHTML += `
            <button class="btn-primary" style="background-color: #000000"
                ${currentPage === 1 ? 'disabled' : ''}
                onclick="goToSponsorPage(${currentPage - 1})">
                Previous
            </button>
        `;

            // -------- CURRENT PAGE --------
            pagination.innerHTML += `
            <button class="btn-primary active" style="background-color: #000000" disabled>
                ${currentPage}
            </button>
        `;

            // -------- NEXT (COLOR INCLUDED AS REQUESTED) --------
            pagination.innerHTML += `
            <button class="btn-primary" style="background-color: #000000"
                ${currentPage === totalPages ? 'disabled' : ''}
                onclick="goToSponsorPage(${currentPage + 1})">
                Next
            </button>
        `;
        }

        function goToSponsorPage(page) {
            currentPage = page;
            renderSponsors();
        }

        window.goToSponsorPage = goToSponsorPage;

        // Initial render
        renderSponsors();

        // -------- ADD SPONSOR --------
        document.getElementById('sponsorForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);

            Swal.fire({
                title: 'Uploading...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            try {
                const response = await fetch('<?= base_url("admin/save-sponsor") ?>', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();

                Swal.close();

                if (result.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Sponsor added',
                        timer: 1500,
                        showConfirmButton: false
                    });
                    form.reset();
                    location.reload(); // reload page to show new sponsor
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: result.message || 'Something went wrong'
                    });
                }
            } catch (error) {
                Swal.close();
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Server error: ' + error.message
                });
            }
        });

        // -------- DELETE SPONSOR --------
        window.deleteSponsor = async function(id) {
            const result = await Swal.fire({
                title: 'Delete?',
                text: "Remove this sponsor?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete'
            });

            if (result.isConfirmed) {
                try {
                    const res = await fetch(`<?= base_url('admin/delete-sponsor/') ?>${id}`);
                    const data = await res.json();
                    if (data.success) location.reload();
                } catch (err) {
                    Swal.fire('Error', 'Failed to delete sponsor', 'error');
                }
            }
        }
        window.deleteSponsor = async function(id) {

            const result = await Swal.fire({
                title: 'Delete Sponsor?',
                text: 'This action cannot be undone',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete',
                cancelButtonText: 'Cancel'
            });

            if (!result.isConfirmed) return;

            Swal.fire({
                title: 'Deleting...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            try {
                const res = await fetch(`<?= base_url('admin/delete-sponsor/') ?>${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Accept': 'application/json'
                    }
                });

                const data = await res.json();
                Swal.close();

                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Deleted',
                        timer: 1200,
                        showConfirmButton: false
                    });

                    // Remove row from table
                    const row = document.querySelector(
                        `button[onclick="deleteSponsor('${id}')"]`
                    )?.closest('tr');

                    if (row) row.remove();

                    // Re-render pagination
                    renderSponsors();

                } else {
                    Swal.fire('Error', data.message || 'Delete failed', 'error');
                }

            } catch (err) {
                Swal.close();
                Swal.fire('Error', 'Server error', 'error');
            }
        };
    });
</script>
<style>
    .pagination-wrapper button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
</style>