<?php

namespace App\Livewire\Search\Advance;

use App\Models\Docum;
use App\Models\Human;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Livewire\Component;

class Passportsearch extends Component
{
    public $passportnumber;
    public $serialnum;
    public $pinumber;

    public $firstname;
    public $othername;
    public $surname;

    public $dateofissue;
    public $dateofexpiry;

    public $gender;
    public $month;

    protected $rules = [
        'surname' => 'nullable|string|min:3',
    ];

    private array $serial_number;
    private $search_count;

    public function mount()
    {
        $this->surname='';
        $this->othername='';
        $this->firstname='';
        $this->pinumber='';
        $this->passportnumber='';
        $this->serialnum='';
        $this->month='';
        $this->gender='';

    }

    public function search()
    {
        //validate
        $this->getHuman($this->firstname,$this->surname,$this->othername,$this->serialnum, $this->month, $this->gender,
            $this->idnumber, $this->pinumber);
    }


    public function render()
    {
        return view('livewire.search.advance.passportsearch');
    }

    private function getHuman($firstname, $surname, $othername, $serialnum, $passportnumber, $pinumber, $month, $gender)
    {
        $search_count=0;
        $conditions = [
            'name'      => $firstname,
            'surn'      => $surname,
            'last_name' => $othername,
            'o_pid'     => $passportnumber, /* Passport number in db? */
            'pid'       => $pinumber,
            'month_birth'=> $month,
            'sex'    => $gender,
        ];
        // Filter out empty values
        $conditions = array_filter($conditions);
        $query = Human::query();
        foreach ($conditions as $column => $value) {
            $query->where($column, $value);
        }
        $humans =$query->whereColumn('rid', 'pid')->get(['rid', 'pid', 'name', 'surn', 'last_name', 'sex', 'date_birth', 'date_death', 'o_pid']);  /* Passport number in db? */

        if($humans->isEmpty()){
            throw new ModelNotFoundException('No record found');
        }else{
            foreach($humans as $human_serial){
                $pid = $human_serial['pid'];
                $humans[$search_count]['serial_num'] = Docum::where('rid_h', '=', $pid)->value('ser_num');
                $search_count++;
            }
            $this->dispatch('viewAdvResults', $humans, $search_count);
        }
        return $humans;
    }

}