{% extends 'base.html' %}
{% block title %}Super Admin 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">Super Admin Dashboard</h1>
      <p class="text-sm opacity-70">Strategic overview across stock, sales, purchases, and controls.</p>
    </div>
    <div class="flex flex-wrap gap-2">
      <a href="{% url 'accounts:user_create' %}" class="btn btn-primary btn-sm">Add User</a>
      <a href="{% url 'business:profile' %}" class="btn btn-outline btn-sm">System Settings</a>
      <a href="{% url 'finance:profit_loss' %}" class="btn btn-outline btn-sm">Full Reports</a>
      <a href="{% url 'admin:index' %}" class="btn btn-outline btn-sm">Backup System</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_super_admin' %}" 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: {{ 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">Overstock: {{ notifications.overstock_count }}</span>
    <span class="badge badge-secondary p-3">Pending Transfers: {{ notifications.pending_transfer_count }}</span>
    <span class="badge badge-accent p-3">Pending Approvals: {{ pending_approvals }}</span>
  </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">Total Stock Value</div><div class="stat-value text-primary text-2xl">{{ business.currency }} {{ total_stock_value|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Total Items</div><div class="stat-value text-2xl">{{ total_items }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Sales (Period)</div><div class="stat-value text-success text-2xl">{{ business.currency }} {{ revenue|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Purchases (Period)</div><div class="stat-value text-warning text-2xl">{{ business.currency }} {{ total_purchases|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Gross Profit</div><div class="stat-value text-success text-2xl">{{ business.currency }} {{ gross_profit|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Net Profit</div><div class="stat-value {% if net_profit >= 0 %}text-success{% else %}text-error{% endif %} text-2xl">{{ business.currency }} {{ net_profit|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Pending Supplier Payments</div><div class="stat-value text-secondary text-2xl">{{ notifications.pending_supplier_payment_count }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Sales Count</div><div class="stat-value text-2xl">{{ 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">Monthly Sales vs Purchases (Chart)</h2>
        <div class="h-72"><canvas id="saSalesPurchasesChart"></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">Stock Movement Trend (Chart)</h2>
        <div class="h-72"><canvas id="saStockMovementChart"></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">Top 10 Items by Quantity Sold</h2>
        <div class="h-72"><canvas id="saTopItemsChart"></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">Expense Breakdown (Pie)</h2>
        <div class="h-72"><canvas id="saExpensePieChart"></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">Monthly Sales vs Purchases</h2>
        <table class="table table-sm">
          <thead><tr><th>Month</th><th>Sales</th><th>Purchases</th></tr></thead>
          <tbody>
            {% for row in monthly_sales_vs_purchases %}
            <tr><td>{{ row.month }}</td><td class="text-success">{{ business.currency }} {{ row.sales|floatformat:0 }}</td><td class="text-warning">{{ business.currency }} {{ row.purchases|floatformat:0 }}</td></tr>
            {% empty %}<tr><td colspan="3" 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">Stock Movement Trend (Last 30 Days)</h2>
        <table class="table table-sm">
          <thead><tr><th>Date</th><th>In</th><th>Out</th></tr></thead>
          <tbody>
            {% for row in stock_movement_trend|slice:'-10:' %}
            <tr><td>{{ row.day }}</td><td class="text-success">{{ row.stock_in|floatformat:0 }}</td><td class="text-error">{{ row.stock_out|floatformat:0 }}</td></tr>
            {% empty %}<tr><td colspan="3" class="text-center opacity-70">No movement</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">Top 10 Items by Sales</h2>
        <table class="table table-sm">
          <thead><tr><th>Item</th><th>Qty</th><th>Revenue</th></tr></thead>
          <tbody>
            {% for item in top_items %}
            <tr><td>{{ item.product__name }}</td><td>{{ item.total_qty|floatformat:0 }}</td><td>{{ business.currency }} {{ item.total_revenue|floatformat:0 }}</td></tr>
            {% empty %}<tr><td colspan="3" class="text-center opacity-70">No sales 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">Expense Breakdown</h2>
        <table class="table table-sm">
          <thead><tr><th>Category</th><th>Amount</th></tr></thead>
          <tbody>
            {% for row in expense_breakdown %}
            <tr><td>{{ row.category__name }}</td><td>{{ business.currency }} {{ row.total|floatformat:0 }}</td></tr>
            {% empty %}<tr><td colspan="2" class="text-center opacity-70">No expenses</td></tr>{% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <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>
      <div class="flex flex-wrap gap-2">
        {% for p in low_stock_products %}
          <a href="{% url 'inventory:product_detail' p.pk %}" class="badge badge-error p-3">{{ p.name }}: {{ p.stock_quantity }} {{ p.unit }}</a>
        {% empty %}
          <span class="opacity-70">No low stock items.</span>
        {% endfor %}
      </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 (Audit Preview)</h2>
      <div class="overflow-x-auto">
        <table class="table table-sm">
          <thead><tr><th>When</th><th>User</th><th>Action</th><th>Object</th></tr></thead>
          <tbody>
            {% for log in recent_activities %}
            <tr><td>{{ log.created_at|date:'Y-m-d H:i' }}</td><td>{{ log.actor.username|default:'System' }}</td><td>{{ log.get_action_display }}</td><td>{{ log.app_label }}.{{ log.model_name }} #{{ log.object_id }}</td></tr>
            {% empty %}<tr><td colspan="4" class="text-center opacity-70">No recent activity</td></tr>{% endfor %}
          </tbody>
        </table>
      </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 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 monthlyLabels = [{% for row in monthly_sales_vs_purchases %}"{{ row.month|escapejs }}",{% endfor %}];
    const monthlySales = [{% for row in monthly_sales_vs_purchases %}Number("{{ row.sales|default_if_none:0 }}"),{% endfor %}];
    const monthlyPurchases = [{% for row in monthly_sales_vs_purchases %}Number("{{ row.purchases|default_if_none:0 }}"),{% endfor %}];

    const salesPurchasesChart = buildChart("saSalesPurchasesChart", {
      type: "line",
      data: {
        labels: monthlyLabels,
        datasets: [
          {
            label: "Sales",
            data: monthlySales,
            borderColor: "#16a34a",
            backgroundColor: "rgba(22, 163, 74, 0.2)",
            tension: 0.3,
            fill: true
          },
          {
            label: "Purchases",
            data: monthlyPurchases,
            borderColor: "#f59e0b",
            backgroundColor: "rgba(245, 158, 11, 0.15)",
            tension: 0.3,
            fill: true
          }
        ]
      }
    });

    const stockMoveLabels = [{% for row in stock_movement_trend|slice:'-14:' %}"{{ row.day|date:'Y-m-d' }}",{% endfor %}];
    const stockIn = [{% for row in stock_movement_trend|slice:'-14:' %}Number("{{ row.stock_in|default_if_none:0 }}"),{% endfor %}];
    const stockOut = [{% for row in stock_movement_trend|slice:'-14:' %}Number("{{ row.stock_out|default_if_none:0 }}"),{% endfor %}];

    const stockMovementChart = buildChart("saStockMovementChart", {
      type: "bar",
      data: {
        labels: stockMoveLabels,
        datasets: [
          {
            label: "Stock In",
            data: stockIn,
            backgroundColor: "rgba(34, 197, 94, 0.75)"
          },
          {
            label: "Stock Out",
            data: stockOut,
            backgroundColor: "rgba(239, 68, 68, 0.75)"
          }
        ]
      }
    });

    const topItemLabels = [{% for item in top_items %}"{{ item.product__name|escapejs }}",{% endfor %}];
    const topItemQty = [{% for item in top_items %}Number("{{ item.total_qty|default_if_none:0 }}"),{% endfor %}];

    const topItemsChart = buildChart("saTopItemsChart", {
      type: "bar",
      data: {
        labels: topItemLabels,
        datasets: [{
          label: "Qty Sold",
          data: topItemQty,
          backgroundColor: "#0ea5e9"
        }]
      },
      options: {
        plugins: { legend: { display: false } }
      }
    });

    const expenseLabels = [{% for row in expense_breakdown %}"{{ row.category__name|default:'Uncategorized'|escapejs }}",{% endfor %}];
    const expenseTotals = [{% for row in expense_breakdown %}Number("{{ row.total|default_if_none:0 }}"),{% endfor %}];

    const expensePieChart = buildChart("saExpensePieChart", {
      type: "doughnut",
      data: {
        labels: expenseLabels,
        datasets: [{
          data: expenseTotals,
          backgroundColor: expenseLabels.map((_, idx) => palette[idx % palette.length])
        }]
      }
    });

    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 (salesPurchasesChart && data.monthly_sales_vs_purchases) {
          salesPurchasesChart.data.labels = data.monthly_sales_vs_purchases.map((row) => row.month);
          salesPurchasesChart.data.datasets[0].data = data.monthly_sales_vs_purchases.map((row) => Number(row.sales || 0));
          salesPurchasesChart.data.datasets[1].data = data.monthly_sales_vs_purchases.map((row) => Number(row.purchases || 0));
          salesPurchasesChart.update();
        }

        if (stockMovementChart && data.stock_movement_trend) {
          const recentRows = data.stock_movement_trend.slice(-14);
          stockMovementChart.data.labels = recentRows.map((row) => row.day);
          stockMovementChart.data.datasets[0].data = recentRows.map((row) => Number(row.stock_in || 0));
          stockMovementChart.data.datasets[1].data = recentRows.map((row) => Number(row.stock_out || 0));
          stockMovementChart.update();
        }

        if (topItemsChart && data.top_items) {
          topItemsChart.data.labels = data.top_items.map((row) => row.name);
          topItemsChart.data.datasets[0].data = data.top_items.map((row) => Number(row.quantity || 0));
          topItemsChart.update();
        }

        if (expensePieChart && data.expense_breakdown) {
          expensePieChart.data.labels = data.expense_breakdown.map((row) => row.category);
          expensePieChart.data.datasets[0].data = data.expense_breakdown.map((row) => Number(row.amount || 0));
          expensePieChart.data.datasets[0].backgroundColor =
            data.expense_breakdown.map((_, idx) => palette[idx % palette.length]);
          expensePieChart.update();
        }
      } catch (error) {
        // Fallback stays on server-rendered chart values.
      }
    }

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