{% extends "base.html" %}

{% block title %}Orders List{% endblock %}

{% block content %}
<style>
  :root {
    --primary-color: #3b82f6;
    --primary-light: #93c5fd;
    --primary-dark: #1e40af;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
    --bg-light: #f0f9ff;
    --bg-card: #ffffff;
    --border-color: #dbeafe;
    --text-dark: #1e293b;
    --text-light: #64748b;
    --shadow-sm: 0 1px 3px rgba(59, 130, 246, 0.12);
    --shadow-md: 0 4px 6px rgba(59, 130, 246, 0.15);
    --shadow-lg: 0 10px 15px rgba(59, 130, 246, 0.2);
  }

  body {
    background: var(--bg-light);
  }

  /* Modern Container */
  .order-container {
    background: var(--bg-card);
    border-radius: 16px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-md);
    border: 1px solid var(--border-color);
  }

  /* Section Headers */
  .section-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 3px solid var(--primary-color);
  }

  .section-header h2, .section-header h3 {
    margin: 0;
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-dark);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .section-icon {
    font-size: 2rem;
    filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.1));
  }

  /* Beautiful Order Table */
  .order-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: var(--shadow-md);
    font-size: 0.9rem;
  }

  .order-table thead {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
  }

  .order-table thead th {
    padding: 1rem 0.75rem;
    text-align: left;
    font-weight: 600;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: white;
    border: none;
    white-space: nowrap;
  }

  .order-table tbody tr {
    border-bottom: 1px solid var(--border-color);
    transition: all 0.3s ease;
  }

  .order-table tbody tr:hover {
    background: linear-gradient(90deg, #f0f9ff 0%, #ffffff 100%);
    transform: translateX(4px);
    box-shadow: var(--shadow-sm);
  }

  .order-table tbody tr:last-child {
    border-bottom: none;
  }

  .order-table tbody td {
    padding: 1rem 0.75rem;
    color: var(--text-dark);
    font-size: 0.85rem;
    vertical-align: middle;
  }

  /* Table Responsive */
  .table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  /* ID Badge */
  .id-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 45px;
    padding: 0.4rem 0.7rem;
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    color: white;
    border-radius: 8px;
    font-weight: 700;
    font-size: 0.85rem;
    box-shadow: var(--shadow-sm);
  }

  /* Status Badges */
  .status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.35rem 0.75rem;
    border-radius: 16px;
    font-weight: 600;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    white-space: nowrap;
  }

  .badge-daraz {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    color: #92400e;
    border: 1px solid #fcd34d;
  }

  .badge-direct {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    color: #065f46;
    border: 1px solid #6ee7b7;
  }

  .badge-tudo {
    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
    color: #1e40af;
    border: 1px solid #93c5fd;
  }

  .badge-payzy {
    background: linear-gradient(135deg, #e9d5ff 0%, #d8b4fe 100%);
    color: #6b21a8;
    border: 1px solid #c084fc;
  }

  /* Store Badges */
  .store-badge {
    display: inline-block;
    padding: 0.3rem 0.6rem;
    border-radius: 12px;
    font-weight: 600;
    font-size: 0.75rem;
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    color: #991b1b;
    border: 1px solid #fca5a5;
  }

  /* Price Display */
  .price-cell {
    font-weight: 700;
    font-size: 0.95rem;
    color: var(--success-color);
  }

  .price-pending {
    color: var(--danger-color);
    font-style: italic;
  }

  /* Action Buttons */
  .action-buttons {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .btn-action {
    padding: 0.5rem 0.75rem;
    border-radius: 8px;
    border: none;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
  }

  .btn-action:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
  }

  .btn-edit {
    background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
    color: white;
  }

  .btn-delete {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
  }

  .btn-invoice {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
  }

  .btn-cash {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
    color: white;
  }

  /* Form Styling */
  .form-control, .form-select {
    border: 2px solid var(--border-color);
    border-radius: 10px;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 0.95rem;
  }

  .form-control:focus, .form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
    outline: none;
  }

  .form-label {
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 0.5rem;
    font-size: 0.85rem;
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  /* Buttons */
  .btn-primary {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    border: none;
    padding: 0.85rem 2rem;
    border-radius: 10px;
    font-weight: 700;
    font-size: 1rem;
    transition: all 0.3s ease;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: white;
  }

  .btn-primary:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e3a8a 100%);
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
  }

  .btn-secondary {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    border: none;
    padding: 0.85rem 2rem;
    border-radius: 10px;
    font-weight: 700;
    color: white;
  }

  .btn-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
    padding: 0.85rem 2rem;
    border-radius: 10px;
    font-weight: 700;
    color: white;
  }

  .btn-outline-primary {
    border: 2px solid var(--primary-color);
    color: var(--primary-color);
    background: white;
    padding: 0.75rem 1.5rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-outline-primary:hover {
    background: var(--primary-color);
    color: white;
  }

  .btn-outline-secondary {
    border: 2px solid #6b7280;
    color: #6b7280;
    background: white;
    padding: 0.75rem 1.5rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-outline-secondary:hover {
    background: #6b7280;
    color: white;
  }

  /* Search Bar */
  .search-container {
    margin-bottom: 1.5rem;
  }

  .input-group .form-control {
    border-right: none;
  }

  .input-group .btn {
    border-left: none;
    background: white;
    border: 2px solid var(--border-color);
    border-left: none;
  }

  /* Modal Styles */
  .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
    animation: fadeIn 0.3s ease;
  }

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  .modal-content {
    background: white;
    margin: 10% auto;
    padding: 2.5rem;
    border-radius: 20px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    animation: slideDown 0.3s ease;
    position: relative;
  }

  @keyframes slideDown {
    from {
      transform: translateY(-50px);
      opacity: 0;
    }
    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    border-bottom: 3px solid var(--primary-color);
  }

  .modal-header h3 {
    margin: 0;
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--text-dark);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .close {
    color: var(--text-light);
    font-size: 2rem;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
    line-height: 1;
    width: 35px;
    height: 35px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }

  .close:hover {
    color: var(--danger-color);
    background: #fee2e2;
    transform: rotate(90deg);
  }

  .modal-body {
    margin-bottom: 2rem;
  }

  .modal-footer {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
  }

  /* Mobile Card Styling */
  @media (max-width: 768px) {
    .order-container {
      padding: 1.5rem;
      border-radius: 12px;
    }

    .mobile-card {
      background: white;
      border-radius: 12px;
      padding: 1.5rem;
      margin-bottom: 1.5rem;
      box-shadow: var(--shadow-md);
      border: 2px solid var(--border-color);
    }
    
    .mobile-card-header {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      margin-bottom: 1.25rem;
      padding-bottom: 1rem;
      border-bottom: 3px solid var(--primary-color);
    }

    .mobile-order-id {
      font-size: 1.1rem;
      font-weight: 800;
      color: var(--text-dark);
    }

    .mobile-invoice {
      font-size: 0.9rem;
      color: var(--text-light);
      font-weight: 600;
    }
    
    .mobile-card-row {
      display: flex;
      justify-content: space-between;
      align-items: start;
      padding: 0.75rem 0;
      border-bottom: 1px solid #f3f4f6;
      gap: 1rem;
    }

    .mobile-card-row:last-child {
      border-bottom: none;
    }
    
    .mobile-card-label {
      font-weight: 700;
      color: var(--text-light);
      font-size: 0.85rem;
      text-transform: uppercase;
      letter-spacing: 0.03em;
      flex-shrink: 0;
    }
    
    .mobile-card-value {
      color: var(--text-dark);
      text-align: right;
      font-size: 0.9rem;
      font-weight: 600;
      word-break: break-word;
    }
    
    .mobile-card-actions {
      margin-top: 1.25rem;
      padding-top: 1rem;
      border-top: 2px solid var(--border-color);
      display: flex;
      gap: 0.5rem;
      justify-content: flex-end;
      flex-wrap: wrap;
    }

    .section-header h2, .section-header h3 {
      font-size: 1.4rem;
    }
    
    .desktop-table {
      display: none;
    }
    
    .mobile-view {
      display: block;
    }

    .btn-mobile-full {
      width: 100%;
      margin-bottom: 0.75rem;
    }

    .search-container {
      max-width: 100%;
    }

    .input-group {
      width: 100%;
    }

    .modal-content {
      margin: 20% auto;
      padding: 2rem;
      width: 95%;
    }
  }
  
  @media (min-width: 769px) {
    .mobile-view {
      display: none;
    }
    
    .desktop-table {
      display: block;
    }
  }

  /* Pagination */
  .pagination {
    gap: 0.5rem;
    flex-wrap: wrap;
  }

  .page-item .page-link {
    border: 2px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-dark);
    font-weight: 600;
    padding: 0.6rem 1.2rem;
    transition: all 0.3s ease;
  }

  .page-item.active .page-link {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    border-color: var(--primary-color);
    color: white;
  }

  .page-item .page-link:hover {
    background: var(--bg-light);
    border-color: var(--primary-color);
    transform: translateY(-2px);
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-light);
  }

  .empty-state-icon {
    font-size: 4rem;
    margin-bottom: 1rem;
    opacity: 0.5;
  }
</style>

<!-- ============================================================================ -->
<!-- ORDER HISTORY / NEW INVOICE NOTICE -->
<!-- ============================================================================ -->

{% if session.get('role') == 'admin' and edit_row %}
<div class="order-container">
  <div class="section-header">
    <span class="section-icon">✏️</span>
    <h2>Edit Old Order</h2>
  </div>
  <div class="alert alert-warning fw-bold">
    This edit screen is only for old single-item orders. For new sales, use the new multi-product/service invoice system.
  </div>
  <form method="POST" action="{{ url_for('edit_order', order_id=edit_row.id) }}" class="row g-3">
    <input type="hidden" name="edit_id" value="{{ edit_row.id }}">
    <div class="col-md-3"><label class="form-label">📅 Date</label><input type="date" class="form-control" name="order_date" value="{{ edit_row.order_date }}" required></div>
    <div class="col-md-3"><label class="form-label">📦 Stock Item</label><select class="form-select" name="stock_id" required><option value="">-- Select Stock --</option>{% for stock in stocks %}<option value="{{ stock.id }}" {% if edit_row.stock_id == stock.id %}selected{% endif %}>{{ stock.stock_id }} - {{ stock.item_name }} (Avail: {{ stock.qty }})</option>{% endfor %}</select></div>
    <div class="col-md-3"><label class="form-label">📄 Invoice No</label><input type="text" class="form-control" name="invoice_no" value="{{ edit_row.invoice_no }}" required></div>
    <div class="col-md-3"><label class="form-label">🔖 Order ID</label><input type="text" class="form-control" name="order_id" value="{{ edit_row.order_id or '' }}"></div>
    <div class="col-md-3"><label class="form-label">🔢 Serial</label><input type="text" class="form-control" name="serial" value="{{ edit_row.serial or '' }}"></div>
    <div class="col-md-3"><label class="form-label">📱 IMEI</label><input type="text" class="form-control" name="imei" value="{{ edit_row.imei or '' }}"></div>
    <div class="col-md-3"><label class="form-label">📞 Contact 1</label><input type="text" class="form-control" name="contact1" value="{{ edit_row.contact1 or '' }}" required></div>
    <div class="col-md-3"><label class="form-label">📞 Contact 2</label><input type="text" class="form-control" name="contact2" value="{{ edit_row.contact2 or '' }}"></div>
    <div class="col-md-3"><label class="form-label">🛒 Order Via</label><input type="text" class="form-control" name="order_via" value="{{ edit_row.order_via or '' }}"></div>
    <div class="col-md-3"><label class="form-label">🏪 Store</label><input type="text" class="form-control" name="store" value="{{ edit_row.store or '' }}"></div>
    <div class="col-md-3"><label class="form-label">📱 Item Name</label><input type="text" class="form-control" name="item_name" value="{{ edit_row.item_name }}" required></div>
    <div class="col-md-3"><label class="form-label">🔢 Qty</label><input type="number" class="form-control" name="qty" value="{{ edit_row.qty }}" required></div>
    <div class="col-md-3"><label class="form-label">💰 Total Price</label><input type="number" step="0.01" class="form-control" name="total_price" value="{{ edit_row.total_price }}" required></div>
    <div class="col-md-3"><label class="form-label">💵 Cash Received</label><input type="number" step="0.01" class="form-control" name="cash_received" value="{{ edit_row.cash_received or 0 }}"></div>
    <div class="col-md-3"><label class="form-label">💸 Cost</label><input type="number" step="0.01" class="form-control" name="cost" value="{{ edit_row.cost }}" required></div>
    <div class="col-md-3"><label class="form-label">🛡️ Product Warranty Days</label><input type="number" class="form-control" name="product_warranty_days" value="{{ edit_row.product_warranty_days or 0 }}"></div>
    <div class="col-md-3"><label class="form-label">🔋 Battery Warranty Days</label><input type="number" class="form-control" name="battery_warranty_days" value="{{ edit_row.battery_warranty_days or 0 }}"></div>
    <div class="col-12"><button type="submit" class="btn btn-primary btn-mobile-full">💾 Update Old Order</button><a href="{{ url_for('index') }}" class="btn btn-secondary ms-2 btn-mobile-full">❌ Cancel</a></div>
  </form>
</div>
{% elif session.get('role') == 'admin' %}
<div class="order-container" style="background:linear-gradient(135deg,#ecfdf5,#ffffff);border:1px solid #bbf7d0;">
  <div class="section-header">
    <span class="section-icon">🧾</span>
    <h2>Create New Invoice</h2>
  </div>
  <p class="fw-bold text-muted mb-3">The old single-order form has been removed. Click below to add multiple products and services in one invoice.</p>
  <a href="{{ url_for('new_invoice') }}" class="btn btn-success btn-lg">➕ Open New Multi-Item Invoice</a>
</div>
{% endif %}

<!-- EXPORT TO EXCEL SECTION -->
<!-- ============================================================================ -->

<div class="order-container">
  <div class="section-header">
    <span class="section-icon">📊</span>
    <h3>Export Orders to Excel</h3>
  </div>
  
  <form method="GET" action="{{ url_for('export_excel') }}" class="row g-3">
    <div class="col-md-4">
      <label for="start_date" class="form-label">📅 From Date</label>
      <input type="date" id="start_date" name="start_date" class="form-control" required>
    </div>
    <div class="col-md-4">
      <label for="end_date" class="form-label">📅 To Date</label>
      <input type="date" id="end_date" name="end_date" class="form-control" required>
    </div>
    <div class="col-md-4 d-flex align-items-end">
      <button type="submit" class="btn btn-success btn-mobile-full">📥 Export to Excel</button>
    </div>
  </form>
</div>

<!-- ============================================================================ -->
<!-- SEARCH & FILTER SECTION -->
<!-- ============================================================================ -->

<div class="order-container">
  <div class="section-header">
    <span class="section-icon">🔍</span>
    <h3>Search & Filter Orders</h3>
  </div>

  <!-- Search Bar -->
  <form method="GET" class="search-container">
    <div class="input-group">
      <input type="text" class="form-control" name="q" placeholder="🔎 Search invoice, order ID, serial, IMEI..."
             value="{{ search_query or '' }}">
      <button class="btn btn-outline-secondary" type="submit">🔍 Search</button>
    </div>
  </form>

  <!-- Filters -->
  <form method="GET" class="row g-3">
    <input type="hidden" name="q" value="{{ search_query or '' }}">
    
    <div class="col-md-2">
      <label for="filter_start_date" class="form-label">📅 From Date</label>
      <input type="date" name="start_date" id="filter_start_date" class="form-control" value="{{ filter_start_date }}">
    </div>
    
    <div class="col-md-2">
      <label for="filter_end_date" class="form-label">📅 To Date</label>
      <input type="date" name="end_date" id="filter_end_date" class="form-control" value="{{ filter_end_date }}">
    </div>
    
    <div class="col-md-2">
      <label for="filter_order_via" class="form-label">🛒 Order Via</label>
      <select name="order_via" id="filter_order_via" class="form-select">
        <option value="All" {% if filter_order_via == 'All' %}selected{% endif %}>All Platforms</option>
        {% for method in ["Daraz", "Direct", "Tudo", "Payzy"] %}
        <option value="{{ method }}" {% if filter_order_via == method %}selected{% endif %}>{{ method }}</option>
        {% endfor %}
      </select>
    </div>
    
    <div class="col-md-2">
      <label for="filter_store" class="form-label">🏪 Store</label>
      <select name="store" id="filter_store" class="form-select">
        <option value="All" {% if filter_store == 'All' %}selected{% endif %}>All Stores</option>
        {% for s in ["NextMode", "3E Solutions", "Cavern&Co", "DirectKA", "DirectYN", "DirectES"] %}
        <option value="{{ s }}" {% if filter_store == s %}selected{% endif %}>{{ s }}</option>
        {% endfor %}
      </select>
    </div>
    
    <div class="col-md-2">
      <label for="filter_cash_status" class="form-label">💵 Cash Status</label>
      <select name="cash_status" id="filter_cash_status" class="form-select">
        <option value="All" {% if filter_cash_status == 'All' %}selected{% endif %}>All Orders</option>
        <option value="Pending" {% if filter_cash_status == 'Pending' %}selected{% endif %}>Pending Only</option>
        <option value="Received" {% if filter_cash_status == 'Received' %}selected{% endif %}>Received Only</option>
      </select>
    </div>
    
    <div class="col-md-2 d-flex align-items-end">
      <div class="w-100">
        <button type="submit" class="btn btn-outline-primary w-100 mb-2">✅ Apply</button>
        <a href="{{ url_for('index') }}" class="btn btn-outline-secondary w-100">🔄 Clear</a>
      </div>
    </div>
  </form>
</div>

<!-- ============================================================================ -->
<!-- ORDERS LIST -->
<!-- ============================================================================ -->

<div class="order-container">
  <div class="section-header">
    <span class="section-icon">📦</span>
    <h2>Orders List</h2>
  </div>

  <!-- Desktop Table View -->
  <div class="desktop-table">
    <div class="table-responsive">
      <table class="order-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Date</th>
            <th>Invoice</th>
            <th>Order ID</th>
            <th>Item</th>
            <th>Serial</th>
            <th>IMEI</th>
            <th>Contact</th>
            <th>Via</th>
            <th>Store</th>
            <th>Qty</th>
            <th>Total</th>
            <th>Cash</th>
            <th>Warranty</th>
            {% if session.get('role') == 'admin' %}
            <th>Actions</th>
            {% endif %}
          </tr>
        </thead>
        <tbody>
          {% for row in orders %}
          <tr>
            <td><span class="id-badge">#{{ row.id }}</span></td>
            <td>{{ row.order_date }}</td>
            <td><strong>{{ row.invoice_no }}</strong></td>
            <td>{{ row.order_id }}</td>
            <td><strong>{{ row.item_name }}</strong></td>
            <td>{{ row.serial }}</td>
            <td>{{ row.imei }}</td>
            <td>{{ row.contact1 }}</td>
            <td>
              <span class="status-badge badge-{{ row.order_via.lower() }}">
                {{ row.order_via }}
              </span>
            </td>
            <td><span class="store-badge">{{ row.store }}</span></td>
            <td>{{ row.qty }}</td>
            <td class="price-cell">Rs. {{ "{:,.2f}".format(row.total_price) }}</td>
            <td>
              {% if row.cash_received == 0 %}
                <span class="price-cell price-pending">Pending</span>
              {% else %}
                <span class="price-cell">Rs. {{ "{:,.2f}".format(row.cash_received) }}</span>
              {% endif %}
            </td>
            <td>{{ row.product_warranty_days }}d / {{ row.battery_warranty_days }}d</td>
            {% if session.get('role') == 'admin' %}
            <td>
              <div class="action-buttons">
                <a href="?edit={{ row.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}" class="btn-action btn-edit" title="Edit">✏️</a>
                <a href="?delete={{ row.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}" onclick="return confirmDelete()" class="btn-action btn-delete" title="Delete">🗑️</a>
                <button onclick="openCashModal({{ row.id }}, {{ row.cash_received }})" class="btn-action btn-cash" title="Update Cash">💵</button>
                <a href="{{ url_for('invoice_options', order_id=row.id) }}" class="btn-action btn-invoice" target="_blank" title="Invoice">📄</a>
              </div>
            </td>
            {% endif %}
          </tr>
          {% else %}
          <tr>
            <td colspan="15">
              <div class="empty-state">
                <div class="empty-state-icon">📭</div>
                <p>No orders found</p>
              </div>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>

  <!-- Mobile Card View -->
  <div class="mobile-view">
    {% for row in orders %}
    <div class="mobile-card">
      <div class="mobile-card-header">
        <span class="mobile-order-id">Order #{{ row.id }}</span>
        <span class="mobile-invoice">Invoice: {{ row.invoice_no }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📅 Date</span>
        <span class="mobile-card-value">{{ row.order_date }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🔖 Order ID</span>
        <span class="mobile-card-value">{{ row.order_id }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📱 Item</span>
        <span class="mobile-card-value"><strong>{{ row.item_name }}</strong></span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🔢 Serial</span>
        <span class="mobile-card-value">{{ row.serial }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📱 IMEI</span>
        <span class="mobile-card-value">{{ row.imei }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">📞 Contact</span>
        <span class="mobile-card-value">{{ row.contact1 }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🛒 Order Via</span>
        <span class="mobile-card-value">
          <span class="status-badge badge-{{ row.order_via.lower() }}">
            {{ row.order_via }}
          </span>
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🏪 Store</span>
        <span class="mobile-card-value">
          <span class="store-badge">{{ row.store }}</span>
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🔢 Quantity</span>
        <span class="mobile-card-value">{{ row.qty }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">💰 Total Price</span>
        <span class="mobile-card-value price-cell">Rs. {{ "{:,.2f}".format(row.total_price) }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">💵 Cash Received</span>
        <span class="mobile-card-value">
          {% if row.cash_received == 0 %}
            <span class="price-cell price-pending">Pending</span>
          {% else %}
            <span class="price-cell">Rs. {{ "{:,.2f}".format(row.cash_received) }}</span>
          {% endif %}
        </span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">💸 Cost</span>
        <span class="mobile-card-value">Rs. {{ "{:,.2f}".format(row.cost) }}</span>
      </div>
      
      <div class="mobile-card-row">
        <span class="mobile-card-label">🛡️ Warranty</span>
        <span class="mobile-card-value">Product: {{ row.product_warranty_days }}d | Battery: {{ row.battery_warranty_days }}d</span>
      </div>
      
      {% if session.get('role') == 'admin' %}
      <div class="mobile-card-actions">
        <a href="?edit={{ row.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}" class="btn-action btn-edit">✏️ Edit</a>
        <a href="?delete={{ row.id }}&page={{ current_page }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}" onclick="return confirmDelete()" class="btn-action btn-delete">🗑️ Delete</a>
        <button onclick="openCashModal({{ row.id }}, {{ row.cash_received }})" class="btn-action btn-cash">💵 Cash</button>
        <a href="{{ url_for('invoice_options', order_id=row.id) }}" class="btn-action btn-invoice" target="_blank">📄 Invoice</a>
      </div>
      {% endif %}
    </div>
    {% else %}
    <div class="empty-state">
      <div class="empty-state-icon">📭</div>
      <p>No orders found</p>
    </div>
    {% endfor %}
  </div>
</div>

<!-- ============================================================================ -->
<!-- PAGINATION -->
<!-- ============================================================================ -->

<nav>
  <ul class="pagination justify-content-center mt-4">
    {% if current_page > 1 %}
    <li class="page-item">
      <a class="page-link" href="?page={{ current_page - 1 }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}">« Prev</a>
    </li>
    {% endif %}
    
    {% for page_num in range(1, total_pages + 1) %}
    <li class="page-item {% if page_num == current_page %}active{% endif %}">
      <a class="page-link" href="?page={{ page_num }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}">{{ page_num }}</a>
    </li>
    {% endfor %}
    
    {% if current_page < total_pages %}
    <li class="page-item">
      <a class="page-link" href="?page={{ current_page + 1 }}{% if search_query %}&q={{ search_query }}{% endif %}{% if filter_start_date %}&start_date={{ filter_start_date }}{% endif %}{% if filter_end_date %}&end_date={{ filter_end_date }}{% endif %}{% if filter_order_via != 'All' %}&order_via={{ filter_order_via }}{% endif %}{% if filter_store != 'All' %}&store={{ filter_store }}{% endif %}{% if filter_cash_status != 'All' %}&cash_status={{ filter_cash_status }}{% endif %}">Next »</a>
    </li>
    {% endif %}
  </ul>
</nav>

<!-- ============================================================================ -->
<!-- CASH RECEIVED UPDATE MODAL -->
<!-- ============================================================================ -->

<div id="cashModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3>💵 Update Cash Received</h3>
      <span class="close" onclick="closeCashModal()">&times;</span>
    </div>
    <div class="modal-body">
      <div class="mb-3">
        <label for="modalCashAmount" class="form-label">Enter Cash Received Amount</label>
        <input type="number" step="0.01" class="form-control" id="modalCashAmount" placeholder="0.00" required>
      </div>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" onclick="closeCashModal()">❌ Cancel</button>
      <button type="button" class="btn btn-primary" onclick="updateCashReceived()">💾 Update</button>
    </div>
  </div>
</div>

<!-- ============================================================================ -->
<!-- JAVASCRIPT -->
<!-- ============================================================================ -->

<script>
  let currentOrderId = null;

  function openCashModal(orderId, currentCash) {
    currentOrderId = orderId;
    document.getElementById('modalCashAmount').value = currentCash || 0;
    document.getElementById('cashModal').style.display = 'block';
  }

  function closeCashModal() {
    document.getElementById('cashModal').style.display = 'none';
    currentOrderId = null;
  }

  window.onclick = function(event) {
    const modal = document.getElementById('cashModal');
    if (event.target === modal) {
      closeCashModal();
    }
  }

  async function updateCashReceived() {
    const cashAmount = parseFloat(document.getElementById('modalCashAmount').value);
    
    if (isNaN(cashAmount) || cashAmount < 0) {
      alert('❌ Please enter a valid amount');
      return;
    }

    try {
      const response = await fetch('/update_cash_received', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          order_id: currentOrderId,
          cash_received: cashAmount
        })
      });

      const result = await response.json();

      if (result.success) {
        alert('✅ Cash received updated successfully!');
        closeCashModal();
        location.reload();
      } else {
        alert('❌ Error: ' + result.message);
      }
    } catch (error) {
      alert('❌ Error updating cash received: ' + error.message);
    }
  }

  function confirmDelete() {
    if (!confirm("⚠️ Are you sure you want to delete this order?")) return false;
    const password = prompt("🔐 Enter password to confirm deletion:");
    if (password === "12345") return true;
    alert("❌ Incorrect password. Deletion canceled.");
    return false;
  }
</script>
{% endblock %}