<?php
namespace App\Repositories\Reports;
use App\Models\AssetHistory;
use App\Models\AssetStatus;

/**
 * AssetsRecovery - Repository for asset recovery report
 */
class AssetRecoveryRepository
{
    protected $assetHistoryModel;
    protected $assetStatusModel;

    /**
     * Constructor for the class.
     *
     * @param AssetHistory $assetHistoryModel description
     * @param AssetStatus $assetStatusModel description
     */
    public function __construct(AssetHistory $assetHistoryModel, AssetStatus $assetStatusModel)
    {
        $this->assetHistoryModel = $assetHistoryModel;
        $this->assetStatusModel = $assetStatusModel;
    }

    /**
     * Retrieves returned assets from terminated users.
     *
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function getReturnedAssetsFromTerminatedUsers()
    {
        $storageStatusIds = $this->assetStatusModel::where('has_location',1)->pluck('id')->toArray();

        return $this->assetHistoryModel::with(
                'asset:id,asset_tag,serial_no,asset_type_id,make_and_model_id,technical_spec_id,asset_status_id,created_at,asset_original_value', 
                'asset.assetType:id,name', 
                'asset.makeAndModel:id,name','asset.technicalSpec:id,details,original_value',
                'asset.assetStatus:id,name','oldStatus:id,name'
            )
            ->select()
            ->redeployedDate()
            ->returnedAssetsFromTerminatedUser()
            ->whereIn('new_asset_status_id',$storageStatusIds)
            ->orderBy('created_at', 'asc')
            ->groupBy('asset_id');
    }

    /**
     * Retrieves the count of returned and redeployed assets.
     *
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function getReturnedAndRedeployedAssetsCount()
    {
        $storageStatusIds = $this->assetStatusModel::where('has_location',1)->pluck('id')->toArray();

        return $this->assetHistoryModel::select('asset_id')
            ->redeployedAssetCount()
            ->returnedAssetsFromTerminatedUser()
            ->distinct()
            ->whereIn('new_asset_status_id',$storageStatusIds)
            ->orderBy('created_at', 'asc')
            ->groupBy('asset_id')
            ->withCount('asset');
    }

}