<?php

namespace App\Livewire\Search\Advance;

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

class Idsearch extends Component
{
    public $idnumber;
    public $serialnum;
    public $pinumber;
    public $firstname;

    public $surname;

    public $othername;

    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->idnumber='';
        $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.idsearch');
    }

    private function getHuman($firstname, $surname, $othername, $serialnum, $idnumber, $pinumber, $month, $gender)
    {
        $search_count=0;
        $conditions = [
            'name'      => $firstname,
            'surn'      => $surname,
            'last_name' => $othername,
            'o_pid'     => $idnumber,
            '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']);

        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;
    }

}
