{% extends 'base.html' %}
{% block content %}
  <h2>New Sale</h2>
  
  <!-- Inventory Status -->
  <div class="card" style="margin-bottom: 16px;">
    <h3>Inventory Status</h3>
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <div>
        <p style="margin: 8px 0; color: #666;">
          Available inventory for sale
        </p>
      </div>
      <div style="font-size: 1.2em; font-weight: bold; color: #059669;">
        {{ available_inventory|kg }}
      </div>
    </div>
  </div>

  <div class="card">
    <form method="post" class="form" id="saleForm">
      {{ form.hidden_tag() }}
      <div class="field">
        <label class="label">Customer</label>
        {{ form.customer_id() }}
      </div>
      <div class="field">
        <label class="label">Date</label>
        {{ form.date(type='date') }}
      </div>
      <div class="field">
        <label class="label">Weight (kg)</label>
        {{ form.weight_kg(step='0.01', id='weightInput') }}
        <small style="color: #666;">Maximum available: {{ available_inventory|kg }}</small>
      </div>
      <div class="field">
        <label class="label">Price per kg</label>
        {{ form.price_per_kg(step='0.01') }}
      </div>
      <div>
        {{ form.submit(class_='btn-primary', id='submitBtn') }}
      </div>
    </form>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const weightInput = document.getElementById('weightInput');
      const submitBtn = document.getElementById('submitBtn');
      const availableInventory = {{ available_inventory }};
      
      function validateInventory() {
        const weight = parseFloat(weightInput.value) || 0;
        if (weight > availableInventory) {
          weightInput.style.borderColor = '#dc2626';
          submitBtn.disabled = true;
          submitBtn.style.opacity = '0.5';
          submitBtn.title = `Cannot sell more than available inventory (${availableInventory} kg)`;
        } else {
          weightInput.style.borderColor = '';
          submitBtn.disabled = false;
          submitBtn.style.opacity = '1';
          submitBtn.title = '';
        }
      }
      
      weightInput.addEventListener('input', validateInventory);
      validateInventory(); // Initial validation
    });
  </script>
{% endblock %}


