<?php

namespace App\Repositories\Reports;

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

class OnHandAssetAgeRepository
{
    protected $assetStatusModel;
    protected $assetModel;

    /**
     * Constructs a new instance of the class.
     *
     * @param AssetStatus $assetStatusModel The asset status model object.
     * @param AssetModel $assetModel The asset model object.
     */
    public function __construct(AssetStatus $assetStatusModel, Asset $assetModel)
    {
        $this->assetStatusModel = $assetStatusModel;
        $this->assetModel = $assetModel;
    }

    /**
     * Retrieves the assets that have aged out based on the given current date.
     *
     * @param string $currentDate The current date in the format "YYYY-MM-DD".
     * @throws \Some_Exception_Class A description of the exception that can be thrown.
     * @return \Illuminate\Database\Eloquent\Builder The query builder instance for further manipulation.
     */
    public function getOnHandAssetAgeAssets($currentDate)
    {
        $assetStatuses = $this->assetStatusModel->whereIn('slug', ['brand_new', 'used', 'like_new'])->pluck('id');
        $assets = $this->assetModel->with('assetType', 'assetStatus', 'makeAndModel', 'technicalSpec', 'location')
            ->select('assets.*', 'assets.id as assetId', DB::raw("cast(DATEDIFF('$currentDate', assets.created_at) / 365.25 as decimal) age"), 'technical_specs.life_of_asset')
            ->join('technical_specs', 'assets.technical_spec_id', 'technical_specs.id')
            ->whereIn('asset_status_id', $assetStatuses)
            ->having('age', '>', DB::raw('technical_specs.life_of_asset'));

        return $assets;
    }
}