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

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

{% block extra_css %}
<style>
/* ── Dashboard Design System ── */
:root {
  --db-purple: #7c3aed;
  --db-purple-soft: #f3f0ff;
  --db-green: #16a34a;
  --db-green-soft: #f0fdf4;
  --db-amber: #d97706;
  --db-amber-soft: #fffbeb;
  --db-blue: #2563eb;
  --db-blue-soft: #eff6ff;
  --db-red: #dc2626;
  --db-red-soft: #fef2f2;
}

/* KPI Cards */
.kpi-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 1px 8px rgba(0,0,0,0.07);
  transition: box-shadow .2s, transform .2s;
  overflow: hidden;
  background: #fff;
}
.kpi-card:hover {
  box-shadow: 0 6px 24px rgba(0,0,0,0.11);
  transform: translateY(-2px);
}
.kpi-icon {
  width: 48px; height: 48px;
  border-radius: 14px;
  display: flex; align-items: center; justify-content: center;
  font-size: 1.15rem;
  flex-shrink: 0;
}
.kpi-label {
  font-size: 0.7rem;
  font-weight: 700;
  letter-spacing: .06em;
  text-transform: uppercase;
  color: #9ca3af;
  margin-bottom: .25rem;
}
.kpi-value {
  font-size: 1.7rem;
  font-weight: 700;
  color: #0f172a;
  line-height: 1.1;
}
.kpi-sub {
  font-size: 0.73rem;
  color: #9ca3af;
  margin-top: .2rem;
}
.kpi-badge {
  font-size: 0.7rem;
  font-weight: 600;
  padding: 0.2em 0.6em;
  border-radius: 999px;
}

/* Chart cards */
.chart-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 1px 8px rgba(0,0,0,0.07);
  background: #fff;
}
.chart-card .card-header {
  border-bottom: 1px solid #f1f5f9;
  border-radius: 16px 16px 0 0;
  background: #fff;
  padding: .9rem 1.2rem;
}
.chart-card .card-title {
  font-size: .82rem;
  font-weight: 700;
  color: #374151;
}

/* Hero welcome banner */
.hero-banner {
  border-radius: 20px;
  background: linear-gradient(135deg, #7c3aed 0%, #4f46e5 60%, #3b82f6 100%);
  color: #fff;
  padding: 1.3rem 1.5rem;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(124,58,237,.3);
}
.hero-banner::before {
  content: '';
  position: absolute;
  top: -40%; right: -10%;
  width: 280px; height: 280px;
  background: rgba(255,255,255,.06);
  border-radius: 50%;
}
.hero-banner::after {
  content: '';
  position: absolute;
  bottom: -60%; left: 30%;
  width: 200px; height: 200px;
  background: rgba(255,255,255,.04);
  border-radius: 50%;
}
.hero-greeting { font-size: .8rem; opacity: .8; margin-bottom: .15rem; }
.hero-name { font-size: 1.4rem; font-weight: 700; line-height: 1.2; }
.hero-role { font-size: .78rem; opacity: .7; margin-top: .15rem; }
.hero-date { font-size: .75rem; opacity: .65; }
.hero-btn {
  border: 1.5px solid rgba(255,255,255,.4);
  color: #fff !important;
  background: rgba(255,255,255,.12);
  backdrop-filter: blur(6px);
  border-radius: 10px;
  font-size: .8rem;
  font-weight: 600;
  padding: .45rem 1rem;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: .4rem;
  transition: background .15s;
}
.hero-btn:hover { background: rgba(255,255,255,.22); }
.hero-btn-primary {
  background: #fff;
  color: var(--db-purple) !important;
  border-color: transparent;
}
.hero-btn-primary:hover { background: rgba(255,255,255,.9); }

/* Activity feed */
.activity-item {
  display: flex;
  align-items: flex-start;
  gap: .75rem;
  padding: .6rem 0;
  border-bottom: 1px solid #f8fafc;
}
.activity-item:last-child { border-bottom: none; }
.activity-dot {
  width: 34px; height: 34px;
  border-radius: 10px;
  display: flex; align-items: center; justify-content: center;
  font-size: .78rem;
  flex-shrink: 0;
}
.activity-title { font-size: .8rem; font-weight: 600; color: #1e293b; }
.activity-sub { font-size: .72rem; color: #9ca3af; }

/* Top product rows */
.top-prod-row {
  display: flex;
  align-items: center;
  gap: .75rem;
  padding: .55rem 0;
  border-bottom: 1px solid #f8fafc;
}
.top-prod-row:last-child { border-bottom: none; }
.top-prod-rank {
  width: 24px; height: 24px;
  border-radius: 7px;
  font-size: .7rem;
  font-weight: 700;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.top-prod-bar {
  flex: 1;
  height: 5px;
  border-radius: 999px;
  background: #f1f5f9;
  overflow: hidden;
}
.top-prod-bar-fill {
  height: 100%;
  border-radius: 999px;
  background: linear-gradient(90deg, #7c3aed, #a78bfa);
}

/* Payment method pills */
.pay-pill {
  border-radius: 12px;
  padding: .75rem 1rem;
  background: #f8fafc;
  text-align: center;
  flex: 1;
}
.pay-pill-label { font-size: .68rem; font-weight: 700; text-transform: uppercase; color: #9ca3af; letter-spacing: .05em; }
.pay-pill-val { font-size: 1.05rem; font-weight: 700; color: #0f172a; margin-top: .15rem; }
.pay-pill-pct { font-size: .7rem; color: #9ca3af; margin-top: .1rem; }

/* License usage bar */
.usage-bar { height: 4px; border-radius: 999px; background: #f1f5f9; overflow: hidden; margin-top: .3rem; }
.usage-bar-fill { height: 100%; border-radius: 999px; background: linear-gradient(90deg, #7c3aed, #4f46e5); }

/* Cashier table */
.cashier-table th, .cashier-table td {
  padding: .5rem .75rem;
  font-size: .78rem;
}
.cashier-table th { color: #9ca3af; font-weight: 600; font-size: .68rem; text-transform: uppercase; letter-spacing: .05em; border: none; }
.cashier-table td { border-bottom: 1px solid #f8fafc; }
.cashier-avatar {
  width: 28px; height: 28px;
  border-radius: 8px;
  background: linear-gradient(135deg, #8b5cf6, #6366f1);
  color: #fff;
  font-size: .68rem;
  font-weight: 700;
  display: inline-flex; align-items: center; justify-content: center;
  margin-right: .4rem;
}

/* Responsive tweaks */
@media (max-width: 575.98px) {
  .kpi-value { font-size: 1.4rem; }
  .hero-name { font-size: 1.1rem; }
}
</style>
{% 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>
    {% if whatsapp_number %}
    <a href="https://wa.me/{{ whatsapp_number }}?text=Hello%2C+I+want+to+renew+SwiftPOS"
       class="btn btn-sm fw-bold" style="background:#25d366;color:#fff;border-radius:8px;" target="_blank">
      <i class="fab fa-whatsapp me-1"></i>Renew
    </a>
    {% endif %}
  </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">{{ currency_symbol }}{{ today_sales|floatformat: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">{{ currency_symbol }}{{ avg_order_value|floatformat: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">{{ currency_symbol }}{{ method.total|floatformat: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;">{{ currency_symbol }}{{ today_sales|floatformat: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;">{{ currency_symbol }}{{ yesterday_sales|floatformat: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;">{{ currency_symbol }}{{ weekly_sales|floatformat: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;">{{ currency_symbol }}{{ monthly_sales|floatformat: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;">{{ currency_symbol }}{{ item.total_revenue|floatformat: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;">{{ currency_symbol }}{{ order.final_amount|floatformat: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 ── -->
  <div class="row g-3 mb-4">

    <!-- Inventory Status with mini bar chart -->
    <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-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-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-user-tie me-2" style="color:#7c3aed;"></i>Cashier Performance — Today</span>
        </div>
        <div class="card-body p-0">
          {% if cashier_performance %}
          <div class="table-responsive">
            <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;">{{ currency_symbol }}{{ c.total_sales|floatformat: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 %}—{% 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>
  </div>

  <!-- ── Subscription / License ── -->
  {% plan_usage as usage %}
  {% if usage.plan_name %}
  <div class="row g-3">
    <div class="col-12">
      <div class="chart-card card">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
              <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#9ca3af;">Subscription</div>
              <div style="font-size:1rem;font-weight:700;color:#0f172a;">{{ usage.plan_name }}</div>
              {% if usage.license_expires_at %}
              <div style="font-size:.72rem;color:#9ca3af;">Expires {{ usage.license_expires_at|date:"M j, Y" }}</div>
              {% endif %}
            </div>
            <span class="badge {% if usage.license_active %}text-success" style="background:#f0fdf4{% else %}text-danger" style="background:#fef2f2{% endif %};font-size:.75rem;padding:.35em .7em;border-radius:8px;">
              {% if usage.license_active %}<i class="fas fa-circle me-1" style="font-size:.5rem;"></i>Active{% else %}Inactive{% endif %}
            </span>
          </div>
          <div class="row g-3">
            <div class="col-6 col-md-3">
              <div style="font-size:.7rem;color:#9ca3af;font-weight:600;">Products</div>
              <div style="font-size:.85rem;font-weight:700;color:#0f172a;">{{ usage.products_count }}{% if usage.max_products %} / {{ usage.max_products }}{% endif %}</div>
              {% if usage.products_percent is not None %}<div class="usage-bar"><div class="usage-bar-fill" style="width:{{ usage.products_percent }}%;"></div></div>{% endif %}
            </div>
            <div class="col-6 col-md-3">
              <div style="font-size:.7rem;color:#9ca3af;font-weight:600;">Categories</div>
              <div style="font-size:.85rem;font-weight:700;color:#0f172a;">{{ usage.categories_count }}{% if usage.max_categories %} / {{ usage.max_categories }}{% endif %}</div>
              {% if usage.categories_percent is not None %}<div class="usage-bar"><div class="usage-bar-fill" style="width:{{ usage.categories_percent }}%;"></div></div>{% endif %}
            </div>
            <div class="col-6 col-md-3">
              <div style="font-size:.7rem;color:#9ca3af;font-weight:600;">Orders Today</div>
              <div style="font-size:.85rem;font-weight:700;color:#0f172a;">{{ usage.today_orders_count }}{% if usage.max_orders_per_day %} / {{ usage.max_orders_per_day }}{% endif %}</div>
              {% if usage.orders_percent is not None %}<div class="usage-bar"><div class="usage-bar-fill" style="width:{{ usage.orders_percent }}%;"></div></div>{% endif %}
            </div>
            <div class="col-6 col-md-3">
              <div style="font-size:.7rem;color:#9ca3af;font-weight:600;">Users</div>
              <div style="font-size:.85rem;font-weight:700;color:#0f172a;">{{ usage.users_count }}{% if usage.max_users %} / {{ usage.max_users }}{% endif %}</div>
              {% if usage.users_percent is not None %}<div class="usage-bar"><div class="usage-bar-fill" style="width:{{ usage.users_percent }}%;"></div></div>{% endif %}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  {% endif %}

</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 %}
