@extends('layouts.adminlte')
@section('title', 'Report')
@section('page_title', 'Report e Statistiche')

@section('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap4-theme@1.0.0/dist/select2-bootstrap4.min.css" rel="stylesheet" />
<style>
.select2-container--bootstrap4 .select2-selection--multiple .select2-selection__choice {
    font-size: 0.8rem;
}
.card-indigo {
    border-top: 3px solid #6610f2;
}
.card-indigo .card-title {
    color: #6610f2;
}
.accordion .card-header .btn-link {
    text-decoration: none;
    font-weight: 600;
    color: #495057;
}
.accordion .card-header .btn-link:hover {
    color: #007bff;
}
.accordion .card-header .btn-link i {
    transition: transform 0.2s ease;
    width: 20px;
}
.accordion .card-header .btn-link[aria-expanded="true"] i.fa-chevron-right {
    transform: rotate(90deg);
}
</style>
@endsection

@section('content')

@if(session('success'))
<div class="alert alert-success alert-dismissible">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ session('success') }}
</div>
@endif

@if(session('error'))
<div class="alert alert-danger alert-dismissible">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ session('error') }}
</div>
@endif

<div class="accordion" id="reportAccordion">
    {{-- Sezione 1: Panoramica Database (sempre aperta) --}}
    <div class="card">
        <div class="card-header" id="headingOne">
            <h2 class="mb-0">
                <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                    <i class="fas fa-chevron-down mr-2 text-primary"></i>
                    <i class="fas fa-chart-bar mr-2 text-primary"></i> Panoramica Database
                </button>
            </h2>
        </div>
        <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#reportAccordion">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-info"><i class="fas fa-users"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Individui</span>
                                <span class="info-box-number">{{ number_format($stats['individui']) }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-warning"><i class="fas fa-folder"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Gruppi</span>
                                <span class="info-box-number">{{ number_format($stats['gruppi']) }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-danger"><i class="fas fa-calendar"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Eventi</span>
                                <span class="info-box-number">{{ number_format($stats['eventi']) }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-secondary"><i class="fas fa-file"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Documenti</span>
                                <span class="info-box-number">{{ number_format($stats['documenti']) }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-purple"><i class="fas fa-list"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Mailing List</span>
                                <span class="info-box-number">{{ number_format($stats['mailing_liste']) }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-4 text-center">
                        <div class="info-box">
                            <span class="info-box-icon bg-teal"><i class="fas fa-address-book"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Contatti</span>
                                <span class="info-box-number">{{ number_format($stats['contatti']) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Sezione 2: Report Predefiniti --}}
    <div class="card">
        <div class="card-header" id="headingTwo">
            <h2 class="mb-0">
                <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                    <i class="fas fa-chevron-right mr-2 text-warning"></i>
                    <i class="fas fa-chart-pie mr-2 text-warning"></i> Report Predefiniti
                    <span class="badge badge-warning badge-pill ml-2">{{ count($prebuiltReports) }}</span>
                </button>
            </h2>
        </div>
        <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#reportAccordion">
            <div class="card-body">
                <div class="row">
                    @foreach($prebuiltReports as $report)
                    <div class="col-md-4 col-lg-3 mb-3">
                        @php
                        $cardColor = $report['colore'] === 'indigo' ? 'card-indigo' : 'card-' . $report['colore'];
                        $btnColor = $report['colore'] === 'indigo' ? 'primary' : $report['colore'];
                        @endphp
                        <div class="card {{ $cardColor }} card-outline h-100">
                            <div class="card-body text-center d-flex flex-column">
                                <i class="fas {{ $report['icona'] }} fa-3x text-{{ $btnColor }} mb-3"></i>
                                <h5>{{ $report['nome'] }}</h5>
                                <p class="text-muted small mb-3 flex-grow-1">{{ $report['descrizione'] }}</p>

                                @if($report['has_tipologia_filter'] ?? false)
                                <form action="{{ route('report.run') }}" method="GET" class="mb-2">
                                    <div class="form-group mb-2">
                                        <select name="tipologia_documento" class="form-control form-control-sm select2-tipologia" style="width: 100%;">
                                            <option value="">Tutte le tipologie</option>
                                            @foreach($tipologieDocumento as $tipologia)
                                            <option value="{{ $tipologia }}">{{ ucfirst($tipologia) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <input type="hidden" name="report" value="{{ $report['id'] }}">
                                    <div class="btn-group btn-group-sm w-100">
                                        <button type="submit" class="btn btn-sm btn-{{ $btnColor }}">
                                            <i class="fas fa-play mr-1"></i> Genera
                                        </button>
                                        <a href="{{ route('report.export', ['report' => $report['id']]) }}" class="btn btn-sm btn-outline-{{ $btnColor }}">
                                            <i class="fas fa-download mr-1"></i> CSV
                                        </a>
                                    </div>
                                </form>
                                @else
                                <div class="btn-group btn-group-sm w-100">
                                    <a href="{{ route('report.run', ['report' => $report['id']]) }}" class="btn btn-sm btn-{{ $btnColor }}">
                                        <i class="fas fa-play mr-1"></i> Genera
                                    </a>
                                    <a href="{{ route('report.export', ['report' => $report['id']]) }}" class="btn btn-sm btn-outline-{{ $btnColor }}">
                                        <i class="fas fa-download mr-1"></i> CSV
                                    </a>
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    {{-- Sezione 3: Report Personalizzati --}}
    <div class="card">
        <div class="card-header" id="headingThree">
            <h2 class="mb-0">
                <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                    <i class="fas fa-chevron-right mr-2 text-info"></i>
                    <i class="fas fa-bookmark mr-2 text-info"></i> Report Personalizzati
                    <span class="badge badge-info badge-pill ml-2">{{ $customReports->count() }}</span>
                </button>
            </h2>
        </div>
        <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#reportAccordion">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        @if($customReports->count() > 0)
                        <table class="table table-striped mb-0">
                            <thead>
                                <tr>
                                    <th>Nome</th>
                                    <th>Tipo</th>
                                    <th>Creato il</th>
                                    <th style="width: 140px;">Azioni</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($customReports as $report)
                                <tr>
                                    <td>
                                        <i class="fas fa-chart-line text-primary mr-1"></i>
                                        {{ $report->nome }}
                                    </td>
                                    <td><span class="badge badge-info">{{ ucfirst($report->tipo_report) }}</span></td>
                                    <td>{{ $report->created_at->format('d/m/Y H:i') }}</td>
                                    <td>
                                        <a href="{{ route('report.run', ['custom_id' => $report->id]) }}" class="btn btn-xs btn-success" title="Esegui">
                                            <i class="fas fa-play"></i>
                                        </a>
                                        <a href="{{ route('report.export', ['custom_id' => $report->id]) }}" class="btn btn-xs btn-info" title="Esporta CSV">
                                            <i class="fas fa-file-csv"></i>
                                        </a>
                                        <form action="{{ route('report.destroy-custom', $report->id) }}" method="POST" class="d-inline">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn btn-xs btn-danger" onclick="return confirm('Eliminare questo report?')" title="Elimina">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                        @else
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-chart-line fa-3x mb-3"></i>
                            <p>Nessun report personalizzato creato.</p>
                        </div>
                        @endif
                    </div>

                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-primary">
                                <h3 class="card-title text-white"><i class="fas fa-plus mr-2"></i>Crea Report Personalizzato</h3>
                            </div>
                            <div class="card-body">
                                <form action="{{ route('report.store-custom') }}" method="POST">
                                    @csrf
                                    <div class="form-group">
                                        <label>Nome Report *</label>
                                        <input type="text" name="nome" class="form-control" required placeholder="Es: Individui attivi">
                                    </div>
                                    <div class="form-group">
                                        <label>Descrizione</label>
                                        <textarea name="descrizione" class="form-control" rows="2" placeholder="Descrizione opzionale..."></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label>Tipo Dato *</label>
                                        <select name="tipo_report" id="tipo_report" class="form-control" required>
                                            <option value="">Seleziona...</option>
                                            @foreach($columnOptions as $type => $columns)
                                            <option value="{{ $type }}">{{ ucfirst($type) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Colonne *</label>
                                        <select name="columns[]" id="columns_select" class="form-control select2-multi" multiple style="width: 100%;">
                                        </select>
                                        <small class="text-muted">Seleziona le colonne da includere nel report</small>
                                    </div>
                                    <div class="form-group">
                                        <label>Ordina per</label>
                                        <select name="sort_by" id="sort_by" class="form-control">
                                            <option value="">Nessun ordinamento</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Direzione ordinamento</label>
                                        <select name="sort_direction" class="form-control">
                                            <option value="asc">Ascendente (A-Z)</option>
                                            <option value="desc" selected>Discendente (Z-A)</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Limite risultati</label>
                                        <input type="number" name="limit" class="form-control" placeholder="Es: 100" min="1">
                                    </div>
                                    <button type="submit" class="btn btn-primary btn-block">
                                        <i class="fas fa-save mr-1"></i> Salva Report
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const columnOptions = @json($columnOptions);
    let columnsSelectInitialized = false;

    function initTipologiaSelect2(container) {
        $(container).find('.select2-tipologia').select2({
            theme: 'bootstrap4',
            placeholder: 'Filtra per tipologia...',
            allowClear: true,
            width: '100%',
        });
    }

    function destroyTipologiaSelect2(container) {
        $(container).find('.select2-tipologia').select2('destroy');
    }

    function initColumnsSelect2() {
        if (columnsSelectInitialized) return;
        $('#columns_select').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleziona le colonne...',
            allowClear: true,
            width: '100%',
        });
        columnsSelectInitialized = true;
    }

    function destroyColumnsSelect2() {
        if (!columnsSelectInitialized) return;
        $('#columns_select').select2('destroy');
        columnsSelectInitialized = false;
    }

    function getSortOptions(tipoReport) {
        const cols = columnOptions[tipoReport] || {};
        const options = [];
        for (const [key, col] of Object.entries(cols)) {
            if (col.type !== 'relation') {
                options.push({ value: key, label: col.label });
            }
        }
        return options;
    }

    $('#collapseTwo').on('shown.bs.collapse', function () {
        initTipologiaSelect2(this);
    }).on('hidden.bs.collapse', function () {
        destroyTipologiaSelect2(this);
    });

    $('#collapseThree').on('shown.bs.collapse', function () {
        initColumnsSelect2();
    }).on('hidden.bs.collapse', function () {
        destroyColumnsSelect2();
    });

    if ($('#collapseTwo').hasClass('show')) {
        initTipologiaSelect2(document);
    }

    if ($('#collapseThree').hasClass('show')) {
        initColumnsSelect2();
    }

    $('#tipo_report').on('change', function() {
        const tipo = this.value;
        const $select = $('#columns_select');
        if (columnsSelectInitialized) {
            $select.empty().trigger('change');
        }
        $select.empty();

        if (tipo && columnOptions[tipo]) {
            const cols = columnOptions[tipo];
            const fragment = document.createDocumentFragment();
            for (const [key, col] of Object.entries(cols)) {
                fragment.appendChild(new Option(col.label, key, false, false));
            }
            $select.append(fragment);
        }
        if (columnsSelectInitialized) {
            $select.trigger('change');
        }

        const $sortBy = $('#sort_by');
        $sortBy.empty();
        $sortBy.append(new Option('Nessun ordinamento', '', false, false));
        const sortOptions = getSortOptions(tipo);
        sortOptions.forEach(function(opt) {
            $sortBy.append(new Option(opt.label, opt.value, false, false));
        });
    });

    if ($('#tipo_report').val()) {
        $('#tipo_report').trigger('change');
    }
});
</script>
@endsection
