{% extends 'base.html' %}
{% block title %}Sales Officer 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">Sales Officer Dashboard</h1>
      <p class="text-sm opacity-70">Fast, clean view for daily sales execution.</p>
    </div>
    <div class="flex gap-2">
      <a href="{% url 'sales:sale_create' %}" class="btn btn-primary btn-sm">Create New Sale</a>
      <a href="{% url 'sales:invoice_list' %}" class="btn btn-outline btn-sm">View Own Invoices</a>
      <a href="{% url 'sales:sale_list' %}" class="btn btn-outline btn-sm">Print Receipt</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">Today's Sales</div><div class="stat-value text-success text-2xl">{{ business.currency }} {{ today_sales_total|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Invoices Created Today</div><div class="stat-value text-primary text-2xl">{{ today_invoices_count }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Monthly Sales</div><div class="stat-value text-2xl">{{ business.currency }} {{ monthly_sales_total|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Monthly Sales Count</div><div class="stat-value text-2xl">{{ monthly_sales_count }}</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">Top-Selling Items Today (Chart)</h2>
        <div class="h-72"><canvas id="soTopItemsChart"></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">Recent Sales Trend</h2>
        <div class="h-72"><canvas id="soRecentSalesChart"></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">Top-Selling Items Today</h2>
      <table class="table table-sm">
        <thead><tr><th>Item</th><th>Qty</th><th>Revenue</th></tr></thead>
        <tbody>
          {% for row in top_selling_today %}
            <tr><td>{{ row.product__name }}</td><td>{{ row.total_qty|floatformat:0 }}</td><td>{{ business.currency }} {{ row.total_revenue|floatformat:0 }}</td></tr>
          {% empty %}<tr><td colspan="3" class="text-center opacity-70">No sales yet today.</td></tr>{% endfor %}
        </tbody>
      </table>
    </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">Recent Sales</h2><ul class="text-sm space-y-1">{% for sale in recent_sales %}<li>{{ sale.date }} — {{ sale.reference }} ({{ business.currency }} {{ sale.total|floatformat:0 }})</li>{% empty %}<li class="opacity-70">No sales records.</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">Recent Invoices</h2><ul class="text-sm space-y-1">{% for inv in recent_invoices %}<li>{{ inv.issue_date }} — {{ inv.reference }} ({{ inv.get_status_display }})</li>{% empty %}<li class="opacity-70">No invoice records.</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">Notifications</h2><div class="flex flex-wrap gap-2"><span class="badge badge-error p-3">Low Stock: {{ notifications.low_stock_count }}</span><span class="badge badge-warning p-3">Expiry Alerts: {{ notifications.expiry_alert_count }}</span><span class="badge badge-info p-3">Transfers Pending: {{ notifications.pending_transfer_count }}</span></div></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 topLabels = [{% for row in top_selling_today %}"{{ row.product__name|escapejs }}",{% endfor %}];
    const topQty = [{% for row in top_selling_today %}Number("{{ row.total_qty|default_if_none:0 }}"),{% endfor %}];
    const topItemsChart = buildChart("soTopItemsChart", {
      type: "bar",
      data: {
        labels: topLabels,
        datasets: [{
          label: "Qty Sold",
          data: topQty,
          backgroundColor: "rgba(14, 165, 233, 0.8)"
        }]
      },
      options: {
        plugins: { legend: { display: false } }
      }
    });

    const recentLabels = [{% for sale in recent_sales %}"{{ sale.date|date:'Y-m-d' }}",{% endfor %}].reverse();
    const recentTotals = [{% for sale in recent_sales %}Number("{{ sale.total|default_if_none:0 }}"),{% endfor %}].reverse();
    const recentSalesChart = buildChart("soRecentSalesChart", {
      type: "line",
      data: {
        labels: recentLabels,
        datasets: [{
          label: "Sale Amount",
          data: recentTotals,
          borderColor: "#16a34a",
          backgroundColor: "rgba(22, 163, 74, 0.2)",
          fill: true,
          tension: 0.3
        }]
      }
    });

    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 (topItemsChart && data.top_selling_today) {
          topItemsChart.data.labels = data.top_selling_today.map((row) => row.name);
          topItemsChart.data.datasets[0].data = data.top_selling_today.map((row) => Number(row.quantity || 0));
          topItemsChart.update();
        }

        if (recentSalesChart && data.recent_sales) {
          const ordered = [...data.recent_sales].reverse();
          recentSalesChart.data.labels = ordered.map((row) => row.date);
          recentSalesChart.data.datasets[0].data = ordered.map((row) => Number(row.total || 0));
          recentSalesChart.update();
        }
      } catch (error) {
        // Keep fallback chart values from initial server render.
      }
    }

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