@extends('layouts.arte-sacra.theme')

@section('title', env('APP_NAME') . ' :: ' . $arte->nome_peca)

@section('content')
    <div class="container py-5 bg-light">
        <div class="text-left pt-5 pb-4">
            <a href="{{ route('paginas.cultura.arteSacra.galeria') }}" class="btn btn-secondary d-inline-block"><i
                    class="fa-solid fa-arrow-left-long"></i> {{ __("Voltar para a lista") }}</a>
        </div>

        <div class="text-center mb-5">
            <h1 class="display-4">{{ $arte->nome_peca }}</h1>
            <p class="lead">{{ __("Autor") }} - {{ $arte->autoria ?? 'Desconhecido' }}</p>
        </div>

        @include('errors.messageFlash')

        <div class="row">
            <div class="col-md-6">
                @if ($arte->imagem && $arte->imagem !== 'pmar/assets/img/icons/default.png')
                    <img src="{{ asset($arte->imagem) }}" class="img-fluid"
                        style="height: 500px; width: 100%; object-fit: contain;" alt="{{ $arte->nome_peca }}">
                @else
                    <img src="{{ asset('pmar/assets/img/arte_sacra/default.jpg') }}" class="img-fluid"
                        style="height: 500px; width: 100%; object-fit: contain;" alt="Imagem não disponível">
                @endif
            </div>

            <div class="col-md-6">
                <h3>{{ __("História da Obra") }}</h3>
                <p>{!! $historia->first()->historia_obra ?? __('Informações sobre a história da obra não disponíveis.') !!}</p>
            </div>
        </div>

        <div class="container my-5">
            <div class="row">
                <div class="col-12">
                    <div class="card shadow">
                        <div class="card-body w-100">
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <h4 class="mb-0">Comentários</h4>
                                @auth
                                    <div class="d-flex align-items-center">
                                        <div class="me-3">
                                            @if (auth()->user()->photo)
                                                <img src="{{ asset(auth()->user()->photo) }}" class="rounded-circle"
                                                    style="width: 48px; height: 48px; object-fit: cover;"
                                                    alt="{{ auth()->user()->firstName }}" data-bs-toggle="modal"
                                                    data-bs-target="#imageModal">
                                            @else
                                                <div class="rounded-circle bg-primary text-white d-flex justify-content-center align-items-center"
                                                    style="width: 48px; height: 48px;">
                                                    <i class="fa-solid fa-user"></i>
                                                </div>
                                            @endif
                                        </div>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"
                                                id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                                {{ auth()->user()->firstName }}
                                            </button>
                                            <ul class="dropdown-menu" aria-labelledby="userDropdown">
                                                <li>
                                                    <a class="dropdown-item"
                                                        href="{{ route('paginas.cultura.arteSacra.edit', auth()->user()->id) }}?redirect_to={{ urlencode(url()->current()) }}">
                                                        <i class="fas fa-user-edit me-2"></i>Editar perfil
                                                    </a>
                                                </li>
                                                <li>
                                                    <form action="{{ route('paginas.cultura.arteSacra.logout') }}" method="POST">
                                                        @csrf
                                                        <button type="submit" class="dropdown-item">
                                                            <i class="fas fa-sign-out-alt me-2"></i>Sair
                                                        </button>
                                                    </form>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                @else
                                    <button id="showLoginModalBtn" class="btn btn-sm btn-primary">
                                        <i class="fas fa-sign-in-alt me-1"></i> Entrar para comentar
                                    </button>
                                @endauth
                            </div>

                            @if ($comentarios->isEmpty())
                                <div class="text-center py-4 border-top">
                                    <i class="far fa-comment-dots fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">Seja o primeiro a compartilhar seu conhecimento sobre esta obra
                                    </p>
                                </div>
                            @else
                                <div class="comment-list mb-4" style="max-height: 400px; overflow-y: auto;">
                                    @foreach ($comentarios as $comentario)
                                        <div class="comment-item p-3 border-bottom">
                                            <div class="d-flex">
                                                <div class="me-3">
                                                    <div class="rounded-circle bg-primary text-white d-flex justify-content-center align-items-center"
                                                        style="width: 40px; height: 40px;">
                                                        <i class="fa-solid fa-user"></i>
                                                    </div>
                                                </div>

                                                <div class="flex-grow-1 w-100" style="padding-top: 4px; padding-left: 4px">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <div>
                                                            <strong class="text-primary">
                                                                {{ $comentario->usuario->firstName . ' ' . $comentario->usuario->lastName }}
                                                            </strong>
                                                        </div>

                                                        <div class="d-flex align-items-center gap-2">
                                                            <small
                                                                class="text-muted mb-0">{{ $comentario->created_at->diffForHumans() }}</small>

                                                            @auth
                                                                @php
                                                                    $usuario = auth()->user();
                                                                    $permissao =
                                                                        auth()->check() &&
                                                                        collect(
                                                                            explode(',', $usuario->permission),
                                                                        )->contains(
                                                                            'GERENCIADOR_DO_CADASTRO_DE_ARTE_SACRA',
                                                                        );
                                                                @endphp

                                                                @if ($usuario->id === $comentario->user_id || $permissao)
                                                                    <form
                                                                        action="{{ route('paginas.cultura.arteSacra.destroy', $comentario->id) }}"
                                                                        method="POST" class="d-inline"
                                                                        style="margin-left: 8px">
                                                                        @csrf
                                                                        @method('DELETE')
                                                                        <button type="submit"
                                                                            class="btn btn-lg text-danger p-0"
                                                                            style="background-color: transparent;"
                                                                            onclick="return confirm('Tem certeza que deseja excluir este comentário?')"
                                                                            title="Excluir comentário">
                                                                            <i class="fas fa-trash-alt"></i>
                                                                        </button>
                                                                    </form>
                                                                @endif
                                                            @endauth
                                                        </div>
                                                    </div>

                                                    <p class="mb-0 text-dark">{{ $comentario->historia_obra }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            @endif

                            @auth
                                <div class="pt-4">
                                    <h5 class="mb-3">Adicione seu comentário</h5>
                                    <form action="{{ route('paginas.cultura.arteSacra.store', $arte->id) }}" method="POST">
                                        @csrf

                                        <input type="hidden" class="form-control" name="recaptcha" id="recaptcha">

                                        <input type="hidden" name="nome_usuario"
                                            value="{{ auth()->user()->firstName . ' ' . auth()->user()->lastName }}">

                                        <input type="hidden" class="form-control" id="email_usuario" name="email_usuario"
                                            required value="{{ auth()->user()->email }}" />

                                        <div class="mb-3">
                                            <textarea class="form-control @error('historia_obra') is-invalid @enderror" id="historia_obra" name="historia_obra"
                                                rows="4" placeholder="Compartilhe seu conhecimento sobre esta obra..." required>{{ old('historia_obra') }}</textarea>

                                            @error('historia_obra')
                                                <div class="invalid-feedback">
                                                    {{ $message }}
                                                </div>
                                            @enderror
                                        </div>

                                        <div class="d-flex justify-content-end">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-paper-plane me-2"></i> Enviar
                                            </button>
                                        </div>

                                        <div id='recaptchaLogin' data-size="invisible"></div>
                                    </form>
                                </div>
                            @endauth
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal para imagem de perfil -->
        @auth
            <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="imageModalLabel">Imagem de Perfil</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body text-center">
                            @if (auth()->user()->photo)
                                <img id="profileImageModal" src="{{ asset(auth()->user()->photo) }}"
                                    class="img-fluid rounded-circle" style="max-width: 100%; max-height: 70vh;"
                                    alt="Imagem do Perfil">
                            @else
                                <div class="d-flex justify-content-center align-items-center" style="height: 200px;">
                                    <i class="fas fa-user-circle fa-5x text-secondary"></i>
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        @endauth

        <div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content p-0 border-0 rounded-4">
                    <div class="card-admin-login text-white w-100 p-4 rounded-4" style="background-color: #342A21;">
                        <div class="modal-header border-0">
                            <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"
                                aria-label="Fechar"><i class="fa-solid fa-xmark fa-2x"></i></button>
                        </div>

                        <div class="modal-body">
                            <form method="POST" action="{{ route('paginas.cultura.arteSacra.login') }}">
                                @csrf
                                <div class="text-center mb-4">
                                    <img src="{{ asset('pmar/assets/img/logo-angra-branco.svg') }}"
                                        alt="Prefeitura Municipal de Angra dos Reis" class="img-fluid"
                                        style="width: 100%; height: 5rem;">
                                </div>

                                <h5 class="card-title text-center mb-4 text-white">Login</h5>
                                <input type="hidden" class="form-control" name="recaptcha" id="recaptcha">

                                <div class="mb-3">
                                    <label for="login" class="form-label fw-bold">Matrícula, CPF ou
                                        E-mail:</label>
                                    <input type="text" name="login" id="login"
                                        class="form-control @error('login') is-invalid @enderror"
                                        value="{{ old('login') }}" autocomplete="off">
                                    @error('login')
                                        <small class="text-warning fw-bold">{{ $message }}</small>
                                    @enderror
                                </div>

                                <div class="mb-3">
                                    <label for="password" class="form-label fw-bold">Senha:</label>
                                    <div class="input-group">
                                        <input type="password" name="password" id="password"
                                            class="form-control @error('password') is-invalid @enderror"
                                            autocomplete="off">
                                        <span class="input-group-text bg-transparent border-0">
                                            <button type="button" class="btn btn-sm show-password text-white"
                                                aria-label="Mostrar senha" id="togglePassword">
                                                <i class="fa-solid fa-eye text-dark"></i>
                                            </button>
                                        </span>
                                    </div>
                                    @error('password')
                                        <small class="text-warning fw-bold">{{ $message }}</small>
                                    @enderror
                                </div>

                                <div class="form-check form-switch mb-3 fs-5 d-flex justify-content-end">
                                    <p class="mt-2 text-light text-end">
                                        Esqueceu sua senha?
                                        <a href="#" id="openResetModal" class="text-white fw-bold"
                                            style="text-decoration: underline;">
                                            Clique aqui para resetar
                                        </a>
                                    </p>
                                </div>

                                <div class="text-center">
                                    <button type="submit" id="submitLogin" class="fs-4 rounded-4 primary-btn px-5 py-2">
                                        {{ __('Entrar') }}
                                    </button>
                                </div>
                                <div id='recaptchaLogin' data-size="invisible"></div>
                            </form>

                            <div class="mt-4 text-center">
                                <p class="text-light">
                                    Ainda não tem cadastro?
                                    <a href="{{ route('paginas.cultura.arteSacra.register') }}" class="text-white fw-bold"
                                        style="text-decoration: underline;">
                                        Clique aqui para se cadastrar!
                                    </a>
                                </p>
                            </div>

                            <div class="mt-3 text-center">
                                <p class="text-light">Apenas usuários cadastrados podem compartilhar histórias</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="resetPasswordModal" tabindex="-1" aria-labelledby="resetPasswordModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content p-0 border-0 rounded-4">
                    <div class="card-admin-login text-white w-100 p-4 rounded-4" style="background-color: #342A21;">
                        <div class="modal-header border-0">
                            <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"
                                aria-label="Fechar"><i class="fa-solid fa-xmark fa-2x"></i></button>
                        </div>

                        <div class="modal-body">
                            @if (session('showCodeField'))
                                <form method="POST" action="{{ route('paginas.cultura.arteSacra.validateCode') }}">
                                    @csrf
                                    <div class="mb-4">
                                        <label for="code" class="form-label fw-bold text-white">Código de
                                            Verificação:
                                            <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control @error('code') is-invalid @enderror"
                                            name="code" id="code" value="{{ old('code') }}" required>
                                        @error('code')
                                            <small class="text-warning fw-bold">{{ $message }}</small>
                                        @enderror
                                    </div>

                                    <div class="d-flex justify-content-center">
                                        <button type="submit" class="fs-4 rounded-4 primary-btn px-5 py-2">Validar
                                            Código</button>
                                    </div>
                                </form>
                            @else
                                <form method="POST" action="{{ route('paginas.cultura.arteSacra.reset') }}">
                                    @csrf
                                    <div class="text-center mb-4">
                                        <img src="{{ asset('pmar/assets/img/logo-angra-branco.svg') }}"
                                            alt="Prefeitura Municipal de Angra dos Reis" class="img-fluid"
                                            style="width: 100%; height: 5rem;">
                                    </div>

                                    <h5 class="card-title text-center mb-4 text-white fw-bold">Redefinir Senha</h5>

                                    <div class="mb-4">
                                        <label for="email" class="form-label fw-bold text-white">Email: <span
                                                class="text-danger">*</span></label>
                                        <input type="email" class="form-control @error('email') is-invalid @enderror"
                                            name="email" id="email" autocomplete="off"
                                            value="{{ old('email', $email ?? '') }}" required>
                                        @error('email')
                                            <small class="text-warning fw-bold">{{ $message }}</small>
                                        @enderror
                                    </div>

                                    <div class="d-flex justify-content-center">
                                        <button type="submit" class="fs-4 rounded-4 primary-btn px-5 py-2">Enviar
                                            Código</button>
                                    </div>
                                </form>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        main {
            background-color: #f8f9fa;
        }
    </style>
@endsection

@push('scripts')
    <script>
        @if ($errors->has('email') || session('showCodeField'))
            window.onload = function() {
                var resetPasswordModal = new bootstrap.Modal(document.getElementById('resetPasswordModal'));
                resetPasswordModal.show();
            };
        @endif

        document.getElementById('openResetModal').addEventListener('click', function(e) {
            e.preventDefault();

            const loginModalEl = document.getElementById('loginModal');
            const resetModalEl = document.getElementById('resetPasswordModal');

            const loginModal = bootstrap.Modal.getInstance(loginModalEl) || new bootstrap.Modal(loginModalEl);
            const resetModal = bootstrap.Modal.getInstance(resetModalEl) || new bootstrap.Modal(resetModalEl);

            loginModal.hide();

            loginModalEl.addEventListener('hidden.bs.modal', function handler() {
                resetModal.show();
                loginModalEl.removeEventListener('hidden.bs.modal', handler);
            });
        });

        const togglePassword = document.querySelector("#togglePassword");
        const passwordField = document.querySelector("#password");

        togglePassword.addEventListener("click", function() {
            const type = passwordField.type === "password" ? "text" : "password";
            passwordField.type = type;

            this.innerHTML = type === "password" ?
                '<i class="fa-solid fa-eye text-dark"></i>' :
                '<i class="fa-solid fa-eye-slash text-dark"></i>';
        });

        @guest
        document.getElementById('showLoginModalBtn').addEventListener('click', function() {
            var loginModal = new bootstrap.Modal(document.getElementById('loginModal'));
            loginModal.show();
        });

        @if ($errors->has('matriculation') || $errors->has('password'))
            window.onload = function() {
                var loginModal = new bootstrap.Modal(document.getElementById('loginModal'));
                loginModal.show();
            };
        @endif
        @endguest
    </script>
@endpush
