<?php

namespace App\Console\Commands;

use App\Models\ActiveUsersCountInMonth;
use Illuminate\Console\Command;
use App\Repositories\UserRepository;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Carbon\CarbonPeriod;

class ActiveUserCountInLastTwelveMonths extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ActiveUserCountInLastTwelveMonths:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This commad used for update last 12 months of active users count';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(protected UserRepository $userRepository)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        ActiveUsersCountInMonth::truncate();
        $this->updateActiveUsersCountByMonths();
        $this->info('Active Users Count Updated');
    }

    /**
     * Calculates the number of active users for each month in the given period and stores it in the database.
     *
     * @param int $months The number of months to go back in time. Defaults to 12 months.
     *
     * @return void
     */
    public function updateActiveUsersCountByMonths($months = 12)
    {
        $start = now()->subMonths($months - 1)->startOfMonth();

        foreach (CarbonPeriod::create($start, '1 month', Carbon::today()) as $date) {
            $lastDay = $date->endOfMonth()->format('Y-m-d');
            $firstDay = $date->startOfMonth()->format('Y-m-d');

            $totalHiredUsers = $this->userRepository->getAciveUserCountByMonth($lastDay);
            $totalTerminatedUsers = $this->userRepository->getTerminatedUserCountByMonth($firstDay, $lastDay);

            $monthName = $date->monthName;

            $activeUsers = ($totalHiredUsers + $totalTerminatedUsers);

            ActiveUsersCountInMonth::insert(['month' => $monthName, 'user_count' => $activeUsers]);
        }
    }
}
