<?php

namespace App\Services\Integrations\Asn;

use App\Events\BulkUpdates;
use App\Models\Asset;
use App\Models\AssetHistory;
use App\Models\AssetStatus;
use App\Models\AsnHardwareMapping;
use App\Services\AssetHistory as RepoAssetHistory;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class InsightUploadService extends AbstractAsnImportService
{
    public function __construct(RepoAssetHistory $repoAssetHistory)
    {
        $this->repoAssetHistory = $repoAssetHistory;
    }

    /**
     * Generate InsightData
     */
    public function createAsnData($item, $count = null)
    {
        $createdData = ['assetData' => [], 'error' => []];
        $assetData = [];
        if ($this->isAccessories($item, 'insight', 'MATERIAL NUMBER')) {
            $createdData = ['assetData' => $assetData, 'error' => ['insightdata' => ['Line No ' . $count . ': The item is mapped as accessory.']]];
            return $createdData;
        }
        if ($this->isServicese($item['PRODUCT TYPE'])) {
            $createdData = ['assetData' => $assetData, 'error' => ['insightdata' => ['Line No ' . $count . ': The item type is services.']]];
            return $createdData;
        }
        if (isset($item['MATERIAL NUMBER'])) {
            if ($this->isUnwantedPart($item['MATERIAL NUMBER'], 'insight')) {
                $createdData = ['assetData' => $assetData, 'error' => ['insightdata' => ['Line No ' . $count . ': The Manufacturer Part is marked as Unwanted.']]];
                return $createdData;
            }
        }

        $assetData = $this->setAssetArray($item);
        $existing = Asset::where('serial_no', $assetData['serial_no'])->orWhere('asset_tag', $assetData['asset_tag'])->first();
        if ($existing) {
            $createdData = ['assetData' => $assetData, 'error' => ['insightdata' => ['Line No ' . $count . ': Asset already exists']]];
            $createdData;
        }
        $createdData = ['assetData' => $assetData, 'error' => []];
        return $createdData;
    }

    /**
     * Asset array to create
     * @param mixed $item
     * 
     * @return [type]
     */
    public function setAssetArray($item)
    {
        $hardware = [];
        if (isset($item['MATERIAL NUMBER'])) {
            $hardware = AsnHardwareMapping::where('part_no', $item['MATERIAL NUMBER'])->first();
        }
        $assetData = $this->getTechDetails($item, $hardware, 'MATERIAL NUMBER');
        $inTransit = AssetStatus::where('slug', 'insight_in_transit')->first();

        $assetData['po_id']                = $item['PO NUMBER'] ?? '';
        $assetData['part_no']              = $item['MATERIAL NUMBER'] ?? '';
        $assetData['serial_no']            = $item['SERIAL NUMBER'] ?? '';
        $assetData['asset_tag']            = stripS($item['SERIAL NUMBER'] ?? '');
        $assetData['asset_original_value'] = $item['UNIT COST'] ??  $item['UNIT PRICE'] ?? '';
        $assetData['asset_status_id']      = $inTransit ? $inTransit->id : '';
        $assetData['location_id']          = null;

        return $assetData;
    }

    /**
     * createAssetHistory
     *
     * @param  mixed $asset
     * @return void
     */
    public function createAssetHistory($asset)
    {
        $inTransit = Cache::remember('InsightTransitAssetStatus', 3600, function () {
            return AssetStatus::where('slug', 'insight_in_transit')->first();
        });
        $assetHistory = [
            'asset_id' => $asset->id,
            'action' => 'imported_by_vendor',
            'new_asset_status_id' => $inTransit->id,
            'new_value' => $asset->serial_no,
            'description' =>  __('history.ImportedByVendor', [
                'asset_name' => $asset->serial_no,
                'asset_id' => $asset->id
            ]),
            'created_by' => 'ASN-Insight',
            '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));
    }
}
