{% extends 'base.html' %}
{% block title %}Storekeeper 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">Storekeeper Dashboard</h1>
      <p class="text-sm opacity-70">Daily stock tasks and alerts only.</p>
      <p class="text-sm">Store: <strong>{{ assigned_location.name|default:'Unassigned (showing all stores)' }}</strong></p>
    </div>
    <div class="flex gap-2">
      <a href="{% url 'inventory:po_list' %}" class="btn btn-primary btn-sm">Record Goods Received</a>
      <a href="{% url 'inventory:product_list' %}" class="btn btn-outline btn-sm">Issue Stock</a>
      <a href="{% url 'inventory:transfer_create' %}" class="btn btn-outline btn-sm">Request Transfer</a>
      <a href="{% url 'inventory:adjustment_request_create' %}" class="btn btn-outline btn-sm">Report Damaged</a>
      <a href="{% url 'finance:dashboard_data' %}" class="btn btn-outline btn-sm">Live JSON</a>
    </div>
  </div>

  <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Items In Store</div><div class="stat-value text-2xl">{{ items_in_store|length }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Today Received</div><div class="stat-value text-success text-2xl">{{ today_goods_received|length }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Today Issued</div><div class="stat-value text-warning text-2xl">{{ today_issued_items|length }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Pending Requests</div><div class="stat-value text-secondary text-2xl">{{ pending_issue_requests|length }}</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">Today Flow (Visual)</h2>
        <div class="h-72"><canvas id="skFlowChart"></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">Low Stock Severity</h2>
        <div class="h-72"><canvas id="skLowStockChart"></canvas></div>
      </div>
    </div>
  </div>

  <div class="card bg-base-100 shadow border border-base-200">
    <div class="card-body">
      <h2 class="card-title text-base">Items In Assigned Store</h2>
      <div class="overflow-x-auto">
        <table class="table table-sm">
          <thead><tr><th>Product</th><th>Location</th><th>Qty</th><th>Status</th></tr></thead>
          <tbody>
            {% for row in items_in_store %}
            <tr>
              <td>{{ row.product.name }}</td>
              <td>{{ row.location.name }}</td>
              <td>{{ row.quantity|floatformat:0 }} {{ row.product.unit }}</td>
              <td>
                {% if row.quantity <= row.product.low_stock_alert %}
                  <span class="badge badge-error">Critical</span>
                {% elif row.quantity <= row.product.low_stock_alert|add:5 %}
                  <span class="badge badge-warning">Warning</span>
                {% else %}
                  <span class="badge badge-success">Healthy</span>
                {% endif %}
              </td>
            </tr>
            {% empty %}<tr><td colspan="4" class="text-center opacity-70">No stocked items.</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 Alerts</h2><ul class="text-sm space-y-1">{% for row in low_stock_alerts %}<li>{{ row.product.name }} — {{ row.quantity|floatformat:0 }} {{ row.product.unit }}</li>{% empty %}<li class="opacity-70">No low stock alerts.</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">Pending Issue/Transfer Requests</h2><ul class="text-sm space-y-1">{% for r in pending_issue_requests %}<li>{{ r.reference }} — {{ r.from_location }} → {{ r.to_location }}</li>{% empty %}<li class="opacity-70">No pending requests.</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="text-sm space-y-1">{% 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 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 flowChart = buildChart("skFlowChart", {
      type: "doughnut",
      data: {
        labels: ["Received", "Issued", "Pending Requests"],
        datasets: [{
          data: [
            Number("{{ today_goods_received|length }}"),
            Number("{{ today_issued_items|length }}"),
            Number("{{ pending_issue_requests|length }}")
          ],
          backgroundColor: ["#22c55e", "#f59e0b", "#0ea5e9"]
        }]
      }
    });

    const lowStockLabels = [{% for row in low_stock_alerts|slice:':10' %}"{{ row.product.name|escapejs }}",{% endfor %}];
    const lowStockValues = [{% for row in low_stock_alerts|slice:':10' %}Number("{{ row.quantity|default_if_none:0 }}"),{% endfor %}];

    const lowStockChart = buildChart("skLowStockChart", {
      type: "bar",
      data: {
        labels: lowStockLabels,
        datasets: [{
          label: "Qty",
          data: lowStockValues,
          backgroundColor: "rgba(239, 68, 68, 0.8)"
        }]
      },
      options: {
        plugins: { legend: { display: false } }
      }
    });

    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 (flowChart && data.counts) {
          flowChart.data.datasets[0].data = [
            Number(data.counts.today_received || 0),
            Number(data.counts.today_issued || 0),
            Number(data.counts.pending_requests || 0),
          ];
          flowChart.update();
        }

        if (lowStockChart && data.low_stock_items) {
          lowStockChart.data.labels = data.low_stock_items.map((row) => row.name);
          lowStockChart.data.datasets[0].data = data.low_stock_items.map((row) => Number(row.quantity || 0));
          lowStockChart.update();
        }
      } catch (error) {
        // Keep fallback chart values from initial server render.
      }
    }

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