<?php $__env->startSection('title', __('Eventos')); ?>

<?php $__env->startSection('content'); ?>
    <?php echo $__env->make('dashboard.partials.bootstrap-table-assets', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

    <div class="rt-events-hub mb-4">
        <div class="d-flex flex-wrap align-items-start justify-content-between rt-flex-gap-3 mb-3">
            <div>
                <h1 class="h3 mb-1 text-gray-800 font-weight-bold"><?php echo e(__('Tus eventos')); ?></h1>
            </div>
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create', \App\Models\Event::class)): ?>
                <a href="<?php echo e(route('dashboard.events.create')); ?>" class="btn rt-btn-cherry btn-sm px-3 shadow-sm flex-shrink-0">
                    <i class="bi bi-plus-lg mr-1" aria-hidden="true"></i> <?php echo e(__('Nuevo evento')); ?>

                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-primary shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1"><?php echo e(__('Total')); ?></div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo e(number_format($stats['total'])); ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-success shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1"><?php echo e(__('Publicados')); ?></div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo e(number_format($stats['published'])); ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-warning shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1"><?php echo e(__('Borrador / revisión')); ?></div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo e(number_format($stats['in_progress'])); ?></div>
                </div>
            </div>
        </div>
        <div class="col-6 col-xl-3 mb-3">
            <div class="card border-left-info shadow h-100 py-2 rt-stat-card">
                <div class="card-body py-3">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1"><?php echo e(__('Próximos publicados')); ?></div>
                    <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo e(number_format($stats['upcoming_published'])); ?></div>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex flex-wrap align-items-center rt-flex-gap-2 mb-3">
        <span class="small font-weight-bold text-muted text-uppercase mr-1"><?php echo e(__('Filtrar:')); ?></span>
        <a href="<?php echo e(route('dashboard.events.index', ['status' => 'all'])); ?>" class="btn btn-sm <?php echo e($statusFilter === 'all' ? 'rt-btn-cherry' : 'btn-outline-secondary'); ?>"><?php echo e(__('Todos')); ?></a>
        <a href="<?php echo e(route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Published->value])); ?>" class="btn btn-sm <?php echo e($statusFilter === \App\Enums\EventStatus::Published->value ? 'rt-btn-cherry' : 'btn-outline-secondary'); ?>"><?php echo e(__('Publicados')); ?></a>
        <a href="<?php echo e(route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Pending->value])); ?>" class="btn btn-sm <?php echo e($statusFilter === \App\Enums\EventStatus::Pending->value ? 'rt-btn-cherry' : 'btn-outline-secondary'); ?>"><?php echo e(__('Pendientes')); ?></a>
        <a href="<?php echo e(route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Draft->value])); ?>" class="btn btn-sm <?php echo e($statusFilter === \App\Enums\EventStatus::Draft->value ? 'rt-btn-cherry' : 'btn-outline-secondary'); ?>"><?php echo e(__('Borradores')); ?></a>
        <a href="<?php echo e(route('dashboard.events.index', ['status' => \App\Enums\EventStatus::Cancelled->value])); ?>" class="btn btn-sm <?php echo e($statusFilter === \App\Enums\EventStatus::Cancelled->value ? 'rt-btn-cherry' : 'btn-outline-secondary'); ?>"><?php echo e(__('Cancelados')); ?></a>
    </div>

    <div class="card shadow mb-4 rt-events-table-card">
        <div class="card-header py-3 d-flex flex-wrap align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary"><?php echo e(__('Listado')); ?></h6>
            <span class="small text-muted"><?php echo e(__('Orden: fecha de inicio más reciente')); ?></span>
        </div>
        <div class="card-body p-0">
            <?php if($events->isEmpty()): ?>
                <div class="rt-empty-events p-5 text-center">
                    <div class="rt-empty-events__icon mb-3 mx-auto d-flex align-items-center justify-content-center rounded-circle bg-light border">
                        <i class="bi bi-calendar-event text-muted" style="font-size: 2rem" aria-hidden="true"></i>
                    </div>
                    <h2 class="h5 font-weight-bold text-gray-800"><?php echo e(__('Aún no tienes eventos')); ?></h2>
                    <p class="text-muted small col-md-8 mx-auto mb-4">
                        <?php echo e(__('Crea tu primer evento: podrás definir distancias para carreras, tipos de entrada y más adelante BIB y resultados al estilo de las mejores plataformas de la región.')); ?>

                    </p>
                    <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create', \App\Models\Event::class)): ?>
                        <a href="<?php echo e(route('dashboard.events.create')); ?>" class="btn rt-btn-cherry px-4"><?php echo e(__('Crear mi primer evento')); ?></a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0 rt-events-wp-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width:220px"><?php echo e(__('Título')); ?></th>
                                <th style="min-width:120px"><?php echo e(__('Autor')); ?></th>
                                <th class="text-center" style="min-width:100px"><?php echo e(__('Asistentes')); ?></th>
                                <th style="min-width:80px"><?php echo e(__('Distancias')); ?></th>
                                <th style="min-width:110px"><?php echo e(__('Fecha de inicio')); ?></th>
                                <th style="min-width:110px"><?php echo e(__('Fecha de fin')); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__currentLoopData = $events; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ev): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $sport   = is_array($ev->metadata) ? ($ev->metadata['sport'] ?? []) : [];
                                    $distances = isset($sport['distances']) && is_array($sport['distances']) ? $sport['distances'] : [];

                                    // Capacity & attendee %
                                    $totalCapacity = $ev->ticketTypes->sum(function ($tt) {
                                        return match ($tt->capacity_strategy->value) {
                                            'unlimited' => 0,
                                            'shared_pool' => $tt->shared_pool_size ?? 0,
                                            default      => $tt->capacity ?? 0,
                                        };
                                    });
                                    $attendeesCount = $ev->attendees_count ?? 0;
                                    $pct = ($totalCapacity > 0)
                                        ? min(100, (int) round(($attendeesCount / $totalCapacity) * 100))
                                        : null;

                                    $authorName  = $ev->organizer?->user?->name ?? '—';
                                    $isPublished = $ev->status === \App\Enums\EventStatus::Published;
                                    $isDraft     = in_array($ev->status, [\App\Enums\EventStatus::Draft, \App\Enums\EventStatus::Pending], true);
                                    $isArchived  = $ev->trashed();
                                    $isCancelled = $ev->status === \App\Enums\EventStatus::Cancelled;
                                ?>
                                <tr class="rt-ev-row <?php echo e($isArchived ? 'table-secondary' : ''); ?>" id="rt-ev-<?php echo e($ev->id); ?>">
                                    
                                    <td>
                                        <div class="d-flex align-items-center mb-1 rt-flex-gap-2">
                                            <?php if($isArchived): ?>
                                                <span class="badge badge-dark rt-badge-xs"><?php echo e(__('Archivado')); ?></span>
                                            <?php else: ?>
                                                <?php switch($ev->status):
                                                    case (\App\Enums\EventStatus::Published): ?>
                                                        <span class="badge badge-success rt-badge-xs"><?php echo e(__('Publicado')); ?></span>
                                                        <?php break; ?>
                                                    <?php case (\App\Enums\EventStatus::Pending): ?>
                                                        <span class="badge badge-warning text-dark rt-badge-xs"><?php echo e(__('En revisión')); ?></span>
                                                        <?php break; ?>
                                                    <?php case (\App\Enums\EventStatus::Draft): ?>
                                                        <span class="badge badge-secondary rt-badge-xs"><?php echo e(__('Borrador')); ?></span>
                                                        <?php break; ?>
                                                    <?php case (\App\Enums\EventStatus::Cancelled): ?>
                                                        <span class="badge badge-danger rt-badge-xs"><?php echo e(__('Cancelado')); ?></span>
                                                        <?php break; ?>
                                                <?php endswitch; ?>
                                            <?php endif; ?>
                                            <?php if($ev->is_featured): ?>
                                                <span class="badge badge-light border rt-badge-xs" title="<?php echo e(__('Destacado')); ?>"><i class="bi bi-star-fill text-warning small" aria-hidden="true"></i></span>
                                            <?php endif; ?>
                                        </div>

                                        <strong class="d-block text-gray-900 rt-ev-title"><?php echo e($ev->title); ?></strong>
                                        <div class="small text-muted mb-1"><?php echo e($ev->venue?->name); ?></div>

                                        
                                        <div class="rt-ev-actions">
                                            <?php if($isArchived): ?>
                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('restore', $ev)): ?>
                                                    <form action="<?php echo e(route('dashboard.events.restore', $ev->id)); ?>" method="post" class="d-inline mr-1">
                                                        <?php echo csrf_field(); ?>
                                                        <button type="submit" class="rt-ev-action btn-reset text-success font-weight-bold"><?php echo e(__('Activar')); ?></button>
                                                    </form>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php endif; ?>
                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('update', $ev)): ?>
                                                    <a href="<?php echo e(route('dashboard.events.edit', $ev)); ?>" class="rt-ev-action"><?php echo e(__('Editar')); ?></a>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('update', $ev)): ?>
                                                    <a href="<?php echo e(route('dashboard.events.edit', $ev)); ?>" class="rt-ev-action"><?php echo e(__('Editar')); ?></a>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php endif; ?>

                                                <?php if($isPublished): ?>
                                                    <a href="<?php echo e(route('landing.event.show', $ev->slug)); ?>" target="_blank" class="rt-ev-action"><?php echo e(__('Ver')); ?></a>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php elseif($isDraft): ?>
                                                    <a href="<?php echo e(route('landing.event.show', $ev->slug)); ?>" target="_blank" class="rt-ev-action text-muted"><?php echo e(__('Vista previa')); ?></a>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php endif; ?>

                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('view', $ev)): ?>
                                                    <a href="<?php echo e(route('dashboard.events.attendees.index', $ev)); ?>" class="rt-ev-action"><?php echo e(__('Asistentes / Check-in')); ?></a>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php endif; ?>
                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('update', $ev)): ?>
                                                    <a href="<?php echo e(route('dashboard.events.edit', $ev)); ?>#qr" class="rt-ev-action"><?php echo e(__('Generar QR')); ?></a>
                                                    <span class="rt-ev-sep">|</span>
                                                <?php endif; ?>

                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('cancel', $ev)): ?>
                                                    <?php if(! $isCancelled): ?>
                                                        <form action="<?php echo e(route('dashboard.events.cancel', $ev)); ?>" method="post" class="d-inline rt-ev-cancel-form mr-1">
                                                            <?php echo csrf_field(); ?>
                                                            <button type="submit" class="rt-ev-action btn-reset text-warning"><?php echo e(__('Desactivar')); ?></button>
                                                        </form>
                                                        <span class="rt-ev-sep">|</span>
                                                    <?php endif; ?>
                                                <?php endif; ?>

                                                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('delete', $ev)): ?>
                                                    <form action="<?php echo e(route('dashboard.events.destroy', $ev)); ?>" method="post" class="d-inline rt-ev-delete-form">
                                                        <?php echo csrf_field(); ?>
                                                        <?php echo method_field('DELETE'); ?>
                                                        <button type="submit" class="rt-ev-action rt-ev-action--danger btn-reset"><?php echo e(__('Eliminar')); ?></button>
                                                    </form>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>

                                    
                                    <td>
                                        <span class="small text-gray-800"><?php echo e($authorName); ?></span>
                                    </td>

                                    
                                    <td class="text-center">
                                        <?php if($attendeesCount > 0 || $totalCapacity > 0): ?>
                                            <strong class="d-block text-gray-800"><?php echo e(number_format($attendeesCount)); ?></strong>
                                            <?php if($pct !== null): ?>
                                                <div class="rt-capacity-bar mt-1" title="<?php echo e($attendeesCount); ?>/<?php echo e($totalCapacity); ?>">
                                                    <div class="rt-capacity-bar__fill <?php if($pct >= 90): ?> rt-capacity-bar__fill--danger <?php elseif($pct >= 70): ?> rt-capacity-bar__fill--warn <?php endif; ?>"
                                                         style="width:<?php echo e($pct); ?>%"></div>
                                                </div>
                                                <span class="text-muted small">(<?php echo e($pct); ?>%)</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-muted">—</span>
                                        <?php endif; ?>
                                    </td>

                                    
                                    <td>
                                        <?php if(! empty($sport['enabled']) && count($distances) > 0): ?>
                                            <div class="d-flex flex-wrap rt-flex-gap-1">
                                                <?php $__currentLoopData = array_slice($distances, 0, 4); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $d): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <span class="badge badge-light border text-dark font-weight-normal"><?php echo e($d); ?></span>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                <?php if(count($distances) > 4): ?>
                                                    <span class="badge badge-secondary">+<?php echo e(count($distances) - 4); ?></span>
                                                <?php endif; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted small">—</span>
                                        <?php endif; ?>
                                    </td>

                                    
                                    <td>
                                        <span class="small"><?php echo e($ev->start_date->timezone($ev->timezone)->format('d/m/Y')); ?></span>
                                        <span class="d-block text-muted" style="font-size:.75rem"><?php echo e($ev->start_date->timezone($ev->timezone)->format('H:i')); ?></span>
                                    </td>

                                    
                                    <td>
                                        <span class="small"><?php echo e($ev->end_date->timezone($ev->timezone)->format('d/m/Y')); ?></span>
                                        <span class="d-block text-muted" style="font-size:.75rem"><?php echo e($ev->end_date->timezone($ev->timezone)->format('H:i')); ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
        <?php if($events->hasPages()): ?>
            <div class="card-footer"><?php echo e($events->links()); ?></div>
        <?php endif; ?>
    </div>

    <?php $__env->startPush('scripts'); ?>
        <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.rt-ev-cancel-form').forEach(function (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'question',
                            title: <?php echo json_encode(__('¿Desactivar (cancelar) este evento?'), 15, 512) ?>,
                            text: <?php echo json_encode(__('Seguirá en la base de datos; el público verá el estado cancelado según tu página.'), 15, 512) ?>,
                            showCancelButton: true,
                            confirmButtonText: <?php echo json_encode(__('Sí, cancelar'), 512) ?>,
                            cancelButtonText: <?php echo json_encode(__('No'), 15, 512) ?>,
                            confirmButtonColor: '#f6993f',
                        }).then(function (r) {
                            if (r.isConfirmed) {
                                form.submit();
                            }
                        });
                    } else if (confirm(<?php echo json_encode(__('¿Marcar este evento como cancelado?'), 15, 512) ?>)) {
                        form.submit();
                    }
                });
            });
            document.querySelectorAll('.rt-ev-delete-form').forEach(function (form) {
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    if (typeof Swal !== 'undefined' && typeof rtSwalCrud !== 'undefined') {
                        rtSwalCrud
                            .confirmDelete(
                                <?php echo json_encode(__('Se archivará el evento; órdenes y asistentes permanecen en la base de datos.'), 15, 512) ?>,
                                <?php echo json_encode(__('¿Archivar este evento?'), 15, 512) ?>
                            )
                            .then(function (r) {
                                if (r.isConfirmed) {
                                    form.submit();
                                }
                            });
                    } else if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'warning',
                            title: <?php echo json_encode(__('¿Archivar este evento?'), 15, 512) ?>,
                            text: <?php echo json_encode(__('Se conservan ventas y asistentes para informes; puedes reactivarlo desde el listado.'), 15, 512) ?>,
                            showCancelButton: true,
                            confirmButtonText: <?php echo json_encode(__('Sí, eliminar'), 512) ?>,
                            cancelButtonText: <?php echo json_encode(__('Cancelar'), 15, 512) ?>,
                            confirmButtonColor: '#b91830',
                        }).then(function (r) {
                            if (r.isConfirmed) {
                                form.submit();
                            }
                        });
                    } else {
                        if (confirm(<?php echo json_encode(__('¿Archivar este evento? Los datos históricos se conservan.'), 15, 512) ?>)) { form.submit(); }
                    }
                });
            });
        });
        </script>
    <?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/resources/views/dashboard/events/index.blade.php ENDPATH**/ ?>