{% extends 'core/base.html' %}
{% load static %}
{% load plan_tags %}
{% load currency_filters %}

{% block title %}Dashboard — SwiftPOS{% endblock %}
{% block topbar_title %}Overview{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/dashboard.css' %}?v=2">
{% endblock %}

{% block content %}
<div class="container-fluid px-0 pb-4">

  <!-- Subscription / Expiry Banner -->
  {% if days_until_expiry is not None and days_until_expiry <= 14 %}
  <div class="alert d-flex align-items-center gap-3 mb-3 border-0 shadow-sm"
       style="border-radius:14px;background:{% if license_expired %}#fef2f2{% else %}#fffbeb{% endif %};
              border-left:4px solid {% if license_expired %}#dc2626{% else %}#f59e0b{% endif %} !important;">
    <i class="fas {% if license_expired %}fa-times-circle text-danger{% else %}fa-exclamation-triangle text-warning{% endif %} fa-lg"></i>
    <div class="flex-grow-1 small">
      <strong>{% if license_expired %}License Expired!{% else %}Subscription expiring in {{ days_until_expiry }} day{{ days_until_expiry|pluralize }}{% endif %}</strong>
      {% if not license_expired %} — Renew now to avoid interruptions.{% endif %}
    </div>
    <a href="{% url 'subscriptions:manage' %}"
       class="btn btn-sm fw-bold" style="background:linear-gradient(135deg,#7c3aed,#6366f1);color:#fff;border-radius:8px;white-space:nowrap;">
      <i class="fas fa-bolt me-1"></i>View Plan
    </a>
  </div>
  {% endif %}

  <!-- ── Hero Banner ── -->
  <div class="hero-banner mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 position-relative" style="z-index:1;">
      <div>
        <div class="hero-greeting">Welcome back 👋</div>
        <div class="hero-name">{{ user_name|default:user.get_full_name|default:user.username|upper }}</div>
        <div class="hero-role">{{ user_role|default:user.get_role_display|default:"Staff" }} &nbsp;·&nbsp; <span class="hero-date">{% now "l, N j Y" %}</span></div>
      </div>
      <div class="d-flex flex-wrap gap-2">
        <a href="{% url 'sales:pos' %}" class="hero-btn hero-btn-primary">
          <i class="fas fa-cash-register"></i> Open POS
        </a>
        <a href="{% url 'inventory:product_list' %}" class="hero-btn">
          <i class="fas fa-boxes-stacked"></i> Inventory
        </a>
        <a href="{% url 'sales:transaction_history' %}" class="hero-btn">
          <i class="fas fa-list"></i> Transactions
        </a>
      </div>
    </div>
  </div>

  <!-- Branch selector -->
  {% if allow_multi_branch %}
  <form method="get" class="mb-3">
    <div class="d-flex gap-2 align-items-end">
      <div>
        <label class="form-label small fw-semibold text-muted mb-1">Branch</label>
        <select name="branch" class="form-select form-select-sm" style="border-radius:8px;min-width:180px;">
          <option value="">All branches</option>
          {% for branch in branches %}
          <option value="{{ branch.id }}" {% if selected_branch and selected_branch.id == branch.id %}selected{% endif %}>{{ branch.name }}</option>
          {% endfor %}
        </select>
      </div>
      <button class="btn btn-sm btn-primary" style="border-radius:8px;">Apply</button>
    </div>
  </form>
  {% endif %}

  <!-- ── KPI Row ── -->
  <div class="row g-3 mb-4">

    <!-- Today's Sales -->
    <div class="col-6 col-lg-3">
      <div class="kpi-card card h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="kpi-icon" style="background:#f3f0ff;color:#7c3aed;">
            <i class="fas fa-chart-line"></i>
          </div>
          <div class="flex-grow-1 min-width-0">
            <div class="kpi-label">Today's Sales</div>
            <div class="kpi-value">{% money today_sales 0 %}</div>
            <div class="kpi-sub">{{ today_transactions|default:0 }} orders</div>
          </div>
          {% if sales_growth_percentage is not None %}
          <div>
            <span class="kpi-badge {% if sales_growth_percentage >= 0 %}text-success" style="background:#f0fdf4{% else %}text-danger" style="background:#fef2f2{% endif %};">
              <i class="fas fa-{% if sales_growth_percentage >= 0 %}arrow-up{% else %}arrow-down{% endif %}"></i>
              {{ sales_growth_percentage|floatformat:1 }}%
            </span>
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Avg Order -->
    <div class="col-6 col-lg-3">
      <div class="kpi-card card h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="kpi-icon" style="background:#f0fdf4;color:#16a34a;">
            <i class="fas fa-receipt"></i>
          </div>
          <div class="flex-grow-1">
            <div class="kpi-label">Avg. Order</div>
            <div class="kpi-value">{% money avg_order_value 0 %}</div>
            <div class="kpi-sub">{{ today_customers|default:0 }} customers</div>
          </div>
        </div>
      </div>
    </div>

    <!-- Inventory -->
    <div class="col-6 col-lg-3">
      <div class="kpi-card card h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="kpi-icon" style="background:#eff6ff;color:#2563eb;">
            <i class="fas fa-boxes-stacked"></i>
          </div>
          <div class="flex-grow-1">
            <div class="kpi-label">Products</div>
            <div class="kpi-value">{{ total_inventory }}</div>
            <div class="kpi-sub">
              <span class="text-warning fw-semibold">{{ low_stock_products }} low</span>
              &nbsp;·&nbsp;
              <span class="text-danger fw-semibold">{{ out_of_stock_products|default:0 }} out</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Team -->
    <div class="col-6 col-lg-3">
      <div class="kpi-card card h-100">
        <div class="card-body d-flex align-items-center gap-3">
          <div class="kpi-icon" style="background:#fffbeb;color:#d97706;">
            <i class="fas fa-users"></i>
          </div>
          <div class="flex-grow-1">
            <div class="kpi-label">Staff</div>
            <div class="kpi-value">{{ total_users }}</div>
            <div class="kpi-sub">{{ active_users }} active</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Row 2: Sales Trend Chart + Payment Breakdown ── -->
  <div class="row g-3 mb-4">

    <!-- Sales Trend (7-day line chart) -->
    <div class="col-lg-7">
      <div class="chart-card card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span class="card-title mb-0"><i class="fas fa-chart-area me-2" style="color:#7c3aed;"></i>Sales Trend — Last 7 Days</span>
          <div class="d-flex gap-3 small text-muted">
            <span><i class="fas fa-circle me-1" style="color:#7c3aed;font-size:.6rem;"></i>Revenue</span>
            <span><i class="fas fa-circle me-1" style="color:#a78bfa;font-size:.6rem;"></i>Orders</span>
          </div>
        </div>
        <div class="card-body" style="position:relative;height:240px;">
          <canvas id="salesTrendChart"></canvas>
        </div>
      </div>
    </div>

    <!-- Payment Breakdown Doughnut -->
    <div class="col-lg-5">
      <div class="chart-card card h-100">
        <div class="card-header">
          <span class="card-title mb-0"><i class="fas fa-wallet me-2" style="color:#7c3aed;"></i>Payment Methods — Today</span>
        </div>
        <div class="card-body d-flex flex-column">
          {% if payment_breakdown %}
          <div style="position:relative;height:160px;flex-shrink:0;">
            <canvas id="paymentChart"></canvas>
          </div>
          <div class="d-flex flex-wrap gap-2 mt-3">
            {% for method in payment_breakdown %}
            <div class="pay-pill">
              <div class="pay-pill-label">{{ method.label }}</div>
              <div class="pay-pill-val">{% money method.total 0 %}</div>
              <div class="pay-pill-pct">{{ method.percentage|floatformat:0 }}%</div>
            </div>
            {% endfor %}
          </div>
          {% else %}
          <div class="text-center text-muted small my-auto py-4">
            <i class="fas fa-wallet fa-2x mb-2 d-block opacity-25"></i>
            No payment data for today yet
          </div>
          {% endif %}
        </div>
      </div>
    </div>
  </div>

  <!-- ── Row 3: Sales Snapshot + Top Products ── -->
  <div class="row g-3 mb-4">

    <!-- Sales Snapshot -->
    <div class="col-lg-4">
      <div class="chart-card card h-100">
        <div class="card-header">
          <span class="card-title mb-0"><i class="fas fa-bolt me-2" style="color:#7c3aed;"></i>Sales Snapshot</span>
        </div>
        <div class="card-body p-0">
          <div class="row g-0 text-center">
            <div class="col-6 p-3" style="border-right:1px solid #f1f5f9;border-bottom:1px solid #f1f5f9;">
              <div style="font-size:.68rem;color:#9ca3af;font-weight:700;text-transform:uppercase;letter-spacing:.06em;">Today</div>
              <div style="font-size:1.2rem;font-weight:700;color:#0f172a;margin:.25rem 0;">{% money today_sales 0 %}</div>
              <div style="font-size:.7rem;color:#9ca3af;">{{ today_transactions }} orders</div>
            </div>
            <div class="col-6 p-3" style="border-bottom:1px solid #f1f5f9;">
              <div style="font-size:.68rem;color:#9ca3af;font-weight:700;text-transform:uppercase;letter-spacing:.06em;">Yesterday</div>
              <div style="font-size:1.2rem;font-weight:700;color:#0f172a;margin:.25rem 0;">{% money yesterday_sales 0 %}</div>
              <div style="font-size:.7rem;color:#9ca3af;">{{ yesterday_transactions }} orders</div>
            </div>
            <div class="col-6 p-3" style="border-right:1px solid #f1f5f9;">
              <div style="font-size:.68rem;color:#9ca3af;font-weight:700;text-transform:uppercase;letter-spacing:.06em;">This Week</div>
              <div style="font-size:1.2rem;font-weight:700;color:#0f172a;margin:.25rem 0;">{% money weekly_sales 0 %}</div>
              <div style="font-size:.7rem;color:#9ca3af;">{{ weekly_transactions }} orders</div>
            </div>
            <div class="col-6 p-3">
              <div style="font-size:.68rem;color:#9ca3af;font-weight:700;text-transform:uppercase;letter-spacing:.06em;">This Month</div>
              <div style="font-size:1.2rem;font-weight:700;color:#0f172a;margin:.25rem 0;">{% money monthly_sales 0 %}</div>
              <div style="font-size:.7rem;color:#9ca3af;">{{ monthly_transactions }} orders</div>
            </div>
          </div>
          {% if sales_growth_percentage is not None %}
          <div class="px-3 pb-3 pt-2">
            <span class="kpi-badge {% if sales_growth_percentage >= 0 %}text-success" style="background:#f0fdf4{% else %}text-danger" style="background:#fef2f2{% endif %};">
              <i class="fas fa-{% if sales_growth_percentage >= 0 %}arrow-up{% else %}arrow-down{% endif %} me-1"></i>
              {{ sales_growth_percentage|floatformat:1 }}% vs yesterday
            </span>
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Top Selling Products -->
    <div class="col-lg-4">
      <div class="chart-card card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span class="card-title mb-0"><i class="fas fa-fire me-2" style="color:#f59e0b;"></i>Top Products Today</span>
          <a href="{% url 'sales:transaction_history' %}" class="small text-muted text-decoration-none">See all →</a>
        </div>
        <div class="card-body">
          {% if top_selling_items %}
            {% for item in top_selling_items %}
            {% with forloop.counter as rank %}
            <div class="top-prod-row">
              <div class="top-prod-rank"
                   style="background:{% if rank == 1 %}#fef3c7;color:#d97706{% elif rank == 2 %}#f1f5f9;color:#64748b{% elif rank == 3 %}#fef2f2;color:#dc2626{% else %}#f8fafc;color:#9ca3af{% endif %};">
                {{ rank }}
              </div>
              <div class="flex-grow-1 min-width-0">
                <div style="font-size:.8rem;font-weight:600;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{ item.product__name }}</div>
                <div class="top-prod-bar mt-1">
                  <div class="top-prod-bar-fill" style="width:{{ item.total_quantity|default:0 }}0%;"></div>
                </div>
              </div>
              <div class="text-end" style="flex-shrink:0;">
                <div style="font-size:.78rem;font-weight:700;color:#0f172a;">{% money item.total_revenue 0 %}</div>
                <div style="font-size:.68rem;color:#9ca3af;">{{ item.total_quantity }} sold</div>
              </div>
            </div>
            {% endwith %}
            {% endfor %}
          {% else %}
          <div class="text-center text-muted small py-4">
            <i class="fas fa-fire fa-2x mb-2 d-block opacity-20"></i>
            No sales recorded today
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Recent Activity Feed -->
    <div class="col-lg-4">
      <div class="chart-card card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span class="card-title mb-0"><i class="fas fa-activity me-1" style="color:#7c3aed;"></i> <i class="fas fa-bolt me-1" style="color:#7c3aed;"></i>Recent Activity</span>
          <a href="{% url 'sales:transaction_history' %}" class="small text-muted text-decoration-none">View all →</a>
        </div>
        <div class="card-body">
          {% if recent_orders %}
            {% for order in recent_orders %}
            <div class="activity-item">
              <div class="activity-dot" style="background:#f3f0ff;color:#7c3aed;">
                <i class="fas fa-cash-register"></i>
              </div>
              <div class="flex-grow-1">
                <div class="activity-title">
                  {% if order.customer %}{{ order.customer.name }}{% else %}Walk-in Sale{% endif %}
                </div>
                <div class="activity-sub">#{{ order.order_number }} · {{ order.created_at|date:"H:i" }}</div>
              </div>
              <div class="text-end" style="flex-shrink:0;">
                <div style="font-size:.8rem;font-weight:700;color:#16a34a;">{% money order.final_amount 0 %}</div>
                <div style="font-size:.68rem;" class="{% if order.payment_status == 'full' %}text-success{% else %}text-warning{% endif %}">
                  {{ order.payment_status|title }}
                </div>
              </div>
            </div>
            {% endfor %}
          {% else %}
          <div class="text-center text-muted small py-4">
            <i class="fas fa-bolt fa-2x mb-2 d-block opacity-20"></i>
            No activity yet today
          </div>
          {% endif %}
        </div>
      </div>
    </div>
  </div>

  <!-- ── Row 4: Inventory Status + Cashier Performance + Subscription ── -->
  <div class="row g-3 mb-4">

    <!-- Inventory Status -->
    <div class="col-lg-4">
      <div class="chart-card card h-100">
        <div class="card-header">
          <span class="card-title mb-0"><i class="fas fa-boxes-stacked me-2" style="color:#2563eb;"></i>Inventory Status</span>
        </div>
        <div class="card-body">
          <div style="position:relative;height:160px;margin-bottom:1rem;">
            <canvas id="inventoryChart"></canvas>
          </div>
          <div class="row g-2 text-center">
            <div class="col-3">
              <div style="font-size:1.1rem;font-weight:700;color:#0f172a;">{{ total_inventory }}</div>
              <div style="font-size:.68rem;color:#9ca3af;">Total</div>
            </div>
            <div class="col-3">
              <div style="font-size:1.1rem;font-weight:700;color:#16a34a;">{{ in_stock_products }}</div>
              <div style="font-size:.68rem;color:#9ca3af;">In Stock</div>
            </div>
            <div class="col-3">
              <div style="font-size:1.1rem;font-weight:700;color:#d97706;">{{ low_stock_products }}</div>
              <div style="font-size:.68rem;color:#9ca3af;">Low</div>
            </div>
            <div class="col-3">
              <div style="font-size:1.1rem;font-weight:700;color:#dc2626;">{{ out_of_stock_products|default:0 }}</div>
              <div style="font-size:.68rem;color:#9ca3af;">Out</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Cashier Performance -->
    <div class="col-lg-4">
      <div class="chart-card card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span class="card-title mb-0"><i class="fas fa-user-tie me-2" style="color:#7c3aed;"></i>Cashier Performance — Today</span>
        </div>
        <div class="card-body p-0">
          {% if cashier_performance %}
          <div class="sp-table-container">
            <table class="table cashier-table mb-0">
              <thead>
                <tr>
                  <th>Cashier</th>
                  <th class="text-center">Orders</th>
                  <th class="text-end">Revenue</th>
                  <th class="text-end">Avg.</th>
                </tr>
              </thead>
              <tbody>
                {% for c in cashier_performance %}
                <tr>
                  <td>
                    <span class="cashier-avatar">{{ c.cashier|slice:':2'|upper }}</span>
                    <span style="font-weight:600;font-size:.8rem;">{{ c.cashier }}</span>
                  </td>
                  <td class="text-center">
                    <span class="badge rounded-pill" style="background:#f3f0ff;color:#7c3aed;font-size:.72rem;">{{ c.total_orders }}</span>
                  </td>
                  <td class="text-end" style="font-weight:700;font-size:.8rem;">{% money c.total_sales 0 %}</td>
                  <td class="text-end text-muted" style="font-size:.76rem;">
                    {% if c.total_orders %}{{ currency_symbol }}{% widthratio c.total_sales c.total_orders 1 %}{% else %}&mdash;{% endif %}
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
          {% else %}
          <div class="text-center text-muted small py-5">
            <i class="fas fa-user-tie fa-2x mb-2 d-block opacity-20"></i>
            No cashier data for today
          </div>
          {% endif %}
        </div>
      </div>
    </div>

    <!-- Subscription / Plan -->
    <div class="col-lg-4">
      <div class="chart-card card h-100" style="border-top:3px solid #7c3aed;">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span class="card-title mb-0"><i class="fas fa-id-card me-2" style="color:#7c3aed;"></i>Subscription</span>
          {% if sub_data %}
          <span class="badge"
            style="font-size:.72rem;padding:.3em .65em;border-radius:8px;
            {% if sub_data.is_accessible %}background:#f0fdf4;color:#16a34a;{% else %}background:#fef2f2;color:#dc2626;{% endif %}">
            <i class="fas fa-circle me-1" style="font-size:.45rem;vertical-align:middle;"></i>
            {% if sub_data.is_accessible %}Active{% elif sub_data.is_expired %}Expired{% else %}Suspended{% endif %}
          </span>
          {% endif %}
        </div>
        <div class="card-body">
          {% if sub_data %}

          <!-- Plan header -->
          <div class="d-flex align-items-center gap-3 mb-3">
            <div style="width:42px;height:42px;border-radius:12px;background:linear-gradient(135deg,#7c3aed,#4f46e5);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
              <i class="fas fa-crown" style="color:#fff;font-size:.9rem;"></i>
            </div>
            <div>
              <div style="font-size:1rem;font-weight:700;color:#0f172a;">{{ sub_data.plan_name }}</div>
              <div style="font-size:.72rem;color:#9ca3af;">
                {% if sub_data.expiry_date %}
                  Expires {{ sub_data.expiry_date|date:"M j, Y" }}
                  {% if sub_data.is_expired %}<span class="text-danger fw-semibold"> &middot; Expired</span>{% endif %}
                {% else %}
                  No expiry date
                {% endif %}
              </div>
            </div>
          </div>

          <!-- Usage bars -->
          <div class="mb-3" style="display:grid;grid-template-columns:1fr 1fr;gap:.6rem .9rem;">

            <!-- Products -->
            <div>
              <div class="d-flex justify-content-between" style="font-size:.68rem;font-weight:600;color:#6b7280;margin-bottom:.2rem;">
                <span>Products</span>
                <span style="color:#0f172a;">{{ sub_data.products_count }}{% if sub_data.max_products %} / {{ sub_data.max_products }}{% else %} / &infin;{% endif %}</span>
              </div>
              <div class="usage-bar"><div class="usage-bar-fill" style="width:{% if sub_data.products_pct %}{{ sub_data.products_pct }}{% else %}0{% endif %}%;"></div></div>
            </div>

            <!-- Categories -->
            <div>
              <div class="d-flex justify-content-between" style="font-size:.68rem;font-weight:600;color:#6b7280;margin-bottom:.2rem;">
                <span>Categories</span>
                <span style="color:#0f172a;">{{ sub_data.categories_count }}{% if sub_data.max_categories %} / {{ sub_data.max_categories }}{% else %} / &infin;{% endif %}</span>
              </div>
              <div class="usage-bar"><div class="usage-bar-fill" style="width:{% if sub_data.categories_pct %}{{ sub_data.categories_pct }}{% else %}0{% endif %}%;"></div></div>
            </div>

            <!-- Orders today -->
            <div>
              <div class="d-flex justify-content-between" style="font-size:.68rem;font-weight:600;color:#6b7280;margin-bottom:.2rem;">
                <span>Orders Today</span>
                <span style="color:#0f172a;">{{ sub_data.orders_today }}{% if sub_data.max_orders_per_day %} / {{ sub_data.max_orders_per_day }}{% else %} / &infin;{% endif %}</span>
              </div>
              <div class="usage-bar"><div class="usage-bar-fill" style="width:{% if sub_data.orders_pct %}{{ sub_data.orders_pct }}{% else %}0{% endif %}%;"></div></div>
            </div>

            <!-- Staff -->
            <div>
              <div class="d-flex justify-content-between" style="font-size:.68rem;font-weight:600;color:#6b7280;margin-bottom:.2rem;">
                <span>Staff</span>
                <span style="color:#0f172a;">{{ sub_data.users_count }}{% if sub_data.max_staff %} / {{ sub_data.max_staff }}{% else %} / &infin;{% endif %}</span>
              </div>
              <div class="usage-bar"><div class="usage-bar-fill" style="width:{% if sub_data.users_pct %}{{ sub_data.users_pct }}{% else %}0{% endif %}%;"></div></div>
            </div>

          </div>

          <!-- Feature flags grid -->
          <div style="border-top:1px solid #f1f5f9;padding-top:.75rem;">
            <div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#9ca3af;margin-bottom:.5rem;">Features</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.25rem .5rem;">
              {% for label, enabled in sub_data.features %}
              <div style="display:flex;align-items:center;gap:.35rem;font-size:.72rem;{% if enabled %}color:#374151;{% else %}color:#c4c4c4;{% endif %}">
                <i class="fas {% if enabled %}fa-check-circle" style="color:#16a34a;{% else %}fa-times-circle" style="color:#e5e7eb;{% endif %}font-size:.7rem;"></i>
                {{ label }}
              </div>
              {% endfor %}
            </div>
          </div>

          {% else %}
          <div class="text-center text-muted small py-4">
            <i class="fas fa-id-card fa-2x mb-2 d-block opacity-20"></i>
            No subscription plan assigned
          </div>
          {% endif %}
        </div>
      </div>
    </div>

  </div><!-- /row 4 -->


</div><!-- /container-fluid -->
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
<script>
Chart.defaults.font.family = "'Poppins', system-ui, sans-serif";
Chart.defaults.font.size = 11;
Chart.defaults.color = '#9ca3af';

/* ─── 7-Day Sales Trend ─── */
(function () {
  const ctx = document.getElementById('salesTrendChart');
  if (!ctx) return;

  const labels = {{ weekly_labels|default:"[]"|safe }};
  const revenues = {{ weekly_revenue_data|default:"[]"|safe }};
  const orders   = {{ weekly_orders_data|default:"[]"|safe }};

  // Fallback: show placeholder if no data
  const hasData = revenues.length > 0;
  const finalLabels   = hasData ? labels   : ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const finalRevenues = hasData ? revenues : [0,0,0,0,0,0,0];
  const finalOrders   = hasData ? orders   : [0,0,0,0,0,0,0];

  new Chart(ctx, {
    type: 'line',
    data: {
      labels: finalLabels,
      datasets: [
        {
          label: 'Revenue',
          data: finalRevenues,
          borderColor: '#7c3aed',
          backgroundColor: 'rgba(124,58,237,0.08)',
          borderWidth: 2.5,
          pointRadius: 4,
          pointBackgroundColor: '#7c3aed',
          fill: true,
          tension: 0.4,
          yAxisID: 'y',
        },
        {
          label: 'Orders',
          data: finalOrders,
          borderColor: '#a78bfa',
          backgroundColor: 'transparent',
          borderWidth: 2,
          pointRadius: 3,
          pointBackgroundColor: '#a78bfa',
          fill: false,
          tension: 0.4,
          borderDash: [5, 4],
          yAxisID: 'y1',
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { mode: 'index', intersect: false },
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#374151',
          bodyColor: '#374151',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          cornerRadius: 10,
          padding: 10,
        }
      },
      scales: {
        x: { grid: { display: false }, border: { display: false } },
        y: {
          position: 'left',
          grid: { color: '#f1f5f9' },
          border: { display: false },
          ticks: { callback: v => '{{ currency_symbol }}' + v.toLocaleString() }
        },
        y1: {
          position: 'right',
          grid: { display: false },
          border: { display: false },
          ticks: { callback: v => v + ' ord' }
        }
      }
    }
  });
})();

/* ─── Payment Methods Doughnut ─── */
(function () {
  const ctx = document.getElementById('paymentChart');
  if (!ctx) return;

  const labels = [{% for m in payment_breakdown %}'{{ m.label }}'{% if not forloop.last %},{% endif %}{% endfor %}];
  const data   = [{% for m in payment_breakdown %}{{ m.total|floatformat:0 }}{% if not forloop.last %},{% endif %}{% endfor %}];

  if (!data.length) return;

  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels,
      datasets: [{
        data,
        backgroundColor: ['#7c3aed','#4f46e5','#3b82f6','#06b6d4','#10b981'],
        borderWidth: 0,
        hoverOffset: 6,
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '72%',
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#374151',
          bodyColor: '#374151',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          cornerRadius: 10,
          callbacks: {
            label: ctx => ` {{ currency_symbol }}${ctx.parsed.toLocaleString()}  (${ctx.dataset.data[ctx.dataIndex]})`
          }
        }
      }
    }
  });
})();

/* ─── Inventory Doughnut ─── */
(function () {
  const ctx = document.getElementById('inventoryChart');
  if (!ctx) return;

  const inStock  = {{ in_stock_products|default:0 }};
  const low      = {{ low_stock_products|default:0 }};
  const out      = {{ out_of_stock_products|default:0 }};

  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['In Stock', 'Low Stock', 'Out of Stock'],
      datasets: [{
        data: [inStock, low, out],
        backgroundColor: ['#16a34a', '#d97706', '#dc2626'],
        borderWidth: 0,
        hoverOffset: 5,
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '68%',
      plugins: {
        legend: {
          display: true,
          position: 'bottom',
          labels: { boxWidth: 10, padding: 12, font: { size: 11 } }
        },
        tooltip: {
          backgroundColor: '#fff',
          titleColor: '#374151',
          bodyColor: '#374151',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          cornerRadius: 10,
        }
      }
    }
  });
})();
</script>
{% endblock %}
