<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreContractAPIRequest;
use App\Models\Contract;
use App\Models\DistrictName;
use App\Models\Human;
use App\Models\User;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class SearchController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return View
     */
    public function index(): View
    {
       /** @var Auth $user current logged-in user */
        $user = Auth::user();

        /** @var User $contract_id  user contract ID */
        $contractId = $user['contract_rid'];

        try {
            $role = Role::findByName('CID-'.$user->contract_rid);
        } catch (Exception $e)
        {
            abort(403, "You don't have permission to perform basic search.");
        }

        // search groups
        $searchGroups = collect();

        // to add more ...
        if ($role->hasPermissionTo('Basic Search ID card')) {
            $searchGroups->add('ID');
        }

        if ($role->hasPermissionTo('Basic Search Passport card')) {
            $searchGroups->add('Passport');
        }

        if ($role->hasPermissionTo('Basic Search Birth Certificate')) {
            $searchGroups->add('Birth');
        }

        return view('search.search', ['searchGroups' => $searchGroups, 'role' => $role]);
    }

    /**
     * @param StoreContractAPIRequest $request
     * @return array
     */
    public function store(StoreContractAPIRequest $request): array
    {
        $validated =$request->validated();

        //@TODO fetch doc category
        $bulkSearch=$request['bulksearch'];
        $docCategory= $validated['docCategory'];
        $docNumber= $validated['docNumber'];


        if($bulkSearch == 'bulk'){
            //BULK SEARCH
            $humans = $this->bulkSearch($docNumber);
            return [
                'html' => view('search.partials.table_rows', compact('humans'))->render()
            ];
        }else{
            /*@TODO add checker to show 2 related ids*/
            //SINGLE SEARCH 39936418
           //$humans = Human::with('addressBirth')->where('o_pid', '=', $docNumber)->get();'addressLive.adresComp'
           //$humans = Human::with('addressLive')->where('o_pid', '=', $docNumber)->get();//,'addressLive.addressDistrict'
            $humans = Human::with(['addressLive.addressLocation', 'addressLive.addressDistrict'])
                            ->where('o_pid', '=', $docNumber)->get();
           // $doc = Human::with('humanDocum')->where('','=', );
            return [
                'html' => view('search.partials.table_search_row', compact('humans'))->render()
                //'html' => view('search.partials.id_search', compact('humans'))->render()
            ];
        }
        /*return response()->json([
            'html' => view('search.partials.table_rows', compact('humans'))->render()
        ]);*/
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        return view('search.search-result');
        //return view('search.searchResult');
    }

    protected function bulkSearch(string $docNums): array
    {
        $results=[];
        $docNums=str_replace(' ', '', $docNums);
        $ids=explode(',' ,$docNums);
        //loop
        foreach($ids as $id){
            //count queries
           $results[]= Human::where('o_pid', '=', $id)->get();
        }
        return $results;
    }

}
