<?php 

namespace App\Services\Api\Slackbot;

use Illuminate\Http\Request;
use App\Models\AssetHistory;
use App\Events\BulkUpdates;
use App\Models\AssetStatus;
use App\Models\Asset;
use Carbon\Carbon;
use App\User;
use Cache;
use Auth;

/**
 * Service class for updating the asset taf from the slack bot
 */
class AssetTagService extends SlackbotApiService
{
    /**
     * Get Asset Details for Asset Tag update
     *
     * @param Request $request
     *
     * @return Collection
     */
    public function getAssetToUpdate(Request $request)
    {

        $user = $this->getUserByEmail($request->user_email);

        if (isset($user['error']) && $user['error'] == true) {
            return $user;
        }

        //check permission
        if (!$user->can('Slackbot Admin Tools')) {
            return $this->getErrorResponse('You do not have permission to update this asset');
        }

        $asset = Asset::where(function($query) use ($request){
                        $query->where('asset_tag', $request->serial_no)
                              ->orWhere('serial_no', $request->serial_no);
                    })
                    ->first();

        if (!$asset) {
            return $this->getErrorResponse('Asset not found in Teqtivity');
        }

        return $this->getSuccessReponse($asset, 'Asset');
    }


    /**
     * Update the Asset tag
     *
     * @param Request $request
     *
     * @return Collection
     */
    public function updateAssetTag(Request $request)
    {
        //Valdiate fields
        $validation = $this->validateFields($request);

        if (isset($validation['error']) && $validation['error'] == true) {
            return $validation;
        }

        $asset = $this->getAssetToUpdate($request);
        if (isset($validation['error']) && $validation['error'] == true) {
            return $asset;
        }


        $response = $this->updateAssetAndCreateHistory($asset['data'], $request);

        return $response;
    }

    /**
     *  Validate the Request from Slack bot
     */
    public function validateFields($request)
    {
        if (empty($request->user_email) || empty($request->serial_no) || empty($request->new_asset_tag)) {
            return $this->getErrorResponse('Something went wrong. Try again later');
        }

        return true;
    }

    /**
     * Updat the asset tag and create a history for it
     * 
     * @param Asset $asset
     * @param Request $request
     */
    public function updateAssetAndCreateHistory($asset, $request)
    {
        $user = $this->getUserByEmail($request->user_email);
        $assetexist = Asset::select('id')->where([['asset_tag', '=', $request->new_asset_tag], ['id', '<>', $asset->id]])->first();
        if ($assetexist) {
            return $this->getErrorResponse('Asset Tag already exists.');
        }
        
        $assetOldValue = $asset->asset_tag;
        $asset->asset_tag = $request->new_asset_tag;
        $asset->save();

        $description = __('history.AssetTagUpdated', [
                'assetid' => $asset->id,
                'oldAssetTag' => $assetOldValue,
                'newAssetTag' => $asset->asset_tag,
            ]);

        $assetHistory = [
            'user_id' => $user->id,
            'asset_id' => $asset->id,
            'action' => 'assetTag_updated',
            'old_value' => $assetOldValue,
            'new_value' => $asset->asset_tag,
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        //AssetHistory::create($assetHistory);
        event(new BulkUpdates($assetHistory));

        return $this->getSuccessReponse($asset, 'Asset Tag Updated');
    }
}