{% extends 'base.html' %}
{% block title %}Auditor 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">Auditor Dashboard</h1>
      <p class="text-sm opacity-70">Read-only mode: compliance, movement history, and user actions.</p>
    </div>
    <div class="flex items-center gap-2">
      <span class="badge badge-neutral p-3">Read-Only</span>
      <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_auditor' %}" class="btn btn-ghost btn-sm">Reset</a>
  </form>

  <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">Revenue</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">COGS</div><div class="stat-value text-warning text-2xl">{{ business.currency }} {{ cogs|floatformat:0 }}</div></div>
    <div class="stat bg-base-100 rounded-box shadow"><div class="stat-title">Expenses</div><div class="stat-value text-error text-2xl">{{ business.currency }} {{ total_expenses|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>

  <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">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 Movement Types</h2>
        <div class="h-72"><canvas id="auMovementTypeChart"></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">Audit Actions Breakdown</h2>
        <div class="h-72"><canvas id="auActionChart"></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">Adjustment Status</h2>
        <div class="h-72"><canvas id="auAdjustmentStatusChart"></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 Movement Logs</h2>
        <ul class="text-sm space-y-1">
          {% for row in stock_movement_logs %}
          <li>{{ row.created_at|date:'Y-m-d H:i' }} — {{ row.product.name }} {{ row.get_movement_type_display }} ({{ row.quantity }})</li>
          {% empty %}<li class="opacity-70">No stock movement logs.</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">Deleted/Voided/Reverse Transactions</h2>
        <ul class="text-sm space-y-1">
          {% for row in voided_deleted_transactions %}
          <li>{{ row.created_at|date:'Y-m-d H:i' }} — {{ row.get_action_display }} {{ row.app_label }}.{{ row.model_name }} #{{ row.object_id }}</li>
          {% empty %}<li class="opacity-70">No void/delete/reverse 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">Adjustment History</h2>
        <ul class="text-sm space-y-1">
          {% for row in adjustment_history %}
          <li>{{ row.created_at|date:'Y-m-d H:i' }} — {{ row.product.name }} {{ row.get_reason_display }} ({{ row.quantity }}) [{{ row.get_status_display }}]</li>
          {% empty %}<li class="opacity-70">No adjustment 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">User Activity Log</h2>
        <ul class="text-sm space-y-1">
          {% for row in user_activity_logs %}
          <li>{{ row.created_at|date:'Y-m-d H:i' }} — {{ row.actor.username|default:'System' }} {{ row.get_action_display }} {{ row.app_label }}.{{ row.model_name }}</li>
          {% empty %}<li class="opacity-70">No user activity logs.</li>{% endfor %}
        </ul>
      </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 movementLabelsRaw = [{% for row in stock_movement_logs %}"{{ row.get_movement_type_display|escapejs }}",{% endfor %}];
    const movementMap = movementLabelsRaw.reduce((acc, label) => {
      if (!label) return acc;
      acc[label] = (acc[label] || 0) + 1;
      return acc;
    }, {});

    const movementTypeChart = buildChart("auMovementTypeChart", {
      type: "bar",
      data: {
        labels: Object.keys(movementMap),
        datasets: [{
          label: "Count",
          data: Object.values(movementMap),
          backgroundColor: "rgba(14, 165, 233, 0.8)"
        }]
      },
      options: {
        plugins: { legend: { display: false } }
      }
    });

    const actionLabelsRaw = [{% for row in user_activity_logs %}"{{ row.get_action_display|escapejs }}",{% endfor %}];
    const actionMap = actionLabelsRaw.reduce((acc, label) => {
      if (!label) return acc;
      acc[label] = (acc[label] || 0) + 1;
      return acc;
    }, {});

    const actionChart = buildChart("auActionChart", {
      type: "doughnut",
      data: {
        labels: Object.keys(actionMap),
        datasets: [{
          data: Object.values(actionMap),
          backgroundColor: ["#16a34a", "#f59e0b", "#0ea5e9", "#ef4444", "#8b5cf6", "#14b8a6"]
        }]
      }
    });

    const adjustmentLabelsRaw = [{% for row in adjustment_history %}"{{ row.get_status_display|escapejs }}",{% endfor %}];
    const adjustmentMap = adjustmentLabelsRaw.reduce((acc, label) => {
      if (!label) return acc;
      acc[label] = (acc[label] || 0) + 1;
      return acc;
    }, {});

    const adjustmentStatusChart = buildChart("auAdjustmentStatusChart", {
      type: "pie",
      data: {
        labels: Object.keys(adjustmentMap),
        datasets: [{
          data: Object.values(adjustmentMap),
          backgroundColor: ["#22c55e", "#f59e0b", "#ef4444", "#64748b"]
        }]
      }
    });

    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 (movementTypeChart && data.stock_movement_types) {
          movementTypeChart.data.labels = data.stock_movement_types.map((row) => row.type);
          movementTypeChart.data.datasets[0].data = data.stock_movement_types.map((row) => Number(row.count || 0));
          movementTypeChart.update();
        }

        if (actionChart && data.audit_action_counts) {
          actionChart.data.labels = data.audit_action_counts.map((row) => row.action);
          actionChart.data.datasets[0].data = data.audit_action_counts.map((row) => Number(row.count || 0));
          actionChart.update();
        }

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

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