{% extends 'base.html' %}

{% block content %}
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h2>Demand Orders</h2>
    {% if current_user.role == 'customer' %}
      <a href="{{ url_for('demand_order_new') }}" class="btn-primary">Create New Order</a>
    {% endif %}
  </div>

  {% if current_user.role == 'admin' %}
    <!-- Admin View -->
    <div class="card">
      <h3>All Demand Orders</h3>
      
      <!-- Live Search -->
      <div style="margin-bottom: 16px;">
        <input type="text" id="demand-order-search" placeholder="🔍 Search orders by ID, customer, date, weight, price, status..." 
               style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; box-sizing: border-box;">
      </div>
      
      {% if orders %}
        <table class="table" id="demand-orders-table">
          <thead>
            <tr>
              <th>Order ID</th>
              <th>Customer</th>
              <th>Date</th>
              <th>Weight</th>
              <th>Price/kg</th>
              <th>Total</th>
              <th>Status</th>
              <th>Supplier</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {% for order in orders %}
              <tr style="background-color: {% if order.status == 'delivered' %}#f0fdf4{% elif order.status == 'paid' %}#ecfdf5{% elif order.status == 'remitted_to_admin' %}#f0fdf4{% elif order.status == 'rejected' %}#fef2f2{% elif order.status == 'approved' %}#d1fae5{% elif order.status == 'assigned' %}#fef3c7{% else %}#fffbeb{% endif %};">
                <td><strong>#{{ order.id }}</strong></td>
                <td>
                  <strong>{{ order.customer.name }}</strong><br>
                  <small style="color: #666;">{{ order.customer.email }}</small>
                </td>
                <td>{{ order.date|date_format }}</td>
                <td>{{ order.weight_kg|kg }}</td>
                <td>{{ order.price_per_kg|currency }}</td>
                <td><strong>{{ order.total_amount|currency }}</strong></td>
                <td>
                  {% if order.status == 'pending' %}
                    <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px;">⏳ Pending</span>
                  {% elif order.status == 'approved' %}
                    <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px;">✅ Approved</span>
                  {% elif order.status == 'rejected' %}
                    <span style="background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 12px; font-size: 12px;">❌ Rejected</span>
                  {% elif order.status == 'assigned' %}
                    <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px;">🚚 Assigned</span>
                  {% elif order.status == 'delivered' %}
                    <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px;">📦 Delivered</span>
                  {% elif order.status == 'paid' %}
                    <span style="background: #10b981; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">💰 Paid</span>
                  {% elif order.status == 'remitted_to_admin' %}
                    <span style="background: #059669; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">✅ Remitted</span>
                  {% endif %}
                </td>
                <td>
                  {% if order.assigned_supplier %}
                    <strong>{{ order.assigned_supplier.name }}</strong>
                    {% if order.assigned_at %}
                      <br><small style="color: #666;">{{ order.assigned_at.strftime('%d %b %H:%M') }}</small>
                    {% endif %}
                  {% else %}
                    <span style="color: #9ca3af;">-</span>
                  {% endif %}
                </td>
                <td>
                  <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    <a href="{{ url_for('demand_order_view', order_id=order.id) }}" class="btn-outline" style="font-size: 12px;">View</a>
                    
                    {% if order.status == 'pending' %}
                      <a href="{{ url_for('demand_order_approve', order_id=order.id) }}" class="btn-primary" style="font-size: 12px;">Approve</a>
                      <button onclick="showRejectModal({{ order.id }})" class="btn-outline" style="font-size: 12px; color: #dc2626;">Reject</button>
                    {% elif order.status == 'approved' %}
                      <a href="{{ url_for('demand_order_assign_supplier', order_id=order.id) }}" class="btn-primary" style="font-size: 12px;">Assign Supplier</a>
                    {% endif %}
                  </div>
                </td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      {% else %}
        <p style="color: #666; text-align: center; padding: 20px;">No demand orders found.</p>
      {% endif %}
    </div>

    <!-- Reject Modal -->
    <div id="rejectModal" class="modal" style="display: none;">
      <div class="modal-content">
        <h3>Reject Order</h3>
        <form id="rejectForm" method="post">
          <div class="field">
            <label class="label">Reason for Rejection</label>
            <textarea name="admin_notes" rows="3" placeholder="Please provide a reason for rejection" required></textarea>
          </div>
          <div style="margin-top: 20px; display: flex; gap: 12px;">
            <button type="submit" class="btn-outline" style="color: #dc2626;">Confirm Rejection</button>
            <button type="button" onclick="hideModal('rejectModal')" class="btn-outline">Cancel</button>
          </div>
        </form>
      </div>
    </div>

  {% elif current_user.role == 'customer' %}
    <!-- Customer View -->
    <div class="card">
      <h3>My Demand Orders</h3>
      {% if orders %}
        <table class="table">
          <thead>
            <tr>
              <th>Order ID</th>
              <th>Date</th>
              <th>Weight</th>
              <th>Price/kg</th>
              <th>Total</th>
              <th>Status</th>
              <th>Supplier</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {% for order in orders %}
              <tr style="background-color: {% if order.status == 'delivered' %}#f0fdf4{% elif order.status == 'paid' %}#ecfdf5{% elif order.status == 'rejected' %}#fef2f2{% elif order.status == 'approved' %}#d1fae5{% elif order.status == 'assigned' %}#fef3c7{% else %}#fffbeb{% endif %};">
                <td><strong>#{{ order.id }}</strong></td>
                <td>{{ order.date|date_format }}</td>
                <td>{{ order.weight_kg|kg }}</td>
                <td>{{ order.price_per_kg|currency }}</td>
                <td><strong>{{ order.total_amount|currency }}</strong></td>
                <td>
                  {% if order.status == 'pending' %}
                    <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px;">⏳ Pending</span>
                  {% elif order.status == 'approved' %}
                    <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px;">✅ Approved</span>
                  {% elif order.status == 'rejected' %}
                    <span style="background: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 12px; font-size: 12px;">❌ Rejected</span>
                  {% elif order.status == 'assigned' %}
                    <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px;">🚚 Assigned</span>
                  {% elif order.status == 'delivered' %}
                    <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px;">📦 Delivered</span>
                  {% elif order.status == 'paid' %}
                    <span style="background: #10b981; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">💰 Paid</span>
                  {% endif %}
                </td>
                <td>
                  {% if order.assigned_supplier %}
                    <strong>{{ order.assigned_supplier.name }}</strong>
                    {% if order.assigned_at %}
                      <br><small style="color: #666;">{{ order.assigned_at.strftime('%d %b %H:%M') }}</small>
                    {% endif %}
                  {% else %}
                    <span style="color: #9ca3af;">-</span>
                  {% endif %}
                </td>
                <td>
                  <a href="{{ url_for('demand_order_view', order_id=order.id) }}" class="btn-outline" style="font-size: 12px;">View Details</a>
                </td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      {% else %}
        <div style="text-align: center; padding: 40px 20px;">
          <div style="font-size: 48px; color: #d1d5db; margin-bottom: 16px;">📋</div>
          <p style="color: #666; margin: 0 0 8px 0; font-size: 16px;">No demand orders yet</p>
          <p style="color: #9ca3af; margin: 0; font-size: 14px;">Create your first demand order to get started</p>
        </div>
      {% endif %}
    </div>

  {% elif current_user.role == 'supplier' %}
    <!-- Supplier View -->
    <div class="card">
      <h3>Orders Assigned to Me</h3>
      {% if orders %}
        <table class="table">
          <thead>
            <tr>
              <th>Order ID</th>
              <th>Customer</th>
              <th>Date</th>
              <th>Weight</th>
              <th>Price/kg</th>
              <th>Total</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {% for order in orders %}
              <tr style="background-color: {% if order.status == 'delivered' %}#f0fdf4{% elif order.status == 'paid' %}#ecfdf5{% elif order.status == 'remitted_to_admin' %}#f0fdf4{% else %}#fef3c7{% endif %};">
                <td><strong>#{{ order.id }}</strong></td>
                <td>
                  <strong>{{ order.customer.name }}</strong><br>
                  <small style="color: #666;">{{ order.customer.email }}</small>
                </td>
                <td>{{ order.date|date_format }}</td>
                <td>{{ order.weight_kg|kg }}</td>
                <td>{{ order.price_per_kg|currency }}</td>
                <td><strong>{{ order.total_amount|currency }}</strong></td>
                <td>
                  {% if order.status == 'assigned' %}
                    <span style="background: #fef3c7; color: #92400e; padding: 4px 8px; border-radius: 12px; font-size: 12px;">🚚 Assigned</span>
                  {% elif order.status == 'delivered' %}
                    <span style="background: #d1fae5; color: #065f46; padding: 4px 8px; border-radius: 12px; font-size: 12px;">📦 Delivered</span>
                  {% elif order.status == 'paid' %}
                    <span style="background: #10b981; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">💰 Paid</span>
                  {% elif order.status == 'remitted_to_admin' %}
                    <span style="background: #059669; color: white; padding: 12px; font-size: 12px;">✅ Remitted</span>
                  {% endif %}
                </td>
                <td>
                  <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    <a href="{{ url_for('demand_order_view', order_id=order.id) }}" class="btn-outline" style="font-size: 12px;">View</a>
                    
                    {% if order.status == 'assigned' %}
                      <form method="post" action="{{ url_for('demand_order_mark_delivered', order_id=order.id) }}" style="display: inline;">
                        <button type="submit" class="btn-primary" style="font-size: 12px;" onclick="return confirm('Mark this order as delivered? This will create a sale record.')">
                          Mark Delivered
                        </button>
                      </form>
                    {% elif order.status == 'delivered' %}
                      <a href="{{ url_for('demand_order_collect_payment', order_id=order.id) }}" class="btn-primary" style="font-size: 12px;">
                        💰 Collect Payment
                      </a>
                    {% endif %}
                  </div>
                </td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      {% else %}
        <div style="text-align: center; padding: 40px 20px;">
          <div style="font-size: 48px; color: #d1d5db; margin-bottom: 16px;">📦</div>
          <p style="color: #666; margin: 0 0 8px 0; font-size: 16px;">No orders assigned yet</p>
          <p style="color: #9ca3af; margin: 0; font-size: 14px;">Admin will assign orders to you when they're ready for delivery</p>
        </div>
      {% endif %}
    </div>
  {% endif %}

  <style>
    .modal {
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
    }
    .modal-content {
      background-color: white;
      margin: 15% auto;
      padding: 20px;
      border-radius: 8px;
      width: 80%;
      max-width: 500px;
    }
    .field textarea {
      width: 100%;
      padding: 8px;
      border: 1px solid #d1d5db;
      border-radius: 4px;
      font-family: inherit;
    }
  </style>

  <script>
    let currentOrderId = null;

    function showRejectModal(orderId) {
      currentOrderId = orderId;
      document.getElementById('rejectForm').action = `/demand-orders/${orderId}/reject`;
      document.getElementById('rejectModal').style.display = 'block';
    }

    function hideModal(modalId) {
      document.getElementById(modalId).style.display = 'none';
    }

    // Close modal when clicking outside
    window.onclick = function(event) {
      if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
      }
    }
    
    // Initialize live search
    document.addEventListener('DOMContentLoaded', function() {
      initLiveSearch('demand-order-search', 'demand-orders-table');
    });
  </script>
{% endblock %}
