@extends('layouts.app')

@section('title', 'Évaluation Activité')

@section('content')
<div class="pagetitle">
    <h1>Détails Activité</h1>
    <nav>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.html">Accueil</a></li>
            <li class="breadcrumb-item"><a href="{{ route('activites.show', $activite->id) }}">Détails Activité</a></li>
            <li class="breadcrumb-item active">Évaluation</li>
        </ol>
    </nav>
</div>

<section class="section">
    <div class="row">
        <div class="col-lg-12">
            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <h5 class="card-title">Détails de l'activité</h5>

                    {{-- Messages de succès --}}
                    @if(session('status'))
                        <div class="alert alert-success text-center">{{ session('status') }}</div>
                    @endif
 @php
                        $usergroupId = Auth::user()->usergroup_id;
                    @endphp
                    {{-- Informations générales --}}
                    <h2>Détails : <strong>{{ $activite->nom }}</strong></h2>
                    <hr>

                    <div class="callout callout-primary p-3 rounded shadow-sm bg-light">
                        <h5><b><u>Informations générales</u></b></h5>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item d-flex justify-content-between"><b>Code :</b> <span>{{ $activite->code }}</span></li>
                            <li class="list-group-item d-flex justify-content-between"><b>Nom :</b> <span>{{ $activite->nom }}</span></li>
                            <li class="list-group-item d-flex justify-content-between"><b>Description :</b> <span>{{ $activite->description ?? '-' }}</span></li>
                            <li class="list-group-item d-flex justify-content-between"><b>Montant :</b> <span>{{ $activite->montant ?? '-' }}</span></li>
                            <li class="list-group-item d-flex justify-content-between"><b>Date Début :</b> <span>{{ $activite->datedebut }}</span></li>
                            <li class="list-group-item d-flex justify-content-between"><b>Date Fin :</b> <span>{{ $activite->datefin ?? 'En cours' }}</span></li>
                            <li class="list-group-item">
                                <b>État :</b>
                                <span class="fw-bold text-{{ $activite->valide ? 'success' : 'danger' }}">{{ $activite->valide ? 'Validée' : 'Non validée' }}</span> |
                                <span class="fw-bold text-{{ $activite->actif ? 'success' : 'danger' }}">{{ $activite->actif ? 'Activée' : 'Non activée' }}</span> |
                                <span class="fw-bold text-{{ $activite->ouvert ? 'success' : 'primary' }}">{{ $activite->ouvert ? 'Révision/Élaboration' : 'Suivi/Évaluation' }}</span>
                            </li>
                        </ul>
                    </div>

                    <hr>

                    {{-- Nouvelle évaluation --}}
                    <div class="callout callout-primary p-3 rounded shadow-sm bg-light">
                        <h5><b><u>Nouvelle évaluation</u></b></h5>
                        <table class="table table-bordered table-hover" id="evaluationTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Extrant</th>
                                    <th>Date de référence</th>
                                    <th>Prévision</th>
                                    <th>Réalisation</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php $grouped = $evalwaitings->groupBy('extrant_id'); @endphp
                                @foreach($grouped as $extrantId => $items)
                                    <tr class="table-primary">
                                        <td colspan="5"><strong>Extrant : {{ $items->first()->extrant->nom ?? '-' }}</strong></td>
                                    </tr>
                                    @foreach($items as $toeval)
                                        <tr data-prevision-id="{{ $toeval->id }}" data-activite-id="{{ $activite->id }}">
                                            <td class="extrant-nom">
                                                {{ $toeval->extrant->nom ?? '-' }}
                                                <input type="hidden" class="extrant-id" value="{{ $toeval->extrant->id ?? '' }}">
                                            </td>
                                            <td class="date-reference">{{ $toeval->dateevaluation }}</td>
                                            <td class="taux-prevision">{{ $toeval->niveaucible }}</td>
                                            <td>
                                                <select class="form-control etape-select" disabled>
                                                    <option value="">-- Choisir une étape --</option>
                                                    @foreach($etapesParExtrant[$toeval->extrant->id] ?? [] as $etape)
                                                        <option value="{{ $etape->id }}" data-taux="{{ $etape->niveauexec }}">
                                                            {{ $etape->nom }} ({{ $etape->niveauexec }}%)
                                                        </option>
                                                    @endforeach
                                                    @if($activite->over_taux)
                                                        <option value="plus100" data-taux="100">Plus de 100%</option>
                                                    @endif
                                                </select>
                                            </td>
                                            <td>
                                                @php $canEvaluate = ($evalwaitings->isNotEmpty() && $activite->valide && $activite->actif && !$activite->ouvert); @endphp
                                                @if($canEvaluate)
                                                    <button class="btn btn-warning btn-sm eval-btn">À Évaluer</button>
                                                    <button class="btn btn-success btn-sm ok-btn d-none">OK</button>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <hr>

                    {{-- Evaluations effectuées --}}
                    <div class="callout callout-primary p-3 rounded shadow-sm bg-light">
                        <h5><b><u>Anciennes évaluations</u></b></h5>
                        <table class="table table-bordered table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Extrant</th>
                                    <th>Date de référence</th>
                                    <th>Date d'évaluation</th>
                                    <th>Prévision</th>
                                    <th>Réalisation</th>
                                    <th>Validé</th>
                                    <th></th>
                                    <th>Commentaire</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php $groupedOld = $activite->evaluations->groupBy('extrant_id'); @endphp
                                @foreach($groupedOld as $extrantId => $evaluations)
                                    <tr class="table-primary">
                                        <td colspan="8"><strong>Extrant : {{ $evaluations->first()->extrant->nom ?? '-' }}</strong></td>
                                    </tr>
                                    @foreach($evaluations as $eval)
                                        <tr>
                                            <td>{{ $eval->extrant->nom ?? '-' }}</td>
                                            <td>{{ $eval->prevision->dateevaluation ?? '-' }}</td>
                                            <td>{{ $eval->date_evaluation ?? '-' }}</td>
                                            <td>{{ $eval->prevision->niveaucible ?? '-' }} %</td>
                                            <td>{{ $eval->taux_realisation ?? '-' }} %</td>
                                            <td>
                                                @if($eval->valide)
                                                    <button class="btn btn-sm {{ $activite->valide ? 'btn-success' : 'btn-secondary' }}" disabled>OUI</button>
                                                @else
                                                    <a href="{{ route('evaluations.valider', $eval->id) }}" class="btn btn-sm btn-secondary">NON</a>
                                                @endif
                                            </td>
                                            <td>
                                            @if(in_array($usergroupId, [1,2]))
                                                @if(!$eval->valide && $loop->last)
                                                    <a href="{{ route('evaluations.edit', $eval->id) }}" class="btn btn-warning"><i class="bi bi-pen"></i></a>
                                                    <a href="{{ route('evaluations.destroy', $eval->id) }}" class="btn btn-danger" onclick="return confirm('Supprimer ?')"><i class="bi bi-trash"></i></a>
                                                @endif
                                             @endif
                                            </td>
                                            <td>{{ $eval->commentaire ?? '-' }}</td>
                                        </tr>
                                    @endforeach
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const log = msg => console.log("%c[DEBUG ÉVAL] " + msg, "color: #0a58ca");

    // --- Bouton "À Évaluer"
    document.querySelectorAll('.eval-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const row = btn.closest('tr');
            row.querySelector('.etape-select').disabled = false;
            row.querySelector('.ok-btn').classList.remove('d-none');
            btn.classList.add('d-none');
            log("Mode évaluation activé.");
        });
    });

    // --- Ajout dynamique du champ pondération si "Plus de 100%" est choisi
    document.querySelectorAll('.etape-select').forEach(select => {
        select.addEventListener('change', function () {
            const row = this.closest('tr');

            // Supprimer ancienne pondération/niveau si existant
            row.querySelectorAll('.pond-container, .niveau-container').forEach(el => el.remove());

            if(this.value === "plus100") {
                // Champ pondération
                const divPond = document.createElement('div');
                divPond.classList.add('pond-container', 'mt-2');
                divPond.innerHTML = '<label><b>Pondération supplémentaire (%) :</b></label>' +
                                     '<input type="number" min="1" class="form-control pond-value" placeholder="Ex : 10 pour obtenir 110%">';
                row.querySelector('td:nth-child(3)').appendChild(divPond);

                // Champ niveau total (lecture seule)
                const divNiveau = document.createElement('div');
                divNiveau.classList.add('niveau-container', 'mt-2');
                divNiveau.innerHTML = '<label><b>Niveau d\'exécution total (%) :</b></label>' +
                                      '<input type="number" class="form-control niveau-value" value="100" readonly>';
                row.querySelector('td:nth-child(3)').appendChild(divNiveau);

                // Mettre à jour en fonction de la pondération
                divPond.querySelector('.pond-value').addEventListener('input', e => {
                    const val = parseFloat(e.target.value);
                    divNiveau.querySelector('.niveau-value').value = 100 + (isNaN(val) ? 0 : val);
                });
            }
        });
    });

    // --- Bouton "OK"
    document.querySelectorAll('.ok-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const row = btn.closest('tr');
            const extrantId = row.querySelector('.extrant-id').value;
            const activiteId = row.dataset.activiteId;
            const previsionId = row.dataset.previsionId;
            const select = row.querySelector('.etape-select');
            const etapeId = select.value;

            if(!etapeId) return alert("Veuillez choisir une étape avant d'enregistrer.");

            let tauxRealisation = parseFloat(select.options[select.selectedIndex]?.dataset.taux) || 0;
            let finalEtapeId = etapeId;

            if(etapeId === "plus100") {
                const pond = parseFloat(row.querySelector('.pond-value')?.value);
                if(!pond || pond <= 0) return alert("Veuillez saisir une pondération valide (>0).");
                tauxRealisation = 100 + pond;
                finalEtapeId = null;
            }

            const tauxPrevision = parseFloat(row.querySelector('.taux-prevision').innerText.replace('%','').trim());
            const dateReference = row.querySelector('.date-reference').innerText.trim();

            const url = "{{ route('evaluations.store', ['activiteid' => 'ID']) }}".replace('ID', activiteId);

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type':'application/json',
                    'Accept':'application/json',
                    'X-CSRF-TOKEN':'{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    activite_id: activiteId,
                    previsionactivite_id: previsionId,
                    etape_id: finalEtapeId,
                    taux_realisation: tauxRealisation,
                    taux_prevision: tauxPrevision,
                    date_reference: dateReference,
                    extrant_id: extrantId
                })
            })
            .then(r => r.ok ? r.json() : r.json().then(err => { throw err; }))
            .then(data => {
                if(!data.success) return alert("Erreur : " + (data.message || "Impossible d'enregistrer."));
                alert("✅ Évaluation enregistrée avec succès !");
                select.disabled = true;
                btn.classList.add('d-none');
                setTimeout(() => window.location.href = "{{ route('redirect.delayed', $activite->id) }}", 600);
            })
            .catch(err => {
                const msg = err.message || JSON.stringify(err.errors) || "Erreur inconnue";
                alert("❌ " + msg);
            });
        });
    });
});
</script>
@endsection
