<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use App\Product;
use App\Category;
use App\Comment;
use App\Device;
use App\Day;
use App\WebsiteVisitor;
use App\Contact;
class DashboardController extends Controller
{

    /**
     * Show the stats of the website.
     * @return Factory|View
     */

    public function index() :View
    {
        $products = Product::count();
        $categories = Category::count();
        
        
        $allCategories = Category::cursor();
        $contacts = Contact::count();
        $comments = Comment::count();
        $users = Device::count();
        $day = Day::where('date',date('Y-m-d'))->first();
        $category = Category::orderBy('counter','DESC')->first();
        $product = Product::orderBy('visit_counts','DESC')->first();
        $difDays = date('d');
        $difMonths = date('n');
        $difDays = 30 - $difDays . ' day';
        $difMonths = 12 - $difMonths . ' month';
        $visitors = WebsiteVisitor::whereYear('created_at', '=', date('Y'))
              ->whereMonth('created_at', '=', date('m'))
              ->count();

        $lastYear = date("Y-m-d", strtotime("-1 year $difMonths $difDays"));
        $nextYear = date("Y-m-d", strtotime("0 year $difMonths $difDays"));

        $lastWeek = date("Y-m-d", strtotime("-1 week"));
        $nextWeek = date("Y-m-d", strtotime("1 day")); // to include today in the statistics

        $toDay = date("Y-m-d");
        $days = [];


        $websiteVisitors = DB::table('website_visitors')
            ->orderBy('created_at', 'asc')
            ->whereBetween('created_at', [$lastYear, $nextYear])
            ->pluck('created_at')->toArray();

        $weekVisitors = DB::table('website_visitors')
            ->orderBy('created_at', 'asc')
            ->whereBetween('created_at', [$lastWeek, $nextWeek])
            ->pluck('created_at')->toArray();


        foreach ($websiteVisitors as $key => $websiteVisitor) {
            $websiteVisitors[$key] = date('n', strtotime($websiteVisitor));
            $days[] = date('Y-m-d', strtotime($websiteVisitor));
        }

        $monthVisitCounts = array_count_values($websiteVisitors);
        $allVisitorCounts = count($websiteVisitors);
        $weekVisitorCounts = count($weekVisitors);

        $days = array_count_values($days);
        $dayVisitCounts = array_key_exists($toDay, $days) ? $days[$toDay] : '';

        return view('admin.index', compact(
            ['monthVisitCounts','allVisitorCounts','weekVisitorCounts','dayVisitCounts','products','categories','comments','contacts','visitors','users','category','product','day','allCategories']
        ));
    }
}
