<?php

namespace App\Http\Controllers\Admin;

use App\Product;
use Morilog\Jalali;
use App\ProductOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class ShopController extends Controller
{
    public function index()
    {
        $products = Product::query()
            ->with(['category' => function ($model) {
                $model->where('active', 1)
                    ->select('id', 'title');
            }])
            ->select([
                'products.id',
                'products.title',
                'products.image',
                'products.product_price',
                'category_id',
            ])
            ->withSum(['productOrder as sum_final_price' => function($model) {
                $model->where('status', 'done');
            }], 'final_price')
            ->withSum(['productOrder as sum_delivery_price' => function($model) {
                $model->where('status', 'done');
            }], 'delivery_price')
            ->withSum(['productOrder as sum_quantity' => function($model) {
                $model->where('status', 'done');
            }], 'quantity')
            ->where('products.approved', 1)
            ->limit(5)
            ->get();

        $productOrder = ProductOrder::query()->where('status', 'done');

        $ordersCount    = $productOrder->count();
        $income = $productOrder->sum('final_price');
        $sumDeliveryPrice   = $productOrder->sum('delivery_price');
        $activeUsers        = $productOrder->distinct()->count('user_id');

        $pendingOrders  = ProductOrder::query()->whereIn('status', ['cart', 'payment-pending'])->count();

        $orders = ProductOrder::query()
            ->select('id', 'user_id', 'final_price', 'status', 'payment_method', 'created_at')
            ->with(['user' => function($query) {
                return $query->select(['id', 'name', 'family']);
            }])
            ->orderBy('updated_at', 'desc')
            ->limit(5)
            ->get();

        if(isset($orders))
            foreach ($orders as $order)
                $order->date = Jalali\CalendarUtils::strftime('H:i Y/m/d', strtotime($order->created_at));

        return view('admin.shop.shop', [
                'products'  => $products,
                'orders'    => $orders,
                'ordersCount'   => $ordersCount,
                'income'        => $income - $sumDeliveryPrice,
                'activeUsers'   => $activeUsers,
                'pendingOrders' => $pendingOrders
            ]
        );
    }
}
