<?php

namespace App\Http\Controllers;

#use Illuminate\Http\Request;
use Request;
use Response;
use Illuminate\Support\Facades\DB;

class Search extends Controller
{
  public function autocomplete(){
		$term = Request::input('term');
		$users = array();
		$computers = array();
		$uin = [];
		$cin = [];
		$results = [];
		
		$queries = DB::table('users')
			->select('id','name')
			->get();
		
		foreach ($queries as $query)
		{
				$users[$query->id] = $query->name;
				if ($term && strpos($query->name, $term) === 0) {
					$uin[] = $query->id;
				}
		}

		$queries = DB::table('computers')
			->select('id','computer')
			->get();

		foreach ($queries as $query)
		{
				$computers[$query->id] = $query->computer ;
				if ($term && strpos(strtolower($query->computer),strtolower($term)) === 0) {
					$cin[] = $query->id;
				}
		}
	
		$queries = DB::table('user_ip')
			->select('computer_id','user_id')->distinct()
			->whereIn('computer_id',$cin)
			->orWhereIn('user_id',$uin)
			->get();

		foreach ($queries as $query) {
			$results[] = [ 'id' => $query->computer_id, 'computer' => $computers[$query->computer_id], 'user' => $users[$query->user_id]];
		}
		return Response::json($results);
	}

	public function multicomplete(){
		$term = Request::input('term');
		$type = Request::input('type');
		$results = [];

		if ($type == 0) {
			$qs = DB::table('users')
			->where('name','LiKE',$term.'%')
			->pluck('name','id');

			foreach ($qs as $id => $name) {
				$results[] = [ 'id' => $id, 'name' => $name];
			}
		}
		if ($type == 1) {
			$qs = DB::table('computers')
			->where('computer','LiKE',$term.'%')
			->pluck('computer','id');

			foreach ($qs as $id => $name) {
				$results[] = [ 'id' => $id, 'name' => $name];
			}
		}
		if ($type == 2) {
			$qs = DB::table('user_ip')
			->select('ip')
			->where('ip','LIKE',$term.'%')
			->distinct()
			->pluck('ip');

			foreach ($qs as $ip) {
				$results[] = [ 'id' => $ip, 'name' => $ip];
			}
		}

		return Response::json($results);
	}

	public function search($var = null)
	{
		$ip = Request::input('ip');
		$user = Request::input('user');
	}
	
}
