<?php 

namespace App\Repositories;

use App\User;
use App\Models\Accessory as AccessoryModel;
use App\Models\AssetType;
use App\Models\MakeAndModel;
use App\Models\Location;
use App\Models\Manufacturer;
use DB;
class Accessory
{

public function searchAccessories_withkeys($searchText = NULL, $type = 'makeAndModel')
	{

   		 $accessory = AccessoryModel::whereHas($type, function ($query) use ($searchText, $type) {

					$query = $this->assetTypeWhere($query, $type);

					return ($searchText) ?
						$this->assetWhereUser($query, $searchText)
						: $query;
    		})->with([
						'makeAndModel',
						'location',
						'technicalSpec',
						
					])->whereIn('make_and_model_id', 
						MakeAndModel::where('name', 'like', "%$value%")->pluck('id')
					)->orWhereIn('location_id',
						Location::where('room_name', 'like', "%$value%")->pluck('id')
					)->orWhereIn('make_and_model_id', 
						MakeAndModel::whereIn('manufacturer_id',
							Manufacturer::where('name','like', "%$value%")->pluck('id')
						)->pluck('id')
					)->get();


		return User::whereHas($type, function ($query) use ($searchText, $type) {

					$query = $this->assetTypeWhere($query, $type);

					return ($searchText) ?
						$this->assetWhereUser($query, $searchText)
						: $query;
    		})->with([
    			'position', 
    			'location.state', 
    			'employeeType',
    			'assets' => function ($query) use ($searchText, $type) {

					$query = $this->assetTypeWhere($query, $type);

    			},  
    			'assets.user',
    			'assets.location',
    			'assets.assetType',
    			'assets.makeAndModel.manufacturer', 
    			'assets.technicalSpec',
    			'assets.assetStatus',
    			'assets.carrier',
    			'assets.parentAsset',
    			'assets.childrenAsset',
    		])
    		->get();
	}

	public function accessorySearch($query, $searchText)
	{
		$searchTerms = explode(' ', $searchText);
		return  $query->where(function ($query) use ($searchTerms) {
			foreach ($searchTerms as $searchText) {
				
				$query->where('asset_tag', 'like', "$searchText") 
					->orWhere('serial_no' , 'like', "$searchText")
					->orWhereIn('user_id', $this->userWhere($searchText));
			}
		});
	}

	public function search($searchText)
	{
      
       	  $arr_keyword = explode(" ", $searchText);

       	  foreach ($arr_keyword as $key => $value) {
       	  
       	  		 $accessory = AccessoryModel::with([
						'makeAndModel',
						'location',
						'technicalSpec',
						
					])->whereIn('make_and_model_id', 
						MakeAndModel::where('name', 'like', "%$value%")->pluck('id')
					)->orWhereIn('location_id',
						Location::where('room_name', 'like', "%$value%")->pluck('id')
					)->orWhereIn('make_and_model_id', 
						MakeAndModel::whereIn('manufacturer_id',
							Manufacturer::where('name','like', "%$value%")->pluck('id')
						)->pluck('id')
					)->get();

       	  }
       	 
		return $accessory;
	}
}