<?php

namespace App\Http\Traits;

use App\Events\BulkUpdates;
use App\Models\Asset;
use App\Models\AssetHistory;
use App\Models\AssetStatus;
use App\Models\Location;
use App\Models\MakeAndModel;
use App\User;
use Facades\App\Services\Asset\AssetStatusService;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Cache;

trait DiscoveryToolsAssetUpdateTrait
{

    /**
     * createData from discovery asset data, to crete teq asset.
     *
     * @param  mixed $discoveryAsset
     * @return void
     */
    public function CreateAsset($discoveryAsset)
    {
        $assetData = $this->getData($discoveryAsset);
        if (!$assetData['serial_no']) {
            return false;
        }

        $existingAsset = Asset::where(['serial_no' => $assetData['serial_no']])->first();
        if (!$existingAsset) {
            $assetId = Asset::create($assetData)->id;
            $discoveryAsset->update([
                'asset_id' => $assetId
            ]);
            $this->createAssetHistory($assetData, $assetId);
        }

        return true;
    }

    /**
     * getData
     *
     * @param  mixed $discoveryAsset
     * @return void
     */
    public function getData($discoveryAsset)
    {
        $assetStatus = AssetStatus::find(request('status_id'));
        $makeAndModel = MakeAndModel::find(request('make_and_model_id'));
        $assetData['technical_spec_id'] = request('technical_spec_id');
        $assetData['make_and_model_id'] = request('make_and_model_id');
        $assetData['serial_no'] = $discoveryAsset->serial_no ?? null;
        $assetData['asset_status_id'] = request('status_id');
        $assetData['asset_type_id'] =  $makeAndModel->asset_type_id ?? 0;
        $assetData['ticket_no'] = request('ticket_no');
        $assetData['vendor_id'] = request('vendor_id');
        $assetData['comments'] = request('comments');

        if ($assetStatus->has_location) {
            $assetData['location_id'] = request('location_id');
        } elseif ($assetStatus->has_user) {
            $assetData['user_id'] = request('user_id');
        }

        return $assetData;
    }
    /**
     * createAssetHistory
     *
     * @param  mixed $assetData
     * @param  mixed $assetId
     * @return void
     */
    public function createAssetHistory($assetData, $assetId)
    {
        $description = __('history.AssetCreated', [
            'assetname' => $assetData['serial_no'],
            'assetid' => $assetId,
            'commenttext' => $assetData['comments'] ? ' with comments ' . $assetData['comments'] : '',
        ]);

        if (isset($assetData['location_id'])) {
            $location = Location::where('id', $assetData['location_id'])->first();
            $description = __('history.Created', [
                'assetname' => $assetData['serial_no'],
                'assetid' => $assetId,
                'newroomname' => $location->room_name ?? '',
            ]);
        } elseif (isset($assetData['user_id'])) {
            $user = User::where('id', $assetData['user_id'])->first();
            $username = ($user != null) ? $user->first_name . " " . $user->last_name : '';
            $description = __('history.CreatedForUser', [
                'assetname' => $assetData['serial_no'],
                'assetid' => $assetId,
                'newuser' => !empty(trim($username)) ? $username : $user->email,
            ]);
        }

        $assetHistory = [
            'user_id'     => Auth::id(),
            'asset_id'    => $assetId,
            'action'      => 'created',
            'new_location_id' => $location->id ?? null,
            'new_user_id' => $user->id ?? null,
            'new_asset_status_id' => $assetData['asset_status_id'] ?? null,
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];
        event(new BulkUpdates($assetHistory));
    }
    function getCachedLocations()
    {
        $installLocations = Cache::remember('install-locations', 720, function () {
            return Location::withoutwarehouse()->active()->orderBy('room_name', 'asc')->get();
        });
        $warehouseLocations = Cache::remember('warehouse-locations', 720, function () {
            return Location::warehouses()->active()->valid()->orderBy('room_name', 'asc')->get();
        });

        $installAndBuildingLocations = Cache::remember('install-building-locations', 720, function () {
            return Location::installBuildings()->active()->orderBy('room_name', 'asc')->get();
        });

        $installedLocations = Cache::remember('installed-locations', 720, function () {
            return Location::installLocations()->active()->orderBy('room_name', 'asc')->get();
        });
        return compact('installLocations', 'warehouseLocations', 'installAndBuildingLocations', 'installedLocations');
    }
}
