// Split from public/app.js v1.7.7. Loaded by public/index.html.
function paymentsView() {
  const studentPayments = (state.data.payments || []).filter((payment) => payment.status !== 'cancelled');
  const teacherPayments = state.data.teacherPayments || [];
  const employeePayments = state.data.employeePayments || [];
  const studentCollection = studentPayments.reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
  const studentDue = (state.data.students || []).reduce((sum, student) => sum + Number(student.finance?.totalDue || 0), 0);
  const teacherPaid = teacherPayments.reduce((sum, payment) => sum + Number(payment.paid ?? payment.paidAmount ?? 0), 0);
  const teacherDue = teacherPayments.reduce((sum, payment) => sum + Number(payment.due ?? payment.dueAmount ?? 0), 0);
  const employeePaid = employeePayments.reduce((sum, payment) => sum + Number(payment.paid ?? payment.paidAmount ?? 0), 0);
  const employeeDue = employeePayments.reduce((sum, payment) => sum + Number(payment.due ?? payment.dueAmount ?? 0), 0);
  const referenceDue = (state.data.referencePayments || []).reduce((sum, payment) => sum + Number(payment.due || 0), 0);
  const otherExpense = (state.data.otherPayments || []).reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
  const shareholderBalance = (state.data.shareholders || []).reduce((sum, item) => sum + Number(item.sessionBalance || 0), 0);
  const todayKey = new Date().toISOString().slice(0, 10);
  const todayCollection = studentPayments
    .filter((payment) => String(payment.paidAt || payment.createdAt || '').slice(0, 10) === todayKey)
    .reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
  const totalDue = studentDue + teacherDue + employeeDue + referenceDue;
  const totalExpense = teacherPaid + employeePaid + otherExpense;
  const netBalance = studentCollection - totalExpense;
  const section = state.paymentSection || 'overview';
  const paymentTabs = [
    ['overview', 'Overview'],
    ['students', 'Student'],
    ['teachers', 'Teacher'],
    ['employees', 'Employee'],
    ['references', 'Reference'],
    ['others', 'Others'],
    ['shareholders', 'Shareholders'],
    ['finance', 'Reports'],
  ];
  return html`
    <section class="panel">
      <div class="panel-header">
        <div>
          <h1>Payments</h1>
          <p class="muted">Student collections, staff payments, expenses, dues and reports in one finance workspace.</p>
        </div>
      </div>
      <div class="section-tabs payment-tabs">
        ${paymentTabs.map(([key, label]) => `<button class="section-tab ${section === key ? 'active' : ''}" data-action="set-payment-section" data-section="${key}">${label}</button>`).join('')}
      </div>
    </section>
    ${section === 'students' ? studentPaymentsView() : section === 'teachers' ? teacherPaymentsView(true) : section === 'employees' ? employeePaymentsView() : section === 'references' ? referencePaymentsView() : section === 'others' ? otherPaymentsView() : section === 'shareholders' ? shareholdersView() : section === 'finance' ? financeReportView() : html`
      <section class="panel finance-overview-panel">
        <div class="finance-hero-grid">
          <div class="finance-hero-card primary">
            <span>Net Balance</span>
            <strong>${formatMoney(netBalance)}</strong>
            <small>Collection minus teacher, employee and other expenses.</small>
          </div>
          <div class="finance-hero-card">
            <span>Today Collection</span>
            <strong>${formatMoney(todayCollection)}</strong>
            <small>Student payments received today.</small>
          </div>
          <div class="finance-hero-card danger">
            <span>Total Due</span>
            <strong>${formatMoney(totalDue)}</strong>
            <small>Student, teacher, employee and reference due.</small>
          </div>
          <div class="finance-hero-card warning">
            <span>Total Expense</span>
            <strong>${formatMoney(totalExpense)}</strong>
            <small>Teacher, employee and other payments.</small>
          </div>
        </div>
        <div class="finance-summary compact-finance-summary">
          ${financeCard('Student Collection', studentCollection)}
          ${financeCard('Student Due', studentDue, 'danger')}
          ${financeCard('Teacher Paid', teacherPaid)}
          ${financeCard('Teacher Due', teacherDue, 'danger')}
          ${financeCard('Employee Paid', employeePaid)}
          ${financeCard('Employee Due', employeeDue, 'danger')}
          ${financeCard('Reference Due', referenceDue, 'danger')}
          ${financeCard('Other Expenses', otherExpense, 'danger')}
          ${financeCard('Shareholder Balance', shareholderBalance, shareholderBalance < 0 ? 'danger' : 'success')}
        </div>
      </section>
      <section class="panel">
        <div class="panel-header"><div><h2>Recent Payment History</h2><p class="muted">Latest student, teacher and employee payment entries.</p></div></div>
        <div class="table-wrap"><table class="smart-table"><thead><tr><th>Type</th><th>Name</th><th>Month / Course</th><th>Paid</th><th>Due</th><th>Date</th></tr></thead><tbody>
          ${[
            ...studentPayments.slice(0, 8).map((payment) => `<tr><td><span class="badge success">Student</span></td><td>${escapeHtml(payment.studentName)}</td><td>${escapeHtml(payment.courseName)}</td><td>${formatMoney(payment.amount)}</td><td>-</td><td>${formatDate(payment.paidAt)}</td></tr>`),
            ...teacherPayments.slice(0, 8).map((payment) => `<tr><td><span class="badge warning">Teacher</span></td><td>${escapeHtml(payment.teacherName || managerName(payment.teacherId))}</td><td>${escapeHtml(payment.month || '-')} / ${escapeHtml(payment.courseName || courseName(payment.courseId))}</td><td>${formatMoney(payment.paid ?? payment.paidAmount)}</td><td>${formatMoney(payment.due ?? payment.dueAmount)}</td><td>${formatDate(payment.paidAt)}</td></tr>`),
            ...employeePayments.slice(0, 8).map((payment) => `<tr><td><span class="badge">Employee</span></td><td>${escapeHtml(payment.employeeName || '-')}</td><td>${escapeHtml(payment.month || '-')}</td><td>${formatMoney(payment.paid ?? payment.paidAmount)}</td><td>${formatMoney(payment.due ?? payment.dueAmount)}</td><td>${formatDate(payment.paidAt)}</td></tr>`),
          ].join('') || '<tr><td colspan="6">No payment history yet.</td></tr>'}
        </tbody></table></div>
      </section>
      <section class="panel">
        <div class="panel-header"><div><h2>Quick Finance Actions</h2><p class="muted">Jump to the right payment register or export area.</p></div></div>
        <div class="quick-action-grid">
          <button class="quick-action-card" data-action="set-payment-section" data-section="students"><strong>Receive Student Fee</strong><span>Collection, due and receipt</span></button>
          <button class="quick-action-card" data-action="set-payment-section" data-section="teachers"><strong>Teacher Payment</strong><span>Class date and subject payments</span></button>
          <button class="quick-action-card" data-action="set-payment-section" data-section="employees"><strong>Employee Salary</strong><span>Salary, allowance and advance</span></button>
          <button class="quick-action-card" data-action="set-payment-section" data-section="others"><strong>Other Expense</strong><span>Rent, snacks, transport and bills</span></button>
          <button class="quick-action-card" data-action="set-payment-section" data-section="references"><strong>Reference Commission</strong><span>Referral payment due/paid</span></button>
          <button class="quick-action-card" data-action="set-payment-section" data-section="finance"><strong>Finance Reports</strong><span>Income, expense and export</span></button>
        </div>
      </section>
    `}
  `;
}

function financeReportView() {
  const sessionId = state.data.activeSession?.id || '';
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Income & Expense Report</h2><p class="muted">Download the full institute income and expense details in one click.</p></div></div>
      <div class="actions">
        <a class="btn secondary small" href="/api/export/session-finance.xlsx?sessionId=${encodeURIComponent(sessionId)}" target="_blank">Download Excel</a>
        <a class="btn secondary small" href="/api/export/session-finance.pdf?sessionId=${encodeURIComponent(sessionId)}" target="_blank">Download PDF</a>
        <a class="btn secondary small" href="/api/export/session-finance.csv?sessionId=${encodeURIComponent(sessionId)}" target="_blank">Download CSV</a>
      </div>
    </section>
  `;
}

function shareholdersView() {
  const shareholders = state.data.shareholders || [];
  const entries = state.data.shareholderLedger || [];
  const active = shareholders.filter((item) => item.status !== 'inactive');
  const totalShare = active.reduce((sum, item) => sum + Number(item.sharePercentage || 0), 0);
  const totalBalance = shareholders.reduce((sum, item) => sum + Number(item.sessionBalance || 0), 0);
  const withdrawals = entries.filter((item) => item.type === 'withdrawal').reduce((sum, item) => sum + Math.abs(Number(item.amount || 0)), 0);
  const reportFilters = currentReportFilters('shareholder-ledger');
  const selectedShareholder = reportFilters.shareholderId || '';
  const filteredEntries = entries.filter((entry) => {
    if (selectedShareholder && entry.shareholderId !== selectedShareholder) return false;
    if (reportFilters.type && entry.type !== reportFilters.type) return false;
    const day = String(entry.entryDate || entry.createdAt || '').slice(0, 10);
    if (reportFilters.from && day < reportFilters.from) return false;
    if (reportFilters.to && day > reportFilters.to) return false;
    return true;
  });
  const typeOptions = Object.entries(shareholderLedgerLabels).map(([value, label]) => `<option value="${value}">${escapeHtml(label)}</option>`).join('');
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Shareholders</h2><p class="muted">Track reference commission, share income, withdrawals, and session expenses in one ledger.</p></div></div>
      <div class="finance-summary">
        ${metricCard('Active Shareholders', String(active.length))}
        ${metricCard('Total Share', String(totalShare), '%')}
        ${financeCard('Session Balance', totalBalance, totalBalance < 0 ? 'danger' : '')}
        ${financeCard('Withdrawn / Advance', withdrawals, 'danger')}
      </div>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Add Shareholder</h2><p class="muted">Opening balance is added to current session ledger once.</p></div></div>
      <form class="form-grid" data-action="add-shareholder">
        <div class="grid-3">
          <label class="field"><span>Name *</span><input name="name" required placeholder="Shareholder name"></label>
          <label class="field"><span>Mobile</span><input name="mobile" placeholder="01XXXXXXXXX"></label>
          <label class="field"><span>Email</span><input name="email" type="email" placeholder="name@example.com"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Share %</span><input name="sharePercentage" type="number" min="0" max="100" step="0.01" placeholder="0"></label>
          <label class="field"><span>Opening Balance</span><input name="openingBalance" type="number" step="0.01" placeholder="0"></label>
          <label class="field"><span>Status</span><select name="status"><option value="active">Active</option><option value="inactive">Inactive</option></select></label>
        </div>
        <label class="field"><span>Note</span><input name="note" placeholder="Agreement, role, or session note"></label>
        <button class="btn" type="submit">Save Shareholder</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header">
        <div><h2>Ledger Entry</h2><p class="muted">Use withdrawal for cash taken, paid for institute for money spent by shareholder.</p></div>
        <div class="actions">
          <button class="btn secondary small" type="button" data-action="generate-shareholder-profit">Generate Session Profit Share</button>
          <a class="btn secondary small" href="/api/export/shareholder-session-closing.xlsx" target="_blank">Closing Excel</a>
          <a class="btn secondary small" href="/api/export/shareholder-session-closing.pdf" target="_blank">Closing PDF</a>
        </div>
      </div>
      <form class="form-grid" data-action="add-shareholder-ledger">
        <div class="grid-3">
          <label class="field"><span>Shareholder *</span><select name="shareholderId" required><option value="">Select shareholder</option>${shareholders.map((item) => `<option value="${item.id}">${escapeHtml(item.name)} (${escapeHtml(item.mobile || '-')})</option>`).join('')}</select></label>
          <label class="field"><span>Type *</span><select name="type" required>${typeOptions}</select></label>
          <label class="field"><span>Amount *</span><input name="amount" type="number" min="0.01" step="0.01" required></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
          <label class="field"><span>Date</span><input name="entryDate" type="datetime-local"></label>
          <label class="field"><span>Reference</span><input name="reference" placeholder="Voucher / transaction no"></label>
        </div>
        <div class="grid-2">
          <label class="field"><span>Title</span><input name="title" placeholder="Short title"></label>
          <label class="field"><span>Note</span><input name="note" placeholder="Ledger note"></label>
        </div>
        <button class="btn" type="submit">Save Ledger Entry</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Shareholder List</h2><p class="muted">Session balance includes commission, profit share, expenses and withdrawals.</p></div></div>
      <div class="table-wrap"><table><thead><tr><th>Name</th><th>Contact</th><th>Share</th><th>Income</th><th>Withdrawal</th><th>Balance</th><th>Status</th><th>Actions</th></tr></thead><tbody>
        ${shareholders.map((item) => `<tr><td><strong>${escapeHtml(item.name)}</strong><br><span class="muted">${escapeHtml(item.note || '')}</span></td><td>${escapeHtml(item.mobile || '-')}<br><span class="muted">${escapeHtml(item.email || '')}</span></td><td>${escapeHtml(String(item.sharePercentage || 0))}%</td><td>${formatMoney(item.sessionIncome)}</td><td>${formatMoney(item.sessionWithdrawal)}</td><td><strong class="${signedMoneyClass(item.sessionBalance)}">${formatMoney(item.sessionBalance)}</strong></td><td><span class="badge ${item.status === 'inactive' ? 'danger' : 'success'}">${escapeHtml(item.status || 'active')}</span></td><td><div class="actions"><button class="btn secondary small" data-action="edit-shareholder" data-id="${item.id}">Edit</button><a class="btn secondary small" href="/api/export/shareholder-ledger.pdf?shareholderId=${encodeURIComponent(item.id)}" target="_blank">PDF</a><a class="btn secondary small" href="/api/export/shareholder-ledger.xlsx?shareholderId=${encodeURIComponent(item.id)}" target="_blank">Excel</a><button class="btn danger small" data-action="delete-shareholder" data-id="${item.id}">Delete</button></div></td></tr>`).join('') || '<tr><td colspan="8">No shareholders yet.</td></tr>'}
      </tbody></table></div>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Ledger Report</h2><p class="muted">Filter and download session-wise shareholder details.</p></div></div>
      <form class="report-filter" data-export-form="shareholder-ledger">
        <select name="shareholderId" data-shareholder-filter><option value="">All Shareholders</option>${shareholders.map((item) => `<option value="${item.id}" ${selectedShareholder === item.id ? 'selected' : ''}>${escapeHtml(item.name)}</option>`).join('')}</select>
        <select name="type"><option value="">All Types</option>${Object.entries(shareholderLedgerLabels).map(([value, label]) => `<option value="${value}" ${reportFilters.type === value ? 'selected' : ''}>${escapeHtml(label)}</option>`).join('')}</select>
        <input name="from" type="date" aria-label="From date" value="${escapeHtml(reportFilters.from || '')}">
        <input name="to" type="date" aria-label="To date" value="${escapeHtml(reportFilters.to || '')}">
        <button class="btn secondary small" type="button" data-action="download-report" data-report="shareholder-ledger" data-format="xlsx">Download Excel</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="shareholder-ledger" data-format="pdf">Download PDF</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="shareholder-ledger" data-format="csv">Download CSV</button>
      </form>
      <div class="table-wrap"><table><thead><tr><th>Date</th><th>Shareholder</th><th>Type</th><th>Title</th><th>Debit</th><th>Credit</th><th>Reference</th></tr></thead><tbody>
        ${filteredEntries.map((entry) => {
          const amount = Number(entry.amount || 0);
          return `<tr><td>${formatDate(entry.entryDate || entry.createdAt)}</td><td>${escapeHtml(entry.shareholderName || shareholderName(entry.shareholderId))}</td><td>${escapeHtml(entry.typeLabel || shareholderLedgerLabels[entry.type] || entry.type)}</td><td>${escapeHtml(entry.title || '-')}<br><span class="muted">${escapeHtml(entry.note || '')}</span></td><td>${amount < 0 ? formatMoney(Math.abs(amount)) : '-'}</td><td>${amount > 0 ? formatMoney(amount) : '-'}</td><td>${escapeHtml(entry.reference || '-')}</td></tr>`;
        }).join('') || '<tr><td colspan="7">No ledger entries yet.</td></tr>'}
      </tbody></table></div>
    </section>
    ${state.editingShareholderId ? shareholderEditDialog() : ''}
  `;
}

function shareholderEditDialog() {
  const item = (state.data.shareholders || []).find((shareholder) => shareholder.id === state.editingShareholderId);
  if (!item) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <div class="panel-header"><div><h2>Edit Shareholder</h2><p class="muted">${escapeHtml(item.name)}</p></div><button class="btn secondary small" data-action="close-shareholder-edit">Close</button></div>
    <form class="form-grid" data-action="edit-shareholder" data-id="${item.id}">
      <label class="field"><span>Name *</span><input name="name" value="${escapeHtml(item.name)}" required></label>
      <div class="grid-2">
        <label class="field"><span>Mobile</span><input name="mobile" value="${escapeHtml(item.mobile || '')}"></label>
        <label class="field"><span>Email</span><input name="email" type="email" value="${escapeHtml(item.email || '')}"></label>
      </div>
      <div class="grid-2">
        <label class="field"><span>Share %</span><input name="sharePercentage" type="number" min="0" max="100" step="0.01" value="${escapeHtml(String(item.sharePercentage || 0))}"></label>
        <label class="field"><span>Status</span><select name="status"><option value="active" ${item.status !== 'inactive' ? 'selected' : ''}>Active</option><option value="inactive" ${item.status === 'inactive' ? 'selected' : ''}>Inactive</option></select></label>
      </div>
      <label class="field"><span>Note</span><input name="note" value="${escapeHtml(item.note || '')}"></label>
      <button class="btn" type="submit">Save Shareholder</button>
    </form>
  </section></div>`;
}

function studentPaymentsView() {
  const students = (state.data.students || []).filter((student) => student.status === 'active');
  const filters = currentReportFilters('payments');
  const payments = (state.data.payments || []).filter((payment) => {
    const student = (state.data.students || []).find((item) => item.id === payment.studentId);
    if (filters.courseId && payment.courseId !== filters.courseId) return false;
    if (filters.batchId && !(student?.batchEnrollments || []).some((item) => item.batchId === filters.batchId)) return false;
    if (filters.method && payment.method !== filters.method) return false;
    if (filters.status && payment.status !== filters.status) return false;
    return matchesDateRange(payment.paidAt, filters);
  });
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  const totalPaid = payments.filter((payment) => payment.status !== 'cancelled').reduce((sum, payment) => sum + Number(payment.amount || 0), 0);
  const totalDue = students.reduce((sum, student) => sum + Number(student.finance?.totalDue || 0), 0);
  return html`
    <section class="panel">
      <div class="panel-header"><div><h1>Payments</h1><p class="muted">Receive course fees, monitor dues, and issue receipts.</p></div></div>
      <div class="finance-summary">
        ${financeCard('Total Collection', totalPaid)}
        ${financeCard('Total Due', totalDue, 'danger')}
        ${financeCard('Payments', payments.filter((item) => item.status !== 'cancelled').length)}
      </div>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Receive Payment</h2><p class="muted">Payment cannot exceed the selected course due.</p></div></div>
      <form class="form-grid" data-action="add-payment">
        <div class="grid-3">
          <label class="field"><span>Student *</span>
            <select name="studentId" required data-payment-student>
              <option value="">Select student</option>
              ${students.map((student) => `<option value="${student.id}">${escapeHtml(student.name)} (${escapeHtml(student.rollNumber)})</option>`).join('')}
            </select>
          </label>
          <label class="field"><span>Course *</span>
            <select name="courseId" required data-payment-course><option value="">Select student first</option></select>
          </label>
          <label class="field"><span>Amount *</span><input name="amount" type="number" min="0.01" step="0.01" required></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
          <label class="field"><span>Payment Date</span><input name="paidAt" type="datetime-local"></label>
          <label class="field"><span>Reference / Transaction</span><input name="reference"></label>
        </div>
        <label class="field"><span>Note</span><input name="note" placeholder="Optional payment note"></label>
        <div class="payment-due-hint muted" data-payment-due>Select a student and course to see due.</div>
        <button class="btn" type="submit">Receive Payment</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Payment History</h2><p class="muted">Print or download any payment receipt.</p></div></div>
      <form class="report-filter" data-export-form="payments">
        <select name="courseId"><option value="">All Courses</option>${courses.map((course) => `<option value="${course.id}" ${filters.courseId === course.id ? 'selected' : ''}>${escapeHtml(course.name)}</option>`).join('')}</select>
        <select name="batchId"><option value="">All Batches</option>${batches.map((batch) => `<option value="${batch.id}" ${filters.batchId === batch.id ? 'selected' : ''}>${escapeHtml(batch.name)}</option>`).join('')}</select>
        <select name="method"><option value="">All Methods</option><option value="cash" ${filters.method === 'cash' ? 'selected' : ''}>Cash</option><option value="bank" ${filters.method === 'bank' ? 'selected' : ''}>Bank</option><option value="mobile_banking" ${filters.method === 'mobile_banking' ? 'selected' : ''}>Mobile Banking</option></select>
        <select name="status"><option value="">All Status</option><option value="completed" ${filters.status === 'completed' ? 'selected' : ''}>Completed</option><option value="cancelled" ${filters.status === 'cancelled' ? 'selected' : ''}>Cancelled</option></select>
        <input name="from" type="date" aria-label="From date" value="${escapeHtml(filters.from || '')}">
        <input name="to" type="date" aria-label="To date" value="${escapeHtml(filters.to || '')}">
        <button class="btn secondary small" type="button" data-action="download-report" data-report="payments" data-format="csv">Download CSV</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="payments" data-format="pdf">Download PDF</button>
      </form>
      <div class="table-toolbar">
        <div><strong>${payments.length}</strong><span class="muted">payment records</span><span class="toolbar-chip success">Total ${formatMoney(totalPaid)}</span>${reportFilterSummary(filters, { courseId: 'Course', batchId: 'Batch', method: 'Method', status: 'Status', from: 'From', to: 'To' })}</div>
        <button class="btn ghost small" type="button" data-action="clear-report-filters" data-report="payments">Clear Filters</button>
      </div>
      <div class="table-wrap">
        <table class="smart-table">
          <thead><tr><th>Receipt</th><th>Student</th><th>Course</th><th>Amount</th><th>Method</th><th>Date</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
            ${payments.map((payment) => html`
              <tr>
                <td><strong>${escapeHtml(payment.receiptNumber)}</strong></td>
                <td>${escapeHtml(payment.studentName)}<br><span class="muted">${escapeHtml(payment.studentRoll)}</span></td>
                <td>${escapeHtml(payment.courseName)}</td>
                <td>${formatMoney(payment.amount)}</td>
                <td>${escapeHtml(payment.method.replaceAll('_', ' '))}</td>
                <td>${formatDate(payment.paidAt)}</td>
                <td><span class="badge ${payment.status === 'cancelled' ? 'danger' : 'success'}">${payment.status}</span></td>
                <td><div class="actions">
                  <button class="btn secondary small" data-action="print-receipt" data-id="${payment.id}">Print</button>
                  <a class="btn secondary small" href="/api/payments/${payment.id}/receipt.pdf" target="_blank">PDF</a>
                  ${state.user.role === 'admin' && payment.status !== 'cancelled' ? `<button class="btn secondary small" data-action="edit-payment" data-id="${payment.id}">Edit</button><button class="btn danger small" data-action="cancel-payment" data-id="${payment.id}">Cancel</button>` : ''}
                </div></td>
              </tr>
            `).join('') || '<tr><td colspan="8">No payments yet.</td></tr>'}
          </tbody>
        </table>
      </div>
    </section>
  `;
}

function teacherPaymentsView(embedded = false) {
  const teachers = (state.data.teachers || []).filter((teacher) => teacher.status === 'active');
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  const filters = currentReportFilters('teacher-payments');
  const payments = (state.data.teacherPayments || []).filter((payment) => {
    if (filters.teacherId && payment.teacherId !== filters.teacherId) return false;
    if (filters.courseId && payment.courseId !== filters.courseId) return false;
    if (filters.batchId && payment.batchId !== filters.batchId) return false;
    if (filters.month && payment.month !== filters.month) return false;
    if (filters.subject && !String(payment.subject || '').toLowerCase().includes(String(filters.subject).toLowerCase())) return false;
    if (filters.status && paymentStatus(payment) !== filters.status) return false;
    return true;
  });
  const payable = payments.reduce((sum, payment) => sum + Number(payment.payable ?? payment.payableAmount ?? 0), 0);
  const paid = payments.reduce((sum, payment) => sum + Number(payment.paid ?? payment.paidAmount ?? 0), 0);
  const due = payments.reduce((sum, payment) => sum + Number(payment.due ?? payment.dueAmount ?? 0), 0);
  const classes = payments.reduce((sum, payment) => sum + (payment.classEntries || []).reduce((total, entry) => total + Number(entry.classes || 0), 0), 0);
  return html`
    ${embedded ? '' : '<section class="panel"><div class="panel-header"><div><h1>Teacher Payments</h1><p class="muted">Track teacher class payments by course, batch, month, subject and class dates.</p></div></div></section>'}
    <section class="panel">
      <div class="panel-header">
        <div>
          <h2>Teacher Payment Summary</h2>
          <p class="muted">Track teacher class payments by course, batch, month, subject and class dates.</p>
        </div>
      </div>
      <div class="finance-summary">
        ${financeCard('Payable', payable)}
        ${financeCard('Paid', paid)}
        ${financeCard('Due', due, 'danger')}
        <div class="finance-card"><span>Classes</span><strong>${classes}</strong></div>
      </div>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Add Teacher Payment</h2><p class="muted">One class entry per line: date, subject, classes, rate, note.</p></div></div>
      <form class="form-grid" data-action="add-teacher-payment">
        <div class="grid-3">
          <label class="field"><span>Teacher *</span><select name="teacherId" required><option value="">Select teacher</option>${teachers.map((teacher) => `<option value="${teacher.id}">${escapeHtml(teacher.name)} (${escapeHtml(teacher.mobile || '-')})</option>`).join('')}</select></label>
          <label class="field"><span>Course *</span><select name="courseId" required><option value="">Select course</option>${courses.map((course) => `<option value="${course.id}">${escapeHtml(course.name)}</option>`).join('')}</select></label>
          <label class="field"><span>Batch</span><select name="batchId"><option value="">No batch</option>${batches.map((batch) => `<option value="${batch.id}">${escapeHtml(batch.name)}</option>`).join('')}</select></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Month *</span><input name="month" type="month" required></label>
          <label class="field"><span>Subject *</span><input name="subject" placeholder="e.g. Biology" required></label>
          <label class="field"><span>Default Rate / Class</span><input name="defaultRate" type="number" min="0" step="0.01" placeholder="0"></label>
        </div>
        <label class="field"><span>Class Dates & Payments *</span><textarea name="classEntriesText" rows="4" placeholder="2026-06-01,Biology,2,500,Chapter 1&#10;2026-06-03,Biology,1,500,Revision" required></textarea></label>
        <div class="grid-3">
          <label class="field"><span>Paid Amount</span><input name="paidAmount" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Payment Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
          <label class="field"><span>Payment Date</span><input name="paidAt" type="datetime-local"></label>
        </div>
        <div class="grid-2">
          <label class="field"><span>Reference</span><input name="reference" placeholder="Transaction / voucher no."></label>
          <label class="field"><span>Note</span><input name="note" placeholder="Optional note"></label>
        </div>
        <button class="btn" type="submit">Save Teacher Payment</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Teacher Payment History</h2><p class="muted">Filter and download teacher payable, paid and due records.</p></div></div>
      <form class="report-filter" data-export-form="teacher-payments">
        <select name="teacherId"><option value="">All Teachers</option>${teachers.map((teacher) => `<option value="${teacher.id}">${escapeHtml(teacher.name)}</option>`).join('')}</select>
        <select name="courseId"><option value="">All Courses</option>${courses.map((course) => `<option value="${course.id}">${escapeHtml(course.name)}</option>`).join('')}</select>
        <select name="batchId"><option value="">All Batches</option>${batches.map((batch) => `<option value="${batch.id}">${escapeHtml(batch.name)}</option>`).join('')}</select>
        <input name="month" type="month" aria-label="Month">
        <input name="subject" placeholder="Subject">
        <select name="status"><option value="">All Status</option><option value="due">Due</option><option value="partial">Partial</option><option value="paid">Paid</option></select>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="teacher-payments" data-format="csv">Download CSV</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="teacher-payments" data-format="pdf">Download PDF</button>
      </form>
      <div class="table-wrap">
        <table>
          <thead><tr><th>Teacher</th><th>Course / Batch</th><th>Month / Subject</th><th>Classes</th><th>Payable</th><th>Paid</th><th>Due</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
            ${payments.map((payment) => html`
              <tr>
                <td>${escapeHtml(payment.teacherName || managerName(payment.teacherId))}</td>
                <td>${escapeHtml(payment.courseName || courseName(payment.courseId))}<br><span class="muted">${escapeHtml(payment.batchName || batchName(payment.batchId))}</span></td>
                <td>${escapeHtml(payment.month)}<br><span class="muted">${escapeHtml(payment.subject)}</span></td>
                <td>${escapeHtml(teacherClassSummary(payment))}</td>
                <td>${formatMoney(payment.payable ?? payment.payableAmount)}</td>
                <td>${formatMoney(payment.paid ?? payment.paidAmount)}</td>
                <td><strong>${formatMoney(payment.due ?? payment.dueAmount)}</strong></td>
                <td>${teacherPaymentStatus(payment)}</td>
                <td><button class="btn secondary small" data-action="edit-teacher-payment" data-id="${payment.id}">Edit</button></td>
              </tr>
            `).join('') || '<tr><td colspan="9">No teacher payments yet.</td></tr>'}
          </tbody>
        </table>
      </div>
    </section>
    ${state.editingTeacherPaymentId ? teacherPaymentEditDialog() : ''}
  `;
}

function teacherPaymentEditDialog() {
  const payment = (state.data.teacherPayments || []).find((item) => item.id === state.editingTeacherPaymentId);
  if (!payment) return '';
  const teachers = (state.data.teachers || []).filter((teacher) => teacher.status === 'active' || teacher.id === payment.teacherId);
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  return html`<div class="modal-backdrop"><section class="modal-card modal-wide">
    <div class="panel-header"><div><h2>Edit Teacher Payment</h2><p class="muted">${escapeHtml(payment.teacherName || managerName(payment.teacherId))}</p></div><button class="btn secondary small" data-action="close-teacher-payment-edit">Close</button></div>
    <form class="form-grid" data-action="edit-teacher-payment" data-id="${payment.id}">
      <div class="grid-3">
        <label class="field"><span>Teacher *</span><select name="teacherId" required>${teachers.map((teacher) => `<option value="${teacher.id}" ${teacher.id === payment.teacherId ? 'selected' : ''}>${escapeHtml(teacher.name)}</option>`).join('')}</select></label>
        <label class="field"><span>Course *</span><select name="courseId" required>${courses.map((course) => `<option value="${course.id}" ${course.id === payment.courseId ? 'selected' : ''}>${escapeHtml(course.name)}</option>`).join('')}</select></label>
        <label class="field"><span>Batch</span><select name="batchId"><option value="">No batch</option>${batches.map((batch) => `<option value="${batch.id}" ${batch.id === payment.batchId ? 'selected' : ''}>${escapeHtml(batch.name)}</option>`).join('')}</select></label>
      </div>
      <div class="grid-3">
        <label class="field"><span>Month *</span><input name="month" type="month" value="${escapeHtml(payment.month)}" required></label>
        <label class="field"><span>Subject *</span><input name="subject" value="${escapeHtml(payment.subject)}" required></label>
        <label class="field"><span>Default Rate / Class</span><input name="defaultRate" type="number" min="0" step="0.01" value="${Number(payment.rate ?? payment.defaultRate ?? 0)}"></label>
      </div>
      <label class="field"><span>Class Dates & Payments *</span><textarea name="classEntriesText" rows="4" required>${escapeHtml(teacherClassEntriesText(payment))}</textarea></label>
      <div class="grid-3">
        <label class="field"><span>Paid Amount</span><input name="paidAmount" type="number" min="0" step="0.01" value="${Number(payment.paid ?? payment.paidAmount ?? 0)}"></label>
        <label class="field"><span>Payment Method</span><select name="method"><option value="cash" ${payment.method === 'cash' ? 'selected' : ''}>Cash</option><option value="bank" ${payment.method === 'bank' ? 'selected' : ''}>Bank</option><option value="mobile_banking" ${payment.method === 'mobile_banking' ? 'selected' : ''}>Mobile Banking</option></select></label>
        <label class="field"><span>Payment Date</span><input name="paidAt" type="datetime-local" value="${escapeHtml(String(payment.paidAt || '').slice(0, 16))}"></label>
      </div>
      <div class="grid-2">
        <label class="field"><span>Reference</span><input name="reference" value="${escapeHtml(payment.reference || '')}"></label>
        <label class="field"><span>Note</span><input name="note" value="${escapeHtml(payment.note || '')}"></label>
      </div>
      <button class="btn" type="submit">Save Teacher Payment</button>
    </form>
  </section></div>`;
}

function employeePaymentStatus(payment) {
  const payable = Number(payment.payable ?? 0);
  const paid = Number(payment.paid ?? payment.paidAmount ?? 0);
  const due = Number(payment.due ?? Math.max(0, payable - paid));
  if (due <= 0 && payable > 0) return '<span class="badge success">paid</span>';
  if (paid > 0) return '<span class="badge warning">partial</span>';
  return '<span class="badge danger">due</span>';
}

function currentReportFilters(report) {
  return state.reportFilters?.[report] || {};
}

function matchesDateRange(value, filters) {
  const day = String(value || '').slice(0, 10);
  if (filters.from && day < filters.from) return false;
  if (filters.to && day > filters.to) return false;
  return true;
}

function paymentStatus(payment) {
  const due = Number(payment.due || 0);
  const paid = Number(payment.paid ?? payment.paidAmount ?? payment.amount ?? 0);
  if (due <= 0) return 'paid';
  if (paid > 0) return 'partial';
  return 'due';
}

function employeePaymentsView() {
  const employees = (state.data.employees || []).filter((employee) => employee.status === 'active');
  const filters = currentReportFilters('employee-payments');
  const payments = (state.data.employeePayments || []).filter((payment) => {
    if (filters.employeeId && payment.employeeId !== filters.employeeId) return false;
    if (filters.month && payment.month !== filters.month) return false;
    if (filters.method && payment.method !== filters.method) return false;
    if (filters.status && paymentStatus(payment) !== filters.status) return false;
    return true;
  });
  const payable = payments.reduce((sum, payment) => sum + Number(payment.payable || 0), 0);
  const paid = payments.reduce((sum, payment) => sum + Number(payment.paid ?? payment.paidAmount ?? 0), 0);
  const due = payments.reduce((sum, payment) => sum + Number(payment.due || 0), 0);
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Employee Payment Summary</h2><p class="muted">Track salary, allowance, bonus, deduction, advance, paid and due.</p></div></div>
      <div class="finance-summary">
        ${financeCard('Payable', payable)}
        ${financeCard('Paid', paid)}
        ${financeCard('Due', due, 'danger')}
      </div>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Add Employee Payment</h2><p class="muted">Monthly salary payment with allowance, advance and deduction.</p></div></div>
      <form class="form-grid" data-action="add-employee-payment">
        <div class="grid-3">
          <label class="field"><span>Employee *</span><select name="employeeId" required><option value="">Select employee</option>${employees.map((employee) => `<option value="${employee.id}">${escapeHtml(employee.name)} (${escapeHtml(employee.designation || '-')})</option>`).join('')}</select></label>
          <label class="field"><span>Month *</span><input name="month" type="month" required></label>
          <label class="field"><span>Salary Amount</span><input name="salaryAmount" type="number" min="0" step="0.01" placeholder="0"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Allowance</span><input name="allowance" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Bonus</span><input name="bonus" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Deduction</span><input name="deduction" type="number" min="0" step="0.01" placeholder="0"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Advance</span><input name="advance" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Paid Amount</span><input name="paidAmount" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Payment Date</span><input name="paidAt" type="datetime-local"></label>
          <label class="field"><span>Reference</span><input name="reference" placeholder="Transaction / voucher no."></label>
          <label class="field"><span>Note</span><input name="note" placeholder="Optional note"></label>
        </div>
        <button class="btn" type="submit">Save Employee Payment</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Employee Payment History</h2><p class="muted">Filter and download salary payment records.</p></div></div>
      <form class="report-filter" data-export-form="employee-payments">
        <select name="employeeId"><option value="">All Employees</option>${employees.map((employee) => `<option value="${employee.id}">${escapeHtml(employee.name)}</option>`).join('')}</select>
        <input name="month" type="month" aria-label="Month">
        <select name="method"><option value="">All Methods</option><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select>
        <select name="status"><option value="">All Status</option><option value="due">Due</option><option value="partial">Partial</option><option value="paid">Paid</option></select>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="employee-payments" data-format="csv">Download CSV</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="employee-payments" data-format="pdf">Download PDF</button>
      </form>
      <div class="table-wrap"><table><thead><tr><th>Employee</th><th>Month</th><th>Payable</th><th>Paid</th><th>Due</th><th>Method</th><th>Status</th><th>Actions</th></tr></thead><tbody>
        ${payments.map((payment) => `<tr><td>${escapeHtml(payment.employeeName || '-')}<br><span class="muted">${escapeHtml(payment.designation || '')}</span></td><td>${escapeHtml(payment.month)}</td><td>${formatMoney(payment.payable)}</td><td>${formatMoney(payment.paid ?? payment.paidAmount)}</td><td><strong>${formatMoney(payment.due)}</strong></td><td>${escapeHtml((payment.method || '').replaceAll('_', ' '))}</td><td>${employeePaymentStatus(payment)}</td><td><button class="btn secondary small" data-action="edit-employee-payment" data-id="${payment.id}">Edit</button></td></tr>`).join('') || '<tr><td colspan="8">No employee payments yet.</td></tr>'}
      </tbody></table></div>
    </section>
    ${state.editingEmployeePaymentId ? employeePaymentEditDialog() : ''}
  `;
}

function employeePaymentEditDialog() {
  const payment = (state.data.employeePayments || []).find((item) => item.id === state.editingEmployeePaymentId);
  if (!payment) return '';
  const employees = (state.data.employees || []).filter((employee) => employee.status === 'active' || employee.id === payment.employeeId);
  return html`<div class="modal-backdrop"><section class="modal-card modal-wide">
    <div class="panel-header"><div><h2>Edit Employee Payment</h2><p class="muted">${escapeHtml(payment.employeeName || '')}</p></div><button class="btn secondary small" data-action="close-employee-payment-edit">Close</button></div>
    <form class="form-grid" data-action="edit-employee-payment" data-id="${payment.id}">
      <div class="grid-3">
        <label class="field"><span>Employee *</span><select name="employeeId" required>${employees.map((employee) => `<option value="${employee.id}" ${employee.id === payment.employeeId ? 'selected' : ''}>${escapeHtml(employee.name)}</option>`).join('')}</select></label>
        <label class="field"><span>Month *</span><input name="month" type="month" value="${escapeHtml(payment.month)}" required></label>
        <label class="field"><span>Salary Amount</span><input name="salaryAmount" type="number" min="0" step="0.01" value="${Number(payment.salaryAmount || 0)}"></label>
      </div>
      <div class="grid-3">
        <label class="field"><span>Allowance</span><input name="allowance" type="number" min="0" step="0.01" value="${Number(payment.allowance || 0)}"></label>
        <label class="field"><span>Bonus</span><input name="bonus" type="number" min="0" step="0.01" value="${Number(payment.bonus || 0)}"></label>
        <label class="field"><span>Deduction</span><input name="deduction" type="number" min="0" step="0.01" value="${Number(payment.deduction || 0)}"></label>
      </div>
      <div class="grid-3">
        <label class="field"><span>Advance</span><input name="advance" type="number" min="0" step="0.01" value="${Number(payment.advance || 0)}"></label>
        <label class="field"><span>Paid Amount</span><input name="paidAmount" type="number" min="0" step="0.01" value="${Number(payment.paid ?? payment.paidAmount ?? 0)}"></label>
        <label class="field"><span>Method</span><select name="method"><option value="cash" ${payment.method === 'cash' ? 'selected' : ''}>Cash</option><option value="bank" ${payment.method === 'bank' ? 'selected' : ''}>Bank</option><option value="mobile_banking" ${payment.method === 'mobile_banking' ? 'selected' : ''}>Mobile Banking</option></select></label>
      </div>
      <div class="grid-3">
        <label class="field"><span>Payment Date</span><input name="paidAt" type="datetime-local" value="${escapeHtml(String(payment.paidAt || '').slice(0, 16))}"></label>
        <label class="field"><span>Reference</span><input name="reference" value="${escapeHtml(payment.reference || '')}"></label>
        <label class="field"><span>Note</span><input name="note" value="${escapeHtml(payment.note || '')}"></label>
      </div>
      <button class="btn" type="submit">Save Employee Payment</button>
    </form>
  </section></div>`;
}

function referencePaymentsView() {
  const students = state.data.students || [];
  const shareholders = state.data.shareholders || [];
  const filters = currentReportFilters('reference-payments');
  const payments = (state.data.referencePayments || []).filter((payment) => {
    if (filters.studentId && payment.studentId !== filters.studentId) return false;
    if (filters.referrerType && String(payment.referrerType || '').toLowerCase() !== String(filters.referrerType).toLowerCase()) return false;
    if (filters.method && payment.method !== filters.method) return false;
    if (filters.status && paymentStatus(payment) !== filters.status) return false;
    return true;
  });
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Reference Payments</h2><p class="muted">Track admission reference commission and payout status.</p></div></div>
      <form class="form-grid" data-action="add-reference-payment">
        <div class="grid-3">
          <label class="field"><span>Student *</span><select name="studentId" required><option value="">Select student</option>${students.map((student) => `<option value="${student.id}">${escapeHtml(student.name)} (${escapeHtml(student.rollNumber)})</option>`).join('')}</select></label>
          <label class="field"><span>Referrer Name *</span><input name="referrerName" placeholder="Referrer name" required></label>
          <label class="field"><span>Referrer Mobile</span><input name="referrerMobile" placeholder="01XXXXXXXXX"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Type</span><select name="referrerType"><option>Student</option><option>Teacher</option><option>Employee</option><option>Other</option></select></label>
          <label class="field"><span>Commission</span><input name="commissionAmount" type="number" min="0" step="0.01" required></label>
          <label class="field"><span>Paid Amount</span><input name="paidAmount" type="number" min="0" step="0.01" placeholder="0"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
          <label class="field"><span>Date</span><input name="paidAt" type="datetime-local"></label>
          <label class="field"><span>Link Shareholder</span><select name="shareholderId"><option value="">No shareholder link</option>${shareholders.map((item) => `<option value="${item.id}">${escapeHtml(item.name)}</option>`).join('')}</select></label>
        </div>
        <label class="field"><span>Note</span><input name="note"></label>
        <button class="btn" type="submit">Save Reference Payment</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Reference Payment History</h2><p class="muted">Filter and download reference commission records.</p></div></div>
      <form class="report-filter" data-export-form="reference-payments">
        <select name="studentId"><option value="">All Students</option>${students.map((student) => `<option value="${student.id}">${escapeHtml(student.name)} (${escapeHtml(student.rollNumber)})</option>`).join('')}</select>
        <select name="referrerType"><option value="">All Types</option><option>Student</option><option>Teacher</option><option>Employee</option><option>Other</option></select>
        <select name="method"><option value="">All Methods</option><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select>
        <select name="status"><option value="">All Status</option><option value="due">Due</option><option value="partial">Partial</option><option value="paid">Paid</option></select>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="reference-payments" data-format="csv">Download CSV</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="reference-payments" data-format="pdf">Download PDF</button>
      </form>
      <div class="table-wrap"><table><thead><tr><th>Student</th><th>Referrer</th><th>Shareholder</th><th>Commission</th><th>Paid</th><th>Due</th><th>Status</th></tr></thead><tbody>${payments.map((payment) => `<tr><td>${escapeHtml(payment.studentName || '-')}<br><span class="muted">${escapeHtml(payment.studentRoll || '')}</span></td><td>${escapeHtml(payment.referrerName || '-')}<br><span class="muted">${escapeHtml(payment.referrerMobile || '')}</span></td><td>${escapeHtml(payment.shareholderId ? shareholderName(payment.shareholderId) : '-')}</td><td>${formatMoney(payment.commissionAmount)}</td><td>${formatMoney(payment.paid)}</td><td><strong>${formatMoney(payment.due)}</strong></td><td>${Number(payment.due || 0) > 0 ? '<span class="badge warning">due</span>' : '<span class="badge success">paid</span>'}</td></tr>`).join('') || '<tr><td colspan="7">No reference payments yet.</td></tr>'}</tbody></table></div>
    </section>
  `;
}

function otherPaymentsView() {
  const filters = currentReportFilters('other-payments');
  const payments = (state.data.otherPayments || []).filter((payment) => {
    if (filters.category && String(payment.category || '').toLowerCase() !== String(filters.category).toLowerCase()) return false;
    if (filters.method && payment.method !== filters.method) return false;
    return matchesDateRange(payment.paidAt, filters);
  });
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Other Payments</h2><p class="muted">Record institutional expenses such as rent, electricity, snacks, marketing and transport.</p></div></div>
      <form class="form-grid" data-action="add-other-payment">
        <div class="grid-3">
          <label class="field"><span>Category *</span><select name="category"><option>Snacks</option><option>Electricity Bill</option><option>Rent</option><option>Transport</option><option>Publication</option><option>Marketing</option><option>Others</option></select></label>
          <label class="field"><span>Title</span><input name="title" placeholder="Expense title"></label>
          <label class="field"><span>Amount *</span><input name="amount" type="number" min="0.01" step="0.01" required></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Method</span><select name="method"><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select></label>
          <label class="field"><span>Date</span><input name="paidAt" type="datetime-local"></label>
          <label class="field"><span>Reference</span><input name="reference"></label>
        </div>
        <label class="field"><span>Note</span><input name="note"></label>
        <button class="btn" type="submit">Save Expense</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Other Payment History</h2><p class="muted">Filter and download expense records.</p></div></div>
      <form class="report-filter" data-export-form="other-payments">
        <select name="category"><option value="">All Categories</option><option>Snacks</option><option>Electricity Bill</option><option>Rent</option><option>Transport</option><option>Publication</option><option>Marketing</option><option>Others</option></select>
        <select name="method"><option value="">All Methods</option><option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile_banking">Mobile Banking</option></select>
        <input name="from" type="date" aria-label="From date">
        <input name="to" type="date" aria-label="To date">
        <button class="btn secondary small" type="button" data-action="download-report" data-report="other-payments" data-format="csv">Download CSV</button>
        <button class="btn secondary small" type="button" data-action="download-report" data-report="other-payments" data-format="pdf">Download PDF</button>
      </form>
      <div class="table-wrap"><table><thead><tr><th>Category</th><th>Title</th><th>Amount</th><th>Method</th><th>Date</th><th>Note</th></tr></thead><tbody>${payments.map((payment) => `<tr><td>${escapeHtml(payment.category)}</td><td>${escapeHtml(payment.title || '-')}</td><td>${formatMoney(payment.amount)}</td><td>${escapeHtml((payment.method || '').replaceAll('_', ' '))}</td><td>${formatDate(payment.paidAt)}</td><td>${escapeHtml(payment.note || '-')}</td></tr>`).join('') || '<tr><td colspan="6">No expenses yet.</td></tr>'}</tbody></table></div>
    </section>
  `;
}
