@extends('layouts.admin')

@section('title', 'Demandes d\'audience au rectorat UAC')

<style>
    #appointmentsTable {
        border-collapse: separate;
        border-spacing: 0;
    }

    #appointmentsTable thead th {
        background-color: transparent;
        border-bottom: 2px solid var(--border-light);
        padding-top: 1rem;
        padding-bottom: 1rem;
        font-weight: 600;
        color: var(--text-secondary);
        text-transform: uppercase;
        font-size: 0.875rem;
        letter-spacing: 0.05em;
    }

    #appointmentsTable tbody td {
        border-bottom: 1px solid var(--border-light);
        padding-top: 1rem;
        padding-bottom: 1rem;
        vertical-align: middle;
    }

    #appointmentsTable tbody tr:last-child td {
        border-bottom: none;
    }

    #appointmentsTable tbody tr:hover {
        background-color: rgba(14, 165, 233, 0.04) !important;
    }

    .avatar-xs {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .avatar-xs img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .badge {
        padding: 0.35rem 0.75rem;
        font-weight: 500;
        border-radius: 50px;
        font-size: 0.75rem;
        letter-spacing: 0.02em;
    }

    .dropdown-menu {
        border-radius: var(--radius-md);
        box-shadow: var(--shadow-lg);
        border: 1px solid var(--border-light);
        padding: 0.5rem;
    }

    .dropdown-item {
        border-radius: var(--radius-sm);
        padding: 0.5rem 0.75rem;
        margin: 0.125rem 0;
        transition: all var(--transition-fast);
    }

    .dropdown-item:hover {
        background-color: var(--primary-50);
        color: var(--primary-700);
    }

    @media (max-width: 768px) {
        #appointmentsTable {
            font-size: 0.875rem;
        }

        .stats-header h1 {
            font-size: 1.5rem;
        }
    }
</style>
<style>
    /* Styles spécifiques pour le modal */
    .modal-content {
        border: none;
        box-shadow: var(--shadow-xl);
    }

    .modal-header {
        background: linear-gradient(135deg, rgba(14, 165, 233, 0.05), rgba(14, 165, 233, 0.02));
        border-radius: var(--radius-xl) var(--radius-xl) 0 0 !important;
    }

    .action-icon-container {
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(14, 165, 233, 0.1);
        border-radius: var(--radius-md);
    }

    .form-label {
        color: var(--text-secondary);
        margin-bottom: 0.5rem;
    }

    .input-group-text {
        background-color: var(--bg-secondary);
        border-color: var(--border-light);
        color: var(--text-muted);
    }

    .form-control,
    .form-select {
        border-color: var(--border-light);
        background-color: var(--bg-surface);
        color: var(--text-primary);
        transition: all var(--transition-fast);
    }

    .form-control:focus,
    .form-select:focus {
        border-color: var(--primary-400);
        box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
        background-color: var(--bg-surface);
    }

    .alert {
        border-radius: var(--radius-md);
        border: 1px solid var(--border-light);
        background-color: var(--bg-secondary);
    }

    /* Responsive */
    @media (max-width: 576px) {
        .modal-dialog {
            margin: 0.5rem;
        }

        .modal-header .d-flex {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }

        .action-icon-container {
            align-self: flex-start;
        }
    }
</style>
<style>
    /* Styles spécifiques pour le modal de vue */
    .avatar-large {
        position: relative;
    }

    .avatar-large img {
        width: 56px;
        height: 56px;
        object-fit: cover;
    }

    .icon-container {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: var(--radius-md);
    }

    .card-header-modern {
        padding: 0;
    }

    .card-body-modern {
        padding: 0;
    }

    .info-group {
        margin-bottom: 1rem;
    }

    .info-label {
        margin-bottom: 0.25rem;
    }

    .info-label i {
        width: 16px;
    }

    .info-value {
        color: var(--text-primary);
        line-height: 1.4;
    }

    .message-content {
        font-size: 0.95rem;
        line-height: 1.6;
        border-left: 3px solid var(--primary-400);
        background: var(--bg-secondary) !important;
    }

    .admin-note {
        border-left: 3px solid var(--warning);
        background: var(--warning-bg, rgba(245, 158, 11, 0.1)) !important;
    }

    .file-icon {
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .hover-lift:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
        background: var(--bg-secondary) !important;
    }

    /* Scrollbar personnalisée pour le message */
    .message-content::-webkit-scrollbar {
        width: 6px;
    }

    .message-content::-webkit-scrollbar-track {
        background: transparent;
    }

    .message-content::-webkit-scrollbar-thumb {
        background: var(--primary-300);
        border-radius: 3px;
    }

    .message-content::-webkit-scrollbar-thumb:hover {
        background: var(--primary-400);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .modal-dialog {
            margin: 0.5rem;
        }

        .avatar-large img {
            width: 48px;
            height: 48px;
        }

        .icon-container {
            width: 36px;
            height: 36px;
        }

        .modal-footer .d-flex {
            flex-direction: column;
        }

        .modal-footer .btn {
            width: 100%;
        }
    }

    /* Animation d'entrée pour les éléments */
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .card-modern {
        animation: fadeIn 0.3s ease-out;
    }

    .info-group {
        animation: fadeIn 0.4s ease-out;
    }
</style>
@section('content')
    <div class="container-fluid py-4">
        <div class="stats-header mb-4">
            <div class="row align-items-center">
                <div class="col-12 col-md-8">
                    <h1 class="display-6 text-white fw-bold mb-2">Demandes d'audience</h1>
                    <p class="text-white mb-0">{{ count($appointments) }} demande(s) au total</p>
                </div>

            </div>
        </div>

        <div class="row g-4 mb-4">
            <div class="col-md-3 col-sm-6">
                <div class="card-modern">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <div class="p-3 rounded-circle" style="background: rgba(14, 165, 233, 0.1);">
                                <i class="bi bi-clock-history text-primary" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                        <div>
                            <h3 class="mb-0 fw-bold">{{ $appointments->where('status', 'pending')->count() }}</h3>
                            <p class="text-muted mb-0 small">En attente</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="card-modern">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <div class="p-3 rounded-circle" style="background: rgba(34, 197, 94, 0.1);">
                                <i class="bi bi-check-circle text-success" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                        <div>
                            <h3 class="mb-0 fw-bold">{{ $appointments->where('status', 'confirmed')->count() }}</h3>
                            <p class="text-muted mb-0 small">Confirmés</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="card-modern">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <div class="p-3 rounded-circle" style="background: rgba(239, 68, 68, 0.1);">
                                <i class="bi bi-x-circle text-danger" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                        <div>
                            <h3 class="mb-0 fw-bold">{{ $appointments->where('status', 'rejected')->count() }}</h3>
                            <p class="text-muted mb-0 small">Rejetés</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="card-modern">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <div class="p-3 rounded-circle" style="background: rgba(148, 163, 184, 0.1);">
                                <i class="bi bi-calendar-x text-secondary" style="font-size: 1.5rem;"></i>
                            </div>
                        </div>
                        <div>
                            <h3 class="mb-0 fw-bold">{{ $appointments->where('status', 'canceled')->count() }}</h3>
                            <p class="text-muted mb-0 small">Annulés</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card-modern">
            <div class="card-body p-0">
                <div class="">
                    <table class="table table-hover datatable mb-0 " id="appointmentsTable">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4">Nom</th>
                                <th>Contact</th>
                                <th>Objet</th>
                                <th>Date de soumission</th>
                                <th>Date demandée</th>
                                <th>Status</th>
                                <th>Date Programmée</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($appointments as $key => $appointment)
                                <tr class="align-middle">
                                    <td class="ps-4">
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-xs me-3">
                                                <img src="https://ui-avatars.com/api/?name={{ urlencode($appointment->first_name . ' ' . $appointment->last_name) }}&background=0ea5e9&color=fff"
                                                    alt="{{ $appointment->first_name }} {{ $appointment->last_name }}"
                                                    class="rounded-circle" width="32" height="32">
                                            </div>
                                            <div>
                                                <div class="fw-semibold">{{ $appointment->first_name }}
                                                    {{ $appointment->last_name }}
                                                </div>
                                                <div class="small text-muted">{{ $appointment->email }}</div>
                                            </div>
                                        </div>
                                    </td>

                                    <td>
                                        <div class="d-flex flex-column">
                                            <span class="fw-semibold">{{ $appointment->mobile }}</span>

                                        </div>
                                    </td>
                                    <td>
                                        <span class="text-truncate d-inline-block" style="max-width: 200px;"
                                            title="{{ $appointment->subject }}">
                                            {{ $appointment->subject }}
                                        </span>
                                    </td>

                                    <td>
                                        <div class="d-flex flex-column">
                                            <span
                                                class="fw-semibold">{{ \Carbon\Carbon::parse($appointment->created_at)->format('d/m/Y') }}</span>
                                            <small
                                                class="text-muted">{{ \Carbon\Carbon::parse($appointment->created_at)->format('H:i') }}</small>
                                        </div>
                                    </td>
                                    <td>
                                        @if ($appointment->requested_at)
                                            <div class="d-flex flex-column">
                                                <span
                                                    class="fw-semibold">{{ \Carbon\Carbon::parse($appointment->requested_at)->format('d/m/Y') }}</span>
                                                <small
                                                    class="text-muted">{{ \Carbon\Carbon::parse($appointment->requested_at)->format('H:i') }}</small>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php
                                            $class = '';
                                            $icon = '';
                                            switch ($appointment->status) {
                                                case 'pending':
                                                    $class = 'bg-warning text-dark';
                                                    $icon = 'bi-clock';
                                                    break;
                                                case 'confirmed':
                                                    $class = 'bg-success text-white';
                                                    $icon = 'bi-check-circle';
                                                    break;
                                                case 'rejected':
                                                    $class = 'bg-danger text-white';
                                                    $icon = 'bi-x-circle';
                                                    break;
                                                case 'canceled':
                                                    $class = 'bg-secondary text-white';
                                                    $icon = 'bi-calendar-x';
                                                    break;
                                                case 'processing':
                                                    $class = 'bg-info text-white';
                                                    $icon = 'bi-info-circle';
                                                    break;
                                                default:
                                                    $class = 'bg-info text-white';
                                                    $icon = 'bi-info-circle';
                                                    break;
                                            }
                                        @endphp
                                        <span class="badge {{ $class }} d-flex align-items-center gap-1"
                                            style="width: fit-content;">
                                            <i class="bi {{ $icon }}"></i>
                                            {{ demandStatus($appointment->status) }}
                                        </span>
                                    </td>
                                    <td>
                                        @if ($appointment->scheduled_at)
                                            <div class="d-flex flex-column">
                                                <span
                                                    class="fw-semibold">{{ \Carbon\Carbon::parse($appointment->scheduled_at)->format('d/m/Y') }}</span>
                                                <small
                                                    class="text-muted">{{ \Carbon\Carbon::parse($appointment->scheduled_at)->format('H:i') }}</small>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="text-end pe-4">
                                        <div class="dropdown d-inline-block">
                                            <button
                                                class="btn btn-sm btn-outline-secondary rounded-circle d-flex align-items-center justify-content-center"
                                                type="button" id="dropdownMenu{{ $key }}"
                                                data-bs-toggle="dropdown" aria-expanded="false"
                                                style="width: 36px; height: 36px;">
                                                <i class="bi bi-three-dots"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0"
                                                style="min-width: 220px;">
                                                @php
                                                    $role = auth()->user()->role;
                                                @endphp

                                                {{-- Sécrétaire --}}
                                                @if ($role === 'secretaire' && !is_null(auth()->user()->service_id))
                                                    @if ($appointment->status == 'pending')
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="processing">
                                                                <i class="bi bi-play-circle text-info"></i> Commencer le
                                                                traitement
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="repending">
                                                                <i class="bi bi-clock text-warning"></i> Mettre en attente
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-institutions='@json($institutions)'
                                                                data-users='@json($users)'
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="ask_opinion">
                                                                <i class="bi bi-send text-primary"></i> Demander un avis
                                                                technique
                                                            </a>
                                                        </li>
                                                    @elseif($appointment->status == 'processing')
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-email="{{ $appointment->email }}"
                                                                data-mobile="{{ $appointment->mobile }}"
                                                                data-subject="{{ $appointment->subject }}"
                                                                data-message="{{ $appointment->message }}"
                                                                data-requested-at="{{ $appointment->requested_at }}"
                                                                data-duration="{{ $appointment->duration_minutes }}"
                                                                data-status="{{ demandStatus($appointment->status) }}"
                                                                data-scheduled-at="{{ $appointment->scheduled_at }}"
                                                                data-admin-note="{{ $appointment->admin_note }}"
                                                                data-attachments="{{ $appointment->uploads ? json_encode($appointment->uploads) : '[]' }}"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="repending">
                                                                <i class="bi bi-clock text-warning"></i> Mettre en attente
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="ask_opinion">
                                                                <i class="bi bi-send text-primary"></i> Demander un avis
                                                                technique
                                                            </a>
                                                        </li>
                                                    @elseif($appointment->status == 'confirmed')
                                                        @if (!$appointment->report)
                                                            <li>
                                                                <a href="{{ route('admin.reports.create', $appointment) }}"
                                                                    class="dropdown-item">
                                                                    <i class="bi bi-journal-text text-primary"></i>
                                                                    Rédiger le compte-rendu
                                                                </a>
                                                            </li>
                                                        @else
                                                            <li>
                                                                <a href="{{ route('admin.reports.show', $appointment->report) }}"
                                                                    class="dropdown-item">
                                                                    <i class="bi bi-eye text-primary"></i>
                                                                    Voir le compte-rendu
                                                                </a>
                                                            </li>
                                                            @if ($appointment->report->status == 'confirmed')
                                                                <li>
                                                                    <a href="{{ route('admin.reports.download', $appointment->report) }}"
                                                                        class="dropdown-item">
                                                                        <i class="bi bi-download text-primary"></i>
                                                                        Técharger le compte-rendu
                                                                    </a>
                                                                </li>
                                                            @elseif ($appointment->report->status == 'pending' && in_array($appointment->report->status, ['pending', 'rejected']))
                                                                <li>
                                                                    <a href="{{ route('admin.reports.edit', $appointment->report) }}"
                                                                        class="dropdown-item">
                                                                        <i class="bi-pencil-square text-primary"></i>
                                                                        Modifier le compte-rendu
                                                                    </a>
                                                                </li>
                                                            @endif
                                                        @endif
                                                    @endif


                                                    {{-- VR-AA --}}
                                                @elseif($role === 'vr-aa')
                                                    @if (in_array($appointment->status, ['pending', 'processing']))
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-subject="{{ $appointment->subject }}"
                                                                data-requested-at="{{ $appointment->requested_at }}"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="confirm">
                                                                <i class="bi bi-check-circle text-success"></i> Approuver
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="reject">
                                                                <i class="bi bi-x-circle text-danger"></i> Rejeter
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-institutions='@json($institutions)'
                                                                data-users='@json($users)'
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="ask_opinion">
                                                                <i class="bi bi-send text-primary"></i> Demander un avis
                                                                technique
                                                            </a>
                                                        </li>
                                                    @elseif(in_array($appointment->status, ['confirmed', 'rescheduled']))
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="reschedule">
                                                                <i class="bi bi-calendar-plus text-primary"></i>
                                                                Reprogrammer
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="cancel">
                                                                <i class="bi bi-x-circle text-secondary"></i> Annuler
                                                            </a>
                                                        </li>
                                                        @if (!$appointment->report)
                                                            <li>
                                                                <a href="{{ route('admin.reports.create', $appointment) }}"
                                                                    class="dropdown-item">
                                                                    <i class="bi bi-journal-text text-primary"></i>
                                                                    Rédiger le compte-rendu
                                                                </a>
                                                            </li>
                                                        @else
                                                            <li>
                                                                <a href="{{ route('admin.reports.show', $appointment->report) }}"
                                                                    class="dropdown-item">
                                                                    <i class="bi bi-eye text-primary"></i>
                                                                    Voir le compte-rendu
                                                                </a>
                                                            </li>
                                                            @if ($appointment->report->status == 'confirmed')
                                                                <li>
                                                                    <a href="{{ route('admin.reports.download', $appointment->report) }}"
                                                                        class="dropdown-item">
                                                                        <i class="bi bi-download text-primary"></i>
                                                                        Técharger le compte-rendu
                                                                    </a>
                                                                </li>
                                                            @elseif ($appointment->report->status == 'pending' && in_array($appointment->report->status, ['pending', 'rejected']))
                                                                <li>
                                                                    <a href="{{ route('admin.reports.edit', $appointment->report) }}"
                                                                        class="dropdown-item">
                                                                        <i class="bi-pencil-square text-primary"></i>
                                                                        Modifier le compte-rendu
                                                                    </a>
                                                                </li>
                                                            @endif
                                                        @endif
                                                    @endif

                                                    {{-- Chef d'institution --}}
                                                @elseif($role === 'chef-institution' && !is_null(auth()->user()->service_id))
                                                    @if (in_array($appointment->status, ['pending', 'processing']))
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-subject="{{ $appointment->subject }}"
                                                                data-requested-at="{{ $appointment->requested_at }}"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="confirm">
                                                                <i class="bi bi-check-circle text-success"></i> Approuver
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="reject">
                                                                <i class="bi bi-x-circle text-danger"></i> Rejeter
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-institutions='@json($institutions)'
                                                                data-users='@json($users)'
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="ask_opinion">
                                                                <i class="bi bi-send text-primary"></i> Demander un avis
                                                                technique
                                                            </a>
                                                        </li>
                                                    @elseif(in_array($appointment->status, ['confirmed', 'rescheduled']))
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="reschedule">
                                                                <i class="bi bi-calendar-plus text-primary"></i>
                                                                Reprogrammer
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a href="javascript:void(0);" class="dropdown-item"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#modalAppointmentAction"
                                                                data-appointment-id="{{ $appointment->id }}"
                                                                data-action="cancel">
                                                                <i class="bi bi-x-circle text-secondary"></i> Annuler
                                                            </a>
                                                        </li>
                                                    @endif

                                                    {{-- Chef d'institution --}}
                                                @elseif($role === 'chef-institution' && is_null(auth()->user()->service_id))
                                                    <li>
                                                        <a href="javascript:void(0);" class="dropdown-item"
                                                            data-bs-toggle="modal"
                                                            data-bs-target="#modalAppointmentAction"
                                                            data-appointment-id="{{ $appointment->id }}"
                                                            data-action="give_advice">
                                                            <i class="bi bi-pencil-square text-primary"></i> Donner mon
                                                            avis
                                                        </a>
                                                    </li>
                                                @elseif($role === 'secretaire' && is_null(auth()->user()->service_id))
                                                    <li>
                                                        <a href="javascript:void(0);" class="dropdown-item"
                                                            data-bs-toggle="modal"
                                                            data-bs-target="#modalAppointmentAction"
                                                            data-appointment-id="{{ $appointment->id }}"
                                                            data-action="give_advice">
                                                            <i class="bi bi-pencil-square text-primary"></i> Donner mon
                                                            avis
                                                        </a>
                                                    </li>
                                                @endif

                                                {{-- Voir les détails pour tous les rôles --}}
                                                <li>
                                                    <a href="javascript:void(0);" data-bs-toggle="modal"
                                                        data-bs-target="#modalViewAppointment"
                                                        data-bs-target="#modalViewAppointment"
                                                        data-appointment-id="{{ $appointment->id }}"
                                                        data-first-name="{{ $appointment->first_name }}"
                                                        data-last-name="{{ $appointment->last_name }}"
                                                        data-email="{{ $appointment->email }}"
                                                        data-mobile="{{ $appointment->mobile }}"
                                                        data-subject="{{ $appointment->subject }}"
                                                        data-message="{{ $appointment->message }}"
                                                        data-requested-at="{{ $appointment->requested_at }}"
                                                        data-duration="{{ $appointment->duration_minutes }}"
                                                        data-status="{{ demandStatus($appointment->status) }}"
                                                        data-scheduled-at="{{ $appointment->scheduled_at }}"
                                                        data-admin-note="{{ $appointment->admin_note }}"
                                                        data-attachments="{{ $appointment->uploads ? json_encode($appointment->uploads) : '[]' }}"
                                                        class="dropdown-item d-flex align-items-center gap-2 py-2">
                                                        <i class="bi bi-eye text-primary"></i>
                                                        <span>Voir les détails de la demande</span>

                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Unique pour toutes les actions -->
    <div class="modal fade" id="modalAppointmentAction" data-bs-backdrop="static" data-bs-keyboard="false"
        tabindex="-1" aria-labelledby="modalAppointmentActionLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content card-modern border-0" style="border-radius: var(--radius-xl);">
                <!-- Header avec badge d'action -->
                <div class="modal-header border-0 pb-0">
                    <div class="d-flex align-items-center gap-3 w-100">
                        <div class="action-icon-container" id="actionIconContainer">
                            <!-- Icône dynamique basée sur l'action -->
                            <i class="bi bi-calendar-check text-success" style="font-size: 1.5rem;"></i>
                        </div>
                        <div class="flex-grow-1">
                            <h1 class="modal-title h4 fw-bold mb-1" id="modalAppointmentActionTitle">
                                Action sur demande d'audience
                            </h1>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-light text-dark border small" id="actionBadge">
                                    Confirmation
                                </span>
                                <span class="text-muted small" id="clientNamePreview"></span>
                            </div>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                </div>
                <div class="modal-body pt-4">

                    <form id="appointmentActionForm" method="POST" enctype="multipart/form-data">
                        @csrf
                        @method('PATCH')

                        <!-- Champ caché pour l'ID du rendez-vous -->
                        <input type="hidden" name="appointment_id" id="appointmentId">
                        <input type="hidden" name="action_type" id="actionType">

                        <!-- Section d'information pré-remplie -->
                        <div class="alert alert-light border mb-4" id="previewInfo" style="display: none;">
                            <div class="d-flex gap-3">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-info-circle text-primary"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="fw-semibold mb-1" id="previewSubject"></h6>
                                    <div class="small text-muted">
                                        <div>Date demandée: <span id="previewRequestedAt" class="fw-medium"></span></div>
                                        <div>Note existante: <span id="previewExistingNote" class="fw-medium"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Champs pour Confirmer/Reprogrammer -->
                        <div id="confirmFields" style="display: none;">
                            <div class="mb-4">
                                <label for="appointmentSubject"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-pencil-square text-primary"></i>
                                    Objet de la demande d'audience
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text bg-light border-end-0">
                                        <i class="bi bi-card-heading text-muted"></i>
                                    </span>
                                    <input type="text" id="appointmentSubject"
                                        class="form-control border-start-0 @error('title') is-invalid @enderror"
                                        placeholder="Ex: Entretien technique, Réunion de suivi..." disabled />
                                </div>
                                @error('title')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label for="appointmentScheduledAt"
                                        class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                        <i class="bi bi-calendar-date text-primary"></i>
                                        Date de la demande
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0">
                                            <i class="bi bi-calendar text-muted"></i>
                                        </span>
                                        <input type="date" class="form-control border-start-0"
                                            name="scheduled_at_date" id="appointmentScheduledAtDate">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                        <i class="bi bi-clock text-primary"></i>
                                        Heure
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0">
                                            <i class="bi bi-clock text-muted"></i>
                                        </span>
                                        <input type="time" class="form-control border-start-0"
                                            name="scheduled_at_time" id="appointmentScheduledAtTime">
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentDuration"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-hourglass-split text-primary"></i>
                                    Durée de l'entretien
                                </label>
                                <div class="input-group">
                                    <span class="input-group-text bg-light border-end-0">
                                        <i class="bi bi-clock-history text-muted"></i>
                                    </span>
                                    <input type="number" class="form-control border-start-0" name="duration"
                                        id="appointmentDuration" value="30" min="5" max="240"
                                        step="5">
                                    <span class="input-group-text bg-light border-start-0">
                                        minutes
                                    </span>
                                </div>
                                <div class="form-text d-flex justify-content-between mt-2">
                                    <small class="text-muted">Durée suggérée: 30 minutes</small>
                                    <small class="text-muted" id="durationPreview">Fin: --:--</small>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentAdminNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-chat-left-text text-primary"></i>
                                    Informations supplémentaires
                                </label>
                                <textarea name="admin_note_confirm" id="appointmentAdminNote"
                                    class="form-control @error('admin_note_confirm') is-invalid @enderror"
                                    placeholder="Ajoutez des détails, instructions ou informations importantes..." rows="3"></textarea>
                                @error('admin_note_confirm')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <!-- Champs pour Rejeter -->
                        <div id="rejectFields" style="display: none;">
                            <div class="alert alert-warning border mb-4">
                                <div class="d-flex gap-3">
                                    <div class="flex-shrink-0">
                                        <i class="bi bi-exclamation-triangle"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-semibold mb-1">Action irréversible</h6>
                                        <p class="small mb-0">La demande d'audience sera marquée comme rejetée. Vous pouvez
                                            ajouter
                                            un motif pour informer le client.</p>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentRejectNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-x-circle text-danger"></i>
                                    Motif de rejet
                                </label>
                                <textarea name="admin_note_reject" id="appointmentRejectNote"
                                    class="form-control @error('admin_note_reject') is-invalid @enderror"
                                    placeholder="Ex: Créneau indisponible, informations incomplètes..." rows="4"></textarea>
                                @error('admin_note_reject')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    <small class="text-muted">Ce message sera visible par l'usager</small>
                                </div>
                            </div>
                        </div>

                        <!-- Champs pour Annuler -->
                        <div id="cancelFields" style="display: none;">
                            <div class="alert alert-secondary border mb-4">
                                <div class="d-flex gap-3">
                                    <div class="flex-shrink-0">
                                        <i class="bi bi-calendar-x"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-semibold mb-1">Annulation de la demande d'audience</h6>
                                        <p class="small mb-0">La demande d'audience sera marquée comme annulé. Vous pouvez
                                            ajouter
                                            une note optionnelle.</p>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentCancelNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-calendar-x text-secondary"></i>
                                    Note d'annulation (optionnelle)
                                </label>
                                <textarea name="admin_note_cancel" id="appointmentCancelNote" class="form-control"
                                    placeholder="Ex: demande d'audience annulé à la demande de l'usager..." rows="3"></textarea>
                                @error('admin_note_cancel')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    <small class="text-muted">Note interne, non visible par le client</small>
                                </div>
                            </div>
                        </div>

                        <!-- Champs pour Remettre en attente -->
                        <div id="rependingFields" style="display: none;">
                            <div class="alert alert-secondary border mb-4">
                                <div class="d-flex gap-3">
                                    <div class="flex-shrink-0">
                                        <i class="bi bi-calendar-x"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-semibold mb-1">Mise en attente de la demande d'audience</h6>
                                        <p class="small mb-0">La demande d'audience sera marquée comme mise en attente.
                                            Vous
                                            pouvez
                                            ajouter une note pour informer le requerant pour qu'il se conforme
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentRependingNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-calendar-x text-secondary"></i>
                                    Note de mise en attente
                                </label>
                                <textarea name="admin_note_repending" id="appointmentRependingNote" class="form-control"
                                    placeholder="Ex: demande d'audience mise en attente pour la raison suivante..." rows="3"></textarea>
                                @error('admin_note_repending')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    <small class="text-muted">Note visible par le client</small>
                                </div>
                            </div>
                        </div>

                        <!-- Champs pour Remettre en attente -->
                        <div id="processingFields" style="display: none;">
                            <div class="alert alert-secondary border mb-4">
                                <div class="d-flex gap-3">
                                    <div class="flex-shrink-0">
                                        <i class="bi bi-calendar-x"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-semibold mb-1">Démarrage du traitement de la demande d'audience</h6>
                                        <p class="small mb-0">La demande d'audience sera marquée comme en cours de
                                            traitement.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Champs pour Rejeter -->
                        <!-- Champs pour donner son avis (chef d'institution) -->
                        <div id="adviceFields" style="display: none;">
                            <div class="alert alert-info border mb-4">
                                <div class="d-flex gap-3">
                                    <div class="flex-shrink-0">
                                        <i class="bi bi-lightbulb"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="fw-semibold mb-1">Donner votre avis</h6>
                                        <p class="small mb-0">Le message sera visible par le secrétaire ou l’utilisateur final.
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentAdviceNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-chat-left-text text-primary"></i>
                                    Avis
                                </label>
                                <textarea name="admin_note_advice" id="appointmentAdviceNote"
                                    class="form-control @error('admin_note_advice') is-invalid @enderror"
                                    placeholder="Ex: Créneau indisponible, informations manquantes..." rows="4"></textarea>
                                @error('admin_note_advice')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <div class="form-text">
                                    <small class="text-muted">Ce message sera visible par le destinataire concerné.</small>
                                </div>
                            </div>
                        </div>


                        <!-- Champs pour demander un avis technique -->
                        <div id="technicalFields" style="display: none;">
                            <div class="mb-4">
                                <label for="technicalInstitution"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-building text-primary"></i>
                                    Sélectionnez l'institution
                                </label>
                                <select name="technical_institution" id="technicalInstitution" class="form-select">
                                    <option value="">-- Choisir une institution --</option>
                                    @foreach ($institutions as $institution)
                                        <option value="{{ $institution->id }}">{{ $institution->name }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="mb-4">
                                <label for="technicalUser" class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-person text-primary"></i>
                                    Sélectionnez l'utilisateur
                                </label>
                                <select name="technical_user" id="technicalUser" class="form-select">
                                    <option value="">-- Choisir un utilisateur --</option>
                                    <!-- Les options seront remplies dynamiquement via JS quand l'institution change -->
                                </select>
                            </div>

                            <div class="mb-4">
                                <label for="appointmentTechnicalNote"
                                    class="form-label fw-semibold d-flex align-items-center gap-2 mb-2">
                                    <i class="bi bi-send text-primary"></i>
                                    Note pour l'avis technique
                                </label>
                                <textarea name="admin_note_technical" id="appointmentTechnicalNote" class="form-control"
                                    placeholder="Ajoutez vos instructions ou questions pour l'avis technique..." rows="4"></textarea>
                                <div class="form-text">
                                    <small class="text-muted">Ce message sera visible par le destinataire technique.</small>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <div class="modal-footer border-0 pt-0">
                    <div class="d-flex gap-2 w-100">
                        <button type="reset" class="btn btn-outline-secondary btn-modern flex-grow-1"
                            data-bs-dismiss="modal">
                            <i class="bi bi-x-circle me-2"></i>
                            Annuler
                        </button>
                        <button type="submit" id="modalAppointmentActionBtn" form="appointmentActionForm"
                            class="btn btn-primary-modern btn-modern flex-grow-1">
                            <i class="bi bi-check-circle me-2"></i>
                            <span id="actionButtonText">Confirmer</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Vue détaillée -->
    <div class="modal fade" id="modalViewAppointment" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
        aria-labelledby="modalViewAppointmentLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
            <div class="modal-content card-modern border-0" style="border-radius: var(--radius-xl);">
                <!-- Header avec avatar -->
                <div class="modal-header border-0 pb-0">
                    <div class="d-flex align-items-center gap-3 w-100">
                        <div class="avatar-large position-relative" id="viewAvatar">
                            <img src="" alt="Avatar" class="rounded-circle" width="56" height="56">
                            <span
                                class="position-absolute bottom-0 end-0 translate-middle badge rounded-circle border border-2 border-white"
                                id="viewStatusBadge"></span>
                        </div>
                        <div class="flex-grow-1">
                            <h1 class="modal-title h4 fw-bold mb-1" id="modalViewAppointmentLabel">
                                Détails de la demande d'audience
                            </h1>
                            <div class="d-flex align-items-center flex-wrap gap-2">
                                <span class="badge" id="viewStatusBadgeLarge"></span>
                                <span class="text-muted small" id="viewRequestedAtBadge"></span>
                            </div>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                </div>

                <div class="modal-body pt-4">
                    <div class="row g-4">
                        <!-- Carte de gauche - Informations client -->
                        <div class="col-md-6">
                            <div class="card-modern h-100">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center gap-2 mb-3">
                                    <div class="icon-container bg-primary bg-opacity-10">
                                        <i class="bi bi-person-circle text-primary"></i>
                                    </div>
                                    <h6 class="mb-0 fw-semibold text-primary">Informations de l'usager</h6>
                                </div>
                                <div class="card-body-modern p-0">
                                    <div class="info-group">
                                        <div class="info-label d-flex align-items-center gap-2">
                                            <i class="bi bi-person text-muted"></i>
                                            <span class="small text-muted">Nom complet</span>
                                        </div>
                                        <div class="info-value fw-semibold" id="viewFullName"></div>
                                    </div>

                                    <div class="info-group mb-3">
                                        <div class="info-label d-flex align-items-center gap-2">
                                            <i class="bi bi-telephone text-muted"></i>
                                            <span class="small text-muted">Contact</span>
                                        </div>
                                        <div class="info-value fw-semibold" id="viewMobile"></div>
                                    </div>

                                    <div class="info-group mb-3">
                                        <div class="info-label d-flex align-items-center gap-2">
                                            <i class="bi bi-envelope text-muted"></i>
                                            <span class="small text-muted">Email</span>
                                        </div>
                                        <div class="info-value">
                                            <a href="#" id="viewEmail"
                                                class="text-decoration-none text-primary"></a>
                                        </div>
                                    </div>

                                    <div class="info-group">
                                        <div class="info-label d-flex align-items-center gap-2">
                                            <i class="bi bi-chat-left-text text-muted"></i>
                                            <span class="small text-muted">Objet</span>
                                        </div>
                                        <div class="info-value fw-medium" id="viewSubject"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Carte de droite - Planification -->
                        <div class="col-md-6">
                            <div class="card-modern h-100">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center gap-2 mb-3">
                                    <div class="icon-container bg-success bg-opacity-10">
                                        <i class="bi bi-calendar-check text-success"></i>
                                    </div>
                                    <h6 class="mb-0 fw-semibold text-success">Planification</h6>
                                </div>
                                <div class="card-body-modern p-0">
                                    <div class="row g-3">
                                        <div class="col-6">
                                            <div class="info-group">
                                                <div class="info-label d-flex align-items-center gap-2">
                                                    <i class="bi bi-calendar-event text-muted"></i>
                                                    <span class="small text-muted">Demandé le</span>
                                                </div>
                                                <div class="info-value fw-semibold" id="viewRequestedAt"></div>
                                            </div>
                                        </div>

                                        <div class="col-6">
                                            <div class="info-group">
                                                <div class="info-label d-flex align-items-center gap-2">
                                                    <i class="bi bi-calendar-date text-muted"></i>
                                                    <span class="small text-muted">Programmé le</span>
                                                </div>
                                                <div class="info-value fw-semibold" id="viewScheduledAt"></div>
                                            </div>
                                        </div>

                                        <div class="col-6">
                                            <div class="info-group">
                                                <div class="info-label d-flex align-items-center gap-2">
                                                    <i class="bi bi-clock text-muted"></i>
                                                    <span class="small text-muted">Durée</span>
                                                </div>
                                                <div class="info-value fw-semibold" id="viewDuration"></div>
                                            </div>
                                        </div>

                                        <div class="col-6">
                                            <div class="info-group">
                                                <div class="info-label d-flex align-items-center gap-2">
                                                    <i class="bi bi-card-checklist text-muted"></i>
                                                    <span class="small text-muted">Statut</span>
                                                </div>
                                                <div class="info-value">
                                                    <span class="badge" id="viewStatus"></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Message client (pleine largeur) -->
                        <div class="col-12">
                            <div class="card-modern">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center gap-2 mb-3">
                                    <div class="icon-container bg-info bg-opacity-10">
                                        <i class="bi bi-chat-left-dots text-info"></i>
                                    </div>
                                    <h6 class="mb-0 fw-semibold text-info">Message de l'usager</h6>
                                </div>
                                <div class="card-body-modern">
                                    <div class="message-content bg-light rounded p-3" id="viewMessage"
                                        style="white-space: pre-wrap; max-height: 200px; overflow-y: auto;"></div>
                                </div>
                            </div>
                        </div>

                        <div class="col-12">
                            <div class="card-modern h-100">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center gap-2 mb-3">
                                    <div class="icon-container bg-warning bg-opacity-10">
                                        <i class="bi bi-chat-square-text text-warning"></i>
                                    </div>
                                    <h6 class="mb-0 fw-semibold text-warning">Avis techniques</h6>
                                </div>

                                <div class="card-body-modern technical-advice p-0">

                                </div>
                            </div>
                        </div>

                        <!-- Note admin (conditionnelle) -->
                        <div class="col-12" id="adminNoteSection" style="display: none;">
                            <div class="card-modern">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center gap-2 mb-3">
                                    <div class="icon-container bg-warning bg-opacity-10">
                                        <i class="bi bi-sticky text-warning"></i>
                                    </div>
                                    <h6 class="mb-0 fw-semibold text-warning">Note de l'administrateur</h6>
                                </div>
                                <div class="card-body-modern">
                                    <div class="admin-note bg-warning bg-opacity-10 rounded p-3" id="viewAdminNote"
                                        style="white-space: pre-wrap;"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Pièces jointes (conditionnelles) -->
                        <div class="col-12" id="attachmentsSection" style="display: none;">
                            <div class="card-modern">
                                <div
                                    class="card-header-modern bg-transparent border-0 d-flex align-items-center justify-content-between mb-3">
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="icon-container bg-secondary bg-opacity-10">
                                            <i class="bi bi-paperclip text-secondary"></i>
                                        </div>
                                        <h6 class="mb-0 fw-semibold text-secondary">Pièces jointes</h6>
                                    </div>
                                    <span class="badge bg-light text-dark" id="attachmentsCount"></span>
                                </div>
                                <div class="card-body-modern">
                                    <div class="list-group list-group-flush" id="viewAttachments">
                                        <!-- Les pièces jointes seront insérées ici -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer border-0 pt-0">
                    <div class="d-flex gap-2 w-100">
                        <button type="button" class="btn btn-outline-secondary btn-modern flex-grow-1"
                            data-bs-dismiss="modal">
                            <i class="bi bi-x-circle me-2"></i>
                            Fermer
                        </button>
                        <button type="button" id="quickActionBtn" class="btn btn-primary-modern btn-modern flex-grow-1"
                            style="display: none;">
                            <i class="bi bi-lightning me-2"></i>
                            <span id="quickActionText"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')

    <script>
        const modal = document.getElementById('modalAppointmentAction');
        modal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const appointmentId = button.getAttribute('data-appointment-id');
            const action = button.getAttribute('data-action');

            const form = modal.querySelector('#appointmentActionForm');
            const actionTitle = modal.querySelector('#modalAppointmentActionTitle');
            const actionBtn = modal.querySelector('#modalAppointmentActionBtn');
            const actionBtnText = modal.querySelector('#actionButtonText');
            const confirmFields = modal.querySelector('#confirmFields');
            const rejectFields = modal.querySelector('#rejectFields');
            const cancelFields = modal.querySelector('#cancelFields');
            const adviceFields = modal.querySelector('#adviceFields');
            const technicalFields = modal.querySelector('#technicalFields');
            const pendingFields = modal.querySelector('#rependingFields');
            const processingFields = modal.querySelector('#processingFields');
            const actionBadge = modal.querySelector('#actionBadge');
            const actionIconContainer = modal.querySelector('#actionIconContainer');
            const clientNamePreview = modal.querySelector('#clientNamePreview');

            // Réinitialiser tous les champs
            confirmFields.style.display = 'none';
            rejectFields.style.display = 'none';
            adviceFields.style.display = 'none';
            if (cancelFields) cancelFields.style.display = 'none';


            // Récupérer le nom de l'usager depuis la ligne du tableau
            const clientName = button.closest('tr')?.querySelector('.fw-semibold')?.textContent || '';
            if (clientNamePreview && clientName) {
                clientNamePreview.textContent = clientName;
            }

            // Pré-remplir les champs
            const subjectInput = document.getElementById('appointmentSubject');
            const scheduledAtInput = document.getElementById('appointmentScheduledAt');
            const scheduledAtInputDate = document.getElementById('appointmentScheduledAtDate');
            const scheduledAtInputTime = document.getElementById('appointmentScheduledAtTime');
            const adminNoteInput = document.getElementById('appointmentAdminNote');
            // Configuration selon l'action
            switch (action) {
                case 'confirm':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/confirm`;
                    actionTitle.textContent = 'Confirmation de la demande d\'audience';
                    actionBtnText.textContent = 'Confirmer';
                    actionBtn.className = 'btn btn-success btn-modern flex-grow-1';
                    actionBadge.textContent = 'Confirmation';
                    actionBadge.className = 'badge bg-success text-white small';
                    confirmFields.style.display = 'block';

                    // Icône
                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-calendar-check text-success" style="font-size: 1.5rem;"></i>';
                    }

                    if (subjectInput) {
                        subjectInput.value = button.getAttribute('data-subject') || '';
                    }
                    if (scheduledAtInputDate && scheduledAtInputTime) {
                        scheduledAtInputDate.value = button.getAttribute('data-requested-at').split(' ')[0] || '';
                        scheduledAtInputTime.value = (button.getAttribute('data-requested-at').split(' ')[1] || '')
                            .substring(0, 5) || '';
                    }
                    if (adminNoteInput) {
                        adminNoteInput.value = button.getAttribute('data-admin-note') || '';
                    }
                    break;

                case 'reject':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/reject`;
                    actionTitle.textContent = 'Rejet de demande d\'audience';
                    actionBtnText.textContent = 'Rejeter';
                    actionBtn.className = 'btn btn-danger btn-modern flex-grow-1';
                    actionBadge.textContent = 'Rejet';
                    actionBadge.className = 'badge bg-danger text-white small';
                    rejectFields.style.display = 'block';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-x-circle text-danger" style="font-size: 1.5rem;"></i>';
                    }

                    const rejectNoteInput = document.getElementById('appointmentRejectNote');
                    if (rejectNoteInput) {
                        rejectNoteInput.value = button.getAttribute('data-admin-note') || '';
                    }
                    break;

                case 'cancel':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/cancel`;
                    actionTitle.textContent = 'Annulation de demande d\'audience';
                    actionBtnText.textContent = 'Annuler la demande d\'audience';
                    actionBtn.className = 'btn btn-warning btn-modern flex-grow-1';
                    actionBadge.textContent = 'Annulation';
                    actionBadge.className = 'badge bg-warning text-dark small';
                    if (cancelFields) cancelFields.style.display = 'block';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-calendar-x text-warning" style="font-size: 1.5rem;"></i>';
                    }
                    break;

                case 'repending':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/repending`;
                    actionTitle.textContent = 'Mise en attente de demande d\'audience';
                    actionBtnText.textContent = 'Mettre en attente la demande d\'audience';
                    actionBtn.className = 'btn btn-warning btn-modern flex-grow-1';
                    actionBadge.textContent = 'Mise en attente';
                    actionBadge.className = 'badge bg-warning text-dark small';
                    if (pendingFields) pendingFields.style.display = 'block';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-calendar-x text-warning" style="font-size: 1.5rem;"></i>';
                    }
                    break;

                case 'reschedule':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/reschedule`;
                    actionTitle.textContent = 'Reprogrammer la demande d\'audience';
                    actionBtnText.textContent = 'Reprogrammer';
                    actionBtn.className = 'btn btn-primary-modern btn-modern flex-grow-1';
                    actionBadge.textContent = 'Reprogrammation';
                    actionBadge.className = 'badge bg-primary text-white small';
                    confirmFields.style.display = 'block';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-calendar-plus text-primary" style="font-size: 1.5rem;"></i>';
                    }

                    if (subjectInput) {
                        subjectInput.value = button.getAttribute('data-subject') || '';
                    }
                    if (scheduledAtInputDate && scheduledAtInputTime) {
                        scheduledAtInputDate.value = button.getAttribute('data-requested-at').split(' ')[0] || '';
                        scheduledAtInputTime.value = (button.getAttribute('data-requested-at').split(' ')[1] || '')
                            .substring(0, 5) || '';
                    }
                    if (adminNoteInput) {
                        adminNoteInput.value = button.getAttribute('data-admin-note') || '';
                    }
                    break;

                case 'ask_opinion':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/ask-opinion`;

                    actionTitle.textContent = 'Demande d’avis technique';
                    actionBtnText.textContent = 'Envoyer la demande';
                    actionBtn.className = 'btn btn-primary btn-modern flex-grow-1';

                    actionBadge.textContent = 'Avis technique';
                    actionBadge.className = 'badge bg-primary text-white small';

                    document.getElementById('technicalFields').style.display = 'block';

                    // Icône
                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-send text-primary" style="font-size: 1.5rem;"></i>';
                    }

                    // Récupération des datasets
                    const institutions = JSON.parse(button.getAttribute('data-institutions') || '[]');
                    const users = JSON.parse(button.getAttribute('data-users') || '[]');

                    const institutionSelect = document.getElementById('technicalInstitution');
                    const userSelect = document.getElementById('technicalUser');

                    // Reset
                    institutionSelect.innerHTML = '<option value="">-- Choisir une institution --</option>';
                    userSelect.innerHTML = '<option value="">-- Choisir un utilisateur --</option>';

                    // Remplir institutions
                    institutions.forEach(inst => {
                        const option = document.createElement('option');
                        option.value = inst.id;
                        option.textContent = inst.name;
                        institutionSelect.appendChild(option);
                    });

                    // Filtrage users selon institution
                    institutionSelect.addEventListener('change', function() {
                        const institutionId = this.value;
                        userSelect.innerHTML = '<option value="">-- Choisir un utilisateur --</option>';

                        if (!institutionId) return;

                        users
                            .filter(user => user.institution_id == institutionId)
                            .forEach(user => {
                                const option = document.createElement('option');
                                option.value = user.id;
                                option.textContent = user.name ??
                                    `${user.first_name} ${user.last_name}`;
                                userSelect.appendChild(option);
                            });
                    });

                    break;
                case 'give_advice': // nouvelle action pour chef d'institution
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/give-advice`;
                    actionTitle.textContent = 'Donner votre avis';
                    actionBtnText.textContent = 'Envoyer';
                    actionBtn.className = 'btn btn-primary btn-modern flex-grow-1';
                    actionBadge.textContent = 'Avis';
                    actionBadge.className = 'badge bg-info text-white small';

                    adviceFields.style.display = 'block';
                    rejectFields.style.display = 'none';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-lightbulb text-info" style="font-size: 1.5rem;"></i>';
                    }

                    const adviceNoteInput = document.getElementById('appointmentAdviceNote');
                    if (adviceNoteInput) {
                        adviceNoteInput.value = button.getAttribute('data-admin-note') || '';
                    }
                    break;

                case 'processing':
                    form.action = `{{ url('admin/appointments') }}/${appointmentId}/processing`;
                    actionTitle.textContent = 'Démarrage du traitement de demande d\'audience';
                    actionBtnText.textContent = 'Demarrer le traitement la demande d\'audience';
                    actionBtn.className = 'btn btn-warning btn-modern flex-grow-1';
                    actionBadge.textContent = 'Démarrage traitement';
                    actionBadge.className = 'badge bg-warning text-dark small';
                    if (processingFields) processingFields.style.display = 'block';

                    if (actionIconContainer) {
                        actionIconContainer.innerHTML =
                            '<i class="bi bi-calendar-x text-warning" style="font-size: 1.5rem;"></i>';
                    }
                    break;


                default:
                    break;
            }
        });

        document.getElementById('appointmentActionForm')?.addEventListener('submit', function (e) {
            e.preventDefault();

            const form = this;
            const submitBtn = document.getElementById('modalAppointmentActionBtn');
            const originalText = submitBtn.innerHTML;

            // Afficher l'état de chargement
            submitBtn.innerHTML = 'Traitement en cours...';
            submitBtn.disabled = true;

            // Préparer les données
            const formData = new FormData(form);

            // Pour les dates et heures séparées (si vous avez ce système)
            const date = document.getElementById('appointmentScheduledAtDate');
            const time = document.getElementById('appointmentScheduledAtTime');

            if (date?.value && time?.value) {
                formData.set('scheduled_at', `${date.value} ${time.value}:00`);
            }

            // Envoyer la requête
            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content
                }
            })
            .then(res => res.json())
            .then(data => {
                if (!data.success) throw new Error(data.message);

                Swal.fire({
                    icon: 'success',
                    title: 'Succès',
                    text: data.message ?? 'Action effectuée avec succès',
                    timer: 2500,
                    showConfirmButton: false
                });

                const modal = document.getElementById('modalAppointmentAction');
                bootstrap.Modal.getInstance(modal)?.hide();

                setTimeout(() => location.reload(), 1000);
            })
            .catch(err => {
                Swal.fire({
                    icon: 'error',
                    title: 'Erreur',
                    text: err.message
                });
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });


        function combineDateTime() {
            const dateField = document.getElementById('appointmentScheduledAtDate');
            const timeField = document.getElementById('appointmentScheduledAtTime');
            const combinedField = document.getElementById('appointmentScheduledAt');

            if (dateField && timeField && combinedField && dateField.value && timeField.value) {
                combinedField.value = `${dateField.value}T${timeField.value}`;
            }
        }

        document.getElementById('appointmentScheduledAtDate')?.addEventListener('change', combineDateTime);
        document.getElementById('appointmentScheduledAtTime')?.addEventListener('change', combineDateTime);

        document.getElementById('appointmentDuration')?.addEventListener('input', function() {
            const durationField = this;
            const durationPreview = document.getElementById('durationPreview');

            if (durationPreview && durationField.value) {
                const minutes = parseInt(durationField.value);
                const hours = Math.floor(minutes / 60);
                const remainingMinutes = minutes % 60;

                if (hours > 0) {
                    durationPreview.textContent =
                        `${hours}h${remainingMinutes > 0 ? `${remainingMinutes}min` : ''}`;
                } else {
                    durationPreview.textContent = `${minutes} minutes`;
                }
            }
        });
    </script>

    <script>
        // Modal Vue détaillée modernisée
        const modalView = document.getElementById('modalViewAppointment');
        modalView.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;

            // Informations de base
            const firstName = button.getAttribute('data-first-name');
            const lastName = button.getAttribute('data-last-name');
            const email = button.getAttribute('data-email');
            const mobile = button.getAttribute('data-mobile');
            const subject = button.getAttribute('data-subject');
            const message = button.getAttribute('data-message');
            const requestedAt = button.getAttribute('data-requested-at');
            const duration = button.getAttribute('data-duration');
            const status = button.getAttribute('data-status');
            const scheduledAt = button.getAttribute('data-scheduled-at');
            const adminNote = button.getAttribute('data-admin-note');
            const attachments = JSON.parse(button.getAttribute('data-attachments') || '[]');

            fetch(`{{ url('admin/technical-requests') }}/${button.getAttribute('data-appointment-id')}`)
                .then(response => response.json())
                .then(data => {
                    const technicalAdvice = data || [];
                    const technicalAdviceContainer = modalView.querySelector('.technical-advice');
                    technicalAdviceContainer.innerHTML = '';
                    if (technicalAdvice.length > 0) {
                        technicalAdvice.forEach(avis => {
                            const avisDiv = document.createElement('div');
                            avisDiv.className = 'mb-3';
                            avisDiv.innerHTML = `
                                <div class="fw-semibold">
                                    ${avis.assigned_to.name}
                                </div>
                                <div class="small text-muted">
                                    ${avis.assigned_to.institution ? avis.assigned_to.institution.name : '-'}
                                </div>
                                <div class="mt-1">
                                    ${avis.answer_message ? avis.answer_message : '_'}
                                </div>
                            `;
                            technicalAdviceContainer.appendChild(avisDiv);
                        });
                    } else {
                        technicalAdviceContainer.innerHTML =
                            '<div class="message-content bg-light rounded p-3" style="white-space: pre-wrap; max-height: 200px; overflow-y: auto;">Aucun avis technique</div>';
                    }

                })
                .catch(error => {
                    console.error('Erreur lors de la récupération des avis techniques :', error);
                });



            // Générer l'avatar
            const avatar = document.getElementById('viewAvatar').querySelector('img');
            if (firstName && lastName) {
                const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
                avatar.src =
                    `https://ui-avatars.com/api/?name=${encodeURIComponent(firstName + ' ' + lastName)}&background=0ea5e9&color=fff&bold=true&size=128`;
            } else if (email) {
                avatar.src =
                    `https://ui-avatars.com/api/?name=${encodeURIComponent(email)}&background=0ea5e9&color=fff&size=128`;
            }

            // Remplir les informations
            document.getElementById('viewFullName').textContent = `${firstName} ${lastName}`;
            document.getElementById('viewEmail').textContent = email;
            document.getElementById('viewMobile').textContent = mobile;
            document.getElementById('viewEmail').href = `mailto:${email}`;
            document.getElementById('viewSubject').textContent = subject || '-';
            document.getElementById('viewMessage').textContent = message || 'Aucun message';

            // Formater les dates
            if (requestedAt) {
                const requestedDate = new Date(requestedAt);
                document.getElementById('viewRequestedAt').textContent = requestedDate.toLocaleDateString('fr-FR', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric'
                });
                document.getElementById('viewRequestedAtBadge').textContent = requestedDate.toLocaleTimeString(
                    'fr-FR', {
                        hour: '2-digit',
                        minute: '2-digit'
                    });
            } else {
                document.getElementById('viewRequestedAt').textContent = '-';
                document.getElementById('viewRequestedAtBadge').textContent = '';
            }

            if (scheduledAt) {
                const scheduledDate = new Date(scheduledAt);
                document.getElementById('viewScheduledAt').textContent = scheduledDate.toLocaleDateString('fr-FR', {
                    weekday: 'long',
                    day: 'numeric',
                    month: 'long',
                    year: 'numeric'
                }) + ' à ' + scheduledDate.toLocaleTimeString('fr-FR', {
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } else {
                document.getElementById('viewScheduledAt').textContent = 'Non programmé';
            }

            // Durée
            document.getElementById('viewDuration').textContent = duration ? `${duration} min` : '-';

            // Statut avec badge coloré
            const statusBadge = document.getElementById('viewStatus');
            const statusBadgeLarge = document.getElementById('viewStatusBadgeLarge');
            const avatarStatusBadge = document.getElementById('viewStatusBadge');

            let statusText, badgeClass, statusColor;

            switch (status) {
                case 'En attente':
                case 'pending':
                    statusText = 'En attente';
                    badgeClass = 'bg-warning text-dark';
                    statusColor = '#f59e0b';
                    break;
                case 'Confirmé':
                case 'confirmed':
                    statusText = 'Confirmé';
                    badgeClass = 'bg-success text-white';
                    statusColor = '#10b981';
                    break;
                case 'Rejeté':
                case 'rejected':
                    statusText = 'Rejeté';
                    badgeClass = 'bg-danger text-white';
                    statusColor = '#ef4444';
                    break;
                case 'Annulé':
                case 'canceled':
                    statusText = 'Annulé';
                    badgeClass = 'bg-secondary text-white';
                    statusColor = '#64748b';
                    break;
                case 'processing':
                    statusText = 'En cours de traitement';
                    badgeClass = 'bg-secondary text-white';
                    statusColor = '#64748b';
                    break;
                case 'occurred':
                    statusText = 'Auditée';
                    badgeClass = 'bg-secondary text-white';
                    statusColor = '#64748b';
                    break;

                default:
                    statusText = status;
                    badgeClass = 'bg-info text-white';
                    statusColor = '#0ea5e9';
            }

            statusBadge.textContent = statusText;
            statusBadge.className = `badge ${badgeClass}`;

            statusBadgeLarge.textContent = statusText;
            statusBadgeLarge.className = `badge ${badgeClass} px-3 py-2`;

            avatarStatusBadge.className =
                `position-absolute bottom-0 end-0 translate-middle badge rounded-circle border border-2 border-white`;
            avatarStatusBadge.style.backgroundColor = statusColor;
            avatarStatusBadge.style.width = '12px';
            avatarStatusBadge.style.height = '12px';
            avatarStatusBadge.setAttribute('title', statusText);

            // Note admin
            const adminNoteSection = document.getElementById('adminNoteSection');
            if (adminNote && adminNote.trim() !== '') {
                document.getElementById('viewAdminNote').textContent = adminNote;
                adminNoteSection.style.display = 'block';
            } else {
                adminNoteSection.style.display = 'none';
            }

            // Pièces jointes
            const attachmentsSection = document.getElementById('attachmentsSection');
            const attachmentsList = document.getElementById('viewAttachments');
            const attachmentsCount = document.getElementById('attachmentsCount');

            if (attachments && attachments.length > 0) {
                attachmentsList.innerHTML = '';
                attachmentsCount.textContent = `${attachments.length} fichier(s)`;

                attachments.forEach(attachment => {
                    const fileSize = attachment.size ? (attachment.size / 1024).toFixed(2) : 'N/A';
                    const fileIcon = getFileIcon(attachment.mime || attachment.type);
                    const fileName = attachment.original_name || attachment.name || 'Fichier';
                    const fileUrl = attachment.url ||
                        `{{ url('storage/') }}/${attachment.path}`;

                    const attachmentItem = document.createElement('a');
                    attachmentItem.href = fileUrl;
                    attachmentItem.target = '_blank';
                    attachmentItem.className =
                        'list-group-item list-group-item-action d-flex align-items-center gap-3 p-3 border-0 hover-lift';
                    attachmentItem.style.borderRadius = 'var(--radius-sm)';
                    attachmentItem.style.marginBottom = '0.5rem';
                    attachmentItem.style.transition = 'all var(--transition-fast)';

                    attachmentItem.innerHTML =
                        `
                                                                                                                            <div class="flex-shrink-0">
                                                                                                                                <div class="file-icon ${getFileColorClass(attachment.mime)} p-2 rounded">
                                                                                                                                    <i class="${fileIcon} fs-5"></i>
                                                                                                                                </div>
                                                                                                                            </div>
                                                                                                                            <div class="flex-grow-1">
                                                                                                                                <div class="d-flex justify-content-between align-items-center">
                                                                                                                                    <h6 class="mb-0 small fw-semibold text-truncate" style="max-width: 200px;">${fileName}</h6>
                                                                                                                                    <span class="badge bg-light text-dark small">${fileSize} KB</span>
                                                                                                                                </div>
                                                                                                                                <div class="small text-muted mt-1">
                                                                                                                                    <span class="d-flex align-items-center gap-1">
                                                                                                                                        <i class="bi bi-download"></i>
                                                                                                                                        Télécharger
                                                                                                                                    </span>
                                                                                                                                </div>
                                                                                                                            </div>
                                                                                                                        `;

                    attachmentsList.appendChild(attachmentItem);
                });
                attachmentsSection.style.display = 'block';
            } else {
                attachmentsSection.style.display = 'none';
            }

            // Bouton d'action rapide
            const quickActionBtn = document.getElementById('quickActionBtn');
            const quickActionText = document.getElementById('quickActionText');

            if (status === 'En attente' || status === 'pending') {
                quickActionBtn.style.display = 'block';
                quickActionText.textContent = 'Confirmer cette demande d\'audience';
                quickActionBtn.onclick = function() {
                    const confirmBtn = button.closest('tr').querySelector('[data-action="confirm"]');
                    if (confirmBtn) {
                        confirmBtn.click();
                        const modalInstance = bootstrap.Modal.getInstance(modalView);
                        modalInstance.hide();
                    }
                };
            } else if (status === 'Confirmé' || status === 'confirmed') {
                quickActionBtn.style.display = 'block';
                quickActionText.textContent = 'Reprogrammer';
                quickActionBtn.className = 'btn btn-warning btn-modern flex-grow-1';
                quickActionBtn.onclick = function() {
                    const rescheduleBtn = button.closest('tr').querySelector('[data-action="reschedule"]');
                    if (rescheduleBtn) {
                        rescheduleBtn.click();
                        const modalInstance = bootstrap.Modal.getInstance(modalView);
                        modalInstance.hide();
                    }
                };
            } else {
                quickActionBtn.style.display = 'none';
            }
        });

        // Fonction pour obtenir l'icône selon le type MIME
        function getFileIcon(mime) {
            if (!mime) return 'bi bi-file-earmark';
            if (mime.startsWith('image/')) return 'bi bi-file-image';
            if (mime.startsWith('application/pdf')) return 'bi bi-file-pdf';
            if (mime.startsWith('application/vnd.ms-excel') || mime.includes('spreadsheet')) return 'bi bi-file-excel';
            if (mime.startsWith('application/msword') || mime.includes('document')) return 'bi bi-file-word';
            if (mime.startsWith('application/zip') || mime.includes('compressed')) return 'bi bi-file-zip';
            if (mime.startsWith('text/')) return 'bi bi-file-text';
            return 'bi bi-file-earmark';
        }

        // Fonction pour obtenir la classe de couleur selon le type MIME
        function getFileColorClass(mime) {
            if (!mime) return 'bg-primary bg-opacity-10 text-primary';
            if (mime.startsWith('image/')) return 'bg-info bg-opacity-10 text-info';
            if (mime.startsWith('application/pdf')) return 'bg-danger bg-opacity-10 text-danger';
            if (mime.startsWith('application/vnd.ms-excel') || mime.includes('spreadsheet'))
                return 'bg-success bg-opacity-10 text-success';
            if (mime.startsWith('application/msword') || mime.includes('document'))
                return 'bg-primary bg-opacity-10 text-primary';
            if (mime.startsWith('application/zip') || mime.includes('compressed'))
                return 'bg-warning bg-opacity-10 text-warning';
            return 'bg-secondary bg-opacity-10 text-secondary';
        }
    </script>

    <script>
        function submit(btn, formId) {
            btn.disabled = true;
            $('#' + formId).submit();
        }
    </script>
    <script>
        function updateStatus(appointmentId, newStatus) {
            fetch(`appointments/${appointmentId}/status`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        status: newStatus
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Succès',
                            text: data.message || 'Action effectuée avec succès',
                            timer: 3000,
                            showConfirmButton: false,
                            background: 'var(--bg-surface)',
                            color: 'var(--text-primary)'
                        });
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                        // ou mettre à jour dynamiquement le status dans la page
                    } else {
                        alert('Erreur lors de la mise à jour du status.');
                    }
                })
                .catch(err => console.error(err));
        }
    </script>
    <script>
        const institutionSelect = document.getElementById('technicalInstitution');
        const userSelect = document.getElementById('technicalUser');

        institutionSelect?.addEventListener('change', function() {
            const institutionId = this.value;

            // Réinitialiser le dropdown utilisateur
            userSelect.innerHTML = '<option value="">-- Choisir un utilisateur --</option>';

            if (!institutionId) return;

            // Exemple: récupération dynamique via fetch (adaptable à ton backend)
            fetch(`/admin/institutions/${institutionId}/users`)
                .then(res => res.json())
                .then(data => {
                    data.users.forEach(user => {
                        const option = document.createElement('option');
                        option.value = user.id;
                        option.textContent = user.name;
                        userSelect.appendChild(option);
                    });
                })
                .catch(err => console.error('Erreur récupération utilisateurs:', err));
        });
    </script>
    @if (session('modal') == 'appointment')
        <script>
            window.addEventListener('load', function() {
                new bootstrap.Modal(document.getElementById('confirm')).show();
            });
        </script>
    @endif
@endsection
