{% extends 'base.html' %}
{% block title %}Store Manager Dashboard{% endblock %}
{% block content %}
<div class="space-y-6">
  <div class="flex flex-wrap justify-between items-center gap-3">
    <div>
      <h1 class="text-2xl font-bold">Store Manager Dashboard</h1>
      <p class="text-sm opacity-70">Operational control of stock health and approvals.</p>
    </div>
    <div class="flex gap-2">
      <a href="{% url 'inventory:transfer_list' %}" class="btn btn-primary btn-sm">Approve Transfers</a>
      <a href="{% url 'inventory:adjustment_request_list' %}" class="btn btn-outline btn-sm">Approve Adjustments</a>
      <a href="{% url 'inventory:po_create' %}" class="btn btn-outline btn-sm">Create PO</a>
      <a href="{% url 'finance:dashboard_data' %}?start={{ start_date|date:'Y-m-d' }}&end={{ end_date|date:'Y-m-d' }}" class="btn btn-outline btn-sm">Live JSON</a>
    </div>
  </div>

  <form method="get" class="bg-base-100 border border-base-200 rounded-box p-3 flex flex-wrap items-end gap-2">
    <label class="form-control">
      <span class="label-text text-xs">Start</span>
      <input type="date" name="start" value="{{ start_date|date:'Y-m-d' }}" class="input input-bordered input-sm">
    </label>
    <label class="form-control">
      <span class="label-text text-xs">End</span>
      <input type="date" name="end" value="{{ end_date|date:'Y-m-d' }}" class="input input-bordered input-sm">
    </label>
    <button type="submit" class="btn btn-primary btn-sm">Apply</button>
    <a href="{% url 'finance:dashboard_store_manager' %}" class="btn btn-ghost btn-sm">Reset</a>
  </form>

  <div class="flex flex-wrap gap-2">
    <span class="badge badge-error p-3">Low Stock: {{ low_stock_items|length }}</span>
    <span class="badge badge-warning p-3">Out of Stock: {{ out_of_stock_items|length }}</span>
    <span class="badge badge-secondary p-3">Pending Transfers: {{ pending_transfer_requests|length }}</span>
    <span class="badge badge-info p-3">Pending Adjustments: {{ notifications.pending_adjustment_count }}</span>
  </div>

  <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
    <div class="card bg-base-100 shadow border border-base-200">
      <div class="card-body">
        <h2 class="card-title text-base">Stock by Category (Pie)</h2>
        <div class="h-72"><canvas id="smStockCategoryChart"></canvas></div>
      </div>
    </div>
    <div class="card bg-base-100 shadow border border-base-200">
      <div class="card-body">
        <h2 class="card-title text-base">Adjustments by Reason (Pie)</h2>
        <div class="h-72"><canvas id="smAdjustmentChart"></canvas></div>
      </div>
    </div>
    <div class="card bg-base-100 shadow border border-base-200">
      <div class="card-body">
        <h2 class="card-title text-base">Fast vs Slow Movement</h2>
        <div class="h-72"><canvas id="smVelocityChart"></canvas></div>
      </div>
    </div>
  </div>

  <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Stock by Category</h2><table class="table table-sm"><thead><tr><th>Category</th><th>Items</th><th>Qty</th><th>Value</th></tr></thead><tbody>{% for row in stock_by_category %}<tr><td>{{ row.category__name|default:'Uncategorized' }}</td><td>{{ row.total_items }}</td><td>{{ row.total_qty|floatformat:0 }}</td><td>{{ business.currency }} {{ row.total_value|floatformat:0 }}</td></tr>{% empty %}<tr><td colspan="4" class="text-center opacity-70">No stock data</td></tr>{% endfor %}</tbody></table></div></div>
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Stock Adjustments (This Period)</h2><table class="table table-sm"><thead><tr><th>Reason</th><th>Total</th></tr></thead><tbody>{% for row in stock_adjustments_month %}<tr><td>{{ row.reason|title }}</td><td>{{ row.total }}</td></tr>{% empty %}<tr><td colspan="2" class="text-center opacity-70">No adjustments</td></tr>{% endfor %}</tbody></table></div></div>
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Fast-Moving Items (30 days)</h2><table class="table table-sm"><thead><tr><th>Item</th><th>Qty</th></tr></thead><tbody>{% for row in fast_moving_items %}<tr><td>{{ row.product__name }}</td><td class="text-success">{{ row.total_qty|floatformat:0 }}</td></tr>{% empty %}<tr><td colspan="2" class="text-center opacity-70">No data</td></tr>{% endfor %}</tbody></table></div></div>
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Slow-Moving Items (30 days)</h2><table class="table table-sm"><thead><tr><th>Item</th><th>Qty</th></tr></thead><tbody>{% for row in slow_moving_items %}<tr><td>{{ row.product__name }}</td><td class="text-warning">{{ row.total_qty|floatformat:0 }}</td></tr>{% empty %}<tr><td colspan="2" class="text-center opacity-70">No data</td></tr>{% endfor %}</tbody></table></div></div>
  </div>

  <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base text-error">Low Stock Items</h2><ul class="space-y-1 text-sm">{% for p in low_stock_items %}<li>{{ p.name }} — <span class="text-error">{{ p.stock_quantity }} {{ p.unit }}</span></li>{% empty %}<li class="opacity-70">None</li>{% endfor %}</ul></div></div>
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base text-warning">Out of Stock Items</h2><ul class="space-y-1 text-sm">{% for p in out_of_stock_items %}<li>{{ p.name }}</li>{% empty %}<li class="opacity-70">None</li>{% endfor %}</ul></div></div>
  </div>

  <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Pending Transfer Requests</h2><ul class="space-y-1 text-sm">{% for t in pending_transfer_requests %}<li>{{ t.reference }} — {{ t.from_location }} → {{ t.to_location }}</li>{% empty %}<li class="opacity-70">No pending transfer requests.</li>{% endfor %}</ul></div></div>
    <div class="card bg-base-100 shadow border border-base-200"><div class="card-body"><h2 class="card-title text-base">Recently Received Goods</h2><ul class="space-y-1 text-sm">{% for po in recent_received_goods %}<li>{{ po.reference }} — {{ po.supplier.name }} ({{ po.received_date|default:po.date }})</li>{% empty %}<li class="opacity-70">No recent receipts.</li>{% endfor %}</ul></div></div>
  </div>

  <div class="card bg-base-100 shadow border border-base-200">
    <div class="card-body">
      <h2 class="card-title text-base">Recent Activity</h2>
      <ul class="space-y-1 text-sm">
        {% for m in recent_activities %}
          <li>{{ m.created_at|date:'Y-m-d H:i' }} — {{ m.product.name }} {{ m.get_movement_type_display }} ({{ m.quantity }})</li>
        {% empty %}<li class="opacity-70">No recent activity.</li>{% endfor %}
      </ul>
    </div>
  </div>
</div>
{% endblock %}
{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
  (function () {
    if (typeof Chart === "undefined") {
      return;
    }

    const palette = [
      "#16a34a", "#f59e0b", "#0ea5e9", "#ef4444", "#8b5cf6",
      "#14b8a6", "#f97316", "#64748b", "#e11d48", "#22c55e"
    ];
    const dataUrl = "{% url 'finance:dashboard_data' %}" + (window.location.search || "");

    function buildChart(id, config) {
      const canvas = document.getElementById(id);
      if (!canvas) return;
      return new Chart(canvas, {
        ...config,
        options: {
          responsive: true,
          maintainAspectRatio: false,
          ...config.options
        }
      });
    }

    const categoryLabels = [{% for row in stock_by_category %}"{{ row.category__name|default:'Uncategorized'|escapejs }}",{% endfor %}];
    const categoryQty = [{% for row in stock_by_category %}Number("{{ row.total_qty|default_if_none:0 }}"),{% endfor %}];
    const stockCategoryChart = buildChart("smStockCategoryChart", {
      type: "doughnut",
      data: {
        labels: categoryLabels,
        datasets: [{
          data: categoryQty,
          backgroundColor: categoryLabels.map((_, idx) => palette[idx % palette.length])
        }]
      }
    });

    const adjustmentLabels = [{% for row in stock_adjustments_month %}"{{ row.reason|title|escapejs }}",{% endfor %}];
    const adjustmentTotals = [{% for row in stock_adjustments_month %}Number("{{ row.total|default_if_none:0 }}"),{% endfor %}];
    const adjustmentChart = buildChart("smAdjustmentChart", {
      type: "pie",
      data: {
        labels: adjustmentLabels,
        datasets: [{
          data: adjustmentTotals,
          backgroundColor: adjustmentLabels.map((_, idx) => palette[(idx + 2) % palette.length])
        }]
      }
    });

    const fastValues = [{% for row in fast_moving_items|slice:':7' %}Number("{{ row.total_qty|default_if_none:0 }}"),{% endfor %}];
    const slowValues = [{% for row in slow_moving_items|slice:':7' %}Number("{{ row.total_qty|default_if_none:0 }}"),{% endfor %}];
    const velocityLen = Math.max(fastValues.length, slowValues.length);
    const velocityLabels = Array.from({ length: velocityLen }, (_, idx) => `Rank ${idx + 1}`);

    const velocityChart = buildChart("smVelocityChart", {
      type: "bar",
      data: {
        labels: velocityLabels,
        datasets: [
          {
            label: "Fast Moving Qty",
            data: fastValues,
            backgroundColor: "rgba(34, 197, 94, 0.75)"
          },
          {
            label: "Slow Moving Qty",
            data: slowValues,
            backgroundColor: "rgba(245, 158, 11, 0.75)"
          }
        ]
      }
    });

    async function refreshFromApi() {
      try {
        const response = await fetch(dataUrl, { headers: { "X-Requested-With": "XMLHttpRequest" } });
        if (!response.ok) return;
        const payload = await response.json();
        const data = payload.data || {};

        if (stockCategoryChart && data.stock_by_category) {
          stockCategoryChart.data.labels = data.stock_by_category.map((row) => row.category);
          stockCategoryChart.data.datasets[0].data = data.stock_by_category.map((row) => Number(row.quantity || 0));
          stockCategoryChart.data.datasets[0].backgroundColor =
            data.stock_by_category.map((_, idx) => palette[idx % palette.length]);
          stockCategoryChart.update();
        }

        if (adjustmentChart && data.adjustments) {
          adjustmentChart.data.labels = data.adjustments.map((row) => row.reason);
          adjustmentChart.data.datasets[0].data = data.adjustments.map((row) => Number(row.total || 0));
          adjustmentChart.data.datasets[0].backgroundColor =
            data.adjustments.map((_, idx) => palette[(idx + 2) % palette.length]);
          adjustmentChart.update();
        }

        if (velocityChart && data.fast_moving_items && data.slow_moving_items) {
          const fast = data.fast_moving_items.slice(0, 7).map((row) => Number(row.quantity || 0));
          const slow = data.slow_moving_items.slice(0, 7).map((row) => Number(row.quantity || 0));
          const length = Math.max(fast.length, slow.length);
          velocityChart.data.labels = Array.from({ length }, (_, idx) => `Rank ${idx + 1}`);
          velocityChart.data.datasets[0].data = fast;
          velocityChart.data.datasets[1].data = slow;
          velocityChart.update();
        }
      } catch (error) {
        // Keep fallback chart values from initial server render.
      }
    }

    refreshFromApi();
    setInterval(refreshFromApi, 60000);
  })();
</script>
{% endblock %}
