<?php

namespace App\Services\Asn\Connection;

use App\Repositories\Asn\ConnectionRepository;
use App\Models\AsnAccessoriesMapping;
use App\Services\Asn\AbstractAsnMappingService;
use Exception;
use Illuminate\Support\Facades\Validator;

class ConnectionAccessoriesMappingService extends AbstractAsnMappingService
{
    protected $repository;

    public function __construct(ConnectionRepository $repository)
    {
        $this->repository = $repository;
    }

    public function getAccessoriesMappingData()
    {
        return $this->repository->getAccessoriesMappingData()->get();
    }


    public function getAccessoriesMappingSearch()
    {
        $searchText = request('searchText');
        $connectionMappingData = $this->repository->getAccessoriesMappingData();

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

        return $connectionMappingData->get();
    }


    /**
     * Bulk upload
     *
     */
    public function bulkUpload()
    {
        $extension = strtolower(request()->file('bulk_upload_connection-accessories-mapping')->getClientOriginalExtension());
        $path = request()->file('bulk_upload_connection-accessories-mapping')->storeAs('public/connection_mapping_bulk_upload', 'connection-accessories-mapping-' . date('m-d-y') . '.' . $extension);
        $path = storage_path('app/' . $path);
        $headerMap = Config('bulk-upload.asnAccessoriesMappingData');

        $checkHeader =  $this->checkHeader($path, $headerMap);
        if ($checkHeader) {
            $errors = 'Upload file do not match the template';

            return compact('errors');
        }

        $errors =  $this->importAccessoryMappingData($path, 'connection');

        if ($errors) {
            $message = 'Mapping completed with errors';

            return compact('message', 'errors');
        }

        $message = 'Bulk mapping successful.';

        return compact('message');
    }
}
