<?php

namespace App\Services\Integrations\Asn;

use App\Events\BulkUpdates;
use App\Models\Asset;
use App\Models\AssetStatus;
use App\Models\AsnHardwareMapping;
use App\Services\Integrations\Asn\AbstractAsnImportService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class ConnectionUploadService extends AbstractAsnImportService
{
    /**
     * Generate ConnectionData
     */
    public function createAsnData($item, $count = null)
    {
        $createdData = ['assetData' => [], 'error' => []];
        $assetData = [];
        if ($this->isAccessories($item, 'connection', 'Mfg Part')) {
            $createdData = ['assetData' => $assetData, 'error' => ['cdwdata' => ['Line No ' . $count . ': The item is mapped as accessory.']]];
            return $createdData;
        }
        if ($this->isServicese(isset($item['Item Type']) ? $item['Item Type'] : '')) {
            $createdData = ['assetData' => $assetData, 'error' => ['cdwdata' => ['Line No ' . $count . ': The item type is services.']]];
            return $createdData;
        }
        if ($this->isUnwantedPart($item['Mfg Part'], 'connection')) {
            $createdData = ['assetData' => $assetData, 'error' => ['cdwdata' => ['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' => ['cdwdata' => ['Line No ' . $count . ': Asset already exists']]];
            $createdData;
        }
        $createdData = ['assetData' => $assetData, 'error' => []];
        return $createdData;
    }

    /**
     *  Asset array to create
     * @param mixed $assetData
     * 
     * @return [type]
     */

    public function setAssetArray($assetData)
    {
        $returnArray = array();
        $hardware = [];
        if (isset($item['Mfg Part'])) {
            $hardware = AsnHardwareMapping::where(['provider' => 'connection', 'part_no', $item['Mfg Part']])->first();
        }
        $returnArray = $this->getTechDetails($assetData, $hardware, 'Mfg Part');

        $inTransit = AssetStatus::where('slug', 'connection_in_transit')->first();
        $returnArray['po_id']             = validatePONumber($assetData['Customer Purchase Order'] ?? ($assetData['PO'] ?? ''));

        $serial_no                        = trim($assetData['Serial Number']) ?? '';
        $serial_no                        = (strlen($serial_no) >= 8) ? substr($serial_no, -8) : $serial_no;
        $serial_no                        = stripS($serial_no);

        $asset_tag                        = trim($assetData['Asset Tag'] ?? '');
        $asset_tag                        = (strlen($asset_tag) >= 8) ? substr($asset_tag, -8) : $asset_tag;
        $asset_tag                        = stripS($asset_tag);

        if ($asset_tag == '') {
            $asset_tag         = stripS($serial_no);
        }

        $returnArray['serial_no']         = $serial_no;
        $returnArray['asset_tag']         = $asset_tag;

        $returnArray['asset_status_id']   = $inTransit ? $inTransit->id : '';
        $returnArray['ticket_no']         = $assetData['Ticket Number'] ?? '';
        $returnArray['part_no']       = $assetData['Mfg Part'] ?? '';
        $assetData['location_id'] = null;

        return $returnArray;
    }

    /*
    * function to create asset history, when creating a new asset
    */

    public function createAssetHistory($asset)
    {
        $inTransit = Cache::remember('ConnectionTransitAssetStatus', 3600, function () {
            return AssetStatus::where('slug', 'connection_in_transit')->first();
        });

        $assetHistory = [
            'asset_id' => $asset->id,
            'action' => 'imported_by_vendor',
            'description' =>  __('history.ImportedByVendor', [
                'asset_name' => $asset->serial_no,
                'asset_id' => $asset->id
            ]),
            'new_asset_status_id' => $inTransit->id,
            'created_by' => 'Connection Import',
            '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));
    }
}
