{% extends 'base.html' %}
{% block content %}
  <div class="mobile-sales-header" style="display:flex;justify-content:space-between;align-items:center;">
    <h2>Sales</h2>
    <div class="mobile-sales-actions" style="display: flex; gap: 12px; align-items: center;">
      {% if current_user.role == 'customer' %}
        <a href="{{ url_for('customer_my_ledger') }}" class="btn-outline">View My Ledger</a>
      {% endif %}
      {% if current_user.role == 'admin' %}
        <a href="{{ url_for('sale_new') }}" class="btn-primary">New Sale</a>
      {% endif %}
    </div>
  </div>

  {% if current_user.role == 'admin' %}
    <!-- Global Search and Filter Panel -->
    <div class="card" style="margin-top:8px;">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h3 style="margin:0;">Search & Filter Sales</h3>
        <div style="display:flex;gap:8px;align-items:center;">
          <span style="font-size:12px;color:var(--muted);">Filter sales by customer:</span>
        </div>
      </div>
      
      <!-- Search and Filter Form -->
      <form method="GET" class="search-form-mobile" style="display:grid;grid-template-columns:1fr 1fr auto;gap:12px;padding:16px;background:#f8f9fa;border-radius:8px;border:1px solid var(--border);">
        <div class="field" style="margin:0;position:relative;">
          <div class="dropdown-container">
            <input type="text" name="search_name" id="customerSearch" placeholder="Search by customer name..." value="{{ search_name }}" 
                   style="padding:10px 12px;border-radius:8px;border:1px solid var(--border);background:#fff;width:100%;"
                   autocomplete="off" onkeyup="filterCustomers()" onfocus="showDropdown()" onblur="hideDropdown()">
            <div id="customerDropdown" class="dropdown-menu" style="display:none;">
              {% for customer in all_customers %}
                <div class="dropdown-item" onclick="selectCustomer('{{ customer.name }}', '{{ customer.phone or '' }}')">
                  <div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:24px;height:24px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:50%;display:flex;align-items:center;justify-content:center;color:white;font-weight:600;font-size:12px;">
                      {{ customer.name[0].upper() }}
                    </div>
                    <div>
                      <div style="font-weight:600;font-size:14px;">{{ customer.name }}</div>
                      {% if customer.phone %}
                        <div style="font-size:12px;color:var(--muted);">{{ customer.phone }}</div>
                      {% endif %}
                    </div>
                  </div>
                </div>
              {% endfor %}
            </div>
          </div>
        </div>
        <div class="field" style="margin:0;position:relative;">
          <div class="dropdown-container">
            <input type="text" name="search_phone" id="phoneSearch" placeholder="Search by phone number..." value="{{ search_phone }}" 
                   style="padding:10px 12px;border-radius:8px;border:1px solid var(--border);background:#fff;width:100%;"
                   autocomplete="off" onkeyup="filterPhones()" onfocus="showPhoneDropdown()" onblur="hidePhoneDropdown()">
            <div id="phoneDropdown" class="dropdown-menu" style="display:none;">
              {% for customer in all_customers %}
                {% if customer.phone %}
                  <div class="dropdown-item" onclick="selectPhone('{{ customer.phone }}', '{{ customer.name }}')">
                    <div style="display:flex;align-items:center;gap:8px;">
                      <div style="width:24px;height:24px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:50%;display:flex;align-items:center;justify-content:center;color:white;font-weight:600;font-size:12px;">
                        {{ customer.name[0].upper() }}
                      </div>
                      <div>
                        <div style="font-weight:600;font-size:14px;">{{ customer.phone }}</div>
                        <div style="font-size:12px;color:var(--muted);">{{ customer.name }}</div>
                      </div>
                    </div>
                  </div>
                {% endif %}
              {% endfor %}
            </div>
          </div>
        </div>
        <div style="display:flex;gap:8px;">
          <button type="submit" class="btn-primary" style="padding:10px 16px;">Search Sales</button>
          <a href="{{ url_for('sales_list') }}" class="btn-outline" style="padding:10px 16px;">Clear</a>
        </div>
      </form>
      
      {% if search_name or search_phone %}
        <div style="margin-top:12px;padding:12px;background:#e3f2fd;border-radius:8px;border-left:4px solid #1976d2;">
          <strong>Filtered Results:</strong> 
          {% if search_name %}Name: "{{ search_name }}"{% endif %}
          {% if search_name and search_phone %} | {% endif %}
          {% if search_phone %}Phone: "{{ search_phone }}"{% endif %}
          <span style="color:var(--muted);margin-left:8px;">({{ sales|length }} sales found)</span>
        </div>
      {% endif %}
    </div>
  {% endif %}

  {% if current_user.role == 'admin' %}
    <!-- Inventory Status for Admin -->
    {% set total_purchased = sales|sum(attribute='weight_kg') if sales else 0 %}
    {% set total_sold = sales|sum(attribute='weight_kg') if sales else 0 %}
    {% set available_inventory = total_purchased - total_sold %}
    
    {% if available_inventory <= 0 %}
      <div class="card mobile-inventory-alert" style="margin-top: 8px; border-color: #dc2626; background-color: #fef2f2;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div>
            <h4 style="color: #dc2626; margin: 0;">⚠️ No Inventory Available</h4>
            <p style="color: #dc2626; margin: 4px 0 0 0;">Cannot create new sales until you purchase more meat.</p>
          </div>
          <a href="{{ url_for('purchase_new') }}" class="btn-primary">Purchase Meat</a>
        </div>
      </div>
    {% elif available_inventory < 100 %}
      <div class="card mobile-inventory-alert" style="margin-top: 8px; border-color: #f59e0b; background-color: #fffbeb;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div>
            <h4 style="color: #f59e0b; margin: 0;">⚠️ Low Inventory</h4>
            <p style="color: #f59e0b; margin: 4px 0 0 0;">Only {{ available_inventory|kg }} remaining for sales.</p>
          </div>
          <a href="{{ url_for('purchase_new') }}" class="btn-outline">Purchase Meat</a>
        </div>
      </div>
    {% endif %}
  {% endif %}
  <div class="card" style="margin-top:8px">
    <div class="table-responsive mobile-table-container">
      <table class="table sales-report-table mobile-sales-table" id="sales-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</th>
          <th>Status</th>
          <th>Payment Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        {% for s in sales %}
        <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|capitalize }}</td>
          <td>
            {% if s.payment_status == 'unpaid' %}
              <span style="color: #dc2626;">Unpaid</span>
            {% elif s.payment_status == 'paid_to_admin' %}
              <span style="color: #059669;">Paid</span>
            {% else %}
              <span class="muted">{{ s.payment_status|default('Unpaid') }}</span>
            {% endif %}
          </td>
          <td>
            {% if current_user.role == 'admin' %}
              <span class="muted">-</span>
            {% endif %}
          </td>
        </tr>
        {% else %}
          <tr><td colspan="8" class="muted">No sales yet.</td></tr>
        {% endfor %}
      </tbody>
      <tfoot>
        <tr class="total-row">
          <th colspan="4">Grand Total</th>
          <th class="highlight-total grand-total">{{ (sales|sum(attribute='total_amount'))|currency }}</th>
          <th colspan="4"></th>
        </tr>
      </tfoot>
    </table>
    </div>
  </div>

  {% if current_user.role == 'admin' %}
    <div class="card mobile-customer-balances" style="margin-top:12px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h3 style="margin:0;">All Customer Balances & Reports</h3>
        <div style="display:flex;gap:8px;align-items:center;">
          <span style="font-size:12px;color:var(--muted);">Complete customer overview</span>
        </div>
      </div>
      
      <div class="table-responsive">
        <table class="table customer-balances-table" id="customer-balances-table">
          <thead>
            <tr>
              <th>Customer Name</th>
              <th>Phone Number</th>
              <th>Email</th>
              <th class="highlight-balance">Total Balance</th>
              <th>Total Sales</th>
              <th>Total Payments</th>
              <th>Orders Count</th>
              <th>Last Order</th>
            </tr>
          </thead>
          <tbody>
            {% for customer in filtered_customers %}
              {% set balance_data = customer_balances.get(customer.id, {}) %}
              <tr>
                <td>
                  <div style="display:flex;align-items:center;gap:8px;">
                    <div style="width:32px;height:32px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:50%;display:flex;align-items:center;justify-content:center;color:white;font-weight:600;font-size:14px;">
                      {{ customer.name[0].upper() }}
                    </div>
                    <span style="font-weight:600;">{{ customer.name }}</span>
                  </div>
                </td>
                <td>
                  {% if customer.phone %}
                    <span style="color:var(--primary);font-weight:500;">{{ customer.phone }}</span>
                  {% else %}
                    <span class="muted">-</span>
                  {% endif %}
                </td>
                <td>
                  <span style="color:var(--muted);font-size:13px;">{{ customer.email }}</span>
                </td>
                <td class="highlight-balance">
                  <div style="display:flex;align-items:center;gap:8px;">
                    <span style="font-size:16px;font-weight:700;">{{ balance_data.get('balance', 0)|currency }}</span>
                    {% if balance_data.get('balance', 0) > 0 %}
                      <span style="background:#e8f5e8;color:#1b5e20;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600;">OWES</span>
                    {% elif balance_data.get('balance', 0) < 0 %}
                      <span style="background:#fff3e0;color:#e65100;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600;">CREDIT</span>
                    {% else %}
                      <span style="background:#f5f5f5;color:#666;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:600;">ZERO</span>
                    {% endif %}
                  </div>
                </td>
                <td>
                  <span style="color:var(--success);font-weight:600;">{{ balance_data.get('total_sales', 0)|currency }}</span>
                </td>
                <td>
                  <span style="color:var(--primary);font-weight:600;">{{ balance_data.get('total_payments', 0)|currency }}</span>
                </td>
                <td>
                  <span style="background:#f0f4ff;color:var(--primary);padding:4px 8px;border-radius:12px;font-size:12px;font-weight:600;">
                    {{ balance_data.get('sales_count', 0) }} orders
                  </span>
                </td>
                <td>
                  {% if balance_data.get('last_sale') %}
                    <span style="color:var(--muted);font-size:13px;">{{ balance_data.get('last_sale').strftime('%Y-%m-%d') }}</span>
                  {% else %}
                    <span class="muted">No orders</span>
                  {% endif %}
                </td>
              </tr>
            {% else %}
              <tr>
                <td colspan="8" class="muted" style="text-align:center;padding:32px;">
                  No customers found in the system.
                </td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      
      {% if filtered_customers %}
        <div class="mobile-summary-grid" style="margin-top:16px;padding:16px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:8px;color:white;">
          <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;">
            <div class="mobile-summary-item">
              <div class="label" style="font-size:12px;opacity:0.9;margin-bottom:4px;">FILTERED CUSTOMERS</div>
              <div class="value" style="font-size:24px;font-weight:700;">{{ filtered_customers|length }}</div>
            </div>
            <div class="mobile-summary-item">
              <div class="label" style="font-size:12px;opacity:0.9;margin-bottom:4px;">TOTAL OUTSTANDING</div>
              <div class="value" style="font-size:24px;font-weight:700;">{{ (customer_balances.values() | sum(attribute='balance'))|currency }}</div>
            </div>
            <div class="mobile-summary-item">
              <div class="label" style="font-size:12px;opacity:0.9;margin-bottom:4px;">TOTAL SALES VALUE</div>
              <div class="value" style="font-size:24px;font-weight:700;">{{ (customer_balances.values() | sum(attribute='total_sales'))|currency }}</div>
            </div>
            <div class="mobile-summary-item">
              <div class="label" style="font-size:12px;opacity:0.9;margin-bottom:4px;">TOTAL PAYMENTS</div>
              <div class="value" style="font-size:24px;font-weight:700;">{{ (customer_balances.values() | sum(attribute='total_payments'))|currency }}</div>
            </div>
          </div>
        </div>
      {% endif %}
    </div>
  {% endif %}
{% endblock %}

<script>
// Customer dropdown functionality
function filterCustomers() {
    const input = document.getElementById('customerSearch');
    const dropdown = document.getElementById('customerDropdown');
    const filter = input.value.toLowerCase();
    const items = dropdown.getElementsByClassName('dropdown-item');
    
    for (let i = 0; i < items.length; i++) {
        const customerName = items[i].textContent.toLowerCase();
        if (customerName.includes(filter)) {
            items[i].style.display = 'block';
        } else {
            items[i].style.display = 'none';
        }
    }
    
    if (filter.length > 0) {
        dropdown.style.display = 'block';
    } else {
        dropdown.style.display = 'none';
    }
}

function showDropdown() {
    const dropdown = document.getElementById('customerDropdown');
    dropdown.style.display = 'block';
}

function hideDropdown() {
    setTimeout(() => {
        const dropdown = document.getElementById('customerDropdown');
        dropdown.style.display = 'none';
    }, 300);
}

function selectCustomer(name, phone) {
    document.getElementById('customerSearch').value = name;
    document.getElementById('customerDropdown').style.display = 'none';
}

// Phone dropdown functionality
function filterPhones() {
    const input = document.getElementById('phoneSearch');
    const dropdown = document.getElementById('phoneDropdown');
    const filter = input.value.toLowerCase();
    const items = dropdown.getElementsByClassName('dropdown-item');
    
    for (let i = 0; i < items.length; i++) {
        const phoneNumber = items[i].textContent.toLowerCase();
        if (phoneNumber.includes(filter)) {
            items[i].style.display = 'block';
        } else {
            items[i].style.display = 'none';
        }
    }
    
    if (filter.length > 0) {
        dropdown.style.display = 'block';
    } else {
        dropdown.style.display = 'none';
    }
}

function showPhoneDropdown() {
    const dropdown = document.getElementById('phoneDropdown');
    dropdown.style.display = 'block';
}

function hidePhoneDropdown() {
    setTimeout(() => {
        const dropdown = document.getElementById('phoneDropdown');
        dropdown.style.display = 'none';
    }, 300);
}

function selectPhone(phone, name) {
    document.getElementById('phoneSearch').value = phone;
    document.getElementById('phoneDropdown').style.display = 'none';
}

// Initialize live search for sales table
document.addEventListener('DOMContentLoaded', function() {
  // Add search input if not exists
  const salesTable = document.getElementById('sales-table');
  if (salesTable) {
    const searchContainer = document.createElement('div');
    searchContainer.className = 'card';
    searchContainer.style.cssText = 'margin-top: 8px; margin-bottom: 8px;';
    searchContainer.innerHTML = '<input type="text" id="sales-search" placeholder="🔍 Search sales by date, customer, weight, price, amount, status..." style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">';
    salesTable.parentElement.insertBefore(searchContainer, salesTable.parentElement.firstChild);
    initLiveSearch('sales-search', 'sales-table');
  }
  
  // Add search for customer balances table
  const customerBalancesTable = document.getElementById('customer-balances-table');
  if (customerBalancesTable) {
    const searchContainer = document.createElement('div');
    searchContainer.className = 'card';
    searchContainer.style.cssText = 'margin-top: 8px; margin-bottom: 8px;';
    searchContainer.innerHTML = '<input type="text" id="customer-balances-search" placeholder="🔍 Search customers by name, phone, email, balance, sales, payments..." style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">';
    customerBalancesTable.parentElement.insertBefore(searchContainer, customerBalancesTable);
    initLiveSearch('customer-balances-search', 'customer-balances-table');
  }
});
</script>


