{% extends 'admin/base.html' %}

{% block title %}Billing{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1 class="page-title">Billing</h1>
        <p class="page-subtitle">Review all package subscription payments across companies.</p>
    </div>
</div>

{% if error %}
<div class="alert alert-danger">{{ error }}</div>
{% endif %}

<div class="card">
    <!-- <div class="card-header">
        <div>
            <h2 class="card-title">Payment History</h2>
            <p class="card-subtitle">Each subscription lasts 30 days from the start date.</p>
        </div>
    </div> -->
    <div class="card-body">
        {% if payments %}
        <div class="filters-toolbar">
            <div class="filter-input">
                <label for="filter-company">Company</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-building"></i>
                    <input type="text" id="filter-company" placeholder="Search company">
                </div>
            </div>
            <div class="filter-input">
                <label for="filter-email">Email</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-envelope"></i>
                    <input type="text" id="filter-email" placeholder="Search email">
                </div>
            </div>
            <div class="filter-input">
                <label for="filter-package">Package</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-box"></i>
                    <input type="text" id="filter-package" placeholder="Search package">
                </div>
            </div>
            <div class="filter-input date-range">
                <label>Date range</label>
                <div class="date-range-inputs">
                    <input type="date" id="filter-start">
                    <span class="separator">→</span>
                    <input type="date" id="filter-end">
                </div>
            </div>
            <div class="filter-action">
                <button id="refreshCompanies" class="btn btn-secondary">
                    <i class="fa-light fa-rotate"></i>
                    <span>Refresh</span>
                </button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table" id="payments-table">
                <thead>
                    <tr>
                        <th>Company</th>
                        <th>Email</th>
                        <th>Package</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Started</th>
                        <th>Expires</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    {% for payment in payments %}
                    <tr>

                        <td data-company>{{ payment[1] }}</td>
                        <td data-email>{{ payment[2] }}</td>
                        <td data-package>{{ payment[3] }}</td>
                        <td>{{ payment[4] }} {{ payment[5] }}</td>
                        <td>
                            <span class="status status-{{ payment[6] }}">{{ payment[6]|capitalize }}</span>
                        </td>
                        <td>{{ payment[7].strftime('%Y-%m-%d %H:%M') if payment[7] else '—' }}</td>
                        <td>{{ payment[8].strftime('%Y-%m-%d %H:%M') if payment[8] else '—' }}</td>
                        <td>{{ payment[9].strftime('%Y-%m-%d %H:%M') if payment[9] else '—' }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <div class=" flex-wrap gap-2"
            style="    display: flex;align-items: center;justify-content: space-between; margin-top: 10px;">
            <div id="payments-count" class="text-muted"></div>
            <div class="btn-group" role="group" aria-label="Pagination" id="payments-pagination">
                <button type="button" class="btn btn-outline-secondary btn-sm" id="payments-prev">Previous</button>
                <span class="btn btn-sm btn-light" id="payments-page-label">Page 1</span>
                <button type="button" class="btn btn-outline-secondary btn-sm" id="payments-next">Next</button>
            </div>
        </div>
        {% else %}
        <div class="empty-state">
            <i class="fa-light fa-inbox"></i>
            <p>No payments recorded yet.</p>
        </div>
        {% endif %}
    </div>
</div>

{% endblock %}

{% block extra_js %}
{% if payments %}
<script>
    (function () {
        const paymentRows = Array.from(document.querySelectorAll('#payments-table tbody tr')).map(row => {
            const cells = row.querySelectorAll('td');

            const getDateInfo = (text) => {
                const trimmed = (text || '').trim();
                if (!trimmed || trimmed === '—') {
                    return { text: '—', date: null };
                }
                const parsed = Date.parse(trimmed.replace(/-/g, '/'));
                if (!isNaN(parsed)) {
                    return { text: trimmed, date: new Date(parsed) };
                }
                return { text: trimmed, date: null };
            };

            const started = getDateInfo(cells[5]?.textContent);
            const expires = getDateInfo(cells[6]?.textContent);
            const created = getDateInfo(cells[7]?.textContent);

            return {
                company: cells[0]?.textContent?.trim() || '',
                email: cells[1]?.textContent?.trim() || '',
                package: cells[2]?.textContent?.trim() || '',
                amount: cells[3]?.textContent?.trim() || '',
                status: (cells[4]?.textContent || '').trim(),
                started,
                expires,
                created,
            };
        });
        const rowsPerPage = 10;
        let currentPage = 1;

        const tableBody = document.querySelector('#payments-table tbody');
        const pageLabel = document.getElementById('payments-page-label');
        const prevBtn = document.getElementById('payments-prev');
        const nextBtn = document.getElementById('payments-next');
        const countLabel = document.getElementById('payments-count');
        const refreshButton = document.getElementById('refreshCompanies');
        const companyInput = document.getElementById('filter-company');
        const emailInput = document.getElementById('filter-email');
        const packageInput = document.getElementById('filter-package');
        const startInput = document.getElementById('filter-start');
        const endInput = document.getElementById('filter-end');

        function getFilteredPayments() {
            const companyFilter = companyInput.value.trim().toLowerCase();
            const emailFilter = emailInput.value.trim().toLowerCase();
            const packageFilter = packageInput.value.trim().toLowerCase();
            let startDate = startInput && startInput.value ? new Date(startInput.value) : null;
            let endDate = endInput && endInput.value ? new Date(endInput.value) : null;
            if (startDate && endDate && startDate > endDate) {
                const temp = startDate;
                startDate = endDate;
                endDate = temp;
            }
            if (endDate) {
                endDate.setHours(23, 59, 59, 999);
            }

            return paymentRows.filter(payment => {
                const company = (payment.company || '').toLowerCase();
                const email = (payment.email || '').toLowerCase();
                const pkg = (payment.package || '').toLowerCase();
                const textMatch = company.includes(companyFilter)
                    && email.includes(emailFilter)
                    && pkg.includes(packageFilter);

                let dateMatch = true;
                const createdDate = payment.created.date;
                if (startDate && createdDate) {
                    dateMatch = dateMatch && createdDate >= startDate;
                }
                if (endDate && createdDate) {
                    dateMatch = dateMatch && createdDate <= endDate;
                }

                return textMatch && dateMatch;
            });
        }

        function formatDate(value) {
            if (!value || value === '—') return '—';
            try {
                const date = new Date(value.replace(/-/g, '/'));
                if (!isNaN(date.getTime())) {
                    return date.toLocaleString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
                }
            } catch (e) {
                // fall through
            }
            return value;
        }

        function renderTable() {
            const filtered = getFilteredPayments();
            const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
            if (currentPage > totalPages) currentPage = totalPages;
            const start = (currentPage - 1) * rowsPerPage;
            const end = start + rowsPerPage;
            const pageItems = filtered.slice(start, end);

            tableBody.innerHTML = pageItems.map(payment => `
                <tr>
                    <td>${payment.company}</td>
                    <td>${payment.email}</td>
                    <td>${payment.package}</td>
                    <td>${payment.amount}</td>
                    <td><span class="status status-${payment.status || ''}">${(payment.status || '').charAt(0).toUpperCase() + (payment.status || '').slice(1)}</span></td>
                    <td>${formatDate(payment.started.text)}</td>
                    <td>${formatDate(payment.expires.text)}</td>
                    <td>${formatDate(payment.created.text)}</td>
                </tr>
            `).join('');

            pageLabel.textContent = `Page ${currentPage} of ${totalPages}`;
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;
            countLabel.textContent = `${filtered.length} payment${filtered.length === 1 ? '' : 's'} found`;
        }

        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage -= 1;
                renderTable();
            }
        });

        nextBtn.addEventListener('click', () => {
            const filtered = getFilteredPayments();
            const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
            if (currentPage < totalPages) {
                currentPage += 1;
                renderTable();
            }
        });

        [companyInput, emailInput, packageInput].forEach(input => {
            input.addEventListener('input', () => {
                currentPage = 1;
                renderTable();
            });
        });

        if (startInput) {
            startInput.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        }

        if (endInput) {
            endInput.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        }

        refreshButton.addEventListener('click', () => window.location.reload());

        renderTable();
    })();
</script>
{% endif %}
{% endblock %}
{% block extra_css %}
<style>
    .status-Succeeded {
        background: #22c55e;
    }

    .filters-toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        gap: 16px;
        padding: 16px 20px;
        background: #f8fafc;
        border-radius: 16px;
        border: 1px solid rgba(148, 163, 184, 0.18);
    }

    .filters-toolbar .filter-input {
        display: flex;
        flex-direction: column;
        gap: 6px;
        flex: 1 1 220px;
        min-width: 180px;
    }

    .filters-toolbar .filter-input label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
        font-weight: 600;
    }

    .filters-toolbar .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .filters-toolbar .input-wrapper:focus-within {
        border-color: #2563eb;
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.18);
    }

    .filters-toolbar .input-wrapper i {
        margin-left: 14px;
        color: #94a3b8;
        font-size: 16px;
    }

    .filters-toolbar .input-wrapper input {
        flex: 1;
        border: none;
        background: transparent;
        padding: 12px 16px;
        font-size: 15px;
        color: #0f172a;
        outline: none;
    }

    .filters-toolbar .input-wrapper input::placeholder {
        color: #94a3b8;
    }

    .filters-toolbar .date-range .date-range-inputs {
        display: flex;
        align-items: center;
        gap: 10px;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        padding: 8px 12px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        width: fit-content;
    }
    .filters-toolbar .date-range {
        flex: 1 1 260px;
    }

    .filters-toolbar .date-range-inputs input[type="date"] {
        border: none;
        background: transparent;
        padding: 6px 8px;
        font-size: 14px;
        color: #0f172a;
        outline: none;
    }

    .filters-toolbar .date-range-inputs .separator {
        color: #94a3b8;
        font-size: 14px;
    }

    .filters-toolbar .date-range .date-range-inputs:focus-within {
        border-color: #2563eb;
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.18);
    }

    @media (max-width: 768px) {
        .filters-toolbar {
            flex-direction: column;
            padding: 12px;
        }
    }
</style>
{% endblock %}