@php
    $layout = auth()->user()->role === 'super_admin' ? 'layouts.admin' : 'component3.layout';
@endphp

@extends($layout)

@section('title', 'Component 3 – Prevention Reports & Charts')

@section('content')
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 col-lg-2 d-md-block bg-success sidebar collapse" id="sidebarMenu">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link text-white {{ request()->routeIs('component3.prevention.index') ? 'active bg-white text-success' : '' }}"
                           href="{{ route('component3.prevention.index') }}">
                            Prevention Register
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-white active bg-white text-success fw-bold"
                           href="{{ route('component3.prevention.reports') }}">
                            Reports & Visualization
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Main Content -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between align-items-center pt-3 pb-2 mb-4 border-bottom">
                <h1 class="h2 text-success">Prevention Activities – Reports & Analytics</h1>
                <div>
                    <button id="exportPdf" class="btn btn-danger me-2">
                        Export PDF
                    </button>
                    <button id="exportExcel" class="btn btn-success">
                        Export Excel
                    </button>
                </div>
            </div>

            <!-- Key Summary Cards -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Total Sessions</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalSessions }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-calendar-event fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Participants</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalParticipants }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-people fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Female Reach</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalFemale }} ({{ $femalePercent }}%)</div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-person-standing-dress fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Avg. Participants/Session</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $avgPerSession }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-graph-up fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Charts Row -->
            <div class="row">
                <!-- Sessions Over Time -->
                <div class="col-lg-8 mb-4">
                    <div class="card shadow">
                        <div class="card-header bg-success text-white">
                            <h6 class="m-0 font-weight-bold">Prevention Sessions Trend (Last 12 Months)</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="sessionsTrendChart" height="100"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Gender Distribution -->
                <div class="col-lg-4 mb-4">
                    <div class="card shadow">
                        <div class="card-header bg-success text-white">
                            <h6 class="m-0 font-weight-bold">Overall Gender Reach</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="genderPieChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- County & Topic Breakdown -->
            <div class="row">
                <div class="col-lg-6 mb-4">
                    <div class="card shadow">
                        <div class="card-header bg-success text-white">
                            <h6 class="m-0 font-weight-bold">Sessions by County</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="countyBarChart" height="120"></canvas>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6 mb-4">
                    <div class="card shadow">
                        <div class="card-header bg-success text-white">
                            <h6 class="m-0 font-weight-bold">Top 8 Prevention Topics</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="topicsChart" height="120"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Table Summary -->
            <div class="card shadow mb-5">
                <div class="card-header bg-success text-white">
                    <h6 class="m-0 font-weight-bold">Recent Sessions Summary</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Topic</th>
                                    <th>Location</th>
                                    <th>Male</th>
                                    <th>Female</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($recentSessions as $s)
                                <tr>
                                    <td>{{ $s->session_date->format('d M Y') }}</td>
                                    <td>{{ Str::limit($s->topic, 30) }}</td>
                                    <td>{{ $s->county }} / {{ $s->payam }}</td>
                                    <td><span class="badge bg-primary">{{ $s->male_participants }}</span></td>
                                    <td><span class="badge bg-pink">{{ $s->female_participants }}</span></td>
                                    <td><strong>{{ $s->male_participants + $s->female_participants }}</strong></td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
<style>
    .bg-pink { background-color: #d63384 !important; }
    .border-left-pink { border-left: 0.35rem solid #d63384 !important; }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1"></script>
<script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
const chartData = @json($chartData);

document.addEventListener('DOMContentLoaded', function () {
    // 1. Trend Line Chart
    new Chart(document.getElementById('sessionsTrendChart'), {
        type: 'line',
        data: {
            labels: chartData.months,
            datasets: [
                {
                    label: 'Sessions',
                    data: chartData.sessionsByMonth,
                    borderColor: '#198754',
                    backgroundColor: 'rgba(25, 135, 84, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Participants',
                    data: chartData.participantsByMonth,
                    borderColor: '#0d6efd',
                    backgroundColor: 'rgba(13, 110, 253, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            scales: {
                y: { beginAtZero: true, title: { display: true, text: 'Sessions' } },
                y1: { position: 'right', beginAtZero: true, title: { display: true, text: 'Participants' }, grid: { drawOnChartArea: false } }
            }
        }
    });

    // 2. Gender Pie
    new Chart(document.getElementById('genderPieChart'), {
        type: 'doughnut',
        data: {
            labels: ['Female Participants', 'Male Participants'],
            datasets: [{
                data: [{{ $totalFemale }}, {{ $totalMale }}],
                backgroundColor: ['#d63384', '#0d6efd'],
                borderWidth: 2
            }]
        },
        options: { responsive: true, plugins: { legend: { position: 'bottom' } } }
    });

    // 3. County Bar
    new Chart(document.getElementById('countyBarChart'), {
        type: 'bar',
        data: {
            labels: chartData.counties.map(c => c.county),
            datasets: [{
                label: 'Sessions per County',
                data: chartData.counties.map(c => c.count),
                backgroundColor: '#198754'
            }]
        },
        options: { responsive: true, indexAxis: 'y' }
    });

    // 4. Topics Horizontal Bar
    new Chart(document.getElementById('topicsChart'), {
        type: 'bar',
        data: {
            labels: chartData.topics.map(t => t.topic.substring(0, 30) + (t.topic.length > 30 ? '...' : '')),
            datasets: [{
                label: 'Frequency',
                data: chartData.topics.map(t => t.count),
                backgroundColor: '#6f42c47'
            }]
        },
        options: { responsive: true, indexAxis: 'y', plugins: { legend: { display: false } } }
    });

    // Export Buttons
    document.getElementById('exportPdf').addEventListener('click', () => {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('l', 'mm', 'a4');
        doc.text('SSWSEEP – Component 3 Prevention Report', 15, 15);
        doc.autoTable({ html: '#recentTable', startY: 30 });
        doc.save('prevention-report-{{ now()->format('Y-m-d') }}.pdf');
    });

    document.getElementById('exportExcel').addEventListener('click', () => {
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(chartData.allSessions.map(s => ({
            Date: s.session_date,
            Topic: s.topic,
            County: s.county,
            Payam: s.payam,
            Male: s.male_participants,
            Female: s.female_participants,
            Total: s.male_participants + s.female_participants
        })));
        XLSX.utils.book_append_sheet(wb, ws, "Prevention Sessions");
        XLSX.writeFile(wb, 'prevention-report-{{ now()->format('Y-m-d') }}.xlsx');
    });
});
</script>
@endpush