<?php

namespace App\Services\Asn\Cdw;

use App\Models\AsnUnwantedPart;
use App\Services\Asn\AbstractAsnMappingService;
use Exception;

/**
 * Service class for CDW assets unwanted parts
 */
class CdwUnwantedPartsService extends AbstractAsnMappingService
{
    /**
     * Gets all unwanted parts added.
     * @return collection
     */
    public function getUnwantedPartsData()
    {
        return AsnUnwantedPart::where('provider', 'cdw')->get();
    }


    /**
     * Search through unwanted parts mappings
     * @return collection
     */
    public function getUnwantedPartsSearch()
    {
        $searchText = request('searchText');
        $cdwMappings = AsnUnwantedPart::where('provider', 'cdw');

        if ($searchText) {
            $cdwMappings = $cdwMappings->where('part_no',  'like', '%' . $searchText . '%');
        }

        return $cdwMappings->get();
    }

    /**
     * Handles the unwanted parts bulk upload process
     * @return string
     */
    public function bulkUpload()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();
        
        $extension = strtolower(request()->file('unwanted-parts-bulk-upload')->getClientOriginalExtension());
        $path = request()->file('unwanted-parts-bulk-upload')->storeAs('public/cdw_mapping_bulk_upload', 'cdw-unwanted-parts-' . date('YmdHis') . '.' . $extension);
        $path = storage_path('app/' . $path);
        $headerMap = Config('bulk-upload.asnUnwantedParts');
        $checkHeader =  $this->checkHeader($path, $headerMap);
        if ($checkHeader) {
            $errors = 'Upload file do not match the template';

            return compact('errors');
        }
        $errors =  $this->importUnwantedPartsMappingData($path, 'cdw');
        if ($errors) {
            $message = 'Mapping completed with errors';

            return compact('message', 'errors');
        }
        $message = 'Bulk mapping successful.';
        return compact('message');
    }
}
