@php
    use Illuminate\Support\Facades\DB;
    use App\Models\Order;
    use App\Models\Payment;
    use App\Models\InventoryItem;
    use Illuminate\Support\Facades\Auth;

    /*
    |--------------------------------------------------------------------------
    | CURRENT USER
    |--------------------------------------------------------------------------
    */

    $currentUser = Auth::user();


    /*
    |--------------------------------------------------------------------------
    | SETTINGS
    |--------------------------------------------------------------------------
    |
    | Your settings table may not have "key" and "value" columns.
    | Therefore we safely read the first settings record.
    |
    */

    $appSettings = DB::table('settings')->first();

    /*
    |--------------------------------------------------------------------------
    | NOTIFICATION SETTINGS
    |--------------------------------------------------------------------------
    */

    $notifyLowStock = true;
    $notifyNewOrder = true;
    $notifyPayment = true;

    $lowStockAlert = 10;

    if ($appSettings) {

        if (isset($appSettings->notify_low_stock)) {
            $notifyLowStock = (bool) $appSettings->notify_low_stock;
        }

        if (isset($appSettings->notify_new_order)) {
            $notifyNewOrder = (bool) $appSettings->notify_new_order;
        }

        if (isset($appSettings->notify_payment)) {
            $notifyPayment = (bool) $appSettings->notify_payment;
        }

        if (isset($appSettings->low_stock_alert)) {
            $lowStockAlert = (int) $appSettings->low_stock_alert;
        }
    }


    /*
    |--------------------------------------------------------------------------
    | NEW ORDERS
    |--------------------------------------------------------------------------
    */

    $recentOrders = collect();

    if ($notifyNewOrder) {
        $recentOrders = Order::with(['customer', 'status'])
            ->orderByDesc('order_id')
            ->limit(5)
            ->get();
    }


    /*
    |--------------------------------------------------------------------------
    | NEW ORDER COUNT
    |--------------------------------------------------------------------------
    */

    $newOrderCount = 0;

    if ($notifyNewOrder) {
        $newOrderCount = Order::whereHas('status', function ($query) {
            $query->whereRaw('LOWER(status_name) = ?', ['pending']);
        })->count();
    }


    /*
    |--------------------------------------------------------------------------
    | LOW STOCK
    |--------------------------------------------------------------------------
    */

    $lowStockItems = collect();

    if ($notifyLowStock) {

        try {

            $lowStockItems = InventoryItem::where('quantity', '<=', $lowStockAlert)
                ->orderBy('quantity', 'asc')
                ->limit(5)
                ->get();

        } catch (\Throwable $e) {

            $lowStockItems = collect();

        }
    }


    /*
    |--------------------------------------------------------------------------
    | PAYMENTS
    |--------------------------------------------------------------------------
    */

    $recentPayments = collect();

    if ($notifyPayment) {

        try {

            $recentPayments = Payment::orderByDesc('payment_id')
                ->limit(5)
                ->get();

        } catch (\Throwable $e) {

            $recentPayments = collect();

        }
    }


    /*
    |--------------------------------------------------------------------------
    | NOTIFICATION COUNT
    |--------------------------------------------------------------------------
    */

    $notificationCount =
        ($notifyNewOrder ? $newOrderCount : 0)
        + ($notifyLowStock ? $lowStockItems->count() : 0)
        + ($notifyPayment ? $recentPayments->count() : 0);

@endphp


<div class="iq-top-navbar">

    <div class="iq-navbar-custom">

        <nav class="navbar navbar-expand-lg navbar-light p-0">


            {{-- =====================================================
                 LOGO
            ====================================================== --}}

            <div class="iq-navbar-logo d-flex align-items-center justify-content-between">

                <i class="ri-menu-line wrapper-menu"></i>

                <a href="{{ route('dashboard') }}" class="header-logo">

                    <img
                        src="{{ asset('assets/images/logo.png') }}"
                        class="img-fluid rounded-normal"
                        alt="logo"
                    >

                    <h5 class="logo-title ml-3">
                        Z&T Stationary
                    </h5>

                </a>

            </div>


            {{-- =====================================================
                 SEARCH
            ====================================================== --}}

            <div class="iq-search-bar device-search">

                <form
                    action="{{ route('orders.list') }}"
                    method="GET"
                    class="searchbox"
                >

                    <a
                        class="search-link"
                        href="{{ route('orders.list') }}"
                    >
                        <i class="ri-search-line"></i>
                    </a>

                    <input
                        type="text"
                        name="search"
                        class="text search-input"
                        placeholder="Search orders or customers..."
                        value="{{ request('search') }}"
                    >

                </form>

            </div>


            {{-- =====================================================
                 RIGHT NAVBAR
            ====================================================== --}}

            <div class="d-flex align-items-center">

                <button
                    class="navbar-toggler"
                    type="button"
                    data-toggle="collapse"
                    data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent"
                    aria-label="Toggle navigation"
                >

                    <i class="ri-menu-3-line"></i>

                </button>


                <div
                    class="collapse navbar-collapse"
                    id="navbarSupportedContent"
                >

                    <ul class="navbar-nav ml-auto navbar-list align-items-center">




                        {{-- =================================================
                             CREATE ORDER
                        ================================================== --}}

                        <li>

                            <a
                                href="{{ route('orders.add') }}"
                                class="btn border add-btn shadow-none mx-2 d-none d-md-block"
                            >

                                <i class="las la-plus mr-2"></i>

                                Create Order

                            </a>

                        </li>


                        {{-- =================================================
                             SEARCH ICON
                        ================================================== --}}

                        <li class="nav-item nav-icon search-content">

                            <a
                                href="#"
                                class="search-toggle rounded"
                                id="dropdownSearch"
                                data-toggle="dropdown"
                                aria-haspopup="true"
                                aria-expanded="false"
                            >

                                <i class="ri-search-line"></i>

                            </a>


                            <div
                                class="iq-search-bar iq-sub-dropdown dropdown-menu"
                                aria-labelledby="dropdownSearch"
                            >

                                <form
                                    action="{{ route('orders.list') }}"
                                    method="GET"
                                    class="searchbox p-2"
                                >

                                    <div class="form-group mb-0 position-relative">

                                        <input
                                            type="text"
                                            name="search"
                                            class="text search-input font-size-12"
                                            placeholder="Search orders or customers..."
                                        >

                                        <button
                                            type="submit"
                                            class="btn btn-link position-absolute"
                                            style="right:5px; top:2px;"
                                        >

                                            <i class="ri-search-line"></i>

                                        </button>

                                    </div>

                                </form>

                            </div>

                        </li>


                        {{-- =================================================
                             NOTIFICATIONS
                        ================================================== --}}

                        <li class="nav-item nav-icon dropdown">

                            <a
                                href="#"
                                class="search-toggle dropdown-toggle"
                                id="notificationDropdown"
                                data-toggle="dropdown"
                                aria-haspopup="true"
                                aria-expanded="false"
                            >

                                <i class="ri-notification-3-line"></i>

                                @if($notificationCount > 0)

                                    <span class="bg-danger dots"></span>

                                @endif

                            </a>


                            <div
                                class="iq-sub-dropdown dropdown-menu"
                                aria-labelledby="notificationDropdown"
                                style="width:370px;"
                            >

                                <div class="iq-card shadow-none m-0">


                                    {{-- HEADER --}}

                                    <div class="iq-card-header d-flex justify-content-between align-items-center">

                                        <div class="iq-header-title">

                                            <h5 class="card-title mb-0">
                                                Notifications
                                            </h5>

                                        </div>

                                        @if($notificationCount > 0)

                                            <span class="badge badge-danger">
                                                {{ $notificationCount }}
                                            </span>

                                        @endif

                                    </div>


                                    <div class="iq-card-body p-0">


                                        {{-- =================================================
                                             LOW STOCK NOTIFICATIONS
                                        ================================================== --}}

                                        @if($notifyLowStock)

                                            @foreach($lowStockItems as $item)

                                                <a
                                                    href="{{ route('inventory.list') }}"
                                                    class="iq-sub-card d-flex align-items-center"
                                                >

                                                    <div class="rounded-circle iq-card-icon bg-warning-light">

                                                        <i class="ri-error-warning-line"></i>

                                                    </div>

                                                    <div class="ml-3">

                                                        <h6 class="mb-1">
                                                            Low Stock Alert
                                                        </h6>

                                                        <small class="text-muted">

                                                            {{ $item->item_name ?? $item->name ?? 'Inventory Item' }}

                                                            -

                                                            <span class="text-danger">
                                                                {{ $item->quantity ?? 0 }} left
                                                            </span>

                                                        </small>

                                                    </div>

                                                </a>

                                            @endforeach

                                        @endif


                                        {{-- =================================================
                                             NEW ORDER NOTIFICATIONS
                                        ================================================== --}}

                                        @if($notifyNewOrder)

                                            @foreach($recentOrders as $order)

                                                @php

                                                    $statusName = strtolower(
                                                        $order->status->status_name ?? 'pending'
                                                    );

                                                @endphp


                                                <a
                                                    href="{{ route('orders.list') }}"
                                                    class="iq-sub-card d-flex align-items-center"
                                                >

                                                    <div class="rounded-circle iq-card-icon bg-primary-light">

                                                        <i class="ri-shopping-cart-line"></i>

                                                    </div>


                                                    <div class="ml-3">

                                                        <h6 class="mb-1">

                                                            New Order

                                                            <small class="text-muted">
                                                                #{{ $order->serial_number }}
                                                            </small>

                                                        </h6>


                                                        <div class="d-flex align-items-center">

                                                            <small class="text-muted">

                                                                {{ $order->customer->customer_name ?? 'Unknown Customer' }}

                                                            </small>

                                                            <span class="mx-1">
                                                                •
                                                            </span>

                                                            <small
                                                                class="
                                                                @if($statusName === 'pending')
                                                                    text-warning
                                                                @elseif($statusName === 'completed' || $statusName === 'delivered')
                                                                    text-success
                                                                @else
                                                                    text-info
                                                                @endif
                                                                "
                                                            >

                                                                {{ $order->status->status_name ?? 'Pending' }}

                                                            </small>

                                                        </div>

                                                    </div>

                                                </a>

                                            @endforeach

                                        @endif


                                        {{-- =================================================
                                             PAYMENT NOTIFICATIONS
                                        ================================================== --}}

                                        @if($notifyPayment)

                                            @foreach($recentPayments as $payment)

                                                <a
                                                    href="{{ route('payments.index') }}"
                                                    class="iq-sub-card d-flex align-items-center"
                                                >

                                                    <div class="rounded-circle iq-card-icon bg-success-light">

                                                        <i class="ri-money-dollar-circle-line"></i>

                                                    </div>

                                                    <div class="ml-3">

                                                        <h6 class="mb-1">
                                                            Payment Received
                                                        </h6>

                                                        <small class="text-muted">

                                                            Payment #{{ $payment->payment_id }}

                                                        </small>

                                                    </div>

                                                </a>

                                            @endforeach

                                        @endif


                                        {{-- =================================================
                                             EMPTY STATE
                                        ================================================== --}}

                                        @if(
                                            (!$notifyLowStock || $lowStockItems->isEmpty()) &&
                                            (!$notifyNewOrder || $recentOrders->isEmpty()) &&
                                            (!$notifyPayment || $recentPayments->isEmpty())
                                        )

                                            <div class="text-center p-4">

                                                <i
                                                    class="ri-notification-off-line text-muted"
                                                    style="font-size:30px;"
                                                ></i>

                                                <p class="mb-0 mt-2 text-muted">
                                                    No notifications
                                                </p>

                                            </div>

                                        @endif


                                        {{-- VIEW ALL --}}

                                        <div class="text-center p-2 border-top">

                                            <a
                                                href="{{ route('orders.list') }}"
                                                class="text-primary"
                                            >
                                                View All Orders
                                            </a>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </li>


                        {{-- =================================================
                             USER PROFILE
                        ================================================== --}}

                        <li class="nav-item nav-icon dropdown">

                            <a
                                href="#"
                                class="search-toggle dropdown-toggle"
                                id="profileDropdown"
                                data-toggle="dropdown"
                                aria-haspopup="true"
                                aria-expanded="false"
                            >

                                <div class="iq-waves-effect d-flex align-items-center">

                                    <img
                                        src="{{ asset('assets/images/user/1.png') }}"
                                        class="img-fluid rounded-circle mr-2"
                                        style="width:35px;height:35px;object-fit:cover;"
                                        alt="profile"
                                    >

                                    <span class="ml-1">

                                        {{ $currentUser->user_name ?? $currentUser->name ?? 'User' }}

                                    </span>

                                </div>

                            </a>


                            <div
                                class="iq-sub-dropdown dropdown-menu"
                                aria-labelledby="profileDropdown"
                            >

                                <div class="iq-card shadow-none m-0">

                                    <div class="iq-card-body p-0">


                                        <div class="bg-primary text-white text-center p-3">

                                            <img
                                                src="{{ asset('assets/images/user/1.png') }}"
                                                alt="profile"
                                                class="rounded-circle"
                                                style="width:70px;height:70px;object-fit:cover;"
                                            >


                                            <h5 class="mt-2 mb-1 text-white">

                                                {{ $currentUser->user_name ?? $currentUser->name ?? 'User' }}

                                            </h5>


                                            <p class="mb-0">

                                                {{ optional($currentUser->role)->role_name ?? 'User' }}

                                            </p>

                                        </div>


                                        <div class="p-3">

                                            <a
                                                href="{{ route('dashboard') }}"
                                                class="btn border mr-2"
                                            >
                                                Profile
                                            </a>


                                            <form
                                                action="{{ route('logout') }}"
                                                method="POST"
                                                style="display:inline;"
                                            >

                                                @csrf

                                                <button
                                                    type="submit"
                                                    class="btn border"
                                                >
                                                    Sign Out
                                                </button>

                                            </form>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </li>


                    </ul>

                </div>

            </div>

        </nav>

    </div>

</div>


