@extends('admin.layouts.app')

@section('title', 'Summary Reports')
@section('page-title', 'Summary Reports')
@section('breadcrumb', 'Main / Reports / Summary')

@section('styles')
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;600;700;900&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>
/* ══════════════════════════════════════════
   ROAYA PAY — SUMMARY REPORTS
   Design: Dark-accented financial dashboard
   Font: DM Sans + Space Mono for numbers
   ══════════════════════════════════════════ */
:root {
    --teal:#00b09b; --teal-dk:#008f7a; --teal-lt:rgba(0,176,155,.10); --teal-gl:rgba(0,176,155,.06);
    --blue:#1a8fff; --blue-lt:rgba(26,143,255,.10);
    --red:#e74c3c;  --red-lt:rgba(231,76,60,.10);
    --gold:#f5a623; --gold-lt:rgba(245,166,35,.10);
    --purple:#7c6fcd; --purple-lt:rgba(124,111,205,.10);
    --emerald:#10b981; --emerald-lt:rgba(16,185,129,.10);
    --text:#1a2332; --text-mid:#546e7a; --muted:#90a4ae;
    --border:#e4ecf4; --white:#fff; --bg:#f4f7fb; --card-bg:#fff;
    --sh:0 1px 4px rgba(0,0,0,.05), 0 4px 16px rgba(0,0,0,.06);
    --sh-hover:0 8px 32px rgba(0,0,0,.12);
    --radius:14px;
    --font-body:'DM Sans', sans-serif;
    --font-mono:'Space Mono', monospace;
}

*, *::before, *::after { box-sizing:border-box; }

body { font-family:var(--font-body); }

/* ── Breadcrumb ── */
.bc-bar {
    display:flex; align-items:center; gap:7px;
    font-size:12px; color:var(--muted); margin-bottom:20px;
}
.bc-bar a { color:var(--teal); text-decoration:none; font-weight:700; }
.bc-bar a:hover { text-decoration:underline; }
.bc-sep { font-size:9px; color:var(--border); }

/* ── Page Header ── */
.pg-header {
    display:flex; align-items:flex-start; justify-content:space-between;
    margin-bottom:22px;
}
.pg-header h1 {
    font-size:22px; font-weight:900; color:var(--text); margin:0 0 4px;
    letter-spacing:-0.5px;
}
.pg-header .sub { font-size:12px; color:var(--muted); }
.export-btn {
    display:inline-flex; align-items:center; gap:7px;
    background:var(--text); color:#fff; border:none; border-radius:10px;
    padding:10px 18px; font-size:12px; font-weight:700; cursor:pointer;
    font-family:var(--font-body); transition:.2s; text-decoration:none;
}
.export-btn:hover { background:#2c3e50; box-shadow:0 4px 14px rgba(0,0,0,.2); }

/* ══ FILTER CARD ══ */
.filter-card {
    background:var(--card-bg); border:1px solid var(--border);
    border-radius:var(--radius); margin-bottom:24px;
    box-shadow:var(--sh); overflow:hidden;
}
.filter-header {
    display:flex; align-items:center; justify-content:space-between;
    padding:14px 20px; border-bottom:1px solid var(--border);
    background:linear-gradient(135deg,#f8fbff,#f0f7ff);
}
.filter-header-l { display:flex; align-items:center; gap:8px; font-weight:800; font-size:13px; color:var(--text); }
.filter-body { padding:18px 20px; }

/* Preset Pills */
.preset-row { display:flex; align-items:center; gap:8px; margin-bottom:16px; flex-wrap:wrap; }
.preset-label { font-size:11px; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.5px; }
.pill {
    display:inline-flex; align-items:center; gap:5px;
    padding:6px 14px; border-radius:20px; font-size:12px; font-weight:700;
    border:1.5px solid var(--border); background:var(--bg); color:var(--text-mid);
    cursor:pointer; text-decoration:none; transition:all .2s; white-space:nowrap;
}
.pill:hover { transform:translateY(-1px); box-shadow:0 3px 10px rgba(0,0,0,.1); }
.pill.p-today.active  { background:#1a8fff; border-color:#1a8fff; color:#fff; box-shadow:0 4px 12px rgba(26,143,255,.3); }
.pill.p-week.active   { background:#f5a623; border-color:#f5a623; color:#fff; box-shadow:0 4px 12px rgba(245,166,35,.3); }
.pill.p-month.active  { background:#7c6fcd; border-color:#7c6fcd; color:#fff; box-shadow:0 4px 12px rgba(124,111,205,.3); }
.pill.p-year.active   { background:#e74c3c; border-color:#e74c3c; color:#fff; box-shadow:0 4px 12px rgba(231,76,60,.3); }
.pill.p-all.active    { background:#00b09b; border-color:#00b09b; color:#fff; box-shadow:0 4px 12px rgba(0,176,155,.3); }

/* Filter Grid */
.filter-grid {
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(155px,1fr));
    gap:12px; align-items:end;
}
.fg-group label {
    display:block; font-size:10px; font-weight:800; color:var(--muted);
    text-transform:uppercase; letter-spacing:.6px; margin-bottom:5px;
}
.fg-group input, .fg-group select {
    width:100%; padding:10px 12px;
    border:1.5px solid var(--border); border-radius:9px;
    font-size:13px; color:var(--text); background:var(--bg);
    font-family:var(--font-body); transition:all .2s; appearance:none;
}
.fg-group input:focus, .fg-group select:focus {
    outline:none; border-color:var(--teal);
    background:#fff; box-shadow:0 0 0 3px var(--teal-lt);
}
.fg-actions { display:flex; gap:8px; }
.btn-apply {
    flex:1; background:linear-gradient(135deg,var(--teal),#00c6a8);
    color:#fff; border:none; border-radius:9px; padding:10px 18px;
    font-size:13px; font-weight:800; cursor:pointer; font-family:var(--font-body);
    display:flex; align-items:center; justify-content:center; gap:6px;
    transition:all .2s; box-shadow:0 4px 12px var(--teal-lt);
}
.btn-apply:hover { transform:translateY(-1px); box-shadow:0 6px 18px rgba(0,176,155,.3); }
.btn-reset {
    background:var(--bg); color:var(--text-mid); border:1.5px solid var(--border);
    border-radius:9px; padding:10px 14px; font-size:12px; font-weight:700;
    cursor:pointer; font-family:var(--font-body); transition:.2s; text-decoration:none;
    display:flex; align-items:center; gap:5px; white-space:nowrap;
}
.btn-reset:hover { border-color:var(--red); color:var(--red); }

/* Active Filter Badge */
.active-filters { display:flex; gap:6px; flex-wrap:wrap; margin-top:12px; }
.af-badge {
    display:inline-flex; align-items:center; gap:5px;
    background:var(--teal-lt); color:var(--teal);
    border:1px solid rgba(0,176,155,.2); border-radius:6px;
    padding:3px 10px; font-size:11px; font-weight:700;
}
.af-badge a { color:inherit; text-decoration:none; opacity:.7; margin-left:3px; }
.af-badge a:hover { opacity:1; }

/* ══ KPI CARDS ══ */
.kpi-grid {
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:14px; margin-bottom:22px;
}
.kpi-card {
    background:var(--card-bg); border:1px solid var(--border);
    border-radius:var(--radius); padding:18px 20px;
    box-shadow:var(--sh); position:relative; overflow:hidden;
    transition:all .3s;
}
.kpi-card:hover { box-shadow:var(--sh-hover); transform:translateY(-3px); }
.kpi-card::after {
    content:''; position:absolute; bottom:-20px; right:-20px;
    width:80px; height:80px; border-radius:50%;
    opacity:.05;
}
.kpi-card.c-teal::after   { background:var(--teal); }
.kpi-card.c-blue::after   { background:var(--blue); }
.kpi-card.c-gold::after   { background:var(--gold); }
.kpi-card.c-red::after    { background:var(--red); }
.kpi-card.c-purple::after { background:var(--purple); }
.kpi-card.c-green::after  { background:var(--emerald); }

.kpi-accent {
    position:absolute; top:0; left:0; right:0; height:3px;
    border-radius:var(--radius) var(--radius) 0 0;
}
.c-teal   .kpi-accent { background:linear-gradient(90deg,var(--teal),#00e0c6); }
.c-blue   .kpi-accent { background:linear-gradient(90deg,var(--blue),#5baeff); }
.c-gold   .kpi-accent { background:linear-gradient(90deg,var(--gold),#ffd177); }
.c-red    .kpi-accent { background:linear-gradient(90deg,var(--red),#ff8577); }
.c-purple .kpi-accent { background:linear-gradient(90deg,var(--purple),#a99be0); }
.c-green  .kpi-accent { background:linear-gradient(90deg,var(--emerald),#6ee7c1); }

.kpi-top { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:10px; }
.kpi-icon {
    width:44px; height:44px; border-radius:11px;
    display:flex; align-items:center; justify-content:center; font-size:20px;
}
.c-teal   .kpi-icon { background:var(--teal-lt); color:var(--teal); }
.c-blue   .kpi-icon { background:var(--blue-lt); color:var(--blue); }
.c-gold   .kpi-icon { background:var(--gold-lt); color:var(--gold); }
.c-red    .kpi-icon { background:var(--red-lt); color:var(--red); }
.c-purple .kpi-icon { background:var(--purple-lt); color:var(--purple); }
.c-green  .kpi-icon { background:var(--emerald-lt); color:var(--emerald); }

.kpi-val {
    font-family:var(--font-mono); font-size:24px; font-weight:700;
    color:var(--text); line-height:1; letter-spacing:-1px;
}
.kpi-lbl { font-size:12px; color:var(--muted); margin-top:5px; font-weight:600; }
.kpi-sub {
    font-size:11px; color:var(--muted); margin-top:10px;
    padding-top:10px; border-top:1px dashed var(--border);
    display:flex; align-items:center; gap:5px;
}

/* ══ SECTION HEADER ══ */
.section-hdr {
    display:flex; align-items:center; gap:10px;
    margin-bottom:14px; margin-top:6px;
}
.section-hdr h2 {
    font-size:15px; font-weight:900; color:var(--text);
    margin:0; letter-spacing:-.3px;
}
.section-hdr .sh-line {
    flex:1; height:1px; background:linear-gradient(90deg,var(--border),transparent);
}

/* ══ CHARTS ══ */
.charts-main { display:grid; grid-template-columns:2fr 1fr; gap:14px; margin-bottom:14px; }
.charts-row2 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:14px; margin-bottom:22px; }
.chart-card {
    background:var(--card-bg); border:1px solid var(--border);
    border-radius:var(--radius); padding:20px; box-shadow:var(--sh);
}
.chart-hdr { margin-bottom:16px; }
.chart-title { font-size:13px; font-weight:800; color:var(--text); display:flex; align-items:center; gap:7px; }
.chart-sub { font-size:11px; color:var(--muted); margin-top:3px; }

/* ══ TERMINAL TABLE ══ */
.tbl-card {
    background:var(--card-bg); border:1px solid var(--border);
    border-radius:var(--radius); overflow:hidden;
    box-shadow:var(--sh); margin-bottom:22px;
}
.tbl-toolbar {
    display:flex; align-items:center; justify-content:space-between;
    padding:16px 20px; border-bottom:1px solid var(--border);
    background:linear-gradient(135deg,#f8fbff,#f0f7ff);
}
.tbl-title { font-size:14px; font-weight:800; color:var(--text); display:flex; align-items:center; gap:8px; }
.tbl-count {
    font-size:12px; color:var(--muted); background:var(--bg);
    padding:4px 10px; border-radius:20px; border:1px solid var(--border); font-weight:700;
}

.data-table { width:100%; border-collapse:collapse; font-size:13px; }
.data-table thead tr { background:var(--bg); }
.data-table th {
    padding:12px 16px; color:var(--muted); font-size:10px; font-weight:800;
    border-bottom:1.5px solid var(--border); text-transform:uppercase;
    letter-spacing:.6px; text-align:left; white-space:nowrap;
}
.data-table td { padding:13px 16px; border-bottom:1px solid #f3f7fb; vertical-align:middle; }
.data-table tbody tr:hover { background:#f8fbff; }
.data-table tbody tr:last-child td { border-bottom:none; }

.rank-badge {
    width:28px; height:28px; border-radius:8px;
    display:flex; align-items:center; justify-content:center;
    font-size:11px; font-weight:900; font-family:var(--font-mono);
}
.num-cell { font-family:var(--font-mono); font-size:13px; font-weight:700; }
.progress-wrap { display:flex; align-items:center; gap:8px; }
.progress-bg { flex:1; background:#f0f4f8; border-radius:20px; height:7px; min-width:60px; overflow:hidden; }
.progress-fill { height:100%; border-radius:20px; transition:width .8s cubic-bezier(.4,0,.2,1); }
.pct-lbl { font-size:11px; font-weight:800; font-family:var(--font-mono); min-width:38px; text-align:right; }

/* ══ BOTTOM ROW: Buckets + Mobiles ══ */
.bottom-row { display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:22px; }

.mini-card {
    background:var(--card-bg); border:1px solid var(--border);
    border-radius:var(--radius); overflow:hidden; box-shadow:var(--sh);
}
.mini-card-hdr {
    display:flex; align-items:center; gap:8px;
    padding:14px 18px; border-bottom:1px solid var(--border);
    font-size:13px; font-weight:800; color:var(--text);
    background:linear-gradient(135deg,#f8fbff,#f0f7ff);
}
.mini-card-body { padding:14px 18px; }

.bucket-row {
    display:flex; align-items:center; gap:10px;
    padding:8px 0; border-bottom:1px solid #f3f7fb;
}
.bucket-row:last-child { border-bottom:none; }
.bucket-lbl { font-size:12px; font-weight:700; color:var(--text-mid); width:80px; flex-shrink:0; }
.bucket-bar-bg { flex:1; background:#f0f4f8; border-radius:20px; height:8px; overflow:hidden; }
.bucket-bar-fill { height:100%; border-radius:20px; background:linear-gradient(90deg,var(--teal),var(--blue)); }
.bucket-cnt { font-size:12px; font-weight:800; font-family:var(--font-mono); color:var(--text); min-width:30px; text-align:right; }

.mobile-row {
    display:flex; align-items:center; justify-content:space-between;
    padding:10px 0; border-bottom:1px solid #f3f7fb;
}
.mobile-row:last-child { border-bottom:none; }
.mobile-num { font-family:var(--font-mono); font-size:13px; color:var(--text); font-weight:700; }
.mobile-stats { display:flex; gap:10px; align-items:center; }
.mobile-cnt { font-size:11px; color:var(--muted); }
.mobile-amt { font-size:12px; font-weight:800; color:var(--teal); font-family:var(--font-mono); }

/* ══ Responsive ══ */
@media(max-width:1100px) {
    .kpi-grid { grid-template-columns:repeat(3,1fr); }
    .charts-main { grid-template-columns:1fr; }
    .charts-row2 { grid-template-columns:1fr 1fr; }
}
@media(max-width:768px) {
    .kpi-grid { grid-template-columns:1fr 1fr; }
    .charts-row2 { grid-template-columns:1fr; }
    .bottom-row { grid-template-columns:1fr; }
}
@media(max-width:480px) {
    .kpi-grid { grid-template-columns:1fr; }
}

/* ══ Animations ══ */
@keyframes fadeUp {
    from { opacity:0; transform:translateY(16px); }
    to   { opacity:1; transform:translateY(0); }
}
.kpi-card { animation:fadeUp .4s ease both; }
.kpi-card:nth-child(1){animation-delay:.05s}
.kpi-card:nth-child(2){animation-delay:.10s}
.kpi-card:nth-child(3){animation-delay:.15s}
.kpi-card:nth-child(4){animation-delay:.20s}
.kpi-card:nth-child(5){animation-delay:.25s}
.kpi-card:nth-child(6){animation-delay:.30s}
</style>
@endsection

@section('content')

{{-- ── Breadcrumb ── --}}
<div class="bc-bar">
    <a href="{{ route('admin.dashboard') }}"><i class="las la-home"></i> Dashboard</a>
    <span class="bc-sep">›</span>
    <a href="{{ route('reports.index') }}">Transactions</a>
    <span class="bc-sep">›</span>
    <span>Summary Reports</span>
</div>

{{-- ── Page Header ── --}}
<div class="pg-header">
    <div>
        <h1>📊 Summary Reports</h1>
        <div class="sub">
            Showing
            @if(request('period')) <strong>{{ ucfirst(request('period')) }}</strong> data
            @elseif(request('date_from') || request('date_to')) custom date range
            @else all-time records
            @endif
            — {{ number_format($totalCount) }} transactions total
        </div>
    </div>
</div>

{{-- ══ FILTER CARD ══ --}}
<div class="filter-card">
    <div class="filter-header">
        <div class="filter-header-l">
            <i class="las la-sliders-h" style="color:var(--teal);font-size:16px"></i>
            Filter & Explore
        </div>
    </div>
    <div class="filter-body">

        {{-- Preset Pills --}}
        <div class="preset-row">
            <span class="preset-label">Quick:</span>
            <a href="{{ route('admin.dashboard', ['period'=>'today']) }}"
               class="pill p-today {{ request('period')==='today' ? 'active' : '' }}">
                <i class="las la-sun"></i> Today
            </a>
            <a href="{{ route('admin.dashboard', ['period'=>'week']) }}"
               class="pill p-week {{ request('period')==='week' ? 'active' : '' }}">
                <i class="las la-calendar-week"></i> This Week
            </a>
            <a href="{{ route('admin.dashboard', ['period'=>'month']) }}"
               class="pill p-month {{ request('period')==='month' ? 'active' : '' }}">
                <i class="las la-calendar-alt"></i> This Month
            </a>
            <a href="{{ route('admin.dashboard', ['period'=>'year']) }}"
               class="pill p-year {{ request('period')==='year' ? 'active' : '' }}">
                <i class="las la-calendar"></i> This Year
            </a>
            <a href="{{ route('admin.dashboard') }}"
               class="pill p-all {{ !request('period') && !request('date_from') && !request('terminal_id') && !request('mobile') ? 'active' : '' }}">
                <i class="las la-infinity"></i> All Time
            </a>
        </div>

        {{-- Filter Form --}}
        <form method="GET" action="{{ route('admin.dashboard') }}">
            <div class="filter-grid">
                <div class="fg-group">
                    <label><i class="las la-calendar-day"></i> Date From</label>
                    <input type="date" name="date_from" value="{{ request('date_from') }}">
                </div>
                <div class="fg-group">
                    <label><i class="las la-calendar-day"></i> Date To</label>
                    <input type="date" name="date_to" value="{{ request('date_to') }}">
                </div>
                <div class="fg-group">
                    <label><i class="las la-server"></i> Terminal</label>
                    <select name="terminal_id">
                        <option value="">All Terminals</option>
                        @foreach($allTerminals as $t)
                            <option value="{{ $t->terminal_id }}"
                                {{ request('terminal_id') == $t->terminal_id ? 'selected' : '' }}>
                                {{ $t->terminal_name }} ({{ $t->terminal_id }})
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="fg-group">
                    <label><i class="las la-tag"></i> Terminal Name</label>
                    <input type="text" name="terminal_name" value="{{ request('terminal_name') }}" placeholder="Search name...">
                </div>
                <div class="fg-group">
                    <label><i class="las la-mobile"></i> Mobile</label>
                    <input type="text" name="mobile" value="{{ request('mobile') }}" placeholder="1xxxxxxxx">
                </div>
                <div class="fg-group">
                    <div class="fg-actions">
                        <button type="submit" class="btn-apply">
                            <i class="las la-search"></i> Apply
                        </button>
                        <a href="{{ route('admin.dashboard') }}" class="btn-reset">
                            <i class="las la-undo"></i> Reset
                        </a>
                    </div>
                </div>
            </div>
        </form>

        {{-- Active Filter Badges --}}
        @if(request('date_from') || request('date_to') || request('terminal_id') || request('terminal_name') || request('mobile') || request('period'))
        <div class="active-filters">
            @if(request('period'))
                <span class="af-badge"><i class="las la-tag"></i> Period: {{ ucfirst(request('period')) }}</span>
            @endif
            @if(request('date_from'))
                <span class="af-badge"><i class="las la-calendar"></i> From: {{ request('date_from') }}</span>
            @endif
            @if(request('date_to'))
                <span class="af-badge"><i class="las la-calendar"></i> To: {{ request('date_to') }}</span>
            @endif
            @if(request('terminal_id'))
                <span class="af-badge"><i class="las la-server"></i> Terminal ID: {{ request('terminal_id') }}</span>
            @endif
            @if(request('terminal_name'))
                <span class="af-badge"><i class="las la-tag"></i> Name: {{ request('terminal_name') }}</span>
            @endif
            @if(request('mobile'))
                <span class="af-badge"><i class="las la-mobile"></i> Mobile: {{ request('mobile') }}</span>
            @endif
        </div>
        @endif

    </div>
</div>

{{-- ══ KPI CARDS ══ --}}
<div class="section-hdr">
    <h2>Key Metrics</h2>
    <div class="sh-line"></div>
</div>

<div class="kpi-grid">
    {{-- Total Volume --}}
    <div class="kpi-card c-teal">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($totalAmount, 0) }}</div>
                <div class="kpi-lbl">Total Volume (IQD)</div>
            </div>
            <div class="kpi-icon"><i class="las la-coins"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-chart-line" style="color:var(--teal)"></i>
            Sum of all filtered transactions
        </div>
    </div>

    {{-- Total Transactions --}}
    <div class="kpi-card c-blue">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($totalCount) }}</div>
                <div class="kpi-lbl">Total Transactions</div>
            </div>
            <div class="kpi-icon"><i class="las la-receipt"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-server" style="color:var(--blue)"></i>
            Across {{ $uniqueTerms }} active terminals
        </div>
    </div>

    {{-- Average --}}
    <div class="kpi-card c-gold">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($avgAmount, 0) }}</div>
                <div class="kpi-lbl">Avg per Transaction</div>
            </div>
            <div class="kpi-icon"><i class="las la-balance-scale"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-equals" style="color:var(--gold)"></i>
            Total Volume ÷ Count
        </div>
    </div>

    {{-- Highest --}}
    <div class="kpi-card c-red">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($maxAmount, 0) }}</div>
                <div class="kpi-lbl">Highest Single Txn</div>
            </div>
            <div class="kpi-icon"><i class="las la-trophy"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-arrow-up" style="color:var(--red)"></i>
            Peak transaction recorded
        </div>
    </div>

    {{-- Unique Customers --}}
    <div class="kpi-card c-purple">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($uniqueMobiles) }}</div>
                <div class="kpi-lbl">Unique Customers</div>
            </div>
            <div class="kpi-icon"><i class="las la-users"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-mobile" style="color:var(--purple)"></i>
            Distinct mobile numbers
        </div>
    </div>

    {{-- Lowest --}}
    <div class="kpi-card c-green">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
            <div>
                <div class="kpi-val">{{ number_format($minAmount, 0) }}</div>
                <div class="kpi-lbl">Lowest Transaction</div>
            </div>
            <div class="kpi-icon"><i class="las la-arrow-down"></i></div>
        </div>
        <div class="kpi-sub">
            <i class="las la-tachometer-alt" style="color:var(--emerald)"></i>
            Minimum amount recorded
        </div>
    </div>
</div>

{{-- ══ CHARTS ROW 1: Line + Donut ══ --}}
<div class="section-hdr">
    <h2>Visual Analytics</h2>
    <div class="sh-line"></div>
</div>

<div class="charts-main">
    <div class="chart-card">
        <div class="chart-hdr">
            <div class="chart-title">
                <i class="las la-chart-area" style="color:var(--teal)"></i>
                Daily Volume — Last 30 Days
            </div>
            <div class="chart-sub">Transaction amounts in IQD per day</div>
        </div>
        <canvas id="lineChart" height="90"></canvas>
    </div>

    <div class="chart-card">
        <div class="chart-hdr">
            <div class="chart-title">
                <i class="las la-chart-pie" style="color:var(--purple)"></i>
                Terminal Share
            </div>
            <div class="chart-sub">Top 5 terminals + others</div>
        </div>
        <canvas id="donutChart" height="200"></canvas>
    </div>
</div>

{{-- ══ CHARTS ROW 2: Bar + Count + Monthly ══ --}}
<div class="charts-row2">
    <div class="chart-card">
        <div class="chart-hdr">
            <div class="chart-title">
                <i class="las la-chart-bar" style="color:var(--blue)"></i>
                Top 10 Terminals by Volume
            </div>
            <div class="chart-sub">Total IQD collected</div>
        </div>
        <canvas id="barChart" height="170"></canvas>
    </div>

    <div class="chart-card">
        <div class="chart-hdr">
            <div class="chart-title">
                <i class="las la-stream" style="color:var(--gold)"></i>
                Daily Txn Count (30d)
            </div>
            <div class="chart-sub">Number of transactions per day</div>
        </div>
        <canvas id="countChart" height="170"></canvas>
    </div>

    <div class="chart-card">
        <div class="chart-hdr">
            <div class="chart-title">
                <i class="las la-calendar-alt" style="color:var(--red)"></i>
                Monthly Volume (12 Months)
            </div>
            <div class="chart-sub">Month-over-month comparison</div>
        </div>
        <canvas id="monthChart" height="170"></canvas>
    </div>
</div>

{{-- ══ TERMINAL TABLE ══ --}}
<div class="section-hdr">
    <h2>Terminal Breakdown</h2>
    <div class="sh-line"></div>
</div>

<div class="tbl-card">
    <div class="tbl-toolbar">
        <div class="tbl-title">
            <i class="las la-server" style="color:var(--teal)"></i>
            Performance per Terminal
        </div>
        <span class="tbl-count">{{ $terminalStats->count() }} terminals</span>
    </div>
    <div style="overflow-x:auto">
        <table class="data-table">
            <thead>
                <tr>
                    <th>Rank</th>
                    <th>Terminal ID</th>
                    <th>Terminal Name</th>
                    <th>Txn Count</th>
                    <th>Total Volume (IQD)</th>
                    <th>Avg / Txn</th>
                    <th>Max Txn</th>
                    <th>Min Txn</th>
                    <th>Share</th>
                </tr>
            </thead>
            <tbody>
                @php
                    $grandTotal  = $totalAmount ?: 1;
                    $maxTerm     = $terminalStats->max('total_amount') ?: 1;
                    $rankColors  = ['#00b09b','#1a8fff','#f5a623','#7c6fcd','#e74c3c'];
                @endphp
                @forelse($terminalStats as $i => $t)
                @php
                    $share = round(($t->total_amount / $grandTotal) * 100, 1);
                    $bar   = round(($t->total_amount / $maxTerm) * 100, 1);
                    $clr   = $rankColors[$i] ?? '#90a4ae';
                @endphp
                <tr>
                    <td>
                        <div class="rank-badge" style="background:{{ $clr }}18;color:{{ $clr }}">
                            {{ $i + 1 }}
                        </div>
                    </td>
                    <td><code style="font-size:11px;color:var(--blue);background:var(--blue-lt);padding:2px 7px;border-radius:5px">{{ $t->terminal_id }}</code></td>
                    <td style="font-weight:700;color:var(--text)">{{ $t->terminal_name }}</td>
                    <td>
                        <span class="num-cell" style="color:var(--blue)">
                            {{ number_format($t->txn_count) }}
                        </span>
                    </td>
                    <td>
                        <span class="num-cell" style="font-size:14px;color:var(--text)">
                            {{ number_format($t->total_amount, 0) }}
                        </span>
                    </td>
                    <td class="num-cell" style="color:var(--text-mid)">{{ number_format($t->avg_amount, 0) }}</td>
                    <td class="num-cell" style="color:var(--red)">{{ number_format($t->max_amount, 0) }}</td>
                    <td class="num-cell" style="color:var(--emerald)">{{ number_format($t->min_amount, 0) }}</td>
                    <td style="min-width:140px">
                        <div class="progress-wrap">
                            <div class="progress-bg">
                                <div class="progress-fill" style="width:{{ $bar }}%;background:{{ $clr }}"></div>
                            </div>
                            <span class="pct-lbl" style="color:{{ $clr }}">{{ $share }}%</span>
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="9" style="text-align:center;padding:50px;color:var(--muted)">
                        <i class="las la-search" style="font-size:30px;display:block;margin-bottom:8px"></i>
                        No data found for the selected filters.
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>
</div>

{{-- ══ BOTTOM ROW: Amount Buckets + Top Mobiles ══ --}}
<div class="section-hdr">
    <h2>Deep Insights</h2>
    <div class="sh-line"></div>
</div>

<div class="bottom-row">

    {{-- Amount Distribution --}}
    <div class="mini-card">
        <div class="mini-card-hdr">
            <i class="las la-layer-group" style="color:var(--teal)"></i>
            Amount Distribution
        </div>
        <div class="mini-card-body">
            @php $maxBucket = max(array_values($buckets)) ?: 1; @endphp
            @foreach($buckets as $label => $count)
            <div class="bucket-row">
                <span class="bucket-lbl">{{ $label }}</span>
                <div class="bucket-bar-bg">
                    <div class="bucket-bar-fill" style="width:{{ round(($count/$maxBucket)*100) }}%"></div>
                </div>
                <span class="bucket-cnt">{{ number_format($count) }}</span>
            </div>
            @endforeach
        </div>
    </div>

    {{-- Top Mobile Numbers --}}
    <div class="mini-card">
        <div class="mini-card-hdr">
            <i class="las la-mobile" style="color:var(--purple)"></i>
            Top 5 Customers by Volume
        </div>
        <div class="mini-card-body">
            @forelse($topMobiles as $m)
            <div class="mobile-row">
                <div style="display:flex;align-items:center;gap:10px">
                    <div style="width:32px;height:32px;border-radius:9px;background:var(--purple-lt);display:flex;align-items:center;justify-content:center;color:var(--purple);font-size:14px">
                        <i class="las la-user"></i>
                    </div>
                    <div>
                        <div class="mobile-num">{{ $m->mobile }}</div>
                        <div class="mobile-cnt">{{ $m->cnt }} transactions</div>
                    </div>
                </div>
                <div class="mobile-amt">{{ number_format($m->total, 0) }} IQD</div>
            </div>
            @empty
            <div style="text-align:center;padding:20px;color:var(--muted);font-size:12px">No data available</div>
            @endforelse
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// ── Palette ──
const C = {
    teal   : '#00b09b',
    blue   : '#1a8fff',
    gold   : '#f5a623',
    red    : '#e74c3c',
    purple : '#7c6fcd',
    green  : '#10b981',
    muted  : '#90a4ae',
};
const COLORS = [C.teal, C.blue, C.gold, C.purple, C.red, C.muted];

// ── Data from PHP ──
const lineLabels   = @json($lineLabels);
const lineData     = @json($lineData);
const lineCount    = @json($lineCountData);
const barLabels    = @json($barLabels);
const barData      = @json($barData);
const barCounts    = @json($barCounts);
const donutLabels  = @json($donutLabels);
const donutValues  = @json($donutValues);
const monthLabels  = @json($monthLabels);
const monthData    = @json($monthData);

// ── Shared chart defaults ──
Chart.defaults.font.family = "'DM Sans', sans-serif";
Chart.defaults.color = '#90a4ae';

const gridCfg = {
    color: '#f0f4f8',
    drawBorder: false
};

// ════ 1. LINE CHART — Daily Volume ════
new Chart(document.getElementById('lineChart'), {
    type: 'line',
    data: {
        labels: lineLabels,
        datasets: [{
            label: 'Volume (IQD)',
            data: lineData,
            borderColor: C.teal,
            backgroundColor: (ctx) => {
                const g = ctx.chart.ctx.createLinearGradient(0, 0, 0, 280);
                g.addColorStop(0, 'rgba(0,176,155,0.18)');
                g.addColorStop(1, 'rgba(0,176,155,0.00)');
                return g;
            },
            borderWidth: 2.5,
            fill: true,
            tension: 0.42,
            pointBackgroundColor: C.teal,
            pointBorderColor: '#fff',
            pointBorderWidth: 2,
            pointRadius: 3,
            pointHoverRadius: 7,
        }]
    },
    options: {
        responsive: true,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: { display: false },
            tooltip: {
                backgroundColor: '#1a2332',
                titleColor: '#90a4ae',
                bodyColor: '#fff',
                padding: 10,
                cornerRadius: 8,
                callbacks: {
                    label: ctx => ' ' + Number(ctx.parsed.y).toLocaleString() + ' IQD'
                }
            }
        },
        scales: {
            x: { grid: { display: false }, ticks: { font: { size: 10 }, maxTicksLimit: 10 } },
            y: {
                grid: gridCfg,
                ticks: {
                    font: { size: 10 },
                    callback: v => v >= 1000000 ? (v/1000000).toFixed(1)+'M'
                                 : v >= 1000    ? (v/1000).toFixed(0)+'K'
                                 : v
                }
            }
        }
    }
});

// ════ 2. DONUT CHART ════
new Chart(document.getElementById('donutChart'), {
    type: 'doughnut',
    data: {
        labels: donutLabels,
        datasets: [{
            data: donutValues,
            backgroundColor: COLORS,
            borderWidth: 3,
            borderColor: '#fff',
            hoverOffset: 6
        }]
    },
    options: {
        responsive: true,
        cutout: '68%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: { font: { size: 11 }, padding: 14, usePointStyle: true, pointStyleWidth: 10 }
            },
            tooltip: {
                backgroundColor: '#1a2332',
                titleColor: '#90a4ae',
                bodyColor: '#fff',
                padding: 10,
                cornerRadius: 8,
                callbacks: {
                    label: ctx => ' ' + Number(ctx.parsed).toLocaleString() + ' IQD'
                }
            }
        }
    }
});

// ════ 3. BAR CHART — Top Terminals ════
new Chart(document.getElementById('barChart'), {
    type: 'bar',
    data: {
        labels: barLabels,
        datasets: [{
            label: 'Volume (IQD)',
            data: barData,
            backgroundColor: barLabels.map((_,i) => COLORS[i % COLORS.length] + 'cc'),
            borderRadius: 8,
            borderSkipped: false,
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                backgroundColor: '#1a2332',
                titleColor: '#90a4ae',
                bodyColor: '#fff',
                padding: 10,
                cornerRadius: 8,
                callbacks: {
                    label: ctx => ' ' + Number(ctx.parsed.y).toLocaleString() + ' IQD'
                }
            }
        },
        scales: {
            x: { grid: { display: false }, ticks: { font: { size: 10 }, maxRotation: 35 } },
            y: {
                grid: gridCfg,
                ticks: {
                    font: { size: 10 },
                    callback: v => v >= 1000000 ? (v/1000000).toFixed(1)+'M'
                                 : v >= 1000    ? (v/1000).toFixed(0)+'K'
                                 : v
                }
            }
        }
    }
});

// ════ 4. COUNT CHART — Daily Count ════
new Chart(document.getElementById('countChart'), {
    type: 'bar',
    data: {
        labels: lineLabels,
        datasets: [{
            label: 'Txn Count',
            data: lineCount,
            backgroundColor: C.gold + '99',
            borderRadius: 6,
            borderSkipped: false,
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                backgroundColor: '#1a2332',
                titleColor: '#90a4ae',
                bodyColor: '#fff',
                padding: 10,
                cornerRadius: 8,
            }
        },
        scales: {
            x: { grid: { display: false }, ticks: { font: { size: 10 }, maxTicksLimit: 10 } },
            y: { grid: gridCfg, ticks: { font: { size: 10 } } }
        }
    }
});

// ════ 5. MONTHLY CHART ════
new Chart(document.getElementById('monthChart'), {
    type: 'bar',
    data: {
        labels: monthLabels,
        datasets: [{
            label: 'Monthly Volume (IQD)',
            data: monthData,
            backgroundColor: (ctx) => {
                const g = ctx.chart.ctx.createLinearGradient(0,0,0,200);
                g.addColorStop(0, C.red + 'ee');
                g.addColorStop(1, C.purple + '88');
                return g;
            },
            borderRadius: 8,
            borderSkipped: false,
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            tooltip: {
                backgroundColor: '#1a2332',
                titleColor: '#90a4ae',
                bodyColor: '#fff',
                padding: 10,
                cornerRadius: 8,
                callbacks: {
                    label: ctx => ' ' + Number(ctx.parsed.y).toLocaleString() + ' IQD'
                }
            }
        },
        scales: {
            x: { grid: { display: false }, ticks: { font: { size: 10 }, maxRotation: 35 } },
            y: {
                grid: gridCfg,
                ticks: {
                    font: { size: 10 },
                    callback: v => v >= 1000000 ? (v/1000000).toFixed(1)+'M'
                                 : v >= 1000    ? (v/1000).toFixed(0)+'K'
                                 : v
                }
            }
        }
    }
});
</script>
@endsection