@extends('unit-admin.layout')
@section('title', 'Reports')
@section('page_title', 'Reports')

@section('content')

{{-- ══ UNIT IDENTITY BANNER (same as dashboard) ══ --}}
<div style="background:linear-gradient(135deg,rgba(79,142,247,0.12),rgba(124,58,237,0.08));
            border:1px solid rgba(79,142,247,0.15);border-radius:12px;
            padding:18px 22px;margin-bottom:18px;
            display:flex;align-items:center;gap:16px;flex-wrap:wrap;">
  <div style="width:46px;height:46px;border-radius:11px;
              background:linear-gradient(135deg,#4f8ef7,#7c3aed);
              display:flex;align-items:center;justify-content:center;
              font-size:20px;flex-shrink:0;">📊</div>
  <div style="flex:1;min-width:0;">
    <div style="font-family:'Instrument Serif',serif;font-size:19px;color:var(--text);">
      {{ $unit->name ?? 'Your Unit' }} — Reports
    </div>
    <div style="font-size:11px;color:var(--text-dim);margin-top:2px;">
      {{ $unit->district->name ?? '' }} · {{ $unit->district->state->name ?? '' }}
      &nbsp;·&nbsp;
      <i class="fas fa-calendar" style="color:var(--accent);"></i>
      {{ now()->format('d M Y') }}
    </div>
  </div>
  <a href="{{ route('unit-admin.dashboard') }}" class="btn bo bsm">
    <i class="fas fa-arrow-left"></i> Back to Dashboard
  </a>
</div>

{{-- ══ STAT CARDS — 4 columns matching dashboard ══ --}}
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:18px;">

  <div class="sc" style="--ca:var(--accent)">
    <div class="st">
      <div class="si" style="background:rgba(79,142,247,0.15)">
        <i class="fas fa-users" style="color:var(--accent)"></i>
      </div>
      <span class="str tn">● All</span>
    </div>
    <div class="sv">{{ $totalMembers }}</div>
    <div class="sl2">Total Members</div>
  </div>

  <div class="sc" style="--ca:var(--orange)">
    <div class="st">
      <div class="si" style="background:rgba(251,146,60,0.15)">
        <i class="fas fa-clock" style="color:var(--orange)"></i>
      </div>
      <span class="str" style="background:rgba(251,146,60,0.15);color:var(--orange);">● Pending</span>
    </div>
    <div class="sv">{{ $pendingMembers }}</div>
    <div class="sl2">Pending Approval</div>
  </div>

  <div class="sc" style="--ca:var(--green)">
    <div class="st">
      <div class="si" style="background:rgba(52,211,153,0.15)">
        <i class="fas fa-check-circle" style="color:var(--green)"></i>
      </div>
      <span class="str tu">● Active</span>
    </div>
    <div class="sv">{{ $activeMembers }}</div>
    <div class="sl2">Active Members</div>
  </div>

  <div class="sc" style="--ca:var(--gold)">
    <div class="st">
      <div class="si" style="background:rgba(245,200,66,0.15)">
        <i class="fas fa-indian-rupee-sign" style="color:var(--gold)"></i>
      </div>
      <span class="str" style="background:rgba(245,200,66,0.15);color:var(--gold);">● Revenue</span>
    </div>
    <div class="sv" style="font-size:18px;">₹{{ number_format($totalAmountCollected) }}</div>
    <div class="sl2">Total Collected</div>
  </div>

</div>

{{-- ══ CHARTS ROW 1 — Line + Status Donut (same layout as dashboard) ══ --}}
<div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:16px;">

  <div class="card" style="margin:0">
    <div class="ch">
      <div class="ct"><i class="fas fa-chart-line"></i> Registrations & Revenue — Last 6 Months</div>
    </div>
    <div style="padding:18px;height:220px;position:relative;">
      <canvas id="lineChart"></canvas>
    </div>
  </div>

  <div class="card" style="margin:0">
    <div class="ch">
      <div class="ct"><i class="fas fa-chart-pie"></i> Member Status</div>
    </div>
    <div style="padding:14px 18px;display:flex;flex-direction:column;align-items:center;gap:10px;">
      <div style="width:140px;height:140px;position:relative;">
        <canvas id="statusDonut"></canvas>
        <div style="position:absolute;inset:0;display:flex;flex-direction:column;
                    align-items:center;justify-content:center;pointer-events:none;">
          <div style="font-family:'Instrument Serif',serif;font-size:24px;color:var(--text);">{{ $totalMembers }}</div>
          <div style="font-size:9px;color:var(--text-dim);">TOTAL</div>
        </div>
      </div>
      <div style="width:100%;display:flex;flex-direction:column;gap:5px;">
        @foreach([
          ['Active',   'var(--green)',  $activeMembers],
          ['Approved', 'var(--accent)', $approvedMembers],
          ['Pending',  'var(--orange)', $pendingMembers],
          ['Rejected', 'var(--red)',    $rejectedMembers],
        ] as [$lbl,$col,$cnt])
        <div style="display:flex;align-items:center;justify-content:space-between;font-size:11px;padding:3px 0;">
          <div style="display:flex;align-items:center;gap:6px;">
            <div style="width:8px;height:8px;border-radius:2px;background:{{ $col }};flex-shrink:0;"></div>
            <span style="color:var(--text-dim);">{{ $lbl }}</span>
          </div>
          <b style="color:{{ $col }};">{{ $cnt }}</b>
        </div>
        @endforeach
      </div>
    </div>
  </div>

</div>

{{-- ══ CHARTS ROW 2 — Type donut + Plan bars + Monthly revenue ══ --}}
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:16px;">

  {{-- Type split — same style as dashboard plan type card --}}
  <div class="card" style="margin:0">
    <div class="ch">
      <div class="ct"><i class="fas fa-ring"></i> Plan Type</div>
    </div>
    <div style="padding:14px 18px;">
      <div style="text-align:center;margin-bottom:14px;">
        <div style="width:120px;height:120px;position:relative;margin:0 auto;">
          <canvas id="typeDonut"></canvas>
          <div style="position:absolute;inset:0;display:flex;flex-direction:column;
                      align-items:center;justify-content:center;pointer-events:none;">
            <div style="font-family:'Instrument Serif',serif;font-size:20px;">{{ $totalMembers }}</div>
            <div style="font-size:9px;color:var(--text-dim);">TOTAL</div>
          </div>
        </div>
      </div>
      <div style="display:flex;justify-content:space-between;align-items:center;
                  padding:10px 12px;border-radius:8px;margin-bottom:8px;
                  border:1px solid rgba(245,200,66,0.2);background:rgba(245,200,66,0.05);">
        <div>
          <div style="font-size:10px;color:var(--text-dim);">
            <i class="fas fa-infinity" style="color:var(--gold);"></i> Life
          </div>
          <div style="font-family:'Instrument Serif',serif;font-size:22px;color:var(--gold);">{{ $lifeMembers }}</div>
        </div>
        <div style="text-align:right;">
          <div style="font-size:9px;color:var(--text-dim);">Revenue</div>
          <div style="font-size:12px;color:var(--gold);font-weight:600;">
            ₹{{ number_format($planBreakdown->where('type','LIFE')->sum('total_amount')) }}
          </div>
        </div>
      </div>
      <div style="display:flex;justify-content:space-between;align-items:center;
                  padding:10px 12px;border-radius:8px;
                  border:1px solid rgba(79,142,247,0.2);background:rgba(79,142,247,0.05);">
        <div>
          <div style="font-size:10px;color:var(--text-dim);">
            <i class="fas fa-rotate" style="color:var(--accent);"></i> Annual
          </div>
          <div style="font-family:'Instrument Serif',serif;font-size:22px;color:var(--accent);">{{ $annualMembers }}</div>
        </div>
        <div style="text-align:right;">
          <div style="font-size:9px;color:var(--text-dim);">Revenue</div>
          <div style="font-size:12px;color:var(--accent);font-weight:600;">
            ₹{{ number_format($planBreakdown->where('type','ANNUAL')->sum('total_amount')) }}
          </div>
        </div>
      </div>
    </div>
  </div>

  {{-- Revenue by Plan --}}
  <div class="card" style="margin:0">
    <div class="ch">
      <div class="ct"><i class="fas fa-tags"></i> Revenue by Plan</div>
    </div>
    <div style="padding:14px 18px;">
      @php $colors = ['var(--accent)','var(--green)','var(--gold)','var(--purple)','var(--orange)']; @endphp
      @forelse($planBreakdown as $i => $plan)
      <div style="margin-bottom:11px;">
        <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:4px;">
          <span style="color:var(--text);font-weight:500;white-space:nowrap;
                       overflow:hidden;text-overflow:ellipsis;max-width:120px;">
            {{ $plan->plan_name }}
            <span style="color:var(--text-dim);font-weight:400;">({{ $plan->count }})</span>
          </span>
          <span style="color:{{ $colors[$i % 5] }};font-weight:700;flex-shrink:0;margin-left:6px;">
            ₹{{ number_format($plan->total_amount) }}
          </span>
        </div>
        <div style="height:5px;background:rgba(255,255,255,0.06);border-radius:3px;overflow:hidden;">
          <div style="height:100%;border-radius:3px;transition:width 1s ease;
                      width:{{ $planBreakdown->first()->total_amount > 0 ? round(($plan->total_amount / $planBreakdown->first()->total_amount) * 100) : 0 }}%;
                      background:{{ $colors[$i % 5] }};"></div>
        </div>
      </div>
      @empty
      <div style="text-align:center;color:var(--text-dim);padding:20px;font-size:12px;">No plan data yet</div>
      @endforelse
    </div>
  </div>

  {{-- Monthly revenue bar --}}
  <div class="card" style="margin:0">
    <div class="ch">
      <div class="ct"><i class="fas fa-chart-bar"></i> Monthly Revenue</div>
    </div>
    <div style="padding:14px;height:200px;position:relative;">
      <canvas id="monthlyRevenueBar"></canvas>
    </div>
  </div>

</div>

{{-- ══ REPORT BUTTONS HUB ══ --}}
<div class="card" style="margin-bottom:18px;">
  <div class="ch">
    <div class="ct"><i class="fas fa-chart-bar"></i> Report Categories</div>
    <span style="font-size:11px;color:var(--text-dim);">Click a report to view details below</span>
  </div>
  <div style="padding:18px;display:flex;flex-wrap:wrap;gap:10px;">
    <button class="rpt-btn active" onclick="showReport('status')" id="btn-status">
      <i class="fas fa-toggle-on"></i> Member by Status
    </button>
    <button class="rpt-btn" onclick="showReport('membership')" id="btn-membership">
      <i class="fas fa-id-card"></i> Member by Type
    </button>
    <button class="rpt-btn" onclick="showReport('revenue')" id="btn-revenue">
      <i class="fas fa-indian-rupee-sign"></i> Revenue Report
    </button>
    <button class="rpt-btn" onclick="showReport('pending')" id="btn-pending">
      <i class="fas fa-clock"></i> Pending Members
    </button>
    <button class="rpt-btn" onclick="showReport('monthly')" id="btn-monthly">
      <i class="fas fa-calendar-alt"></i> Monthly Report
    </button>
  </div>
</div>

{{-- ══ REPORT SECTIONS ══ --}}

{{-- ── 1. MEMBER BY STATUS ── --}}
<div class="rpt-section" id="rpt-status">
  <div class="card">
    <div class="ch">
      <div class="ct"><i class="fas fa-toggle-on"></i> Member by Status</div>
    </div>

    {{-- Clickable status cards — same style as dashboard --}}
    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;">
      @foreach([
        ['PENDING',  'var(--orange)', $pendingMembers,  'fa-clock'],
        ['APPROVED', 'var(--accent)', $approvedMembers, 'fa-check-circle'],
        ['ACTIVE',   'var(--green)',  $activeMembers,   'fa-user-check'],
        ['REJECTED', 'var(--red)',    $rejectedMembers, 'fa-times-circle'],
      ] as [$lbl,$col,$cnt,$ico])
      <div style="flex:1;min-width:110px;background:rgba(255,255,255,0.03);
                  border:1px solid var(--border);border-radius:8px;padding:12px;
                  cursor:pointer;transition:all 0.2s;"
           onmouseover="this.style.background='rgba(255,255,255,0.06)'"
           onmouseout="this.style.background='rgba(255,255,255,0.03)'"
           onclick="document.getElementById('sts_status').value='{{ $lbl }}';loadReport('status');">
        <div style="display:flex;align-items:center;gap:7px;margin-bottom:6px;">
          <i class="fas {{ $ico }}" style="color:{{ $col }};font-size:12px;"></i>
          <span style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                       letter-spacing:0.5px;font-weight:700;">{{ $lbl }}</span>
        </div>
        <div style="font-family:'Instrument Serif',serif;font-size:22px;color:{{ $col }};">{{ $cnt }}</div>
      </div>
      @endforeach
    </div>

    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Status</label>
        <select id="sts_status">
          <option value="">All Status</option>
          <option value="PENDING">Pending</option>
          <option value="APPROVED">Approved</option>
          <option value="ACTIVE">Active</option>
          <option value="REJECTED">Rejected</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>From Date</label>
        <input type="date" id="sts_from">
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>To Date</label>
        <input type="date" id="sts_to">
      </div>
      <div style="display:flex;gap:6px;">
        <button class="btn bp" onclick="loadReport('status')"><i class="fas fa-search"></i> Search</button>
        <button class="btn bo" onclick="resetReport('status')"><i class="fas fa-times"></i></button>
      </div>
    </div>
    <div id="sts_stats" class="rpt-stats" style="display:none;"></div>
    <div id="sts_body" class="rpt-body">@include('unit-admin.partials.report-initial')</div>
    <div id="sts_footer" class="rpt-footer" style="display:none;">
      <span style="font-size:11px;color:var(--text-dim);"><i class="fas fa-info-circle"></i> Filtered by status</span>
      <button class="btn bp" onclick="downloadReport('status')"><i class="fas fa-download"></i> Download CSV</button>
    </div>
  </div>
</div>

{{-- ── 2. MEMBER BY TYPE ── --}}
<div class="rpt-section" id="rpt-membership" style="display:none;">
  <div class="card">
    <div class="ch">
      <div class="ct"><i class="fas fa-id-card"></i> Member by Membership Type</div>
    </div>

    {{-- Type quick cards — same style as dashboard plan type --}}
    <div style="padding:14px 18px;border-bottom:1px solid var(--border);display:flex;gap:10px;">
      <div style="flex:1;background:rgba(245,200,66,0.06);border:1px solid rgba(245,200,66,0.2);
                  border-radius:8px;padding:14px;cursor:pointer;transition:all 0.2s;"
           onmouseover="this.style.background='rgba(245,200,66,0.12)'"
           onmouseout="this.style.background='rgba(245,200,66,0.06)'"
           onclick="document.getElementById('mem_type').value='LIFE';loadReport('membership');">
        <div style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                    font-weight:700;margin-bottom:6px;">
          <i class="fas fa-infinity" style="color:var(--gold);margin-right:4px;"></i> Life Members
        </div>
        <div style="font-family:'Instrument Serif',serif;font-size:26px;color:var(--gold);">{{ $lifeMembers }}</div>
        <div style="font-size:11px;color:var(--text-dim);margin-top:4px;">
          Revenue: <span style="color:var(--gold);font-weight:600;">₹{{ number_format($planBreakdown->where('type','LIFE')->sum('total_amount')) }}</span>
        </div>
      </div>
      <div style="flex:1;background:rgba(79,142,247,0.06);border:1px solid rgba(79,142,247,0.2);
                  border-radius:8px;padding:14px;cursor:pointer;transition:all 0.2s;"
           onmouseover="this.style.background='rgba(79,142,247,0.12)'"
           onmouseout="this.style.background='rgba(79,142,247,0.06)'"
           onclick="document.getElementById('mem_type').value='ANNUAL';loadReport('membership');">
        <div style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                    font-weight:700;margin-bottom:6px;">
          <i class="fas fa-rotate" style="color:var(--accent);margin-right:4px;"></i> Annual Members
        </div>
        <div style="font-family:'Instrument Serif',serif;font-size:26px;color:var(--accent);">{{ $annualMembers }}</div>
        <div style="font-size:11px;color:var(--text-dim);margin-top:4px;">
          Revenue: <span style="color:var(--accent);font-weight:600;">₹{{ number_format($planBreakdown->where('type','ANNUAL')->sum('total_amount')) }}</span>
        </div>
      </div>
    </div>

    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Membership Type</label>
        <select id="mem_type">
          <option value="">All Types</option>
          <option value="LIFE">Life</option>
          <option value="ANNUAL">Annual</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Status</label>
        <select id="mem_status">
          <option value="">All</option>
          <option value="PENDING">Pending</option>
          <option value="APPROVED">Approved</option>
          <option value="ACTIVE">Active</option>
          <option value="REJECTED">Rejected</option>
        </select>
      </div>
      <div style="display:flex;gap:6px;">
        <button class="btn bp" onclick="loadReport('membership')"><i class="fas fa-search"></i> Search</button>
        <button class="btn bo" onclick="resetReport('membership')"><i class="fas fa-times"></i></button>
      </div>
    </div>
    <div id="mem_stats" class="rpt-stats" style="display:none;"></div>
    <div id="mem_body" class="rpt-body">@include('unit-admin.partials.report-initial')</div>
    <div id="mem_footer" class="rpt-footer" style="display:none;">
      <span style="font-size:11px;color:var(--text-dim);"><i class="fas fa-info-circle"></i> Filtered by membership type</span>
      <button class="btn bp" onclick="downloadReport('membership')"><i class="fas fa-download"></i> Download CSV</button>
    </div>
  </div>
</div>

{{-- ── 3. REVENUE REPORT ── --}}
<div class="rpt-section" id="rpt-revenue" style="display:none;">
  <div class="card">
    <div class="ch">
      <div class="ct"><i class="fas fa-indian-rupee-sign"></i> Revenue Report</div>
    </div>

    {{-- Revenue summary — same card style as dashboard revenue card --}}
    <div style="padding:14px 18px;border-bottom:1px solid var(--border);display:flex;gap:10px;flex-wrap:wrap;">
      <div style="flex:1;min-width:130px;background:rgba(245,200,66,0.06);
                  border:1px solid rgba(245,200,66,0.2);border-radius:8px;padding:14px;">
        <div style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                    font-weight:700;margin-bottom:4px;">Total Revenue</div>
        <div style="font-family:'Instrument Serif',serif;font-size:24px;color:var(--gold);">
          ₹{{ number_format($totalAmountCollected) }}
        </div>
        <div style="font-size:10px;color:var(--text-dim);margin-top:2px;">{{ $totalMembers }} members</div>
      </div>
      <div style="flex:1;min-width:130px;background:rgba(245,200,66,0.04);
                  border:1px solid rgba(245,200,66,0.15);border-radius:8px;padding:14px;">
        <div style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                    font-weight:700;margin-bottom:4px;">Life Revenue</div>
        <div style="font-family:'Instrument Serif',serif;font-size:24px;color:var(--gold);">
          ₹{{ number_format($planBreakdown->where('type','LIFE')->sum('total_amount')) }}
        </div>
        <div style="font-size:10px;color:var(--text-dim);margin-top:2px;">{{ $lifeMembers }} members</div>
      </div>
      <div style="flex:1;min-width:130px;background:rgba(79,142,247,0.06);
                  border:1px solid rgba(79,142,247,0.2);border-radius:8px;padding:14px;">
        <div style="font-size:9.5px;color:var(--text-dim);text-transform:uppercase;
                    font-weight:700;margin-bottom:4px;">Annual Revenue</div>
        <div style="font-family:'Instrument Serif',serif;font-size:24px;color:var(--accent);">
          ₹{{ number_format($planBreakdown->where('type','ANNUAL')->sum('total_amount')) }}
        </div>
        <div style="font-size:10px;color:var(--text-dim);margin-top:2px;">{{ $annualMembers }} members</div>
      </div>
    </div>

    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Membership</label>
        <select id="rev_type">
          <option value="">All Types</option>
          <option value="LIFE">Life</option>
          <option value="ANNUAL">Annual</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Plan</label>
        <select id="rev_plan">
          <option value="">All Plans</option>
          @foreach($planBreakdown as $plan)
            <option value="{{ $plan->plan_id }}">{{ $plan->plan_name }}</option>
          @endforeach
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:90px;flex:1;">
        <label>Month</label>
        <select id="rev_month">
          <option value="">All</option>
          @foreach(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] as $mi => $mn)
            <option value="{{ $mi+1 }}">{{ $mn }}</option>
          @endforeach
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:80px;flex:1;">
        <label>Year</label>
        <select id="rev_year">
          <option value="">All</option>
          @for($y = now()->year; $y >= now()->year-4; $y--)
            <option value="{{ $y }}">{{ $y }}</option>
          @endfor
        </select>
      </div>
      <div style="display:flex;gap:6px;">
        <button class="btn bp" onclick="loadReport('revenue')"><i class="fas fa-search"></i> Search</button>
        <button class="btn bo" onclick="resetReport('revenue')"><i class="fas fa-times"></i></button>
      </div>
    </div>
    <div id="rev_stats" class="rpt-stats" style="display:none;"></div>
    <div id="rev_body" class="rpt-body">@include('unit-admin.partials.report-initial')</div>
    <div id="rev_footer" class="rpt-footer" style="display:none;">
      <span style="font-size:11px;color:var(--text-dim);"><i class="fas fa-info-circle"></i> Revenue report with plan amounts</span>
      <button class="btn bp" onclick="downloadReport('revenue')"><i class="fas fa-download"></i> Download CSV</button>
    </div>
  </div>
</div>

{{-- ── 4. PENDING MEMBERS ── --}}
<div class="rpt-section" id="rpt-pending" style="display:none;">
  <div class="card">
    <div class="ch">
      <div class="ct"><i class="fas fa-clock"></i> Pending Members</div>
      <span style="font-size:11px;color:var(--orange);">
        <i class="fas fa-exclamation-triangle"></i> {{ $pendingMembers }} awaiting approval
      </span>
    </div>
    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>Membership</label>
        <select id="pen_type">
          <option value="">All Types</option>
          <option value="LIFE">Life</option>
          <option value="ANNUAL">Annual</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>From Date</label>
        <input type="date" id="pen_from">
      </div>
      <div class="fg" style="margin:0;min-width:120px;flex:1;">
        <label>To Date</label>
        <input type="date" id="pen_to">
      </div>
      <div style="display:flex;gap:6px;">
        <button class="btn bp" onclick="loadReport('pending')"><i class="fas fa-search"></i> Search</button>
        <button class="btn bo" onclick="resetReport('pending')"><i class="fas fa-times"></i></button>
      </div>
    </div>
    <div id="pen_stats" class="rpt-stats" style="display:none;"></div>
    <div id="pen_body" class="rpt-body">@include('unit-admin.partials.report-initial')</div>
    <div id="pen_footer" class="rpt-footer" style="display:none;">
      <span style="font-size:11px;color:var(--text-dim);"><i class="fas fa-info-circle"></i> Pending members only</span>
      <button class="btn bp" onclick="downloadReport('pending')"><i class="fas fa-download"></i> Download CSV</button>
    </div>
  </div>
</div>

{{-- ── 5. MONTHLY REPORT ── --}}
<div class="rpt-section" id="rpt-monthly" style="display:none;">
  <div class="card">
    <div class="ch">
      <div class="ct"><i class="fas fa-calendar-alt"></i> Monthly Report</div>
    </div>

    {{-- Mini dual chart inside monthly section --}}
    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                height:180px;position:relative;">
      <canvas id="monthlyMiniChart"></canvas>
    </div>

    <div style="padding:14px 18px;border-bottom:1px solid var(--border);
                display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
      <div class="fg" style="margin:0;min-width:100px;flex:1;">
        <label>Month</label>
        <select id="mon_month">
          <option value="">All Months</option>
          @foreach(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] as $mi => $mn)
            <option value="{{ $mi+1 }}">{{ $mn }}</option>
          @endforeach
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:90px;flex:1;">
        <label>Year</label>
        <select id="mon_year">
          <option value="">All Years</option>
          @for($y = now()->year; $y >= now()->year-4; $y--)
            <option value="{{ $y }}">{{ $y }}</option>
          @endfor
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:110px;flex:1;">
        <label>Status</label>
        <select id="mon_status">
          <option value="">All</option>
          <option value="PENDING">Pending</option>
          <option value="APPROVED">Approved</option>
          <option value="ACTIVE">Active</option>
          <option value="REJECTED">Rejected</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:110px;flex:1;">
        <label>Membership</label>
        <select id="mon_type">
          <option value="">All Types</option>
          <option value="LIFE">Life</option>
          <option value="ANNUAL">Annual</option>
        </select>
      </div>
      <div class="fg" style="margin:0;min-width:120px;">
        <label>From Date</label>
        <input type="date" id="mon_from">
      </div>
      <div class="fg" style="margin:0;min-width:120px;">
        <label>To Date</label>
        <input type="date" id="mon_to">
      </div>
      <div style="display:flex;gap:6px;">
        <button class="btn bp" onclick="loadReport('monthly')"><i class="fas fa-search"></i> Search</button>
        <button class="btn bo" onclick="resetReport('monthly')"><i class="fas fa-times"></i></button>
      </div>
    </div>
    <div id="mon_stats" class="rpt-stats" style="display:none;"></div>
    <div id="mon_body" class="rpt-body">@include('unit-admin.partials.report-initial')</div>
    <div id="mon_footer" class="rpt-footer" style="display:none;">
      <span style="font-size:11px;color:var(--text-dim);"><i class="fas fa-info-circle"></i> Monthly registration results</span>
      <button class="btn bp" onclick="downloadReport('monthly')"><i class="fas fa-download"></i> Download CSV</button>
    </div>
  </div>
</div>

<style>
.rpt-btn {
  display:inline-flex;align-items:center;gap:7px;
  padding:9px 16px;border-radius:8px;font-size:12px;font-weight:600;
  cursor:pointer;background:rgba(255,255,255,0.04);
  border:1px solid var(--border);color:var(--text-dim);
  font-family:'DM Sans',sans-serif;transition:all 0.2s;
}
.rpt-btn:hover { background:rgba(79,142,247,0.1);border-color:rgba(79,142,247,0.3);color:var(--accent-2); }
.rpt-btn.active { background:rgba(79,142,247,0.15);border-color:var(--accent);color:var(--accent-2); }
.rpt-stats {
  padding:10px 18px;background:rgba(79,142,247,0.05);
  border-bottom:1px solid var(--border);
  display:flex;gap:16px;flex-wrap:wrap;align-items:center;
}
.rpt-footer {
  padding:12px 18px;border-top:1px solid var(--border);
  display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;
}
</style>

@endsection

@section('scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
Chart.defaults.color = '#8896b3';
Chart.defaults.borderColor = 'rgba(255,255,255,0.06)';

// ── 6-month data (same pattern as dashboard) ──
const monthlyRaw    = @json($monthlyData);
const monthlyPayRaw = @json($monthlyPayments);
const monthNames    = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const chartLabels = [], chartCounts = [], chartPayments = [];

for (let i = 5; i >= 0; i--) {
  const d = new Date();
  d.setMonth(d.getMonth() - i);
  chartLabels.push(monthNames[d.getMonth()] + ' ' + d.getFullYear());
  const reg = monthlyRaw.find(r => r.month === d.getMonth()+1 && r.year === d.getFullYear());
  chartCounts.push(reg ? reg.count : 0);
  const pay = monthlyPayRaw.find(r => r.month === d.getMonth()+1 && r.year === d.getFullYear());
  chartPayments.push(pay ? parseFloat(pay.total) : 0);
}

// ── Line chart dual axis (same blue as dashboard lineChart) ──
new Chart(document.getElementById('lineChart'), {
  type: 'line',
  data: {
    labels: chartLabels,
    datasets: [
      { label:'New Members', data:chartCounts,
        borderColor:'#4f8ef7', backgroundColor:'rgba(79,142,247,0.08)',
        borderWidth:2.5, pointBackgroundColor:'#4f8ef7',
        pointRadius:4, pointHoverRadius:7, tension:0.4, fill:true, yAxisID:'yLeft' },
      { label:'Revenue (₹)', data:chartPayments,
        borderColor:'#f5c842', backgroundColor:'rgba(245,200,66,0.05)',
        borderWidth:2, borderDash:[5,4], pointBackgroundColor:'#f5c842',
        pointRadius:4, pointHoverRadius:7, tension:0.4, fill:false, yAxisID:'yRight' }
    ]
  },
  options: {
    responsive:true, maintainAspectRatio:false,
    plugins: {
      legend:{ display:true, position:'top', align:'end',
               labels:{ font:{size:10}, boxWidth:10, padding:12 } },
      tooltip:{ callbacks:{ label: ctx => ctx.dataset.yAxisID==='yRight'
        ? ` ₹${Number(ctx.raw).toLocaleString('en-IN')}` : ` ${ctx.raw} members` } }
    },
    scales: {
      x:{ grid:{color:'rgba(255,255,255,0.04)'} },
      yLeft: { position:'left',  grid:{color:'rgba(255,255,255,0.04)'}, beginAtZero:true, ticks:{stepSize:1} },
      yRight:{ position:'right', grid:{drawOnChartArea:false}, beginAtZero:true,
               ticks:{callback:v=>'₹'+Number(v).toLocaleString('en-IN')} }
    }
  }
});

// ── Status donut (same as dashboard statusDonut) ──
new Chart(document.getElementById('statusDonut'), {
  type:'doughnut',
  data:{
    labels:['Active','Approved','Pending','Rejected'],
    datasets:[{ data:[{{ $activeMembers }},{{ $approvedMembers }},{{ $pendingMembers }},{{ $rejectedMembers }}],
      backgroundColor:['rgba(52,211,153,0.85)','rgba(79,142,247,0.85)','rgba(251,146,60,0.85)','rgba(248,113,113,0.85)'],
      borderColor:['#34d399','#4f8ef7','#fb923c','#f87171'], borderWidth:2 }]
  },
  options:{ responsive:true, maintainAspectRatio:false,
    plugins:{legend:{display:false}}, cutout:'68%' }
});

// ── Type donut (same as dashboard typeDonut) ──
new Chart(document.getElementById('typeDonut'), {
  type:'doughnut',
  data:{
    labels:['Life','Annual'],
    datasets:[{ data:[{{ $lifeMembers }},{{ $annualMembers }}],
      backgroundColor:['rgba(245,200,66,0.85)','rgba(79,142,247,0.85)'],
      borderColor:['#f5c842','#4f8ef7'], borderWidth:2 }]
  },
  options:{ responsive:true, maintainAspectRatio:false,
    plugins:{legend:{display:false}}, cutout:'60%' }
});

// ── Monthly revenue bar ──
new Chart(document.getElementById('monthlyRevenueBar'), {
  type:'bar',
  data:{ labels:chartLabels,
    datasets:[{ label:'Revenue (₹)', data:chartPayments,
      backgroundColor:'rgba(245,200,66,0.2)', borderColor:'#f5c842',
      borderWidth:2, borderRadius:4 }]
  },
  options:{ responsive:true, maintainAspectRatio:false, plugins:{legend:{display:false}},
    scales:{
      x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{font:{size:9}}},
      y:{grid:{color:'rgba(255,255,255,0.04)'},beginAtZero:true,
         ticks:{callback:v=>'₹'+Number(v).toLocaleString('en-IN'),font:{size:9}}}
    }
  }
});

// ── Monthly mini chart (inside monthly report section) ──
new Chart(document.getElementById('monthlyMiniChart'), {
  type:'bar',
  data:{ labels:chartLabels,
    datasets:[
      { label:'Members', data:chartCounts,
        backgroundColor:'rgba(79,142,247,0.25)', borderColor:'#4f8ef7',
        borderWidth:2, borderRadius:3, yAxisID:'yL' },
      { label:'Revenue (₹)', data:chartPayments,
        backgroundColor:'rgba(245,200,66,0.2)', borderColor:'#f5c842',
        borderWidth:2, borderRadius:3, yAxisID:'yR' }
    ]
  },
  options:{ responsive:true, maintainAspectRatio:false,
    plugins:{ legend:{display:true,position:'top',align:'end',
              labels:{font:{size:10},boxWidth:10}} },
    scales:{
      x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{font:{size:9}}},
      yL:{position:'left', grid:{color:'rgba(255,255,255,0.04)'},beginAtZero:true,ticks:{stepSize:1,font:{size:9}}},
      yR:{position:'right',grid:{drawOnChartArea:false},beginAtZero:true,
          ticks:{callback:v=>'₹'+Number(v).toLocaleString('en-IN'),font:{size:9}}}
    }
  }
});

// ── Report section switching ──
const reportConfig = {
  status:     { prefix:'sts' },
  membership: { prefix:'mem' },
  revenue:    { prefix:'rev' },
  pending:    { prefix:'pen' },
  monthly:    { prefix:'mon' },
};

function showReport(name) {
  document.querySelectorAll('.rpt-section').forEach(el => el.style.display = 'none');
  document.querySelectorAll('.rpt-btn').forEach(el => el.classList.remove('active'));
  document.getElementById('rpt-' + name).style.display = 'block';
  document.getElementById('btn-' + name).classList.add('active');
  document.getElementById('rpt-' + name).scrollIntoView({ behavior:'smooth', block:'start' });
}

function getReportFilters(name) {
  const get = id => { const el = document.getElementById(id); return el ? el.value : ''; };
  const f = {};
  if (name === 'status')     { f.status=get('sts_status'); f.date_from=get('sts_from'); f.date_to=get('sts_to'); }
  if (name === 'membership') { f.membership_type=get('mem_type'); f.status=get('mem_status'); }
  if (name === 'revenue')    { f.membership_type=get('rev_type'); f.plan_id=get('rev_plan'); f.month=get('rev_month'); f.year=get('rev_year'); }
  if (name === 'pending')    { f.status='PENDING'; f.membership_type=get('pen_type'); f.date_from=get('pen_from'); f.date_to=get('pen_to'); }
  if (name === 'monthly')    { f.month=get('mon_month'); f.year=get('mon_year'); f.status=get('mon_status'); f.membership_type=get('mon_type'); f.date_from=get('mon_from'); f.date_to=get('mon_to'); }
  return f;
}

function loadReport(name) {
  const f      = getReportFilters(name);
  const params = new URLSearchParams();
  Object.entries(f).forEach(([k,v]) => { if (v) params.append(k,v); });

  const pre = reportConfig[name].prefix;
  const bEl = document.getElementById(pre+'_body');
  const sEl = document.getElementById(pre+'_stats');
  const fEl = document.getElementById(pre+'_footer');

  sEl.style.display = 'none';
  fEl.style.display = 'none';
  bEl.innerHTML = '<div style="padding:28px;text-align:center;color:var(--text-dim);"><i class="fas fa-spinner fa-spin" style="font-size:18px;"></i></div>';

  fetch(`{{ route('unit-admin.reports.preview') }}?${params}`, { headers:{'Accept':'application/json'} })
    .then(r => r.json())
    .then(data => {
      if (!data.members || !data.members.length) {
        bEl.innerHTML = `<div style="padding:40px;text-align:center;color:var(--text-dim);">
          <i class="fas fa-search" style="font-size:24px;margin-bottom:10px;opacity:0.4;display:block;"></i>
          <div style="font-size:13px;font-weight:600;">No members found</div>
          <div style="font-size:11px;margin-top:4px;">Try adjusting your filters</div>
        </div>`;
        return;
      }

      const showPlan = ['revenue','membership'].includes(name);

      sEl.style.display = 'flex';
      sEl.innerHTML = `
        <span style="font-size:12px;color:var(--text-dim);">
          <i class="fas fa-users" style="color:var(--accent);"></i>
          Found <b style="color:var(--accent);font-size:14px;">${data.count}</b> members
        </span>
        <span style="font-size:12px;color:var(--text-dim);">
          <i class="fas fa-indian-rupee-sign" style="color:var(--gold);"></i>
          Total: <b style="color:var(--gold);font-size:14px;">₹${Number(data.total_amount).toLocaleString('en-IN')}</b>
        </span>
        <div style="flex:1;display:flex;gap:5px;flex-wrap:wrap;">
          ${Object.entries(f).filter(([,v])=>v).map(([k,v])=>
            `<span style="background:rgba(79,142,247,0.12);color:var(--accent);
              border:1px solid rgba(79,142,247,0.2);border-radius:20px;
              padding:2px 10px;font-size:10px;font-weight:600;">
              ${k.replace(/_/g,' ')}: ${v}</span>`).join('')}
        </div>`;

      fEl.style.display = 'flex';

      const sc = { PENDING:'rgba(251,146,60,0.15)',APPROVED:'rgba(52,211,153,0.15)',
                   ACTIVE:'rgba(79,142,247,0.15)',REJECTED:'rgba(248,113,113,0.15)' };
      const tc = { PENDING:'var(--orange)',APPROVED:'var(--green)',
                   ACTIVE:'var(--accent)',REJECTED:'var(--red)' };

      bEl.innerHTML = `
        <div class="tw">
          <table>
            <thead>
              <tr>
                <th>#</th><th>Member</th><th>Phone</th>
                <th class="hide-mobile">Organization</th>
                ${showPlan ? '<th>Plan</th><th>Amount</th>' : ''}
                <th>Membership</th><th>Status</th><th>Registered</th>
              </tr>
            </thead>
            <tbody>
              ${data.members.map((m,i) => `
                <tr>
                  <td style="color:var(--text-dim)">${i+1}</td>
                  <td>
                    <div class="mc2">
                      <div class="av2" style="background:rgba(79,142,247,0.15);color:#7eb8ff;">
                        ${m.name.substring(0,2).toUpperCase()}
                      </div>
                      <div>
                        <div class="mn">${m.name}</div>
                        <div class="me">${m.email}</div>
                      </div>
                    </div>
                  </td>
                  <td style="color:var(--text-dim)">${m.phone}</td>
                  <td class="hide-mobile" style="color:var(--text-dim)">${m.organization??'—'}</td>
                  ${showPlan ? `
                    <td><span style="background:rgba(245,200,66,0.1);color:var(--gold);
                      border:1px solid rgba(245,200,66,0.2);padding:2px 8px;
                      border-radius:20px;font-size:10px;font-weight:600;">${m.plan_name}</span></td>
                    <td style="color:var(--gold);font-weight:600;">
                      ₹${Number(m.plan_amount).toLocaleString('en-IN')}</td>` : ''}
                  <td><span class="badge ${m.membership_type==='LIFE'?'bli':'ban'}">${m.membership_type}</span></td>
                  <td><span style="background:${sc[m.status]??'rgba(255,255,255,0.05)'};
                    color:${tc[m.status]??'var(--text-dim)'};padding:2px 8px;
                    border-radius:20px;font-size:10px;font-weight:600;">${m.status}</span></td>
                  <td style="color:var(--text-dim)">${m.registered_on}</td>
                </tr>`).join('')}
            </tbody>
          </table>
        </div>`;
    })
    .catch(() => {
      bEl.innerHTML = '<div style="padding:24px;text-align:center;color:var(--red);">Failed to load report.</div>';
    });
}

function resetReport(name) {
  const pre = reportConfig[name].prefix;
  document.getElementById(pre+'_stats').style.display = 'none';
  document.getElementById(pre+'_footer').style.display = 'none';
  document.getElementById(pre+'_body').innerHTML = `
    <div style="padding:36px;text-align:center;color:var(--text-dim);">
      <i class="fas fa-filter" style="font-size:26px;margin-bottom:10px;opacity:0.3;display:block;"></i>
      <div style="font-size:13px;font-weight:600;margin-bottom:4px;">Set filters and click Search</div>
    </div>`;
  document.querySelectorAll(`[id^="${pre}_"]`).forEach(el => {
    if (el.tagName === 'SELECT') el.value = '';
    if (el.tagName === 'INPUT')  el.value = '';
  });
}

function downloadReport(name) {
  const f = getReportFilters(name);
  const params = new URLSearchParams();
  Object.entries(f).forEach(([k,v]) => { if (v) params.append(k,v); });
  window.location.href = `{{ route('unit-admin.reports.download') }}?${params}`;
}
</script>
@endsection
