<?php

namespace Modules\User\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use App\Models\WebsiteVisitor;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use Modules\Canteen\Services\CanteenService;
use Modules\Category\Models\Category;
use Modules\Order\Enums\OrderStatusEnum;
use Modules\Order\Services\OrderService;
use Modules\Product\Models\Product;
use Modules\School\Services\SchoolService;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Models\User;
use Modules\User\Services\UserService;

class DashboardController extends Controller
{

    public function __construct(
        private SchoolService $schoolService,
        private UserService $userService,
        private CanteenService $canteenService,
        private OrderService $orderService,

    )
    {}

    /**
     * Show the stats of the website.٫٣
     *
     * @return Factory|View
     */
    public function stats(Request $request)
    {
        $subscribtions= [];
        for ($i=1; $i < 13; $i++) {
            $month= ($request->year ?? date('Y')).'-'.($i<10 ? '0'.$i : $i);
            $subscribtions[] = [
                'month'=> $i,
                'value'=> WebsiteVisitor::whereRaw("DATE_FORMAT(created_at, '%Y-%m') = '". $month ."'")->count()
            ];
        }
        return response()->json($subscribtions);
    }

    public function index(Request $request) :View
    {
        $date = date('Y-m-d H:i:s',strtotime('- 5 min'));
        $allUsersCounts = WebsiteVisitor::count();
        $nowUsersCounts = WebsiteVisitor::whereDate('updated_at','>=',$date)->count();
        $dayUsers = WebsiteVisitor::whereRaw('DATE(created_at) = CURRENT_DATE')->count();
        $weekUsers = WebsiteVisitor::whereRaw('YEARWEEK(created_at) = YEARWEEK(CURRENT_DATE)')->count();
        $monthUsers = WebsiteVisitor::whereRaw("DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(CURRENT_DATE, '%Y-%m')")->count();
        $yearUsers = WebsiteVisitor::whereRaw("YEAR(created_at) = YEAR(CURRENT_DATE)")->count();

        $parents = $this->userService->get(['role'=>UserRoleEnum::PARENT->value])->count();
        $user_canteens = $this->canteenService->get()->count();
        $schools = $this->schoolService->get()->count();
        $orders = $this->orderService->get()->sum('total');
        $canteens = $this->canteenService->get(['orderBy'=>'ordersCount','paginate'=>10]);

        return view('admin.index',get_defined_vars());
    }
}
