<?php

namespace App\Repositories\Reports;

use App\Models\Asset;
use App\Models\AssetHistory;
use App\Models\AssetStatus;
use Illuminate\Support\Facades\DB;

class AssetsUsedRepository
{
    /**
    * fetch asset data
    * @params
    * @return Asset
    * */
    public function getAssetsData()
    {
        return Asset::with(
                'assetType:id,name','makeAndModel:id,name,manufacturer_id', 'makeAndModel.manufacturer:id,name',
                'technicalSpec:id,details', 'assetStatus:id,name'
            )
            ->select('assets.*')
            ->orderBy('assets.created_at');
    }

    /**
    * fetch reused asset data
    * @params
    * @return Asset
    * */
    public function getReusedAssetsData($noOfTimesReused = '')
    {
        $reusedAssetsData = Asset::has('reusedAssetHistory');

        if ($noOfTimesReused) {
            $reusedAssetsData = Asset::has('reusedAssetHistory', $noOfTimesReused);
        }
        $reusedAssetsData = $reusedAssetsData->with(
            'location:id,room_name', 'user:id,first_name,last_name', 'makeAndModel', 'technicalSpec',
            'assetType:id,name','makeAndModel:id,name,manufacturer_id','makeAndModel.manufacturer:id,name',
            'technicalSpec:id,details','assetStatus:id,name',
            'reusedAssetHistory','latestAssignedAssetHistory'
,        )->withCount('reusedAssetHistory')->orderBy('assets.created_at');

        return $reusedAssetsData;
    }

    /**
    * fetch not reused asset data
    * @params
    * @return Asset
    * */
    public function getNotReusedAssetsData()
    {
        $notReusedStatuses = AssetStatus::whereIn('slug', config('reports.reused_devices.not_reused_statuses'))->pluck('id')->toArray();
        $notReusedAssetsData = Asset::doesntHave('reusedAssetHistory')->whereIn('asset_status_id', $notReusedStatuses);

        return $notReusedAssetsData;
    }

    /**
    * Get Assigned assets data from asset History
    * @explanation This function used to count how many times an asset assigned/loaned/installed. Search asset histoy table and new_asset_status_id is exist in usedStatuses then that asset considered as assigned.
    * @params $noOfTimesAssigned - for filter
    * @return AssetIds and Each asset assigned count
    * */
    public function getAssignedAssetsFromAssetHistory($noOfTimesAssigned='')
    {
        $usedStatuses = $this->getUsedAssetStatus();
        $assignedData  = AssetHistory::select(DB::raw('asset_id,count(id) as count'))
            ->whereIn('new_asset_status_id', $usedStatuses)
            ->groupBy('asset_id');

        if ($noOfTimesAssigned != '') {
            $assignedData  = $assignedData->having('count', '=', $noOfTimesAssigned);
        }

        return $assignedData->get()->toArray();
    }
    
    /**
    * Map each asset with its count
    * @params $assets,$assetCount array having key as assetId
    * @return Asset
    * */
    public function mapAssetsWithAssetCount($assets, $assetCount)
    {
        foreach ($assets as $key => $asset) {
            $assetId = $asset->id;

            if (array_key_exists($assetId, $assetCount)) {
                $assets[$key]->count = $assetCount[$assetId];
            }
        }

        return $assets;
    }
    

    /**
    * filter assets data by removing unwanted status
    * @params $assets,$field and $value
    * @return Asset
    * */
    public function filterAssetsByStatus($assets)
    {
        $unwantedStatus = AssetStatus::whereIn('slug', config('reports.reused_devices.unwanted_statuses'))->pluck('id')->toArray();
        $assets = $assets->whereNotIn('assets.asset_status_id', $unwantedStatus);
        
        return $assets;
    }


    /**
    * Pre defiend set of all asset status that are considered as assigned to a user or installed in a location.
    * @params
    * @return array of status id
    * */
    public function getUsedAssetStatus()
    {
        return AssetStatus::whereIn('slug', config('reports.assigned_devices.used_asset_status'))->get()->modelKeys();
    }

    /**
     * Filter the query with the given number of times the asset was reused.
     *
     * @param datatype $query The query to filter
     * @param datatype $noOfTimes The number of times the asset was reused
     * @return filtered query
     */
    public function filterWithReusedCount($query, $noOfTimes)
    {
        if (empty($noOfTimes)) {
            return $query;
        }
        
        return $query->having('reused_asset_history_count', $noOfTimes);
    }
}
