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

@extends($layout)

@section('title', 'SeedLab Beneficiaries')

@section('content')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<div class="container-fluid py-4">
    <!-- Dashboard Header (unchanged) -->
    <div class="dashboard-header">
        <div class="container-fluid">
            <div class="row align-items-center dashboard-header-content">
                <div class="col-lg-6">
                    <h1 class="dashboard-title">
                        <i class="fas fa-tachometer-alt" style="color: var(--dhis2-blue-primary);"></i>
                        SeedLab Beneficiaries Dashboard
                    </h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="{{ route('component2.dashboard') }}">Component 2 Dashboard</a></li>
                            <li class="breadcrumb-item active">SeedLab Beneficiaries</li>
                        </ol>
                    </nav>
                </div>
                <div class="col-lg-6">
                    <div class="d-flex justify-content-lg-end gap-2 dashboard-actions">
                        <a href="{{ route('component2.seedlab.create') }}" class="btn btn-dark btn-sm">
                            <i class="fas fa-plus"></i> Register New Beneficiary
                        </a>
                        <a href="{{ route('component2.seedlab.export.excel') }}" class="btn btn-success btn-sm">
                            <i class="fas fa-file-excel"></i> Export Excel
                        </a>
                        <a href="{{ route('component2.seedlab.export.pdf') }}" class="btn btn-danger btn-sm">
                            <i class="fas fa-file-pdf"></i> Export PDF
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">
                        <i class="fas fa-seedling"></i> SeedLab Beneficiaries
                    </h4>
                    
                </div>

                <div class="card-body">
                    <!-- Summary Tables from Excel -->
                    <h5>Summary Report - Component 2</h5>
                    <h6>WEOF Result Data</h6>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>WEOF Category</th>
                                <th>RF Target</th>
                                <th>Achieved</th>
                                <th>% Progress</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($woefResults as $result)
                            <tr>
                                <td>{{ $result['category'] }}</td>
                                <td>{{ $result['target'] }}</td>
                                <td>{{ $result['achieved'] }}</td>
                                <td>{{ is_numeric($result['target']) && $result['target'] > 0 ? number_format(($result['achieved'] / $result['target']) * 100, 2) . '%' : 'N/A' }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>

                    <h6>SEEDLAB Participants Receiving Boothcamp Trainings Cumulative</h6>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Total</th>
                                <th>Female</th>
                                <th>Adolescent Girls</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach(['Acacia', 'Women Union', 'Orange Corner'] as $centre)
                            @php $data = $byCentre->firstWhere('training_centre', $centre) ?? (object)['total' => 0, 'female' => 0, 'adol_girls' => 0]; @endphp
                            <tr>
                                <td>{{ $centre }}</td>
                                <td>{{ $data->total }}</td>
                                <td>{{ $data->female }}</td>
                                <td>{{ $data->adol_girls }}</td>
                                <td>{{ $data->female + $data->adol_girls }}</td>
                            </tr>
                            @endforeach
                            <tr>
                                <td><strong>Total</strong></td>
                                <td>{{ $byCentre->sum('total') }}</td>
                                <td>{{ $byCentre->sum('female') }}</td>
                                <td>{{ $byCentre->sum('adol_girls') }}</td>
                                <td>{{ $byCentre->sum('female') + $byCentre->sum('adol_girls') }}</td>
                            </tr>
                        </tbody>
                    </table>

                    
                    <h6>SEEDLAB Participants Receiving Grant Cumulative</h6>
                    <table class="table table-bordered table-striped">
                        <!-- Mirror structure above, using $grantsByCentre -->
                        <thead>
                            <tr>
                                <th></th>
                                <th>Total</th>
                                <th>Female</th>
                                <th>Adolescent Girls</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach(['Acacia', 'Women Union', 'Orange Corner'] as $centre)
                            @php $data = $grantsByCentre->firstWhere('training_centre', $centre) ?? (object)['total' => 0, 'female' => 0, 'adol_girls' => 0]; @endphp
                            <tr>
                                <td>{{ $centre }}</td>
                                <td>{{ $data->total }}</td>
                                <td>{{ $data->female }}</td>
                                <td>{{ $data->adol_girls }}</td>
                                <td>{{ $data->female + $data->adol_girls }}</td>
                            </tr>
                            @endforeach
                            <tr>
                                <td><strong>Total</strong></td>
                                <td>{{ $grantsByCentre->sum('total') }}</td>
                                <td>{{ $grantsByCentre->sum('female') }}</td>
                                <td>{{ $grantsByCentre->sum('adol_girls') }}</td>
                                <td>{{ $grantsByCentre->sum('female') + $grantsByCentre->sum('adol_girls') }}</td>
                            </tr>
                        </tbody>
                    </table>

                    <h6>SeedLab Participants Receiving Capacity Building Cumulative</h6>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Total</th>
                                <th>Female</th>
                                <th>Adolescent Girls</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($byCohort as $cohort)
                            <tr>
                                <td>{{ $cohort->cohort_year }}</td>
                                <td>{{ $cohort->total }}</td>
                                <td>{{ $cohort->female }}</td>
                                <td>{{ $cohort->adol_girls }}</td>
                                <td>{{ $cohort->female + $cohort->adol_girls }}</td>
                            </tr>
                            @endforeach
                            <tr>
                                <td><strong>Total</strong></td>
                                <td>{{ $byCohort->sum('total') }}</td>
                                <td>{{ $byCohort->sum('female') }}</td>
                                <td>{{ $byCohort->sum('adol_girls') }}</td>
                                <td>{{ $byCohort->sum('female') + $byCohort->sum('adol_girls') }}</td>
                            </tr>
                        </tbody>
                    </table>

                    <h6>SeedLab Businesses that Received Grant Cumulative</h6>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Total</th>
                                <th>Female</th>
                                <th>Adolescent Girls</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($grantsByTranche as $tranche => $count)
                            <tr>
                                <td>{{ $tranche }}</td>
                                <td>{{ $count }}</td>
                                <td>0</td> <!-- From Excel; query if gendered -->
                                <td>0</td>
                                <td>{{ $count }}</td>
                            </tr>
                            @endforeach
                            <tr>
                                <td><strong>Total</strong></td>
                                <td>{{ array_sum($grantsByTranche) }}</td>
                                <td>0</td>
                                <td>0</td>
                                <td>{{ array_sum($grantsByTranche) }}</td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="card-body">
                        <!-- Filters -->
                        <div class="row g-3 mb-4">
                            <div class="col-md-3">
                                <input type="text" id="search" class="form-control" placeholder="Search name, business, county...">
                            </div>
                            <div class="col-md-2">
                                <select id="sectorFilter" class="form-select">
                                    <option value="">All Sectors</option>
                                    @foreach(['Agriculture','Education','Healthcare','Real Estate','Services','Supply & Trading','Hospitality','Construction'] as $sector)
                                        <option value="{{ $sector }}">{{ $sector }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select id="cohortFilter" class="form-select">
                                    <option value="">All Cohorts</option>
                                    <option value="Cohort 1/25">Cohort 1/25</option>
                                    <option value="Cohort 2/25">Cohort 2/25</option>
                                    <option value="Cohort 1/26">Cohort 1/26</option>
                                    <option value="Cohort 2/26">Cohort 2/26</option>
                                    <option value="Cohort 3/26">Cohort 3/26</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select id="genderFilter" class="form-select">
                                    <option value="">All Genders</option>
                                    <option value="Female">Female</option>
                                    <option value="Male">Male</option>
                                    <option value="Adol.Girl">Adolescent Girl</option>
                                </select>
                            </div>
                            <div class="col-md-3 text-end">
                                <button id="resetFilters" class="btn btn-outline-secondary">
                                    <i class="fas fa-sync"></i> Reset Filters
                                </button>
                            </div>
                        </div>
    
                        <!-- Quick Stats -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="card text-white bg-primary">
                                    <div class="card-body text-center">
                                        <h5>{{ $totalBeneficiaries }}</h5>
                                        <p class="mb-0">Total Registered</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-pink">
                                    <div class="card-body text-center">
                                        <h5>{{ $femaleCount }}</h5>
                                        <p class="mb-0">Women & Girls</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-info">
                                    <div class="card-body text-center">
                                        <h5>{{ $withGrant }}</h5>
                                        <p class="mb-0">Received Grant</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-success">
                                    <div class="card-body text-center">
                                        <h5>SSP {{ number_format($totalDisbursed, 0) }}</h5>
                                        <p class="mb-0">Total Disbursed</p>
                                    </div>
                                </div>
                            </div>
                        </div>
    
                        <!-- DataTable -->
                        <div class="table-responsive">
                            <table class="table table-hover align-middle" id="seedlabTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>SN</th>
                                        <th>Beneficiary</th>
                                        <th>Sector</th>
                                        <th>Cohort</th>
                                        <th>Gender</th>
                                        <th>County</th>
                                        <th>Modules Completed</th>
                                        <th>Grant</th>
                                        <th>Verification</th>
                                        <th class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($beneficiaries as $b)
                                    <tr>
                                        <td><strong>{{ $b->sn }}</strong></td>
                                        <td>
                                            <div><strong>{{ $b->full_name }}</strong></div>
                                            <small class="text-muted">{{ $b->business_type ?? 'Individual' }}</small>
                                        </td>
                                        <td>
                                            <span class="badge bg-primary">{{ $b->business_sector }}</span>
                                        </td>
                                        <td><span class="badge bg-secondary">{{ $b->cohort_year }}</span></td>
                                        <td>
                                            @if($b->gender === 'Female')
                                                <i class="fas fa-female text-pink"></i>
                                            @elseif($b->gender === 'Adol.Girl')
                                                <i class="fas fa-child text-purple"></i>
                                            @else
                                                <i class="fas fa-male text-blue"></i>
                                            @endif
                                            {{ $b->gender }}
                                        </td>
                                        <td>{{ $b->county ?? '-' }}</td>
                                        <td>
                                            @php
                                                $completed = collect(['1','2','3','4','5','6','7','8'])
                                                    ->filter(fn($m) => $b["module_$m"] === 'Completed')
                                                    ->count();
                                            @endphp
                                            <span class="badge bg-{{ $completed >= 8 ? 'success' : ($completed >= 4 ? 'warning' : 'secondary') }}">
                                                {{ $completed }}/8
                                            </span>
                                        </td>
                                        <td>
                                            @if($b->grant)
                                                @if($b->grant->total_received > 0)
                                                    <span class="badge bg-success">SSP {{ number_format($b->grant->total_received) }}</span>
                                                @else
                                                    <span class="badge bg-warning">Approved</span>
                                                @endif
                                            @else
                                                <span class="badge bg-light text-dark">No Grant</span>
                                            @endif
                                        </td>
                                        <td>
                                            <span class="badge {{ $b->physical_verification === 'Yes' ? 'bg-success' : 'bg-danger' }}">
                                                {{ $b->physical_verification === 'Yes' ? 'Verified' : 'Pending' }}
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <a href="{{ route('component2.seedlab.edit', $b) }}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <form action="{{ route('component2.seedlab.destroy', $b) }}" method="POST" class="d-inline">
                                                @csrf @method('DELETE')
                                                <button type="submit" class="btn btn-sm btn-outline-danger"
                                                        onclick="return confirm('Delete this beneficiary?')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
    
                        <!-- Pagination -->
                        <div class="mt-3">
                            {{ $beneficiaries->links() }}
                        </div>

                    <!-- Visualizations -->
                    <h5 class="mt-5">Visualizations</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <canvas id="targetsVsAchievedChart"></canvas>
                        </div>
                        <div class="col-md-6">
                            <canvas id="genderPieChart"></canvas>
                        </div>
                        <div class="col-md-6">
                            <canvas id="sectorDoughnutChart"></canvas>
                        </div>
                        <div class="col-md-6">
                            <canvas id="countyBarChart"></canvas> <!-- "Map" as bar chart -->
                        </div>
                    </div>
                    <div class="col-12 mt-4">
                        <h5>Beneficiaries by County (Interactive Map)</h5>
                        <div id="countyMap" style="height: 600px; width: 100%; border: 1px solid #ddd; border-radius: 8px;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts (existing + Chart.js) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.min.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.bootstrap5.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/2.0.8/css/dataTables.bootstrap5.min.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1"></script>

<script>
$(document).ready(function() {
    // Existing DataTable script (unchanged)
    const table = $('#seedlabTable').DataTable({
        pageLength: 25,
        responsive: true,
        order: [[0, 'asc']],
        columnDefs: [{ orderable: false, targets: 9 }]
    });

    $('#search').on('keyup', function() {
        table.search(this.value).draw();
    });

    $('#sectorFilter, #cohortFilter, #genderFilter').on('change', function() {
        table.column(2).search($('#sectorFilter').val());
        table.column(3).search($('#cohortFilter').val());
        table.column(4).search($('#genderFilter').val());
        table.draw();
    });

    $('#resetFilters').on('click', function() {
        $('#search, #sectorFilter, #cohortFilter, #genderFilter').val('');
        table.search('').columns().search('').draw();
    });

    // Chart.js Visualizations
    const chartData = @json($chartData);

    // Bar Graph: Targets vs Achieved
    new Chart(document.getElementById('targetsVsAchievedChart'), {
        type: 'bar',
        data: {
            labels: chartData.targets_vs_achieved.labels,
            datasets: [
                { label: 'Target', data: chartData.targets_vs_achieved.targets, backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)' },
                { label: 'Achieved', data: chartData.targets_vs_achieved.achieved, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)' }
            ]
        },
        options: { scales: { y: { beginAtZero: true } } }
    });

    // Pie Chart: Gender Distribution
    new Chart(document.getElementById('genderPieChart'), {
        type: 'pie',
        data: {
            labels: Object.keys(chartData.gender_distribution),
            datasets: [{ data: Object.values(chartData.gender_distribution), backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'] }]
        }
    });

    // Doughnut Chart: Sector Distribution
    new Chart(document.getElementById('sectorDoughnutChart'), {
        type: 'doughnut',
        data: {
            labels: Object.keys(chartData.sector_distribution),
            datasets: [{ data: Object.values(chartData.sector_distribution), backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'] }]
        }
    });

    // Bar Chart: County Distribution (as map alternative)
    new Chart(document.getElementById('countyBarChart'), {
        type: 'bar',
        data: {
            labels: Object.keys(chartData.county_distribution),
            datasets: [{ label: 'Beneficiaries per County', data: Object.values(chartData.county_distribution), backgroundColor: 'rgba(153, 102, 255, 0.2)', borderColor: 'rgba(153, 102, 255, 1)' }]
        },
        options: { scales: { y: { beginAtZero: true } } }
    });
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Initialize map centered on South Sudan
    var map = L.map('countyMap').setView([6.8769, 31.3069], 6);

    // Base tile layer (OpenStreetMap)
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    // Color function: green gradient based on count
    function getColor(count, max) {
        return count > max * 0.8 ? '#006400' :
                count > max * 0.6 ? '#008000' :
                count > max * 0.4 ? '#32CD32' :
                count > max * 0.2 ? '#90EE90' :
                count > 0         ? '#98FB98' :
                                    '#EEEEEE';
    }

    // Style function
    function style(feature) {
        var countyName = feature.properties.admin2Name || feature.properties.county || 'Unknown';
        var count = @json($countyData)[countyName] || 0;
        return {
            fillColor: getColor(count, @json($maxCount)),
            weight: 2,
            opacity: 1,
            color: 'white',
            dashArray: '3',
            fillOpacity: 0.7
        };
    }

    // On each feature: popup + highlight
    function onEachFeature(feature, layer) {
        var countyName = feature.properties.admin2Name || 'Unknown';
        var count = @json($countyData)[countyName] || 0;
        layer.bindPopup('<strong>' + countyName + '</strong><br>Beneficiaries: ' + count);

        layer.on({
            mouseover: function (e) {
                var layer = e.target;
                layer.setStyle({
                    weight: 5,
                    color: '#666',
                    dashArray: '',
                    fillOpacity: 0.9
                });
                layer.bringToFront();
            },
            mouseout: function (e) {
                geojsonLayer.resetStyle(e.target);
            }
        });
    }

    // Load GeoJSON and add to map
    fetch('https://data.humdata.org/dataset/e66dbc70-17fe-4230-b9d6-855d192fc05c/resource/df5c977f-a738-447b-b8c2-55beb387636a/download/south_sudan.json')
        .then(response => response.json())
        .then(data => {
            var geojsonLayer = L.geoJson(data, {
                style: style,
                onEachFeature: onEachFeature
            }).addTo(map);

            // Fit bounds to South Sudan
            map.fitBounds(geojsonLayer.getBounds());
        });

    // Legend
    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'info legend bg-white p-3 shadow rounded');
        var grades = [0, {{ $maxCount*0.2 }}, {{ $maxCount*0.4 }}, {{ $maxCount*0.6 }}, {{ $maxCount*0.8 }}, {{ $maxCount }}];
        var labels = [];
        div.innerHTML = '<strong>Beneficiaries</strong><br>';
        for (var i = 0; i < grades.length; i++) {
            div.innerHTML +=
                '<i style="background:' + getColor(grades[i] + 1, @json($maxCount)) + '; width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7;"></i> ' +
                grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+');
        }
        return div;
    };
    legend.addTo(map);
});
</script>
@endsection