<?php

namespace App\Services\User;

use App\Models\Product;
use Illuminate\Http\Request;

class DashboardService
{
    /** get favorite product list */
    public function getProductFavorites()
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        $productFavorites = $user->productFavorites()->take(3)->get()->map(fn($productFavorite) => [
            'product' => $productFavorite->get_product
        ]);

        return $productFavorites;
    }

    /** get product history list */
    public function getProductHistory(Request $request)
    {
        $productHitsory = $request->session()->get('last_viewed_product');
        if ($productHitsory != null || (is_array($productHitsory) && count($productHitsory) > 0)) {
            if (count($productHitsory) > 3) {
                $productHitsory = array_slice($productHitsory, -3, 3, true);
            }

            $productTemp = [];
            foreach ($productHitsory as $ph) {
                $product = Product::where('id', $ph['id'])->where('status', 'publish')->first();
                if ($product != null) {
                    $productTemp[] = [
                        'title' => $product->title,
                        'slug' => $product->slug,
                        'status' => $product->status,
                        'get_images' => $product->get_images,
                        'in_stock_status' => $product->in_stock_status,
                        'inventory' => $product->inventory,
                        'best_price' => $product->best_price,
                        'unique_color' => $product->unique_color,
                        'comments_info' => $product->comments_info,
                    ];
                }
            }

            $productHitsory = $productTemp;
            $productHitsory = array_reverse($productHitsory);
        } else {
            $productHitsory = [];
        }

        return $productHitsory;
    }

    /** get latest orders */
    public function getLatestOrders($count)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        $orders =  $user->orders()->where('status', '!=', 'awaiting')->where('status', '!=', 'prefactor')->orderBy('created_at', 'desc')->take($count)->get()->map(fn($order) => [
            'id' => $order->id,
            'uuid' => $order->uuid,
            'get_total_bill' => $order->get_total_bill,
            'get_discount' => $order->get_discount,
            'status' => $order->status,
            'jalali_created_at' => $order->jalali_created_at,
        ]);

        return $orders;
    }
}
