@extends('layouts.base')

@section('body')
@php($tenant = app(\App\Support\Tenancy::class)->get())
<nav class="navbar mb-navbar py-2 sticky-top">
    <div class="container-fluid px-3">
        <span class="navbar-brand fw-bold display-font">🦷 {{ $tenant?->name ?? 'MediBook AI' }}</span>
        <div class="d-flex align-items-center gap-2">
            <a class="btn btn-sm mb-btn-ghost" href="?lang={{ app()->getLocale() === 'ar' ? 'en' : 'ar' }}">
                {{ app()->getLocale() === 'ar' ? 'EN' : 'عربي' }}
            </a>
            <button class="btn btn-sm mb-btn-ghost" onclick="mbToggleTheme()" aria-label="theme">◐</button>
            @auth
                <a class="btn btn-sm mb-btn-ghost position-relative" href="{{ route('tenant.notifications') }}" aria-label="{{ __('Notifications') }}">🔔
                    @if(($unreadCount ?? 0) > 0)
                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill text-bg-danger">{{ $unreadCount }}</span>
                    @endif
                </a>
                <form method="POST" action="{{ route('logout') }}" class="d-inline">
                    @csrf
                    <button class="btn btn-sm mb-btn-ghost">{{ __('Log out') }}</button>
                </form>
            @endauth
        </div>
    </div>
</nav>

<div class="d-flex">
    @auth
    <aside class="mb-sidebar p-3 d-none d-md-block">
        @foreach([
            ['tenant.dashboard', __('Dashboard'), '📊'],
            ['tenant.appointments.index', __('Calendar'), '📅'],
            ['tenant.patients.index', __('Patients'), '👤'],
            ['tenant.treatment-plans.index', __('Treatment plans'), '📋'],
            ['tenant.dentists.index', __('Dentists'), '🦷'],
            ['tenant.procedures.index', __('Procedures'), '🧰'],
            ['tenant.invoices.index', __('Invoices'), '🧾'],
            ['tenant.installments.index', __('Installments'), '💰'],
            ['tenant.whatsapp.index', __('WhatsApp'), '💬'],
            ['tenant.recalls.index', __('Recalls'), '🔔'],
            ['tenant.reports.revenue', __('Reports'), '📈'],
            ['tenant.exceptions.index', __('Days off'), '🌴'],
            ['tenant.whatsapp.templates', __('Templates'), '✏️'],
            ['tenant.billing', __('Billing'), '💳'],
        ] as [$route, $label, $icon])
            <a href="{{ route($route) }}"
               class="mb-navlink {{ request()->routeIs(str_replace('.index', '.*', $route)) || request()->routeIs($route) ? 'active' : '' }}">
                <span>{{ $icon }}</span> {{ $label }}
            </a>
        @endforeach
    </aside>
    @endauth

    <main class="flex-grow-1 p-3 p-md-4 mb-has-bottomnav">
        @isset($subscriptionInGrace)
            <div class="alert alert-warning">
                ⚠ {{ __('Your subscription has expired. Renew to regain access.') }}
                — <a href="{{ route('tenant.billing') }}">{{ __('Billing') }}</a>
            </div>
        @endisset
        @isset($waUsage)
            @if($waUsage['level'] === 'warn')
                <div class="alert alert-warning py-2">
                    📊 {{ __('You have used :used of :limit WhatsApp messages this month.', ['used' => $waUsage['used'], 'limit' => $waUsage['limit']]) }}
                    <a href="{{ route('tenant.billing') }}">{{ __('Upgrade') }}</a>
                </div>
            @elseif($waUsage['level'] === 'over')
                <div class="alert alert-danger py-2">
                    📊 {{ __('You have reached your monthly WhatsApp limit (:limit). Messages still send, but consider upgrading.', ['limit' => $waUsage['limit']]) }}
                    <a href="{{ route('tenant.billing') }}">{{ __('Upgrade') }}</a>
                </div>
            @endif
        @endisset
        @if(session('status'))<div class="alert alert-success">{{ session('status') }}</div>@endif
        @if(session('error'))<div class="alert alert-danger">{{ session('error') }}</div>@endif

        @yield('content')
    </main>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
@auth
{{-- Mobile bottom navigation (app-like, <md only) --}}
<nav class="mb-bottomnav d-md-none">
    @foreach([
        ['tenant.dashboard', __('Home'), '📊'],
        ['tenant.appointments.index', __('Calendar'), '📅'],
        ['tenant.patients.index', __('Patients'), '👤'],
        ['tenant.treatment-plans.index', __('Plans'), '📋'],
    ] as [$route, $label, $icon])
        <a href="{{ route($route) }}" class="{{ request()->routeIs(str_replace('.index', '.*', $route)) || request()->routeIs($route) ? 'active' : '' }}">
            <span class="ico">{{ $icon }}</span>{{ $label }}
        </a>
    @endforeach
    <a href="#" data-bs-toggle="offcanvas" data-bs-target="#moreNav"><span class="ico">☰</span>{{ __('More') }}</a>
</nav>

<div class="offcanvas offcanvas-bottom" tabindex="-1" id="moreNav" style="height:auto; background:var(--mb-surface); color:var(--mb-ink)">
    <div class="offcanvas-body">
        @foreach([
            ['tenant.invoices.index', __('Invoices'), '🧾'],
            ['tenant.installments.index', __('Installments'), '💰'],
            ['tenant.whatsapp.index', __('WhatsApp'), '💬'],
            ['tenant.recalls.index', __('Recalls'), '🔔'],
            ['tenant.reports.revenue', __('Reports'), '📈'],
            ['tenant.whatsapp.templates', __('Templates'), '✏️'],
            ['tenant.dentists.index', __('Dentists'), '🦷'],
            ['tenant.procedures.index', __('Procedures'), '🧰'],
            ['tenant.exceptions.index', __('Days off'), '🌴'],
            ['tenant.billing', __('Billing'), '💳'],
        ] as [$route, $label, $icon])
            <a href="{{ route($route) }}" class="mb-navlink">{{ $icon }} {{ $label }}</a>
        @endforeach
        <form method="POST" action="{{ route('logout') }}">@csrf
            <button class="mb-navlink w-100 border-0 bg-transparent text-start">🚪 {{ __('Log out') }}</button>
        </form>
    </div>
</div>
@endauth
<script>
// Quick-pay: Zain Cash / bank transfer need a reference — intercept first tap,
// reveal the field, submit on second tap. Cash/card submit immediately.
document.addEventListener('click', (e) => {
    const btn = e.target.closest('.qp-method');
    if (!btn) return;
    const needsRef = ['zaincash', 'bank_transfer'].includes(btn.value);
    const form = btn.closest('form');
    const ref = form.querySelector('.qp-ref');
    if (needsRef && ref.classList.contains('d-none')) {
        e.preventDefault();
        ref.classList.remove('d-none');
        ref.required = true;
        ref.focus();
        // remember chosen method for the actual submit
        form.dataset.method = btn.value;
    } else if (needsRef === false && ref) {
        ref.required = false;
    }
});
document.addEventListener('submit', (e) => {
    const form = e.target.closest('form.quickpay');
    if (!form) return;
    // if a method was stashed (reference flow), inject it
    if (form.dataset.method && !e.submitter?.classList.contains('qp-method')) {
        const i = document.createElement('input');
        i.type = 'hidden'; i.name = 'method'; i.value = form.dataset.method;
        form.appendChild(i);
    }
});
</script>
@stack('page-scripts')
@endsection
