@extends('layouts.app')

@section('title', 'Reports & Analytics')

@section('content')
<div class="container-fluid px-4 py-6">
    @php
        $topUnit = $volunteersPerUnit->first();
        $topTraining = $trainingStats->sortByDesc('participants')->first();
    @endphp
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="mb-1">Reports & Analytics</h1>
            <p class="text-muted mb-0">Visualise NDRT officer, training and deployment data</p>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a href="{{ route('reports.export', 'raw') }}" class="btn btn-outline-dark">
                <i class="fas fa-file-export"></i> Raw Data (Excel)
            </a>
            <div class="dropdown">
                <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="fas fa-download"></i> Quick Exports
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'officers') }}">All NDRT Surge</a></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'officers-available') }}">Available Officers</a></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'officers-unavailable') }}">Unavailable Officers</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'trainings') }}">Trainings</a></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'deployments') }}">Deployments</a></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'deployments-active') }}">Active Deployments</a></li>
                    <li><a class="dropdown-item" href="{{ route('reports.export', 'deployments-completed') }}">Completed Deployments</a></li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <h6 class="text-muted text-uppercase">Total NDRT Surge</h6>
                    <h2 class="mt-2">{{ number_format($totalOfficers) }}</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <h6 class="text-muted text-uppercase">Active Deployments</h6>
                    <h2 class="mt-2 text-success">{{ number_format($activeDeployments) }}</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <h6 class="text-muted text-uppercase">Completed Deployments</h6>
                    <h2 class="mt-2 text-primary">{{ number_format($completedDeployments) }}</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-center h-100">
                <div class="card-body">
                    <h6 class="text-muted text-uppercase">Available Officers</h6>
                    <h2 class="mt-2 text-info">{{ number_format($availableOfficers) }}</h2>
                    <p class="text-muted small mb-0">{{ number_format($unavailableOfficers) }} unavailable</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Gender Distribution</h5>
                </div>
                <div class="card-body">
                    <canvas id="genderChart" height="250"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Availability</h5>
                </div>
                <div class="card-body">
                    <canvas id="availabilityChart" height="250"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Registrations Trend</h5>
                </div>
                <div class="card-body">
                    <canvas id="registrationsChart" height="250"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-1">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Volunteers by Sector / Unit</h5>
                    <form class="d-flex align-items-center gap-2" action="{{ route('reports.export', 'officers-unit') }}" method="GET">
                        <select class="form-select form-select-sm" name="unit" required>
                            <option value="">Select unit</option>
                            @foreach($unitOptions as $unit)
                                <option value="{{ $unit }}">{{ $unit }}</option>
                            @endforeach
                        </select>
                        <button class="btn btn-sm btn-outline-primary" type="submit">
                            <i class="fas fa-file-export"></i>
                        </button>
                    </form>
                </div>
                <div class="card-body">
                    <canvas id="unitChart" height="280"></canvas>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Officers by Location Type</h5>
                    <form class="d-flex align-items-center gap-2" action="{{ route('reports.export', 'officers-location') }}" method="GET">
                        <select class="form-select form-select-sm" name="location" required>
                            <option value="">Select location type</option>
                            @foreach($locationOptions as $location)
                                <option value="{{ $location }}">{{ $location }}</option>
                            @endforeach
                        </select>
                        <button class="btn btn-sm btn-outline-primary" type="submit">
                            <i class="fas fa-file-export"></i>
                        </button>
                    </form>
                </div>
                <div class="card-body">
                    <canvas id="locationChart" height="280"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-1">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Trainings (Top 10)</h5>
                    <a href="{{ route('reports.export', 'trainings') }}" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-file-export"></i> Export
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Start Date</th>
                                    <th>Location</th>
                                    <th class="text-end">Participants</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($trainingStats->take(10) as $training)
                                    <tr>
                                        <td>{{ $training['name'] }}</td>
                                        <td>{{ $training['start_date'] }}</td>
                                        <td>{{ $training['location'] }}</td>
                                        <td class="text-end">{{ $training['participants'] }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="4" class="text-center text-muted">No trainings recorded.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Deployments by Location</h5>
                    <a href="{{ route('reports.export', 'deployments') }}" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-file-export"></i> Export
                    </a>
                </div>
                <div class="card-body">
                    <canvas id="deploymentLocationChart" height="280"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-1">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Skills & Competencies</h5>
                </div>
                <div class="card-body">
                    <canvas id="skillsChart" height="280"></canvas>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Experience Levels</h5>
                </div>
                <div class="card-body">
                    <canvas id="experienceChart" height="280"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-1">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Top Professions / Areas of Study</h5>
                    <form class="d-flex align-items-center gap-2" action="{{ route('reports.export', 'officers') }}" method="GET">
                        <button class="btn btn-sm btn-outline-secondary" type="submit">
                            <i class="fas fa-file-export"></i> All Officers
                        </button>
                    </form>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Area of Study</th>
                                    <th class="text-end">Officers</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($officersByStudy as $row)
                                    <tr>
                                        <td>{{ $row->area_of_study ?? 'Unspecified' }}</td>
                                        <td class="text-end">{{ $row->total }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="2" class="text-center text-muted">No data available.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mt-1">
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Gender-specific Export</h5>
                </div>
                <div class="card-body">
                    <form class="row g-3 align-items-end" action="{{ route('reports.export', 'officers-gender') }}" method="GET">
                        <div class="col-md-8">
                            <label class="form-label">Select Gender</label>
                            <select class="form-select" name="gender" required>
                                <option value="">Choose...</option>
                                @foreach($genderOptions as $gender)
                                    <option value="{{ $gender }}">{{ $gender }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4 d-grid">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-file-export"></i> Export
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-xl-6">
            <div class="card h-100">
                <div class="card-header bg-white">
                    <h5 class="mb-0">Key Highlights</h5>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0">
                        <li class="mb-2"><i class="fas fa-check-circle text-success me-2"></i>Total volunteers: <strong>{{ number_format($totalOfficers) }}</strong></li>
                        <li class="mb-2"><i class="fas fa-check-circle text-success me-2"></i>Active deployments awaiting debrief: <strong>{{ number_format($activeDeployments) }}</strong></li>
                        <li class="mb-2"><i class="fas fa-check-circle text-success me-2"></i>Completed deployments: <strong>{{ number_format($completedDeployments) }}</strong></li>
                        <li class="mb-2"><i class="fas fa-check-circle text-success me-2"></i>Top sector: <strong>{{ $topUnit->unit ?? 'N/A' }}</strong></li>
                        <li class="mb-0"><i class="fas fa-check-circle text-success me-2"></i>Top training: <strong>{{ $topTraining['name'] ?? 'N/A' }}</strong></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const genderData = {
        labels: @json($officersByGender->pluck('gender')->map(fn($g) => $g ?? 'Unspecified')),
        datasets: [{
            data: @json($officersByGender->pluck('total')),
            backgroundColor: ['#ED1C24', '#2F7ED8', '#50B432', '#FF9655']
        }]
    };

    const availabilityData = {
        labels: ['Available', 'Unavailable'],
        datasets: [{
            data: [{{ $availableOfficers }}, {{ $unavailableOfficers }}],
            backgroundColor: ['#50B432', '#ED1C24']
        }]
    };

    const registrationsData = {
        labels: @json(array_keys($registrationsByMonth)),
        datasets: [{
            label: 'New Officers',
            data: @json(array_values($registrationsByMonth)),
            borderColor: '#ED1C24',
            backgroundColor: 'rgba(237, 28, 36, 0.15)',
            tension: 0.3,
            fill: true
        }]
    };

    const unitData = {
        labels: @json($volunteersPerUnit->pluck('unit')->map(fn($u) => $u ?? 'Unspecified')),
        datasets: [{
            label: 'Officers',
            data: @json($volunteersPerUnit->pluck('total')),
            backgroundColor: '#2F7ED8'
        }]
    };

    const locationData = {
        labels: @json($officersByLocation->pluck('location_type')->map(fn($loc) => $loc ?? 'Unspecified')),
        datasets: [{
            label: 'Officers',
            data: @json($officersByLocation->pluck('total')),
            backgroundColor: '#50B432'
        }]
    };

    const deploymentLocationData = {
        labels: @json($deploymentsByLocation->pluck('mission_location')->map(fn($loc) => $loc ?? 'Unspecified')),
        datasets: [{
            label: 'Deployments',
            data: @json($deploymentsByLocation->pluck('total')),
            backgroundColor: '#ED1C24'
        }]
    };

    const skillsData = {
        labels: @json(array_keys($skillsBreakdown)),
        datasets: [{
            label: 'Officers',
            data: @json(array_values($skillsBreakdown)),
            backgroundColor: '#2F7ED8'
        }]
    };

    const experienceData = {
        labels: @json(array_keys($experienceLevels)),
        datasets: [{
            label: 'Officers',
            data: @json(array_values($experienceLevels)),
            backgroundColor: '#FF9655'
        }]
    };

    const chartConfig = (ctx, type, data, options = {}) => new Chart(ctx, { type, data, options });

    document.addEventListener('DOMContentLoaded', () => {
        chartConfig(document.getElementById('genderChart'), 'doughnut', genderData, { plugins: { legend: { position: 'bottom' } } });
        chartConfig(document.getElementById('availabilityChart'), 'doughnut', availabilityData, { plugins: { legend: { position: 'bottom' } } });
        chartConfig(document.getElementById('registrationsChart'), 'line', registrationsData, { scales: { y: { beginAtZero: true } } });
        chartConfig(document.getElementById('unitChart'), 'bar', unitData, { scales: { y: { beginAtZero: true } } });
        chartConfig(document.getElementById('locationChart'), 'bar', locationData, { scales: { y: { beginAtZero: true } } });
        chartConfig(document.getElementById('deploymentLocationChart'), 'bar', deploymentLocationData, { scales: { y: { beginAtZero: true } } });
        chartConfig(document.getElementById('skillsChart'), 'bar', skillsData, { indexAxis: 'y', scales: { x: { beginAtZero: true } } });
        chartConfig(document.getElementById('experienceChart'), 'bar', experienceData, { scales: { y: { beginAtZero: true } } });
    });
</script>
@endpush

