<?php

namespace App\Repositories\Reports;

use App\Models\Asset;
use App\Models\Department;
use App\User;

/**
 * AssetsByDepartmentRepository - Repository for Department Spend Report
 * */
class AssetsByDepartmentRepository
{
    
    protected $assetModel;
    protected $departmentModel;
    protected $userModel;
    
    /**
     * Constructor for the class.
     *
     * @param Asset $assetModel The asset model instance.
     * @param Department $departmentModel The department model instance.
     * @param User $userModel The user model instance.
     */
    public function __construct(Asset $assetModel, Department $departmentModel, User $userModel) 
    {
        $this->assetModel =  $assetModel;
        $this->departmentModel = $departmentModel;
        $this->userModel = $userModel;
    }

    /**
     * Generates a chart of assets by department.
     *
     * Retrieves all departments and calculates the sum of the original values of assets
     * for each department. Returns an array chart with the department ID, name, and sum of assets.
     *
     * @return array
     */
    public function departmentAssetChart()
	{
		$arrayChart = [];
		$department = $this->departmentModel->all();
		$i = 0;
		foreach ($department as $dept) {
			$arrayChart[$i]['department_id'] = $dept->id;
			$arrayChart[$i]['name'] = $dept->name;
			$sum = $this->assetModel->selectRaw('sum(technical_specs.original_value) as sum')
				->join('technical_specs', 'technical_specs.id', '=', 'assets.technical_spec_id')
				->whereIn('user_id', User::where('department_id', $dept->id)->pluck('id'))
				->pluck('sum')[0];
			$arrayChart[$i]['sum'] = $sum == null ? 0 : $sum;
			$i++;
		}

		return $arrayChart;
	}

    /**
     * Retrieves all departments.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getAllDepartments()
    {
        return $this->departmentModel->orderBy('name')->get();  
    }

    /**
     * Retrieves department data based on the given department ID.
     *
     * @param int $departmentId The ID of the department.
     * @return mixed The department data.
     */
    public function getDepartmentData($departmentId)
    {
        return $this->assetModel->with(
            'assetType:id,name','user:id,first_name,last_name,department_id,user_type_id', 
            'makeAndModel:id,name,manufacturer_id', 'makeAndModel.manufacturer:id,name', 'technicalSpec:id,details,original_value'
        )->whereIn('user_id', $this->userModel->superAdmin()->where('department_id', $departmentId)->pluck('id'));
    }
}