{% extends 'base.html' %}
{% block content %}
  <div style="display:flex;justify-content:space-between;align-items:center;">
    <h2>Sales Report</h2>
    <a class="btn-outline" href="{{ url_for('report_export_csv', kind='sales', start=start, end=end) }}">Export CSV</a>
  </div>
  <div class="card" style="margin-top:8px">
    <table class="table sales-report-table">
      <thead>
        <tr>
          <th>Date</th>
          <th>Customer</th>
          <th class="highlight-quantity">Weight (kg)</th>
          <th class="highlight-price">Price/kg</th>
          <th class="highlight-total">Total Amount</th>
          <th>Status</th>
          <th>Payment</th>
        </tr>
      </thead>
      <tbody>
        {% for s in rows %}
          <tr>
            <td>{{ s.date }}</td>
            <td>{{ s.customer.name }}</td>
            <td class="highlight-quantity">{{ s.weight_kg|kg }}</td>
            <td class="highlight-price">{{ s.price_per_kg|currency }}</td>
            <td class="highlight-total">{{ s.total_amount|currency }}</td>
            <td>{{ s.status }}</td>
            <td>{{ s.payment_status }}</td>
          </tr>
        {% else %}
          <tr><td colspan="7" class="muted">No data.</td></tr>
        {% endfor %}
      </tbody>
      <tfoot>
        <tr class="total-row">
          <th colspan="4">Grand Total</th>
          <th class="highlight-total grand-total">{{ total|currency }}</th>
          <th colspan="3"></th>
        </tr>
      </tfoot>
    </table>
  </div>

  <!-- Live Search for Customer Balances -->
  <div class="card" style="margin-top:12px; margin-bottom:8px;">
    <input type="text" id="customer-balances-report-search" placeholder="🔍 Search customers by name, balance..." 
           style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">
  </div>
  
  <div class="card" style="margin-top:12px">
    <h3>Customer Balances</h3>
    <table class="table customer-balances-table" id="customer-balances-report-table">
      <thead>
        <tr>
          <th>Customer</th>
          <th class="highlight-balance">Balance</th>
        </tr>
      </thead>
      <tbody>
        {% for s in rows | map(attribute='customer') | unique %}
          <tr>
            <td>{{ s.name }}</td>
            <td class="highlight-balance">{{ (balances[s.id] if balances and s and s.id in balances else 0)|currency }}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      initLiveSearch('sales-report-search', 'sales-report-table');
      initLiveSearch('customer-balances-report-search', 'customer-balances-report-table');
    });
  </script>
{% endblock %}


