@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 -->
    <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="javascript:history.back()">Back</a></li>
                            <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 -->
                    <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 Bootcamp Training Cumulative</h6>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Training Centre</th>
                                <th>Total</th>
                                <th>Female</th>
                                <th>Adolescent Girls</th>
                                <th>Female + Adol. Girls</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($byCentre as $centre)
                            <tr>
                                <td>{{ $centre->training_centre ?? 'N/A' }}</td>
                                <td>{{ $centre->total }}</td>
                                <td>{{ $centre->female }}</td>
                                <td>{{ $centre->adol_girls }}</td>
                                <td>{{ $centre->female + $centre->adol_girls }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>

                    <!-- Keep other summary tables if you have them (by cohort, grants by centre, etc.) -->

                    <!-- Beneficiaries Table -->
                    <div class="table-responsive mt-5">
                        <table class="table table-hover table-striped">
                            <thead class="table-dark">
                                <tr>
                                    <th>SN</th>
                                    <th>Name</th>
                                    <th>Sector</th>
                                    <th>Status</th>
                                    <th>Cohort</th>
                                    <th>Centre</th>
                                    <th>County</th>
                                    <th>Gender</th>
                                    <th>Age</th>
                                    <th>Bootcamp /5</th>
                                    <th>Pitch</th>
                                    <th>Accelerator /10</th>
                                    <th>WEOF Connect</th>
                                    <th>Grant</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($beneficiaries as $b)
                                <tr>
                                    <td>{{ $b->sn }}</td>
                                    <td>{{ $b->full_name }}</td>
                                    <td>{{ $b->business_sector }}</td>
                                    <td>{{ $b->residential_status }}</td>
                                    <td>{{ $b->cohort_year }}</td>
                                    <td>{{ $b->training_centre }}</td>
                                    <td>{{ $b->county ?? 'N/A' }}</td>
                                    <td>{{ $b->gender }}</td>
                                    <td>{{ $b->age ?? '?' }}</td>
                                    <td class="{{ $b->bootcamp_is_fully_completed ? 'text-success fw-bold' : '' }}">
                                        {{ $b->bootcamp_completed_count }} / 5
                                    </td>
                                    <td>
                                        @if($b->pitch_presentation === 'Completed')
                                            <span class="{{ $b->pitch_outcome === 'Passed' ? 'text-success' : 'text-danger' }}">
                                                {{ $b->pitch_outcome ?? 'Outcome missing' }}
                                            </span>
                                        @else
                                            Not Completed
                                        @endif
                                    </td>
                                    <td>{{ $b->accelerator_passed_count }} / 10</td>
                                    <td>{{ $b->woef_connect_participation }}</td>
                                    <td>
                                        @if($b->grant)
                                            <span class="badge bg-success">Yes ({{ number_format($b->grant->total_received ?? 0) }})</span>
                                        @else
                                            <span class="badge bg-secondary">No</span>
                                        @endif
                                    </td>
                                    <td>
                                        <a href="{{ route('component2.seedlab.edit', $b) }}" class="btn btn-sm btn-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-danger" onclick="return confirm('Are you sure?')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="15" class="text-center text-muted py-4">No beneficiaries found.</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>

                        {{ $beneficiaries->links() }}
                    </div>

                    <!-- Charts Section -->
                    <div class="row mt-5">
                        <!-- Targets vs Achieved -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Targets vs Achieved</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="targetsBarChart" height="200"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- Gender Distribution -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Gender Distribution</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="genderDoughnutChart" height="200"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- Sector Distribution -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Business Sector Distribution</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="sectorDoughnutChart" height="200"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- Bootcamp Completion Rates -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Bootcamp Module Completion (%)</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="bootcampBarChart" height="200"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- Accelerator Pass Rates -->
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow-sm h-100">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Accelerator Module Pass Rates (%)</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="acceleratorBarChart" height="200"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- County Map -->
                        <div class="col-12 mb-4">
                            <div class="card shadow-sm">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Beneficiaries by County</h5>
                                </div>
                                <div class="card-body p-0" style="height: 500px;">
                                    <div id="countyMap" style="height: 100%;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const chartData = @json($chartData);

    // Targets vs Achieved Bar
    new Chart(document.getElementById('targetsBarChart'), {
        type: 'bar',
        data: {
            labels: chartData.targets_vs_achieved.labels,
            datasets: [
                { label: 'Target', data: chartData.targets_vs_achieved.targets, backgroundColor: '#FFCE56' },
                { label: 'Achieved', data: chartData.targets_vs_achieved.achieved, backgroundColor: '#36A2EB' }
            ]
        },
        options: { scales: { y: { beginAtZero: true } } }
    });

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

    // Sector Doughnut
    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']
            }]
        }
    });

    // Bootcamp Completion Rates
    new Chart(document.getElementById('bootcampBarChart'), {
        type: 'bar',
        data: {
            labels: ['Module 1', 'Module 2', 'Module 3', 'Module 4', 'Module 5'],
            datasets: [{
                label: '% Completed',
                data: Object.values(chartData.bootcamp_completion_rates || {}),
                backgroundColor: '#4CAF50'
            }]
        },
        options: {
            scales: { y: { beginAtZero: true, max: 100, ticks: { callback: v => v + '%' } } }
        }
    });

    // Accelerator Pass Rates
    new Chart(document.getElementById('acceleratorBarChart'), {
        type: 'bar',
        data: {
            labels: Array.from({length: 10}, (_, i) => `Module ${i+1}`),
            datasets: [{
                label: '% Passed',
                data: Object.values(chartData.accelerator_pass_rates || {}),
                backgroundColor: '#2196F3'
            }]
        },
        options: {
            scales: { y: { beginAtZero: true, max: 100, ticks: { callback: v => v + '%' } } }
        }
    });

    // Leaflet Map (your original code - kept unchanged)
    var map = L.map('countyMap').setView([6.8769, 31.3069], 6);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    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';
    }

    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
        };
    }

    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) {
                e.target.setStyle({ weight: 5, color: '#666', dashArray: '', fillOpacity: 0.9 });
                e.target.bringToFront();
            },
            mouseout: function (e) {
                map.resetStyle(e.target);
            }
        });
    }

    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);
            map.fitBounds(geojsonLayer.getBounds());
        });

    var legend = L.control({position: 'bottomright'});
    legend.onAdd = function () {
        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 }}];
        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] ? '–' + grades[i + 1] + '<br>' : '+');
        }
        return div;
    };
    legend.addTo(map);
});
</script>
@endsection