<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

use App\Models\{Account,Invoice,Payment,Service,User};

class SearchController extends Controller
{
	/**
	 * Search from the Application Dashboard.
	 *
	 * @param Request $request
	 * @return Collection
	 */
	public function search(Request $request): Collection
	{
		$result = collect();

		// If the user isnt logged in
		if (! Auth::user())
			abort(401,'Need to login');

		// If there isnt a term value, return null
		if (! $request->input('term'))
			return $result;

		$account_ids = ($x=Auth::user()->accounts_all)->pluck('id');
		$user_ids = $x->pluck('user_id')->unique();

		// Look for User
		foreach (User::Search($request->input('term'))
			->whereIN('id',$user_ids)
			->orderBy('lastname')
			->orderBy('firstname')
			->limit(10)->get() as $o)
		{
			$result->push(['name'=>sprintf('%s (%s) - %s',$o->name,$o->lid,$o->email),'value'=>'/u/home/'.$o->id,'category'=>'Users']);
		}

		// Look for User by their Supplier ID with some suppliers
		if (is_numeric($request->input('term')))
			foreach (Account::select(['user_id','suppliers.name AS supplier_name','account_supplier.supplier_ref AS pivot_id'])
				->join('account_supplier',['account_supplier.account_id'=>'accounts.id'])
				->join('suppliers',['suppliers.id'=>'account_supplier.supplier_id'])
				->whereIN('accounts.id',$account_ids)
				->where('account_supplier.supplier_ref','like','%'.$request->input('term').'%')
				->orderBy('company')
				->limit(10)->get() as $o)
			{
				$result->push(['name'=>sprintf('%s (%s:%s)',$o->company,$o->supplier_name,$o->supplier_ref),'value'=>'/u/home/'.$o->user_id,'category'=>'Suppliers']);
			}

		// Look for Account
		foreach (Account::Search($request->input('term'))
			->whereIN('id',$account_ids)
			->orderBy('company')
			->limit(10)->get() as $o)
		{
			$result->push(['name'=>sprintf('%s (%s)',$o->name,$o->lid),'value'=>'/u/home/'.$o->user_id,'category'=>'Accounts']);
		}

		// Look for a Service
		foreach (Service::Search($request->input('term'))
			->whereIN('account_id',$account_ids)
			->orderBy('id')
			->limit(20)
			->with(['product'])
			->get() as $o)
		{
			$result->push(['name'=>sprintf('%s (%s) %s',$o->name,$o->lid,$o->active ? '' : '<small>INACT</small>'),'value'=>'/u/service/'.$o->id,'category'=>$o->product->category_name]);
		}

		// Look for an Invoice
		foreach (Invoice::Search($request->input('term'))
			->whereIN('account_id',$account_ids)
			->orderBy('id')
			->limit(10)->get() as $o)
		{
			$result->push(['name'=>sprintf('%s: %s',$o->lid,$o->account->name),'value'=>'/u/invoice/'.$o->id,'category'=>'Invoices']);
		}

		if (Gate::any(['wholesaler'],new Payment)) {
			// Look for Payments
			foreach (Payment::Search($request->input('term'))
				->whereIN('account_id',$account_ids)
				->limit(10)->get() as $o)
			{
				$result->push(['name'=>sprintf('%s: %s $%s',$o->lid,$o->account->name,number_format($o->total,2)),'value'=>'/r/payment/addedit/'.$o->id,'category'=>'Payments']);
			}
		}

		return $result
			->sortBy(fn($item)=>$item['category'].$item['name'])
			->values();
	}
}