<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\Interfaces\OrderRepositoryInterface;
use App\Services\Interfaces\ReservationRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use App\Models\WebsiteVisitor;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class DashboardController extends Controller
{

    private OrderRepositoryInterface $orderRepository;
    private ReservationRepositoryInterface $reservationRepository;
    
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        ReservationRepositoryInterface $reservationRepository
    )
    {
        $this->orderRepository = $orderRepository;
        $this->reservationRepository = $reservationRepository;
    }
    /**
     * 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
    {
        
        $allUsersCounts = WebsiteVisitor::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 = $this->orderRepository->get($request)->count();
        $orders_total = $this->orderRepository->get($request)->sum('payment.total');
        $reservations = $this->reservationRepository->get($request)->count();
        $reservations_total = $this->reservationRepository->get($request)->sum('payment.total');

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