<%- include('../layouts/admin-header') %>

<!-- Summary Cards Grid -->
<div class="stat-grid">
  <!-- 1. Active Products -->
  <a href="/admin/products?status=active" class="stat-card stat-card-link" title="Click to view all active products in catalogue">
    <div class="stat-icon" style="background:#EFF6FF; color:#3B82F6;">👔</div>
    <div style="flex-grow: 1;">
      <div class="stat-val"><%= stats.activeProducts %></div>
      <div class="stat-label">Active Products</div>
      <span class="stat-card-action">View Catalogue →</span>
    </div>
  </a>

  <!-- 2. Product Variations -->
  <a href="/admin/inventory" class="stat-card stat-card-link" title="Click to view all variations and sizes">
    <div class="stat-icon" style="background:#F3E8FF; color:#9333EA;">🧩</div>
    <div style="flex-grow: 1;">
      <div class="stat-val"><%= stats.totalVariations %></div>
      <div class="stat-label">Total Variations</div>
      <span class="stat-card-action">View Variations →</span>
    </div>
  </a>

  <!-- 3. Total Inventory Units -->
  <a href="/admin/inventory" class="stat-card stat-card-link" title="Click to view inventory units and stock levels">
    <div class="stat-icon" style="background:#ECFDF5; color:#10B981;">📦</div>
    <div style="flex-grow: 1;">
      <div class="stat-val"><%= stats.totalUnits %></div>
      <div class="stat-label">Units in Stock</div>
      <span class="stat-card-action">Manage Inventory →</span>
    </div>
  </a>

  <!-- 4. Low-Stock Products -->
  <a href="/admin/inventory?filter=low_stock" class="stat-card stat-card-link" title="Click to filter low-stock variations needing replenishment">
    <div class="stat-icon" style="background:#FFFBEB; color:#F59E0B;">⚠️</div>
    <div style="flex-grow: 1;">
      <div class="stat-val"><%= stats.lowStockCount %></div>
      <div class="stat-label">Low-Stock Products</div>
      <span class="stat-card-action" style="color:#B45309;">Review Alerts →</span>
    </div>
  </a>

  <!-- 5. Out-of-Stock Variations -->
  <a href="/admin/inventory?filter=out_of_stock" class="stat-card stat-card-link" title="Click to view sold out items and restock">
    <div class="stat-icon" style="background:#FEF2F2; color:#EF4444;">🚫</div>
    <div style="flex-grow: 1;">
      <div class="stat-val"><%= stats.outOfStockCount %></div>
      <div class="stat-label">Out-of-Stock Variations</div>
      <span class="stat-card-action" style="color:#DC2626;">Restock Items →</span>
    </div>
  </a>
</div>

<!-- Low Stock Warnings Alert Banner if any -->
<% if (stats.lowStockAlerts && stats.lowStockAlerts.length > 0) { %>
  <div class="panel" style="border-left: 4px solid var(--admin-warning); margin-bottom: 2rem;">
    <div class="panel-header" style="background:#FFFBEB;">
      <div class="panel-title" style="color:#B45309; display:flex; align-items:center; gap:0.5rem;">
        <span>⚠️</span> Immediate Attention: Low &amp; Out-of-Stock Alerts
      </div>
      <a href="/admin/inventory?filter=low_stock" class="admin-btn admin-btn-sm admin-btn-secondary">View Inventory Filter →</a>
    </div>
    <div class="panel-body" style="padding:0;">
      <div class="table-responsive">
        <table class="data-table">
          <thead>
            <tr>
              <th>Product</th>
              <th>Variation SKU</th>
              <th>Size / Quality</th>
              <th>Current Stock</th>
              <th>Threshold</th>
              <th>Status</th>
              <th style="text-align: right;">Quick Action</th>
            </tr>
          </thead>
          <tbody>
            <% stats.lowStockAlerts.forEach(alert => { %>
              <tr>
                <td><strong><%= alert.product_name %></strong></td>
                <td><code style="background:#F1ECE4; padding:2px 6px; border-radius:4px; color:#8F7B6B;"><%= alert.sku %></code></td>
                <td><%= alert.size ? `${alert.size} — ` : '' %><%= alert.quality %></td>
                <td><strong style="color: <%= alert.stock_quantity === 0 ? '#EF4444' : '#F59E0B' %>; font-size:1.1rem;"><%= alert.stock_quantity %></strong> units</td>
                <td><%= alert.low_stock_threshold %> units</td>
                <td>
                  <% if (alert.stock_quantity === 0) { %>
                    <span class="admin-badge badge-out">Sold Out</span>
                  <% } else { %>
                    <span class="admin-badge badge-low">Low Stock</span>
                  <% } %>
                </td>
                <td style="text-align: right;">
                  <button type="button" class="admin-btn admin-btn-sm admin-btn-primary" 
                    onclick="openStockModal('<%= alert.variation_id %>', '<%= alert.sku %>', '<%= alert.stock_quantity %>', '<%= alert.product_name %>')">
                    Adjust / Replenish
                  </button>
                </td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<% } %>

<!-- Two Columns: Recent Orders & Recent Stock Movements -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; align-items: start;">
  
  <!-- Left: Recent WhatsApp Orders / Inquiries -->
  <div class="panel">
    <div class="panel-header">
      <div class="panel-title">Recent WhatsApp Orders &amp; Inquiries</div>
      <a href="/admin/orders" class="admin-btn admin-btn-sm admin-btn-secondary">All Orders →</a>
    </div>
    <div class="panel-body" style="padding:0;">
      <% if (stats.recentOrders && stats.recentOrders.length > 0) { %>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>Reference</th>
                <th>Customer</th>
                <th>Subtotal</th>
                <th>Status</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <% stats.recentOrders.forEach(o => { %>
                <tr>
                  <td><code style="font-weight:700;"><%= o.order_reference %></code></td>
                  <td>
                    <div><%= o.customer_name %></div>
                    <small style="color:#64748B;"><%= o.customer_phone %></small>
                  </td>
                  <td><strong>₹<%= o.subtotal.toLocaleString('en-IN') %></strong></td>
                  <td>
                    <% if (o.status === 'confirmed') { %>
                      <span class="admin-badge badge-confirmed">Confirmed</span>
                    <% } else if (o.status === 'fulfilled') { %>
                      <span class="admin-badge badge-fulfilled">Fulfilled</span>
                    <% } else if (o.status === 'cancelled') { %>
                      <span class="admin-badge badge-cancelled">Cancelled</span>
                    <% } else { %>
                      <span class="admin-badge badge-inquiry">Inquiry</span>
                    <% } %>
                  </td>
                  <td>
                    <a href="/admin/orders/<%= o.id %>" class="admin-btn admin-btn-sm admin-btn-secondary">Inspect</a>
                  </td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      <% } else { %>
        <div style="padding: 2.5rem; text-align: center; color: #64748B;">No recent orders recorded.</div>
      <% } %>
    </div>
  </div>

  <!-- Right: Recent Stock Movements Audit -->
  <div class="panel">
    <div class="panel-header">
      <div class="panel-title">Recent Stock Movements</div>
      <a href="/admin/stock-history" class="admin-btn admin-btn-sm admin-btn-secondary">Full Audit Log →</a>
    </div>
    <div class="panel-body" style="padding:0;">
      <% if (stats.recentMovements && stats.recentMovements.length > 0) { %>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th>Date/Time</th>
                <th>Product &amp; SKU</th>
                <th>Movement</th>
                <th>New Stock</th>
                <th>Reason</th>
              </tr>
            </thead>
            <tbody>
              <% stats.recentMovements.forEach(m => { %>
                <tr>
                  <td style="font-size:0.75rem; color:#64748B;"><%= m.created_at.slice(0, 16) %></td>
                  <td>
                    <div style="font-weight:600;"><%= m.product_name %></div>
                    <small style="color:#64748B;"><%= m.variation_sku %></small>
                  </td>
                  <td>
                    <span style="font-weight:700; color: <%= m.quantity_change > 0 ? '#10B981' : '#EF4444' %>;">
                      <%= m.quantity_change > 0 ? `+${m.quantity_change}` : m.quantity_change %>
                    </span>
                  </td>
                  <td><strong><%= m.new_quantity %></strong></td>
                  <td><small><%= m.reason %></small></td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      <% } else { %>
        <div style="padding: 2.5rem; text-align: center; color: #64748B;">No recent stock movements.</div>
      <% } %>
    </div>
  </div>

</div>

<!-- Stock Adjustment & Replenishment Modal -->
<div id="stockAdjustModal" style="display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.65); backdrop-filter: blur(2px); z-index: 9999; align-items: center; justify-content: center; padding: 1.5rem;">
  <div style="background: #FFFFFF; border: 1px solid var(--admin-border); border-radius: 12px; width: 100%; max-width: 520px; box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden;">
    <div style="display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--admin-border); background: #FAF8F5;">
      <h3 style="margin: 0; font-size: 1.15rem; font-weight: 700; color: var(--admin-text-main);">Adjust &amp; Replenish Stock</h3>
      <button type="button" onclick="closeStockModal()" style="background: transparent; border: none; font-size: 1.5rem; line-height: 1; color: var(--admin-text-muted); cursor: pointer;" title="Close modal">&times;</button>
    </div>

    <form action="/admin/inventory/adjust" method="POST" style="padding: 1.5rem;">
      <input type="hidden" id="modal_var_id" name="variation_id">

      <div style="background: #FAF8F5; border: 1px solid var(--admin-border); border-radius: 8px; padding: 0.85rem 1rem; margin-bottom: 1.25rem;">
        <div id="modal_product_name" style="font-weight: 700; color: var(--admin-text-main); font-size: 0.95rem;"></div>
        <div style="display: flex; gap: 1rem; margin-top: 0.35rem; font-size: 0.82rem; color: var(--admin-text-muted);">
          <span>SKU: <code id="modal_sku" style="color: #8F7B6B; background: #F1ECE4; padding: 1px 6px; border-radius: 4px;"></code></span>
          <span>Current Units: <strong id="modal_cur_stock" style="color: var(--admin-text-main); font-size: 0.95rem;"></strong></span>
        </div>
      </div>

      <div class="admin-form-group">
        <label class="admin-label" for="adj_type">Adjustment Type *</label>
        <select id="adj_type" name="adjustment_type" class="admin-select" required onchange="handleAdjTypeChange(this.value)">
          <option value="add">➕ Incoming Stock / Replenish from Mill (Add to stock)</option>
          <option value="physical_count">📊 Physical Inventory Recount (Set exact stock)</option>
          <option value="remove">➖ Remove / Write-off Stock (Deduct from stock)</option>
          <option value="damaged">⚠️ Damaged / Defective Stock (Deduct from stock)</option>
          <option value="sold">🛍️ In-Store Offline Sale (Deduct from stock)</option>
        </select>
      </div>

      <div class="admin-form-group">
        <label class="admin-label" id="qty_label" for="qty_val">Units to Add *</label>
        <input type="number" id="qty_val" name="quantity_value" class="admin-input" min="1" value="10" required>
        <small id="qty_help" style="color: var(--admin-text-muted); font-size: 0.78rem; display: block; margin-top: 0.3rem;">
          Enter the number of units received to add to the existing stock.
        </small>
      </div>

      <div class="admin-form-group">
        <label class="admin-label" for="adj_reason">Adjustment Reason *</label>
        <input type="text" id="adj_reason" name="reason" class="admin-input" required placeholder="e.g. Weaving mill delivery batch, seasonal restock, count audit">
      </div>

      <div class="admin-form-group" style="margin-bottom: 1.5rem;">
        <label class="admin-label" for="adj_notes">Additional Audit Notes (Optional)</label>
        <textarea id="adj_notes" name="notes" rows="2" class="admin-textarea" placeholder="Internal notes for stock movement audit log..."></textarea>
      </div>

      <div style="display: flex; justify-content: flex-end; gap: 0.75rem;">
        <button type="button" onclick="closeStockModal()" class="admin-btn admin-btn-secondary">Cancel</button>
        <button type="submit" class="admin-btn admin-btn-primary">Apply Stock Update</button>
      </div>
    </form>
  </div>
</div>

<script>
  function openStockModal(varId, sku, curStock, prodName) {
    document.getElementById('modal_var_id').value = varId;
    document.getElementById('modal_sku').textContent = sku;
    document.getElementById('modal_product_name').textContent = prodName;
    document.getElementById('modal_cur_stock').textContent = curStock + ' units';
    document.getElementById('adj_type').value = 'add';
    handleAdjTypeChange('add');
    document.getElementById('stockAdjustModal').style.display = 'flex';
  }

  function closeStockModal() {
    document.getElementById('stockAdjustModal').style.display = 'none';
  }

  function handleAdjTypeChange(type) {
    const lbl = document.getElementById('qty_label');
    const hlp = document.getElementById('qty_help');
    if (type === 'physical_count') {
      lbl.textContent = 'Exact Physical Count *';
      hlp.textContent = 'Set the exact number of units physically in the atelier/warehouse.';
    } else if (type === 'add') {
      lbl.textContent = 'Units to Add *';
      hlp.textContent = 'Enter the number of units received to add to existing stock.';
    } else {
      lbl.textContent = 'Units to Deduct *';
      hlp.textContent = 'Enter the number of units to subtract from available stock.';
    }
  }

  document.getElementById('stockAdjustModal').addEventListener('click', function(e) {
    if (e.target === this) closeStockModal();
  });
</script>

<%- include('../layouts/admin-footer') %>
