<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Ad;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index() {
        $totalCount = DB::table('users')->where('role_id',2)->where('deleted',0)->count();
        $totalMalecustomer = DB::table('users')->where('gender','Male')->where('role_id',2)->where('deleted',0)->count();
        $totalFemalecustomer = DB::table('users')->where('gender','Female')->where('role_id',2)->where('deleted',0)->count();
        $pricingPlans = DB::table('pricing_plans')->where('status', 1)->pluck('name', 'id');
        $pieChart = [];
        foreach ($pricingPlans as $key => $plan) {
            $count = DB::table('user_plans')->where('plan_id', $key)->count();
            $pieChart['labels'][] = $plan;
            $pieChart['values'][] = $count;
        }
        
        $lastFourMonths = collect(range(0, 3))->map(function ($i) {
            return now()->subMonths($i)->format('Y-m');
        })->reverse();

        $genderData = [
            'Male' => [],
            'Female' => []
        ];

        foreach ($lastFourMonths as $month) {
            $maleCount = DB::table('users')
                ->where('role_id', 2)
                ->where('gender', 'Male')
                ->whereYear('created_at', substr($month, 0, 4))
                ->whereMonth('created_at', substr($month, 5, 2))
                ->count();

            $femaleCount = DB::table('users')
                ->where('role_id', 2)
                ->where('gender', 'Female')
                ->whereYear('created_at', substr($month, 0, 4))
                ->whereMonth('created_at', substr($month, 5, 2))
                ->count();

            $genderData['Male'][] = $maleCount;
            $genderData['Female'][] = $femaleCount;
        }

        $barChatData = [
            [
            'name' => 'Male',
            'data' => $genderData['Male']
            ],
            [
            'name' => 'Female',
            'data' => $genderData['Female']
            ]
        ];

        $months = $lastFourMonths->map(function ($month) {
            return date('F', strtotime($month . '-01'));
        })->toArray();

        $months = array_values($months);
        
        return view('admin.dashboard', compact('totalCount','totalMalecustomer', 'totalFemalecustomer','pieChart','barChatData','months'));
    }
    
}
