<?php

namespace App\Http\Traits\Asn;

use App\Models\AssetTracking;
use App\Models\MakeAndModel;
use App\Events\BulkUpdates;
use App\Models\AsnAccessoriesMapping;
use App\Models\AsnHardwareMapping;
use App\Models\AsnUnwantedPart;
use App\Models\Asset;
use App\Models\PurchaseOrder;

/**
 * to support ASN Presidio integration
 */
trait AsnPresidioTrait
{
    /**
     * Validate the Data before saving
     *
     * @param Array $item
     *
     * @return Boolean
     */
    public function validateItem($item)
    {
        if (empty($item)) {
            return false;
        }

        if ($item['serial_no'] == '') {
            return false;
        }

        if ($item['asset_status_id'] == '') {
            return false;
        }

        $existing = Asset::where('serial_no', $item['serial_no'])->first();
        if ($existing) {
            $existing->update(['asset_original_value' => $item['asset_original_value']]);

            return false;
        }

        return true;
    }

    /**
     * Check the item is Accessory or based on the Mapping
     *
     * @param Array $item
     *
     * @return Boolean
     */
    public function isAccessories($item)
    {
        if (isset($item['itemCode'])) {
            return AsnAccessoriesMapping::where('provider', 'presidio')->where('part_no', trim($item['itemCode']))->exists();
        }

        return false;
    }

    /**
     * Check the item is Unwanted part or not based on the Mapping
     *
     * @param Array $item
     *
     * @return Boolean
     */
    public function isUnwantedPart($item)
    {
        if (isset($item['itemCode'])) {
            return AsnUnwantedPart::where('provider', 'presidio')->where('part_no', trim($item['itemCode']))->exists();
        }

        return false;
    }

    /**
     * Taking the Hardware and Technical spec details based on the mapping
     *
     * @param Array $item
     * @return Array
     */
    public function getHardwareDetails($item)
    {
        $assetData['make_and_model_id'] = '';
        $assetData['technical_spec_id'] = '';
        $assetData['asset_type_id']     = '';

        if (isset($item['itemCode'])) {
            $hardware = AsnHardwareMapping::where('provider', 'presidio')->where('part_no', 'like', trim($item['itemCode']))->select('make_and_model_id', 'technical_spec_id')->first();

            if ($hardware) {
                $makeAndModel = MakeAndModel::findOrFail($hardware->make_and_model_id);

                $assetData['make_and_model_id'] = $hardware->make_and_model_id;
                $assetData['technical_spec_id'] = $hardware->technical_spec_id;
                $assetData['asset_type_id']     = $makeAndModel->asset_type_id;
            }
        }

        return $assetData;
    }

    /**
     * Create the Presidio Asset creation History
     */
    public function createAssetHistory($asset, $presidioStatusId)
    {
        $assetHistory = [
            'asset_id'              => $asset->id,
            'action'                => 'imported_by_vendor',
            'description'           => '',
            'new_asset_status_id'   => $presidioStatusId,
            'created_by'            => 'ASN - Presidio Import',
        ];

        event(new BulkUpdates($assetHistory));
    }

    /**
     * Create the Asset Tracking details
     *
     * @param string $trackingNo   Tracking number
     */
    public function createAssetTracking($trackingNo)
    {
        if ($trackingNo) {
            return AssetTracking::firstOrCreate(['tracking_number' => $trackingNo]);
        }
        return null;
    }

    /**
     * get purchase order id if po # already exists
     */
    public function getPurchaseOrderId($poNumber)
    {
        if ($poNumber) {
            $po = PurchaseOrder::where('number', $poNumber)->first();
            return $po ? $po->id : null;
        }
        return null;
    }

    /**
     * Returns the serial number, formatted according to the manufacturer
     * 
     * For Apple devices, the serial number is modified to remove the first 's' character
     * (ticket#MOL-126)
     * 
     * @param array $item ASN item data
     * @param array $assetData the asset data
     * @return string the formatted serial number
     */
    public function getSerialNumber($item, $assetData)
    {
        $serialNo = $item['serialNumber'] ? trim($item['serialNumber']) : null;
        
        if (empty($assetData['make_and_model_id'])) {
            return $serialNo;
        }
    
        // If manufacturer is APPLE, remove first 's' from serial number (ticket#MOL-126)
        $makeAndModel = MakeAndModel::find($assetData['make_and_model_id']);
        $manufacturerSlug = $makeAndModel->manufacturer->slug ?? null;
        
        if ($manufacturerSlug === 'apple' && $serialNo && str_starts_with(lcfirst($serialNo), 's')) {
            $serialNo = ltrim(lcfirst($serialNo), 's');
        }
    
        return $serialNo;
    }
}
