<?php

namespace App\Livewire\Search\Advance;

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

class Deathsearch extends Component
{
    public $birthnumber;
    public $serialnum;
    public $pinumber;

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

    public $dateofregistration;
    public $dob;
    public $mothername;

    public $gender;
    public $placeofbirth;

    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->birthnumber=''; /* */
        $this->serialnum='';
        $this->dob=''; /* */
        $this->gender='';
        $this->mothername=''; /* */
        $this->dateofregistration=''; /* */
        $this->placeofbirth=''; /* */

    }

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

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

    private function getHuman($firstname, $surname, $othername, $serialnum, $birthnumber, $pinumber, $month, $gender, $dob, $dateofregistration, $placeofbirth)
    {
        $search_count=0;
        $conditions = [
            'name'      => $firstname,
            'surn'      => $surname,
            'last_name' => $othername,
            'o_pid'     => $birthnumber, /* */
            'pid'       => $pinumber,
            'dob'       => $dob, /* */
            'month_birth'=> $month, /* */
            /* place of birth */
            /* date of registration */
            /* mother name */
            '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']);  /* Birth 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;
    }

}