{% extends 'companies/superadmin/base.html' %}
{% load humanize %}

{% block content %}

<style>
.stat-card {
  border: none;
  border-radius: 20px;
  overflow: hidden;
  transition: transform 0.18s, box-shadow 0.18s;
}
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 16px 32px rgba(0,0,0,0.1) !important; }
.revenue-section {
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.06);
  padding: 28px 32px;
  margin-bottom: 28px;
}
.day-bar-wrap {
  display: flex;
  align-items: flex-end;
  gap: 3px;
  height: 80px;
}
.day-bar {
  flex: 1;
  background: linear-gradient(to top, #4F46E5, #7C3AED);
  border-radius: 4px 4px 0 0;
  min-height: 4px;
  cursor: pointer;
  transition: opacity 0.15s;
  position: relative;
}
.day-bar:hover { opacity: 0.8; }
.day-bar-tip {
  position: absolute;
  bottom: calc(100% + 6px);
  left: 50%;
  transform: translateX(-50%);
  background: #1e1b4b;
  color: #fff;
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 6px;
  white-space: nowrap;
  display: none;
  z-index: 10;
}
.day-bar:hover .day-bar-tip { display: block; }
.co-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 14px;
  border-radius: 12px;
  transition: background 0.15s;
  cursor: pointer;
}
.co-row:hover { background: #f1f5f9; }
.co-rank {
  width: 28px; height: 28px;
  border-radius: 8px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: #fff;
  font-size: 12px;
  font-weight: 700;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.co-bar-outer {
  flex: 1;
  height: 6px;
  background: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
}
.co-bar-inner {
  height: 100%;
  background: linear-gradient(90deg, #4F46E5, #7C3AED);
  border-radius: 4px;
}
.gradient-header {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  border-radius: 20px;
  padding: 28px 32px;
  margin-bottom: 28px;
}
.company-card {
  transition: transform 0.2s, box-shadow 0.2s;
  border-radius: 16px;
  border: none;
  overflow: hidden;
}
.company-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0,0,0,0.08) !important;
}
.search-wrapper { position: relative; }
.search-wrapper i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #888; }
.search-wrapper input { padding-left: 45px; border-radius: 30px; border: 2px solid transparent; box-shadow: 0 4px 6px rgba(0,0,0,0.05); transition: all 0.3s; }
.search-wrapper input:focus { border-color: #2a5298; }
</style>

<!-- ═══════════════════════════════════════════════════════════════ -->
<!--  PLATFORM REVENUE ANALYTICS                                    -->
<!-- ═══════════════════════════════════════════════════════════════ -->
<div class="revenue-section">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h4 class="fw-bold mb-1" style="color:#1e1b4b;">
        <i class="fas fa-chart-line me-2 text-primary"></i> Platform Revenue Overview
      </h4>
      <p class="text-muted small mb-0">Aggregated across all companies &mdash; sorted by date</p>
    </div>
    <span class="badge rounded-pill px-3 py-2" style="background:#eef2ff;color:#4F46E5;font-size:0.82rem;">
      <i class="fas fa-calendar-day me-1"></i> {{ today|date:"d M Y" }}
    </span>
  </div>

  <!-- KPI row -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#eef2ff,#e0e7ff);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#6366f1;margin-bottom:6px;">All-Time Revenue</div>
          <div style="font-size:20px;font-weight:800;color:#1e1b4b;">₦{{ platform_total_revenue|floatformat:0|intcomma }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#f0fdf4,#dcfce7);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#10b981;margin-bottom:6px;">Today's Revenue</div>
          <div style="font-size:20px;font-weight:800;color:#064e3b;">₦{{ platform_today_revenue|floatformat:0|intcomma }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#fff7ed,#fed7aa);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#d97706;margin-bottom:6px;">Total Orders</div>
          <div style="font-size:20px;font-weight:800;color:#78350f;">{{ platform_total_orders|intcomma }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#fdf4ff,#f3e8ff);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#7c3aed;margin-bottom:6px;">Active Companies</div>
          <div style="font-size:20px;font-weight:800;color:#4c1d95;">{{ active_companies }}</div>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-4">
    <!-- Daily revenue bar chart (last 30 days) -->
    <div class="col-lg-7">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#64748b;margin-bottom:12px;">
        Daily Revenue — Last 30 Days
      </div>
      {% if daily_revenue %}
        <div class="day-bar-wrap" id="revChart">
          {% for day in daily_revenue %}
          <div class="day-bar"
               style="min-height:4px;"
               data-total="{{ day.total|floatformat:0 }}"
               data-orders="{{ day.orders }}">
            <div class="day-bar-tip">{{ day.day|date:"d M" }}<br>₦{{ day.total|floatformat:0|intcomma }}<br>{{ day.orders }} orders</div>
          </div>
          {% endfor %}
        </div>
        <!-- Date labels: first and last -->
        <div class="d-flex justify-content-between mt-1">
          <span style="font-size:11px;color:#94a3b8;">{{ daily_revenue.0.day|date:"d M" }}</span>
          {% with last_day=daily_revenue|last %}
          <span style="font-size:11px;color:#94a3b8;">{{ last_day.day|date:"d M" }}</span>
          {% endwith %}
        </div>
      {% else %}
        <div class="text-muted text-center py-4 small">No order data for the last 30 days.</div>
      {% endif %}
    </div>

    <!-- Per-company leaderboard -->
    <div class="col-lg-5">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#64748b;margin-bottom:12px;">
        Top Companies by Revenue
      </div>
      {% if company_revenues %}
        {% for co in company_revenues %}
        <a href="{% url 'superadmin_company_detail' co.company__slug %}" class="text-decoration-none">
          <div class="co-row">
            <div class="co-rank">{{ forloop.counter }}</div>
            <div style="flex:1;min-width:0;">
              <div class="fw-semibold small text-dark text-truncate">{{ co.company__name }}</div>
              <div class="co-bar-outer mt-1">
                <div class="co-bar-inner"
                     style="width:{% widthratio co.total company_revenues.0.total 100 %}%"></div>
              </div>
            </div>
            <div class="text-end" style="flex-shrink:0;">
              <div style="font-size:13px;font-weight:700;color:#1e1b4b;">₦{{ co.total|floatformat:0|intcomma }}</div>
              <div style="font-size:11px;color:#94a3b8;">{{ co.orders }} orders</div>
            </div>
          </div>
        </a>
        {% endfor %}
      {% else %}
        <div class="text-muted text-center py-4 small">No revenue data yet.</div>
      {% endif %}
    </div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════ -->
<!--  SWIFTPOS SUBSCRIPTION REVENUE                                 -->
<!-- ═══════════════════════════════════════════════════════════════ -->
<div class="revenue-section" style="border-left: 5px solid #0ea5e9;">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h4 class="fw-bold mb-1" style="color:#0c4a6e;">
        <i class="fas fa-credit-card me-2" style="color:#0ea5e9;"></i>SwiftPOS Subscription Revenue
      </h4>
      <p class="text-muted small mb-0">Revenue earned from paid subscription plans &mdash; successful payments only</p>
    </div>
    <span class="badge rounded-pill px-3 py-2" style="background:#e0f2fe;color:#0284c7;font-size:0.82rem;">
      <i class="fas fa-shield-check me-1"></i> Verified Paid Only
    </span>
  </div>

  <!-- KPI row -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#e0f2fe,#bae6fd);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#0284c7;margin-bottom:6px;">All-Time Revenue</div>
          <div style="font-size:20px;font-weight:800;color:#0c4a6e;">₦{{ sub_total_revenue|floatformat:0|intcomma }}</div>
          <div style="font-size:11px;color:#64748b;margin-top:4px;">{{ sub_total_count }} payment{{ sub_total_count|pluralize }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#f0fdf4,#bbf7d0);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#16a34a;margin-bottom:6px;">This Month</div>
          <div style="font-size:20px;font-weight:800;color:#14532d;">₦{{ sub_this_month|floatformat:0|intcomma }}</div>
          <div style="font-size:11px;color:#64748b;margin-top:4px;">{{ sub_this_month_count }} payment{{ sub_this_month_count|pluralize }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:linear-gradient(135deg,#fef3c7,#fde68a);">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#d97706;margin-bottom:6px;">Last Month</div>
          <div style="font-size:20px;font-weight:800;color:#78350f;">₦{{ sub_last_month|floatformat:0|intcomma }}</div>
          <div style="font-size:11px;color:#64748b;margin-top:4px;">{{ today|date:"F Y" }}</div>
        </div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-card card shadow-sm" style="background:{% if sub_mom_growth and sub_mom_growth >= 0 %}linear-gradient(135deg,#fdf4ff,#f3e8ff){% else %}linear-gradient(135deg,#fff1f2,#fecdd3){% endif %};">
        <div class="card-body p-3 text-center">
          <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#7c3aed;margin-bottom:6px;">MoM Growth</div>
          {% if sub_mom_growth is not None %}
            <div style="font-size:20px;font-weight:800;color:{% if sub_mom_growth >= 0 %}#4c1d95{% else %}#be123c{% endif %};">
              {% if sub_mom_growth >= 0 %}<i class="fas fa-arrow-trend-up me-1" style="font-size:16px;"></i>+{% endif %}{{ sub_mom_growth }}%
            </div>
          {% else %}
            <div style="font-size:20px;font-weight:800;color:#94a3b8;">—</div>
            <div style="font-size:11px;color:#94a3b8;margin-top:4px;">No prior month data</div>
          {% endif %}
        </div>
      </div>
    </div>
  </div>

  <div class="row g-4">
    <!-- 12-month trend chart -->
    <div class="col-lg-6">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#64748b;margin-bottom:12px;">
        <i class="fas fa-chart-bar me-1 text-sky-500"></i> Monthly Trend — Last 12 Months
      </div>
      {% if sub_monthly_trend %}
        <div class="day-bar-wrap" id="subTrendChart" style="height:90px;">
          {% for m in sub_monthly_trend %}
          <div class="day-bar"
               style="background:linear-gradient(to top,#0ea5e9,#38bdf8);min-height:4px;"
               data-total="{{ m.total|floatformat:0 }}"
               data-count="{{ m.count }}">
            <div class="day-bar-tip">{{ m.month|date:"M Y" }}<br>₦{{ m.total|floatformat:0|intcomma }}<br>{{ m.count }} payment{{ m.count|pluralize }}</div>
          </div>
          {% endfor %}
        </div>
        <div class="d-flex justify-content-between mt-1">
          <span style="font-size:11px;color:#94a3b8;">{{ sub_monthly_trend.0.month|date:"M Y" }}</span>
          {% with last_m=sub_monthly_trend|last %}
          <span style="font-size:11px;color:#94a3b8;">{{ last_m.month|date:"M Y" }}</span>
          {% endwith %}
        </div>
      {% else %}
        <div class="text-muted text-center py-4 small">No subscription payments recorded yet.</div>
      {% endif %}
    </div>

    <!-- Plan breakdown -->
    <div class="col-lg-3">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#64748b;margin-bottom:12px;">
        Revenue by Plan
      </div>
      {% if sub_by_plan %}
        {% for p in sub_by_plan %}
        <div class="co-row mb-1">
          <div class="co-rank" style="background:linear-gradient(135deg,#0ea5e9,#0284c7);font-size:10px;">{{ forloop.counter }}</div>
          <div style="flex:1;min-width:0;">
            <div class="fw-semibold small text-dark text-truncate">{{ p.plan__name|default:"Unknown" }}</div>
            <div class="co-bar-outer mt-1">
              <div class="co-bar-inner" style="width:{% widthratio p.total sub_by_plan.0.total 100 %}%;background:linear-gradient(90deg,#0ea5e9,#38bdf8);"></div>
            </div>
          </div>
          <div class="text-end" style="flex-shrink:0;">
            <div style="font-size:12px;font-weight:700;color:#0c4a6e;">₦{{ p.total|floatformat:0|intcomma }}</div>
            <div style="font-size:10px;color:#94a3b8;">{{ p.count }} paid</div>
          </div>
        </div>
        {% endfor %}
      {% else %}
        <div class="text-muted text-center py-4 small">No data yet.</div>
      {% endif %}
    </div>

    <!-- Top paying companies -->
    <div class="col-lg-3">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:#64748b;margin-bottom:12px;">
        Top Subscribers
      </div>
      {% if sub_top_companies %}
        {% for co in sub_top_companies %}
        <a href="{% url 'superadmin_company_detail' co.company__slug %}" class="text-decoration-none">
          <div class="co-row mb-1">
            <div class="co-rank" style="background:linear-gradient(135deg,#0ea5e9,#0369a1);">{{ forloop.counter }}</div>
            <div style="flex:1;min-width:0;">
              <div class="fw-semibold small text-dark text-truncate">{{ co.company__name }}</div>
              <div style="font-size:10px;color:#94a3b8;">{{ co.count }} payment{{ co.count|pluralize }}</div>
            </div>
            <div style="font-size:12px;font-weight:700;color:#0c4a6e;flex-shrink:0;">₦{{ co.total|floatformat:0|intcomma }}</div>
          </div>
        </a>
        {% endfor %}
      {% else %}
        <div class="text-muted text-center py-4 small">No data yet.</div>
      {% endif %}
    </div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════ -->
<!--  COMPANIES LIST HEADER                                         -->
<!-- ═══════════════════════════════════════════════════════════════ -->
<div class="gradient-header d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
  <h2 class="mb-0 fw-bold text-white"><i class="fas fa-building me-2 opacity-75"></i> Companies</h2>
  <div class="d-flex flex-column flex-md-row align-items-center gap-3 w-100 w-md-auto justify-content-end">
    <div class="d-flex flex-wrap gap-2 w-100">
      <select id="planFilter" class="form-select form-select-lg border-0 shadow-sm" style="border-radius:30px;max-width:150px;">
        <option value="">All Plans</option>
      </select>
      <select id="statusFilter" class="form-select form-select-lg border-0 shadow-sm" style="border-radius:30px;max-width:150px;">
        <option value="">All Status</option>
        <option value="active">Active</option>
        <option value="suspended">Suspended</option>
      </select>
      <div class="search-wrapper flex-grow-1" style="min-width:200px;">
        <i class="fas fa-search"></i>
        <input type="text" id="companySearch" class="form-control form-control-lg" placeholder="Search companies...">
      </div>
    </div>
    <a href="{% url 'superadmin_company_create' %}" class="btn btn-light btn-lg shadow-sm text-primary fw-bold text-nowrap rounded-pill px-4">
      <i class="fas fa-plus me-2"></i> New Company
    </a>
  </div>
</div>

<!-- Companies grid -->
<div class="row g-4" id="companyContainer">
  {% for company in companies %}
  <div class="col-12 col-md-6 col-lg-4 company-item"
       data-status="{% if company.is_active %}active{% else %}suspended{% endif %}"
       data-plan="{{ company.plan.name|default:'None'|lower }}">
    <div class="card company-card shadow-sm h-100">
      <div class="card-body p-4 position-relative">
        <div class="d-flex justify-content-between align-items-start mb-3">
          <div>
            <h5 class="fw-bold mb-1 text-dark company-name">{{ company.name }}</h5>
            <p class="text-muted small mb-0"><i class="fas fa-link me-1"></i>/{{ company.slug }}/</p>
          </div>
          {% if company.is_active %}
            <span class="badge bg-success-subtle text-success border border-success-subtle" style="border-radius:20px;padding:6px 16px;font-weight:600;">Active</span>
          {% else %}
            <span class="badge bg-danger-subtle text-danger border border-danger-subtle" style="border-radius:20px;padding:6px 16px;font-weight:600;">Suspended</span>
          {% endif %}
        </div>
        <div class="d-flex flex-wrap gap-2 mb-4">
          <div class="bg-light rounded p-2 flex-fill text-center">
            <small class="text-muted d-block text-uppercase" style="font-size:0.7rem;">Plan</small>
            <span class="fw-bold text-dark">{{ company.plan.name|default:"None" }}</span>
          </div>
          <div class="bg-light rounded p-2 flex-fill text-center">
            <small class="text-muted d-block text-uppercase" style="font-size:0.7rem;">Created</small>
            <span class="fw-bold text-dark">{{ company.created_at|date:"M d, Y" }}</span>
          </div>
        </div>
        <a href="{% url 'superadmin_company_detail' company.slug %}" class="btn btn-outline-primary w-100 rounded-pill fw-bold">
          Manage Workspace
        </a>
      </div>
    </div>
  </div>
  {% empty %}
  <div class="col-12 text-center py-5">
    <div class="bg-white p-5 rounded-4 shadow-sm d-inline-block">
      <i class="fas fa-box-open fa-4x text-muted mb-3 opacity-50"></i>
      <h4 class="fw-bold text-muted">No companies found</h4>
      <p class="text-muted mb-4">You haven't added any client companies yet.</p>
      <a href="{% url 'superadmin_company_create' %}" class="btn btn-primary rounded-pill px-4">Create Your First</a>
    </div>
  </div>
  {% endfor %}
</div>

<script>
// ── Bar chart normalizer ────────────────────────────────────────────
(function() {
  const bars = document.querySelectorAll('.day-bar');
  if (!bars.length) return;
  let max = 0;
  bars.forEach(b => { const t = parseFloat(b.dataset.total) || 0; if (t > max) max = t; });
  if (max === 0) return;
  bars.forEach(b => {
    const t = parseFloat(b.dataset.total) || 0;
    b.style.height = Math.max(4, Math.round((t / max) * 80)) + 'px';
  });
})();

// ── Company filter ─────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", function() {
  const planFilter = document.getElementById('planFilter');
  const items = document.querySelectorAll('.company-item');
  const plans = new Set();
  items.forEach(item => {
    const p = item.getAttribute('data-plan');
    if (p && p !== 'none') plans.add(p);
  });
  plans.forEach(plan => {
    const opt = document.createElement('option');
    opt.value = plan;
    opt.textContent = plan.charAt(0).toUpperCase() + plan.slice(1);
    planFilter.appendChild(opt);
  });
});

function filterCompanies() {
  const search = document.getElementById('companySearch').value.toLowerCase();
  const status = document.getElementById('statusFilter').value;
  const plan   = document.getElementById('planFilter').value;
  document.querySelectorAll('.company-item').forEach(item => {
    const matchSearch = item.textContent.toLowerCase().includes(search);
    const matchStatus = !status || item.dataset.status === status;
    const matchPlan   = !plan   || item.dataset.plan   === plan;
    item.style.display = (matchSearch && matchStatus && matchPlan) ? '' : 'none';
  });
}
document.getElementById('companySearch').addEventListener('input', filterCompanies);
document.getElementById('statusFilter').addEventListener('change', filterCompanies);
document.getElementById('planFilter').addEventListener('change', filterCompanies);
</script>

{% endblock %}
