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



<?php $__env->startSection('title', 'Component 3 – Prevention Reports & Charts'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <!-- Main Content -->
        <main class="ms-sm-auto 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 Stats -->
            <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="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"><?php echo e($totalSessions); ?></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="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"><?php echo e($totalParticipants); ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-3">
                    <div class="card border-left-pink shadow h-100 py-2">
                        <div class="card-body">
                            <div class="text-xs font-weight-bold text-pink text-uppercase mb-1">Female Reach</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo e($totalFemale); ?> (<?php echo e($femalePercent); ?>%)</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="text-xs font-weight-bold text-warning text-uppercase mb-1">Avg per Session</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo e($avgPerSession); ?></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Charts -->
            <div class="row">
                <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">Trend: Sessions & Participants (Last 12 Months)</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="trendChart" height="100"></canvas>
                        </div>
                    </div>
                </div>

                <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">Gender Distribution</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="genderChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <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">Top 10 Counties</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="countyChart" height="140"></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">Most Delivered Activities</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="activitiesChart" height="140"></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>

            <!-- Recent Sessions Table -->
            <div class="card shadow">
                <div class="card-header bg-success text-white">
                    <h6 class="m-0 font-weight-bold">Recent Sessions</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover" id="recentTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Location</th>
                                    <th>Male</th>
                                    <th>Female</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $recentSessions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td><?php echo e($s->session_date->format('d M Y')); ?></td>
                                    <td><?php echo e($s->county); ?> / <?php echo e($s->payam); ?></td>
                                    <td><span class="badge bg-primary"><?php echo e($s->males); ?></span></td>
                                    <td><span class="badge bg-pink"><?php echo e($s->females); ?></span></td>
                                    <td><strong><?php echo e($s->total_participants); ?></strong></td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
<style>
    .bg-pink { background-color: #d63384 !important; }
    .text-pink { color: #d63384 !important; }
    .border-left-pink { border-left: 0.35rem solid #d63384 !important; }
</style>
<?php $__env->stopPush(); ?>

<?php
    $exportData = $recentSessions->map(function($s) {
        return [
            'Date' => $s->session_date->format('Y-m-d'),
            'County' => $s->county,
            'Payam' => $s->payam,
            'Male' => (int) $s->males,
            'Female' => (int) $s->females,
            'Total' => (int) $s->total_participants,
        ];
    })->toArray();
?>

<?php $__env->startPush('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.0.1"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.2.0"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const chartData = <?php echo json_encode($chartData, 15, 512) ?>;
    console.log("Script Loaded...")
    console.log(chartData);
    
    // 1. Trend Chart
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    new Chart(trendCtx, {
        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 Chart
    const genderCtx = document.getElementById('genderChart').getContext('2d');
    new Chart(genderCtx, {
        type: 'doughnut',
        data: {
            labels: ['Male', 'Female'],
            datasets: [{
                data: [chartData.genderData.male, chartData.genderData.female],
                backgroundColor: ['#0d6efd', '#d63384'],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // 3. County Chart
    const countyCtx = document.getElementById('countyChart').getContext('2d');
    new Chart(countyCtx, {
        type: 'bar',
        data: {
            labels: chartData.topCounties.names,
            datasets: [{
                label: 'Participants',
                data: chartData.topCounties.values,
                backgroundColor: '#198754'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // 4. Activities Chart
    const activitiesCtx = document.getElementById('activitiesChart').getContext('2d');
    new Chart(activitiesCtx, {
        type: 'bar',
        data: {
            labels: chartData.topActivities.names,
            datasets: [{
                label: 'Times Delivered',
                data: chartData.topActivities.values,
                backgroundColor: '#6610f2'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true
                }
            }
        }
    });

    const topicsArray = Object.entries(chartData.topics || {}).map(([topic, count]) => ({
        topic,
        count
    }));

    // Then use topicsArray instead of chartData.topics in your chart
    new Chart(document.getElementById('topicsChart'), {
        type: 'bar',
        data: {
            labels: topicsArray.map(t => t.topic.substring(0, 30) + (t.topic.length > 30 ? '...' : '')),
            datasets: [{
                label: 'Frequency',
                data: topicsArray.map(t => t.count),
                backgroundColor: '#6f42c4'
            }]
        },
        options: { responsive: true, indexAxis: 'y', plugins: { legend: { display: false } } }
    });

    // Export functionality
    document.getElementById('exportPdf').addEventListener('click', function() {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        doc.text('Prevention Activities Report', 14, 20);
        doc.autoTable({
            head: [['Date', 'County', 'Payam', 'Male', 'Female', 'Total']],
            body: <?php echo json_encode($exportData, 15, 512) ?>.map(row => [
                row.Date,
                row.County,
                row.Payam,
                row.Male,
                row.Female,
                row.Total
            ])
        });
        doc.save('prevention-report.pdf');
    });

    document.getElementById('exportExcel').addEventListener('click', function() {
        const ws = XLSX.utils.json_to_sheet(<?php echo json_encode($exportData, 15, 512) ?>);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Prevention Report');
        XLSX.writeFile(wb, 'prevention-report.xlsx');
    });
});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make($layout, array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\wamp64\www\sswseepcomponents\resources\views/component3/prevention/reports.blade.php ENDPATH**/ ?>