<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="app-base-url" content="{{ config('app.url') }}">

    <title>{{ config('app.name', 'AdminFit') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])

    <style>
    body {
        @if(!empty($company?->url_imagen_back))
            background-image: url('{{ route('user_fit.company.image', $company->url_imagen_back) }}') !important;
        @endif
    }
    .rate-capsule {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 3px 10px;
        border-radius: 999px;
        font-size: 0.75rem;
        font-weight: 600;
        background: rgba(255, 255, 255, 0.15);
        color: rgba(255, 255, 255, 0.9);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }
    </style>
    @stack('styles')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-dark bg-dark shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/home') }}">
                    {{ config('app.name', 'AdminFit') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">Ingresar</a>
                                </li>
                            @endif
                            {{-- 
                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                            --}}


                        @else
                            @if (!empty($rateTodayInfo['is_active_today']) && isset($rateTodayInfo['usd_rate']))
                            <li class="nav-item d-flex align-items-center me-3">
                                <span class="rate-capsule">
                                    1$ USD = {{ number_format((float) $rateTodayInfo['usd_rate'], 2, ',', '.') }}
                                </span>
                            </li>
                            @endif
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                    @if(Auth::user()->roles->isNotEmpty())
                                        <small class="badge bg-info ms-1">{{ Auth::user()->getRoleNames()->first() }}</small>
                                    @endif
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                        <a class="dropdown-item" href="{{ route('user_fit.edituser', Auth::user()) }}">
                                            {{ __('Editar usuario') }}
                                        </a>
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                        onclick="event.preventDefault();
                                                document.getElementById('logout-form').submit();">
                                        {{ __('Cerrar sesión') }}
                                    </a>
                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @if (!empty($rateWarning))
            <div class="container-fluid mt-1">
                <div class="rate-alert-shell">
                    <div class="rate-alert-left">
                        <form
                            method="POST"
                            action="{{ $rateWarning['quick_store_link'] ?? route('admin_fit.rate.quick_store') }}"
                            class="rate-quick-form js-quick-rate-form"
                        >
                            @csrf
                            <input type="hidden" name="return_to" value="{{ $rateWarning['return_to'] ?? request()->fullUrl() }}">
                            <div class="rate-alert-inline-row">
                                <div class="rate-alert-inline-message">
                                    <span class="rate-alert-title d-inline">Tasa pendiente del día.</span>
                                    <span class="rate-alert-message d-inline">{{ $rateWarning['message'] }}</span>
                                </div>
                                <div class="rate-alert-inline-form">
                                    <input
                                        type="text"
                                        id="quick_usd_rate"
                                        name="usd_rate"
                                        class="form-control form-control-sm js-quick-rate-input"
                                        placeholder="Ej: 1.234,5678"
                                        inputmode="decimal"
                                        autocomplete="off"
                                        required
                                    >
                                </div>
                                <div class="rate-alert-inline-actions">
                                    <button type="submit" class="btn btn-sm btn-outline-dark">Guardar tasa</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        @endif

        <main class="py-1">
            @auth
                <div class="wrapper">
                    <!-- Sidebar -->
                    <aside id="sidebar" class="collapsed">
                            <div class="h-100">
                                <div class="sidebar-logo">
                                    <a href="{{ url('/home') }}">
                                        @if(!empty($company?->url_logo_header))
                                            <img
                                                src="{{ route('user_fit.company.image', $company->url_logo_header) }}"
                                                alt="Logo empresa"
                                                style="max-height: 60px; width: auto;"
                                            >
                                        @else
                                            {{ config('app.name', 'Laravel') }}
                                        @endif
                                    </a>
                                </div>
                                <!-- Sidebar Navigation -->
                                <ul class="sidebar-nav">
                                    <li class="sidebar-header">
                                        Menú Principal
                                    </li>
                                    @role('Cliente')
                                    <li class="sidebar-item">
                                        <a href="{{ route('user_fit.dashboard') }}" class="sidebar-link">
                                            <i class="bi bi-grid-1x2-fill pe-2"></i>
                                            Mi dashboard
                                        </a>
                                    </li>
                                    <li class="sidebar-item">
                                        <a href="{{ route('user_fit.pay.create') }}" class="sidebar-link">
                                            <i class="bi bi-credit-card-fill pe-2"></i>
                                            Agregar pago
                                        </a>
                                    </li>
                                    @endrole
                                    @role('Administrador|Empleado')
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashclientes"
                                            aria-expanded="false" aria-controls="dashclientes">
                                            <i class="bi bi-people-fill pe-2"></i>
                                            Clientes
                                        </a>
                                        <ul id="dashclientes" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.users.index') }}" class="sidebar-link">
                                                    <i class="bi bi-person-lines-fill pe-2"></i>
                                                    Usuarios
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.assistance.takeAssistance') }}" class="sidebar-link">
                                                <i class="bi bi-clipboard-check-fill pe-2"></i>
                                                    Tomar asistencia
                                                </a>
                                            </li>

                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.assistance.index') }}" class="sidebar-link">
                                                <i class="bi bi-bar-chart-fill pe-2"></i>
                                                    Reporte de Asistencia
                                                </a>
                                            </li>
                                            {{-- <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.assistance.history') }}" class="sidebar-link">
                                                <i class="fa-solid fa-list pe-2"></i>
                                                    Asistencia historico
                                                </a>
                                            </li> --}}
                                        </ul>
                                    </li>
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashcobranzas"
                                            aria-expanded="false" aria-controls="dashcobranzas">
                                            <i class="bi bi-wallet2 pe-2"></i>
                                            Cobranzas
                                        </a>
                                        <ul id="dashcobranzas" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.pay.index') }}" class="sidebar-link">
                                                    <i class="bi bi-cash-stack pe-2"></i>
                                                    Pagos
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashventas"
                                            aria-expanded="false" aria-controls="dashventas">
                                            <i class="bi bi-cart-fill pe-2"></i>
                                            Ventas
                                        </a>
                                        <ul id="dashventas" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.product.index') }}" class="sidebar-link">
                                                <i class="bi bi-box-seam-fill pe-2"></i>
                                                    Productos
                                                </a>
                                            </li>
											<li class="sidebar-item  ps-3">
												<a href="{{ route('admin_fit.pos.index') }}" class="sidebar-link">
													<i class="bi bi-shop pe-2"></i>
													POS
												</a>
											</li>

                                            @if(env('SHOW_PART_TWO'))
											<li class="sidebar-item  ps-3">
												<a href="{{ route('admin_fit.sales.index') }}" class="sidebar-link">
													<i class="bi bi-graph-up-arrow pe-2"></i>
													Ventas
												</a>
											</li>
                                            @endif
                                        </ul>
                                    </li> 
                                    
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashcompras"
                                            aria-expanded="false" aria-controls="dashcompras">
                                            <i class="bi bi-bag-fill pe-2"></i>
                                            Compras
                                        </a>
                                        <ul id="dashcompras" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.bill.index') }}" class="sidebar-link">
                                                <i class="bi bi-receipt pe-2"></i>
                                                    Compras
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.pay_bill.index') }}" class="sidebar-link">
                                                <i class="bi bi-cash-coin pe-2"></i>
                                                    Pagos Internos
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.supplier.index') }}" class="sidebar-link">
                                                <i class="bi bi-truck pe-2"></i>
                                                    Proveedores
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashconfig"
                                            aria-expanded="false" aria-controls="dashconfig">
                                            <i class="bi bi-gear-fill pe-2"></i>
                                            Configuraciones
                                        </a>
                                        <ul id="dashconfig" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.membership.index') }}" class="sidebar-link">
                                                <i class="bi bi-card-checklist pe-2"></i>
                                                    Membresías
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.entry_time.index') }}" class="sidebar-link">
                                                <i class="bi bi-clock pe-2"></i>
                                                    Horarios
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.rate.index') }}" class="sidebar-link">
                                                <i class="bi bi-currency-exchange pe-2"></i>
                                                    Tasas de cambio
                                                </a>
                                            </li>
                                            @role('Administrador')
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.company.edit') }}" class="sidebar-link">
                                                    <i class="bi bi-building pe-2"></i>
                                                    Empresa
                                                </a>
                                            </li>
                                            @endrole
                                        </ul>
                                    </li>
                                    @endrole

                                    @role('SuperAdmin')
                                    <li class="sidebar-item">
                                        <a href="#" class="sidebar-link collapsed" data-bs-toggle="collapse" data-bs-target="#dashsuperadmin"
                                            aria-expanded="false" aria-controls="dashsuperadmin">
                                            <i class="bi bi-shield-lock pe-2"></i>
                                            Super Admin
                                        </a>
                                        <ul id="dashsuperadmin" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.super_admin.companies.index') }}" class="sidebar-link">
                                                    <i class="bi bi-building pe-2"></i>
                                                    Empresas
                                                </a>
                                            </li>
                                            <li class="sidebar-item  ps-3">
                                                <a href="{{ route('admin_fit.super_admin.users.create') }}" class="sidebar-link">
                                                    <i class="bi bi-person-plus pe-2"></i>
                                                    Crear Usuario
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    @endrole

                                    <!-- <li class="sidebar-item">
                                        <a href="{{ route('admin_fit.users.index') }}" class="sidebar-link">
                                            <i class="fa-solid fa-list pe-2"></i>
                                            link ejemplo
                                        </a>
                                    </li> -->
                                </ul>
                            </div>
                        </aside>
                        <!-- Main Component -->
                        <div class="main">
                            <div class="py-2 px-3">
                                <button class="btn sidebar-toggle-btn" type="button">
                                    <span class="navbar-toggler-icon"></span>
                                </button>
                            </div>
                            <main class="content px-3 py-2">
                                <div class="container-fluid">
                                    @yield('content')
                                </div>
                            </main>
                        </div>
                    </div>
            @else
                <main class="content px-3 py-2">
                    <div class="container-fluid">
                        @yield('content')
                    </div>
                </main>
            @endauth
        </main>
    </div>
    <script>
document.addEventListener('DOMContentLoaded', function () {
    const quickRateForm = document.querySelector('.js-quick-rate-form');
    if (!quickRateForm) {
        return;
    }

    const rateInput = quickRateForm.querySelector('.js-quick-rate-input');
    let isConfirmedSubmit = false;

    const keepAllowedChars = (value) => value.replace(/[^\d,]/g, '');

    const formatRateEs = (value) => {
        const cleaned = keepAllowedChars(value);
        const parts = cleaned.split(',');
        const hasComma = cleaned.includes(',');
        const integerRaw = (parts[0] || '').replace(/^0+(?=\d)/, '');
        const integerPart = integerRaw.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        const decimalPart = parts.slice(1).join('').slice(0, 4);

        if (decimalPart.length > 0) {
            return `${integerPart || '0'},${decimalPart}`;
        }

        if (hasComma) {
            return `${integerPart || '0'},`;
        }

        return integerPart;
    };

    const toBackendDecimal = (value) => {
        if (!value) {
            return '';
        }
        return value.replace(/\./g, '').replace(',', '.');
    };

    const validateRate = () => {
        const formatted = (rateInput?.value || '').trim();
        const normalized = toBackendDecimal(formatted);
        const numericValue = Number(normalized);
        const regex = /^\d+(\.\d{1,4})?$/;

        if (!formatted || !regex.test(normalized) || Number.isNaN(numericValue) || numericValue <= 0) {
            rateInput.setCustomValidity('Ingrese una tasa válida con formato 1.234,5678 (máximo 4 decimales).');
            return false;
        }

        rateInput.setCustomValidity('');
        return true;
    };

    rateInput?.addEventListener('input', function () {
        rateInput.value = formatRateEs(rateInput.value);
        validateRate();
    });

    quickRateForm.addEventListener('submit', async function (event) {
        if (isConfirmedSubmit) {
            return;
        }

        event.preventDefault();
        event.stopPropagation();

        rateInput.value = formatRateEs(rateInput.value);

        if (!validateRate()) {
            rateInput.reportValidity();
            return;
        }

        const rateToConfirm = rateInput.value.trim();
        let confirmed = false;

        if (typeof Swal !== 'undefined' && typeof Swal.fire === 'function') {
            const result = await Swal.fire({
                title: 'Confirmar tasa rápida',
                html: `Se guardará la tasa del día: <strong>${rateToConfirm}</strong>`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Sí, guardar',
                cancelButtonText: 'Cancelar',
                reverseButtons: true,
                allowOutsideClick: true,
            });
            confirmed = result.isConfirmed;
        } else {
            confirmed = window.confirm(`¿Deseas guardar esta tasa rápida?\n\nTasa: ${rateToConfirm}`);
        }

        if (!confirmed) {
            return;
        }

        rateInput.value = toBackendDecimal(rateInput.value);
        isConfirmedSubmit = true;
        quickRateForm.submit();
    });
});
</script>
    @stack('scripts')
</body>
</html>
