<?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\Area\Services\AreaService;
use Modules\Category\Models\Category;
use Modules\Order\Enums\OrderStatusEnum;
use Modules\Order\Services\OrderService;
use Modules\Product\Models\Product;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Models\User;
use Modules\User\Services\UserService;
use Modules\Store\Services\StoreService;
use Modules\Store\Models\Store;

class DashboardController extends Controller
{
    public function __construct(
        private AreaService $areaService,
        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();
        $orders_count = $this->orderService->get()->count();

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

    public function areas(Request $request)
    {
        $areas = $this->areaService->get(['city_id'=>$request->city_id]);
        return response()->json($areas);
    }
}
