<?php

namespace App\Repositories\NewHire;

use App\Models\AssetStatus;
use App\Models\DepartmentHardwareMapping;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class ForecastingToolRepository
{

    /**
     * It returns a collection of departments with their hardwarekits, makeAndModel, technicalSpec and
     * department. It also counts the number of users and hardwarekits
     */
    public function getForcastingData()
    {
        return DepartmentHardwareMapping::with('makeAndModel:id,name', 'technicalSpec:id,details', 'singleDepartment:id,name')
            ->withCount('inStockAssets as in_stock_assets_count');
    }


    /**
     * > When the department is not null, filter the newhireData by the department
     *
     * @param newhireData The data that you want to filter.
     * @param department The department id or array of department ids to filter by.
     *
     * @return A collection of new hires.
     */
    public function filterWithDepartment($newhireData, $department)
    {
        return $newhireData->when(
            $department ?? false,
            function ($newhireData, $department) {
                return is_array($department) ? $newhireData->whereIn('department_hardware_mappings.department_id', $department) : $newhireData->where('department_hardware_mappings.department_id', $department);
            }
        );
    }

    /**
     * > This function takes in a collection of newhire data and a hire date, and returns a collection
     * of newhire data with a count of users who were hired before the hire date and after the current
     * date
     *
     * @param newhireData This is the data that you want to filter.
     * @param hireDate The date you want to filter by.
     *
     * @return The number of users that have a hire date that is less than the hire date passed in and
     * greater than or equal to the current date.
     */
    public function filterWithHireMonthRange($newhireData, $hireStartDate, $hireEndDate)
    {
        return $newhireData->withCount(
            [
                'user' =>
                function (Builder $query) use ($hireStartDate, $hireEndDate) {
                    if ($hireStartDate != null) {
                        $query->whereDate('hire_date', '>', $hireStartDate);
                    } else {
                        $query->whereDate('hire_date', '>', Carbon::now()->format('Y-m-d'));
                    }
                    if ($hireEndDate != null) {
                        $query->whereDate('hire_date', '<=', $hireEndDate);
                    }
                }
            ]
        );
    }
}
