@extends('adminlte::page')

@section('title', 'Lista de Películas')

@can('crear peliculas')
@section('content_header')
<!-- Incluir SweetAlert2 desde CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="icon" href="{{ asset('icons/pelicula.png') }}" type="image/x-icon">

<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

<div class="card-header d-flex justify-content-between align-items-center bg-gradient-primary p-3 rounded-top">
    <!-- Parte izquierda: Agregar Película -->
    <div class="d-flex align-items-center">
        <button class="btn btn-light btn-hover-primary d-flex align-items-center fw-bold" 
                data-bs-toggle="modal" data-bs-target="#addMovieModal">
            <i class="fas fa-plus-circle me-2"></i> Nueva Película
        </button>
    </div>

    <!-- Parte central: Acciones de exportación/importación -->
    <div class="d-flex justify-content-center flex-wrap gap-2">
        <!-- Botón para Excel -->
        <a href="{{ route('peliculas.export-excel') }}" 
           class="btn btn-success btn-hover-light d-flex align-items-center fw-bold"
           title="Exportar a Excel">
            <i class="fas fa-file-excel me-2"></i> Excel
        </a>
        
        @can('crear peliculas')
        <a href="{{ route('peliculas.export-pdf') }}" 
           class="btn btn-danger btn-hover-light d-flex align-items-center fw-bold"
           target="_blank" title="Descargar PDF">
            <i class="fas fa-file-pdf me-2"></i> PDF
        </a>
        @endcan
        
        <button type="button" 
                class="btn btn-info text-white btn-hover-light d-flex align-items-center fw-bold"
                data-bs-toggle="modal" data-bs-target="#importModal">
            <i class="fas fa-file-import me-2"></i> Importar
        </button>
    </div>

    <!-- Parte derecha: Filtros -->
    <div class="d-flex align-items-center gap-3">
        <!-- Filtro por Categoría -->
        <form action="{{ route('peliculas.index') }}" method="GET" class="d-flex align-items-center">
            <div class="input-group input-group-sm">
                <span class="input-group-text bg-white">
                    <i class="fas fa-filter text-primary"></i>
                </span>
                <select name="categoria_id" id="categoria_id" 
                        class="form-select form-select-sm shadow-none" 
                        onchange="this.form.submit()">
                    <option value="">Todas las categorías</option>
                    @foreach($categorias as $categoria)
                        <option value="{{ $categoria->id }}" {{ request('categoria_id') == $categoria->id ? 'selected' : '' }}>
                            {{ $categoria->nombre }}
                        </option>
                    @endforeach
                </select>
            </div>
        </form>

        <!-- Formulario de Búsqueda -->
        <form action="{{ route('peliculas.index') }}" method="GET" class="d-flex align-items-center">
            <div class="input-group input-group-sm">
                <input type="text" name="search" value="{{ request()->search }}" 
                       class="form-control form-control-sm shadow-none" 
                       placeholder="Buscar..." 
                       aria-label="Buscar película">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<style>
    .bg-gradient-primary {
        background: linear-gradient(135deg, #3a7bd5 0%, #00d2ff 100%);
    }
    
    .btn-hover-primary:hover {
        background-color: #3a7bd5;
        color: white !important;
        transform: translateY(-2px);
    }
    
    .btn-hover-light:hover {
        background-color: white;
        color: #3a7bd5 !important;
    }
    
    .rounded-top {
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }
    
    .input-group-sm .form-control, 
    .input-group-sm .form-select {
        min-height: 32px;
    }
    
    .shadow-none {
        box-shadow: none !important;
    }
</style>
@stop

@section('content')
<div class="card shadow-sm">
    <div class="card-body">
        @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        @if ($errors->any()))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <ul class="mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
   
        <div class="table-responsive">
            <table class="table table-hover table-striped">
                <thead class="bg-gradient-primary text-white">
                    <tr>
                        <th class="text-center">ID</th>
                        <th>Título</th>
                        <th class="text-center">Duración</th>
                        <th class="text-center">Formato</th>
                        <th class="text-center">Categoría</th>
                        <th class="text-center">Estado</th>
                        <th class="text-center">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($peliculas as $pelicula)
                        <tr>
                            <td class="text-center fw-bold">{{ $pelicula->id }}</td>
                            <td>{{ $pelicula->titulo }}</td>
                            <td class="text-center">
                                <span class="badge bg-dark text-white p-2">
                                    {{ floor($pelicula->duracion / 60) }}h {{ $pelicula->duracion % 60 }}min
                                </span>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-info text-dark p-2">
                                    {{ $pelicula->formato }}
                                </span>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-purple text-white p-2">
                                    {{ optional($pelicula->categoria)->nombre ?? 'Sin categoría' }}
                                </span>
                            </td>
                            <td class="text-center">
                                <span class="badge rounded-pill {{ $pelicula->estado == 'disponible' ? 'bg-success' : 'bg-danger' }} p-2">
                                    <i class="fas {{ $pelicula->estado == 'disponible' ? 'fa-check-circle' : 'fa-times-circle' }} me-1"></i>
                                    {{ strtoupper($pelicula->estado) }}
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="d-flex justify-content-center gap-2">
                                    <a href="{{ route('peliculas.show', $pelicula) }}" 
                                       class="btn btn-sm btn-outline-primary rounded-circle action-btn"
                                       data-bs-toggle="tooltip" data-bs-placement="top" title="Ver detalles">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="{{ route('peliculas.edit', $pelicula) }}" 
                                       class="btn btn-sm btn-outline-warning rounded-circle action-btn"
                                       data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <form action="{{ route('peliculas.destroy', $pelicula) }}" method="POST" class="d-inline delete-form">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" 
                                                class="btn btn-sm btn-outline-danger rounded-circle action-btn"
                                                data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        <div class="d-flex justify-content-center mt-4">
            <ul class="pagination pagination-sm">
                @if ($peliculas->currentPage() > 5)
                    <li class="page-item">
                        <a class="page-link" href="{{ $peliculas->url($peliculas->currentPage() - 5) }}">&laquo;</a>
                    </li>
                @endif

                @php
                    $currentBlock = floor(($peliculas->currentPage() - 1) / 5);
                    $startPage = $currentBlock * 5 + 1;
                    $endPage = min($startPage + 4, $peliculas->lastPage());
                @endphp

                @for ($i = $startPage; $i <= $endPage; $i++)
                    <li class="page-item {{ $peliculas->currentPage() == $i ? 'active' : '' }}">
                        <a class="page-link" href="{{ $peliculas->url($i) }}">{{ $i }}</a>
                    </li>
                @endfor

                @if ($endPage < $peliculas->lastPage())
                    <li class="page-item">
                        <a class="page-link" href="{{ $peliculas->url($endPage + 1) }}">&raquo;</a>
                    </li>
                @endif
            </ul>
        </div>
    </div>
</div>

<!-- Modal para Agregar Película - Versión Mejorada -->
<div class="modal fade" id="addMovieModal" tabindex="-1" aria-labelledby="addMovieModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-gradient-primary text-white">
                <h5 class="modal-title fw-bold" id="addMovieModalLabel">
                    <i class="fas fa-film me-2"></i>Agregar Nueva Película
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <form action="{{ route('peliculas.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <!-- Título -->
                    <div class="mb-4 form-floating">
                        <input type="text" name="titulo" id="titulo" 
                               class="form-control shadow-sm" 
                               placeholder="Título de la película"
                               required>
                        <label for="titulo" class="text-muted">
                            <i class="fas fa-heading me-1"></i>Título de la Película
                        </label>
                    </div>

                    <!-- Duración -->
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted">
                            <i class="fas fa-clock me-1"></i>Duración
                        </label>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="number" name="horas" 
                                           class="form-control shadow-sm" 
                                           placeholder="Horas"
                                           min="0" required>
                                    <label>Horas</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="number" name="minutos" 
                                           class="form-control shadow-sm" 
                                           placeholder="Minutos"
                                           min="0" max="59" required>
                                    <label>Minutos</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Formato -->
                    <div class="mb-4 form-floating">
                        <input type="text" name="formato" id="formato" 
                               class="form-control shadow-sm" 
                               placeholder="Blu-ray, DVD, etc."
                               required>
                        <label for="formato" class="text-muted">
                            <i class="fas fa-compact-disc me-1"></i>Formato
                        </label>
                    </div>

                    <!-- Categoría -->
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted">
                            <i class="fas fa-tag me-1"></i>Categoría
                        </label>
                        <select name="categoria_id" id="categoria_id" 
                                class="form-select shadow-sm py-3" required>
                            <option value="">Selecciona una categoría</option>
                            <!-- Las opciones se cargarán mediante AJAX -->
                        </select>
                    </div>

                    <!-- Estado -->
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted">
                            <i class="fas fa-check-circle me-1"></i>Estado
                        </label>
                        <select name="estado" id="estado" 
                                class="form-select shadow-sm py-3" required>
                            <option value="disponible">
                                <i class="fas fa-check text-success me-2"></i>Disponible
                            </option>
                            <option value="alquilada">
                                <i class="fas fa-times text-danger me-2"></i>Alquilada
                            </option>
                        </select>
                    </div>

                    <!-- Botones -->
                    <div class="d-flex justify-content-end mt-4 pt-3 border-top">
                        <button type="button" class="btn btn-outline-secondary me-3" data-bs-dismiss="modal">
                            <i class="fas fa-times me-1"></i>Cancelar
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i>Guardar Película
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal para importar Excel - Versión mejorada -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content rounded-4 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title d-flex align-items-center" id="importModalLabel">
                    <i class="fas fa-file-import me-2"></i> Importar Películas desde Excel
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div class="alert alert-info d-flex align-items-center">
                    <i class="fas fa-info-circle me-2 fs-4"></i>
                    <div>
                        <strong>Formato requerido:</strong> El archivo Excel debe contener columnas con los siguientes encabezados: 
                        <code>Título, Duración (minutos), Formato, Categoría, Estado</code>.
                        <a href="{{ asset('plantillas/plantilla_peliculas.xlsx') }}" class="alert-link d-block mt-2">
                            <i class="fas fa-download me-1"></i> Descargar plantilla de ejemplo
                        </a>
                    </div>
                </div>
                
                <form action="{{ route('peliculas.import') }}" method="POST" enctype="multipart/form-data" class="mt-4">
                    @csrf
                    <div class="mb-4">
                        <label for="file" class="form-label fw-bold mb-3">Seleccionar archivo Excel</label>
                        <div class="input-group">
                            <input type="file" class="form-control form-control-lg border-2" id="file" name="file" required accept=".xlsx, .xls, .csv">
                            <button class="btn btn-outline-secondary" type="button" id="clearFile">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="form-text">Formatos admitidos: .xlsx, .xls, .csv (Tamaño máximo: 5MB)</div>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-2"></i> Cancelar
                        </button>
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-upload me-2"></i> Importar Datos
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@stop

@section('footer')
    <div class="text-center">
        <small>Sistema de Gestión de Películas © {{ date('Y') }}</small>
    </div>
@stop

@section('js')
<script>
    // Inicializar tooltips
    $(function () {
        $('[data-bs-toggle="tooltip"]').tooltip();
    });

    $('#addMovieModal').on('show.bs.modal', function (event) {
        $.ajax({
            url: '{{ route('categorias.json') }}',
            type: 'GET',
            success: function(response) {
                var select = $('#categoria_id');
                select.empty();
                select.append('<option value="">Selecciona una categoría</option>');
                response.forEach(function(categoria) {
                    select.append('<option value="' + categoria.id + '">' + categoria.nombre + '</option>');
                });
            },
            error: function() {
                alert('Hubo un problema al cargar las categorías.');
            }
        });
    });

    // Función para hacer la búsqueda en tiempo real
    $(document).ready(function() {
        $('#search').on('input', function() {
            var searchTerm = $(this).val();
            if (searchTerm.length >= 3) {
                $.ajax({
                    url: '{{ route('peliculas.search') }}',
                    type: 'GET',
                    data: { term: searchTerm },
                    success: function(response) {
                        var peliculas = response.peliculas;
                        console.log(peliculas);
                    }
                });
            }
        });
        
        // Mejorar el modal de importación
        // Limpiar selección de archivo
        $('#clearFile').click(function() {
            $('#file').val('');
        });
        
        // Validación del archivo antes de enviar
        $('form[action="{{ route('peliculas.import') }}"]').submit(function(e) {
            var fileInput = $('#file');
            var filePath = fileInput.val();
            var allowedExtensions = /(\.xlsx|\.xls|\.csv)$/i;
            
            if(!allowedExtensions.exec(filePath)) {
                Swal.fire({
                    title: 'Formato inválido',
                    text: 'Por favor sube un archivo con extensión .xlsx, .xls o .csv',
                    icon: 'error',
                    confirmButtonText: 'Entendido'
                });
                return false;
            }
            
            return true;
        });
    });

    // Usar SweetAlert2 para confirmar la eliminación
    document.querySelectorAll('.delete-form').forEach(form => {
        form.addEventListener('submit', function(event) {
            event.preventDefault();

            Swal.fire({
                title: '¿Estás seguro?',
                text: "¡No podrás revertir esta acción!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sí, eliminar!',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    this.submit();
                }
            });
        });
    });
</script>

<style>
    .bg-purple {
        background-color: #6f42c1;
    }
    
    .action-btn {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
    }
    
    .action-btn:hover {
        transform: scale(1.1);
    }
    
    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(0, 0, 0, 0.02);
    }
    
    .table-hover tbody tr:hover {
        background-color: rgba(0, 0, 0, 0.05);
    }
    
    .bg-gradient-primary {
        background: linear-gradient(135deg, #3a7bd5 0%, #00d2ff 100%);
    }
    
    .badge.rounded-pill {
        padding: 0.5em 1em;
        font-size: 0.85em;
        letter-spacing: 0.5px;
    }
</style>
@stop
@endcan