{% extends 'core/base.html' %}
{% load static %}

{% block title %}Variants — {{ product.name }} | SwiftPOS{% endblock %}
{% block topbar_title %}Product Variants{% endblock %}

{% block extra_css %}
<style>
/* Keep variant modals interactive above any page overlay */
#variantModal, #restockModal { z-index: 1000020 !important; }
.modal .form-control, .modal input, .modal textarea, .modal select {
  pointer-events: auto !important;
}
</style>
{% endblock %}

{% block content %}
<div class="variants-page">

  <!-- Header -->
  <div class="page-header d-flex align-items-center justify-content-between mb-4">
    <div>
      <a href="{% url 'inventory:product_detail' product.id %}" class="btn btn-sm btn-outline-secondary me-2">
        <i class="fas fa-arrow-left"></i> Back
      </a>
      <h4 class="d-inline-block mb-0 fw-bold">Product Variants</h4>
      <span class="text-muted ms-2">{{ product.name }}</span>
    </div>
    <button class="btn btn-primary" id="addVariantBtn">
      <i class="fas fa-plus me-1"></i> Add Variant
    </button>
  </div>

  <!-- Variants Grid View -->
  <div class="row g-4 mb-4">
    {% if variants %}
      {% for v in variants %}
      <div class="col-12 col-md-6 col-xl-4 align-self-stretch" id="row-{{ v.id }}">
        <div class="card h-100 shadow-sm border-0 position-relative transition-hover" style="border-radius: 16px;">
          <div class="card-body">
            <!-- Header: Label + Status -->
            <div class="d-flex justify-content-between align-items-start mb-2">
              <h5 class="fw-bold text-dark mb-0 d-flex align-items-center gap-2">
                {{ v.display_label }}
              </h5>
              <div>
                {% if v.stock_status == 'in_stock' %}
                  <span class="badge bg-success-subtle text-success border-0 px-2 py-1">In Stock</span>
                {% elif v.stock_status == 'low_stock' %}
                  <span class="badge bg-warning-subtle text-warning border-0 px-2 py-1">Low Stock</span>
                {% else %}
                  <span class="badge bg-danger-subtle text-danger border-0 px-2 py-1">Out of Stock</span>
                {% endif %}
              </div>
            </div>

            <!-- SKU/Barcode -->
            <div class="mb-3 small text-muted">
              <span>SKU: <code class="text-primary">{{ v.sku }}</code></span>
              {% if v.barcode %} • Barcode: {{ v.barcode }}{% endif %}
            </div>

            <!-- Attributes Badges -->
            <div class="mb-3 d-flex flex-wrap gap-2">
              {% for attr in v.attributes.all %}
                <span class="badge bg-light text-dark border">{{ attr.attribute_name|title }}: {{ attr.attribute_value }}</span>
              {% empty %}
                <span class="badge bg-light text-muted border border-dashed">Standard</span>
              {% endfor %}
            </div>

            <!-- Safe attributes data for JS edit form -->
            <div class="d-none variant-attrs-data" data-id="{{ v.id }}">
               {% for key, val in v.attribute_values.items %}
                   <span data-key="{{ key }}" data-value="{{ val }}"></span>
               {% endfor %}
            </div>

            <!-- Pricing & Stock -->
            <div class="row g-2 mb-3 bg-light rounded p-2" style="margin-left: 0; margin-right: 0;">
              <div class="col-4 px-1 text-center">
                <div class="text-muted" style="font-size:0.75rem;">Price</div>
                <div class="fw-bold text-success">{{ currency_symbol }}{{ v.effective_price|floatformat:2 }}</div>
              </div>
              <div class="col-4 px-1 border-start border-end text-center">
                <div class="text-muted" style="font-size:0.75rem;">Cost</div>
                <div class="fw-semibold">{{ currency_symbol }}{{ v.effective_cost|floatformat:2 }}</div>
              </div>
              <div class="col-4 px-1 text-center">
                {% if user_branch %}
                  <div class="text-muted" style="font-size:0.75rem;">Branch Stock</div>
                  <div class="fw-bold" id="vstock-{{ v.id }}"
                       data-global="{{ v.stock_quantity }}">{{ v.stock_quantity }}</div>
                  <div class="text-muted" id="vstock-global-lbl-{{ v.id }}" style="font-size:0.65rem;">Global: {{ v.stock_quantity }}</div>
                {% else %}
                  <div class="text-muted" style="font-size:0.75rem;">Stock</div>
                  <div class="fw-bold" id="vstock-{{ v.id }}">{{ v.stock_quantity }}</div>
                {% endif %}
              </div>
            </div>
          </div>

          <!-- Card Footer for actions -->
          <div class="card-footer bg-transparent border-top-0 pt-0 pb-3 d-flex gap-2 justify-content-end">
            <!-- Edit Button -->
            <button class="btn btn-sm btn-outline-primary edit-btn flex-grow-1"
                    data-id="{{ v.id }}"
                    data-sku="{{ v.sku }}"
                    data-barcode="{{ v.barcode|default:'' }}"
                    data-price="{{ v.price|default:'' }}"
                    data-cost="{{ v.cost_price|default:'' }}"
                    data-stock="{{ v.stock_quantity }}"
                    data-min-stock="{{ v.minimum_stock }}"
                    title="Edit Variant">
              <i class="fas fa-pencil-alt"></i> Edit
            </button>
            <!-- Quick Restock -->
            <button class="btn btn-sm btn-outline-success restock-btn flex-grow-1"
                    data-id="{{ v.id }}" data-name="{{ v.display_label }}" title="Quick Restock directly">
              <i class="fas fa-plus"></i> Restock
            </button>
            <!-- Delete -->
            <button class="btn btn-sm btn-outline-danger delete-btn"
                    data-id="{{ v.id }}" data-name="{{ v.display_label }}" title="Delete">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>
      {% endfor %}
    {% else %}
      <div class="col-12">
        <div class="card shadow-sm border-0 py-5 text-center" style="border-radius: 16px;">
          <div class="card-body">
             <i class="fas fa-swatchbook fa-3x text-muted mb-3 d-block"></i>
            <h5 class="fw-bold">No variants yet</h5>
            <p class="text-muted mb-4">Add your first variant (e.g. Size: M, Colour: Red) to track product variations.</p>
            <button class="btn btn-primary px-4 fw-bold shadow-sm" id="addVariantBtnEmpty">
              <i class="fas fa-plus me-1"></i> Add First Variant
            </button>
          </div>
        </div>
      </div>
    {% endif %}
  </div>

</div>

<!-- ── Add / Edit Variant Modal ─────────────────────────── -->
<div class="modal fade" id="variantModal" tabindex="-1" aria-labelledby="variantModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="variantModalLabel">Add Variant</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="variantForm">
          <input type="hidden" id="variantId" value="">

          <!-- Attribute Builder -->
          <div class="mb-3">
            <label class="form-label fw-bold">Attributes <small class="text-muted">(e.g. Size: XL, Colour: Red)</small></label>
            <div id="attrBuilder"></div>
            <button type="button" class="btn btn-sm btn-outline-secondary mt-2" id="addAttrRow">
              <i class="fas fa-plus me-1"></i> Add Attribute
            </button>
          </div>

          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label fw-bold">SKU <span class="text-danger">*</span></label>
              <input type="text" class="form-control" id="variantSku" required placeholder="e.g. SNKR-XL-RED">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-bold">Barcode</label>
              <input type="text" class="form-control" id="variantBarcode" placeholder="Optional">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-bold">Stock Quantity</label>
              <input type="number" class="form-control" id="variantStock" value="0" min="0">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-bold">Selling Price (₦)</label>
              <input type="number" class="form-control" id="variantPrice" step="0.01" placeholder="Leave blank = inherit">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-bold">Cost Price (₦)</label>
              <input type="number" class="form-control" id="variantCost" step="0.01" placeholder="Leave blank = inherit">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-bold">Minimum Stock</label>
              <input type="number" class="form-control" id="variantMinStock" value="5" min="0">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="saveVariantBtn">
          <i class="fas fa-save me-1"></i> Save Variant
        </button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="restockModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content border-0 shadow">
      <div class="modal-header bg-success text-white">
        <h6 class="modal-title"><i class="fas fa-boxes me-1"></i> Quick Restock</h6>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p class="mb-3 small fw-semibold text-dark" id="restockVariantName"></p>

        <div class="mb-3">
          <label class="form-label small fw-semibold">Quantity to Add <span class="text-danger">*</span></label>
          <input type="number" class="form-control" id="restockQty" value="1" min="1">
        </div>

        {% if branches %}
        <div class="mb-2">
          <label class="form-label small fw-semibold">Add Stock To Branch</label>
          <select class="form-select" id="restockBranch">
            <option value="">— Global (no specific branch) —</option>
            {% for branch in branches %}
            <option value="{{ branch.id }}">{{ branch.name }}</option>
            {% endfor %}
          </select>
          <div class="form-text text-muted">Choose a branch to update branch-level stock, or leave blank to update global stock.</div>
        </div>
        {% endif %}

        <input type="hidden" id="restockVariantId">
      </div>
      <div class="modal-footer">
        <button class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-sm btn-success" id="confirmRestockBtn">
          <i class="fas fa-plus me-1"></i> Add Stock
        </button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    var m1 = document.getElementById('variantModal');
    if (m1) document.body.appendChild(m1);
    var m2 = document.getElementById('restockModal');
    if (m2) document.body.appendChild(m2);
});

const PRODUCT_ID   = {{ product.id }};
const BASE_URL     = `/{{ request.company.slug }}/inventory/products/${PRODUCT_ID}/variants/`;
const CSRF         = document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';

// ── Attribute Builder ─────────────────────────────────────
function addAttrRow(key='', val='') {
  const row = document.createElement('div');
  row.className = 'input-group mb-2 attr-row';
  row.innerHTML = `
    <input type="text" class="form-control attr-key" placeholder="Attribute (e.g. Size)" value="${key}">
    <input type="text" class="form-control attr-val" placeholder="Value (e.g. XL)" value="${val}">
    <button class="btn btn-outline-danger remove-attr" type="button"><i class="fas fa-times"></i></button>
  `;
  row.querySelector('.remove-attr').onclick = () => row.remove();
  document.getElementById('attrBuilder').appendChild(row);
}
document.getElementById('addAttrRow').onclick = () => addAttrRow();
document.getElementById('addVariantBtn')?.addEventListener('click', openAddModal);
document.getElementById('addVariantBtnEmpty')?.addEventListener('click', openAddModal);

function openAddModal() {
  document.getElementById('variantModalLabel').textContent = 'Add Variant';
  document.getElementById('variantId').value = '';
  document.getElementById('variantSku').value = '';
  document.getElementById('variantBarcode').value = '';
  document.getElementById('variantStock').value = '0';
  document.getElementById('variantPrice').value = '';
  document.getElementById('variantCost').value = '';
  document.getElementById('variantMinStock').value = '5';
  document.getElementById('attrBuilder').innerHTML = '';
  addAttrRow();
  bootstrap.Modal.getOrCreateInstance(document.getElementById('variantModal')).show();
}

document.querySelectorAll('.edit-btn').forEach(btn => {
  btn.onclick = () => {
    document.getElementById('variantModalLabel').textContent = 'Edit Variant';
    document.getElementById('variantId').value    = btn.dataset.id;
    document.getElementById('variantSku').value   = btn.dataset.sku;
    document.getElementById('variantBarcode').value = (btn.dataset.barcode !== 'None') ? btn.dataset.barcode : '';
    document.getElementById('variantStock').value = btn.dataset.stock;
    document.getElementById('variantPrice').value = (btn.dataset.price && btn.dataset.price !== 'None' && btn.dataset.price !== 'NaN') ? btn.dataset.price : '';
    document.getElementById('variantCost').value  = (btn.dataset.cost && btn.dataset.cost !== 'None' && btn.dataset.cost !== 'NaN') ? btn.dataset.cost : '';
    document.getElementById('variantMinStock').value = btn.dataset.minStock;
    document.getElementById('attrBuilder').innerHTML = '';
    
    // Safely reconstruct the attributes dict by retrieving the hidden data keys/values inside the matching card
    const dataContainer = document.querySelector(`.variant-attrs-data[data-id="${btn.dataset.id}"]`);
    if (dataContainer) {
        dataContainer.querySelectorAll('span').forEach(span => {
            addAttrRow(span.dataset.key, span.dataset.value);
        });
    }

    // Default to at least one empty row if no attributes exist
    if (document.getElementById('attrBuilder').children.length === 0) {
        addAttrRow();
    }

    bootstrap.Modal.getOrCreateInstance(document.getElementById('variantModal')).show();
  };
});

// ── Save (create / update) ────────────────────────────────
document.getElementById('saveVariantBtn').onclick = async () => {
  const id = document.getElementById('variantId').value;
  const attrs = {};
  document.querySelectorAll('.attr-row').forEach(row => {
    const k = row.querySelector('.attr-key').value.trim();
    const v = row.querySelector('.attr-val').value.trim();
    if (k && v) attrs[k] = v;
  });

  const payload = {
    sku:              document.getElementById('variantSku').value.trim(),
    barcode:          document.getElementById('variantBarcode').value.trim(),
    attribute_values: attrs,
    price:            document.getElementById('variantPrice').value || null,
    cost_price:       document.getElementById('variantCost').value || null,
    stock_quantity:   parseInt(document.getElementById('variantStock').value, 10) || 0,
    minimum_stock:    parseInt(document.getElementById('variantMinStock').value, 10) || 5,
  };

  const url    = id ? `${BASE_URL}${id}/` : BASE_URL;
  const method = id ? 'POST' : 'POST';

  const resp = await fetch(url, {
    method,
    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': CSRF },
    body: JSON.stringify(payload),
  });
  const data = await resp.json();
  if (data.ok) {
    bootstrap.Modal.getInstance(document.getElementById('variantModal')).hide();
    location.reload();
  } else {
    alert(data.error || 'Failed to save variant');
  }
};

// ── Delete ────────────────────────────────────────────────
document.querySelectorAll('.delete-btn').forEach(btn => {
  btn.onclick = async () => {
    if (!confirm(`Delete variant "${btn.dataset.name}"?`)) return;
    const resp = await fetch(`${BASE_URL}${btn.dataset.id}/`, {
      method: 'DELETE',
      headers: { 'X-CSRFToken': CSRF },
    });
    const data = await resp.json();
    if (data.ok) document.getElementById(`row-${btn.dataset.id}`)?.remove();
    else alert(data.error || 'Delete failed');
  };
});

// ── Restock ───────────────────────────────────────────────
document.querySelectorAll('.restock-btn').forEach(btn => {
  btn.onclick = () => {
    document.getElementById('restockVariantName').textContent = btn.dataset.name;
    document.getElementById('restockVariantId').value = btn.dataset.id;
    document.getElementById('restockQty').value = '1';
    bootstrap.Modal.getOrCreateInstance(document.getElementById('restockModal')).show();
  };
});

document.getElementById('confirmRestockBtn').onclick = async () => {
  const id        = document.getElementById('restockVariantId').value;
  const qty       = parseInt(document.getElementById('restockQty').value, 10);
  const branchEl  = document.getElementById('restockBranch');
  const branch_id = branchEl ? (branchEl.value || null) : null;

  if (!qty || qty < 1) { alert('Please enter a valid quantity.'); return; }

  const payload = { quantity: qty };
  if (branch_id) payload.branch_id = parseInt(branch_id, 10);

  const resp = await fetch(`${BASE_URL}${id}/restock/`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-CSRFToken': CSRF },
    body: JSON.stringify(payload),
  });
  const data = await resp.json();
  if (data.ok) {
    bootstrap.Modal.getInstance(document.getElementById('restockModal')).hide();
    const branchMsg = data.branch_name ? ` (${data.branch_name})` : ' (global)';

    // ── Update the card stock div in-place immediately ──────────────
    const stockEl = document.getElementById(`vstock-${id}`);
    if (stockEl) {
      stockEl.textContent = data.new_stock;
      const globalLbl = document.getElementById(`vstock-global-lbl-${id}`);
      if (globalLbl) globalLbl.textContent = `Global: ${data.variant_total_stock}`;
    }

    // ── Toast ────────────────────────────────────────────────────────
    const toastEl = document.createElement('div');
    toastEl.className = 'alert alert-success position-fixed bottom-0 start-50 translate-middle-x mb-3 shadow px-4 py-2';
    toastEl.style.zIndex = '9999';
    toastEl.textContent = `+${qty} units added${branchMsg}. Branch: ${data.new_stock} | Global: ${data.variant_total_stock}`;
    document.body.appendChild(toastEl);
    setTimeout(() => { toastEl.remove(); location.reload(); }, 2000);
  } else {
    alert(data.error || 'Restock failed');
  }
};

// ── Inject branch stocks from server-side JSON on page load ────────────────
(function () {
  {% if user_branch and vbs_list %}
  const vbsData = {{ vbs_list|safe }};
  const vbsMap = {};
  vbsData.forEach(function(item) { vbsMap[item.variant_id] = item.quantity; });

  document.querySelectorAll('[id^="vstock-"]').forEach(function(el) {
    if (el.id.indexOf('global-lbl') !== -1) return; // skip label spans
    const variantId = parseInt(el.id.replace('vstock-', ''), 10);
    if (!variantId) return;
    if (vbsMap.hasOwnProperty(variantId)) {
      el.textContent = vbsMap[variantId];
    } else {
      // No branch stock record: append * to signal global fallback
      const globalVal = el.dataset.global || el.textContent;
      el.textContent = globalVal + '\u2009*';
      el.setAttribute('title', 'No branch-specific stock. Showing global stock.');
    }
  });
  {% endif %}
})();
</script>
{% endblock %}

