<?php

namespace App\Livewire\Search;

use App\Models\Human;
use App\Models\Relative;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Component;
use Spatie\Permission\Models\Role;

class BirthModal extends Component
{

    protected $listeners = ['openBirthModal'];
    public $birth_human;
    public $hasRole = false;
    public $role;
    public $isOpen = false;
    public $birth_docums;
    public $birth_serialNum='';
    public $birth_familyrelation;
    public function mount()
    {
        /** @var Auth $user current logged-in user */
        $user = Auth::user();

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

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

    public function render()
    {
        return view('livewire.search.birth-modal');
    }

    #[On('openBirthModal')]
    public function openBirthModal($data): void
    {
        $entryNum= $data['entry_num'];
        $birth= $this->getHumanBirth($entryNum);
        if($birth){
            $this->birth_human           = $birth[0];
            $this->birth_docums          = $birth[1];
            $this->birth_familyrelation  = $birth[2];
            $this->isOpen = true;
            $this->birth_serialNum = $data['entry_num'];
        }
    }

    /*public function placeholder()
    {
        return view('livewire.search.skeleton.resultsmodal');
    }*/
    public function closeModal()
    {
       // $this->isOpen = false;
    }

    private function getHumanBirth($entry_num)
    {
        $docums_data=[];
        $relation=[];
        $parents=[];

        if(!empty($entry_num)){
            $query = "SELECT json_array(doc_rekv),pid FROM docums WHERE ser_num = :ser_num ORDER BY DAT_PRODUCT desc";
            $query_docums = DB::select($query, ['ser_num' => $entry_num]);
            $docums_json = json_decode(json_encode($query_docums), true);

            foreach($docums_json as $doc_array) {
                $rid=$doc_array['pid'];
                $docums_data = json_decode($doc_array["json_array(doc_rekv)"], true);
            }
            //$motherId=$docums_data[0]['MOTHER_DOC_NUMBER'];
            $parents['mother']=$docums_data[0]['M_NAME'].' '.$docums_data[0]['M_OTHNAME'].' '.$docums_data[0]['M_SURN'];
            $parents['father']=$docums_data[0]['F_NAME'].' '.$docums_data[0]['F_OTHNAME'].' '.$docums_data[0]['F_SURN'];
           // $birthReg_num=$docums_data[0]['BIRTHREG_NUMBER'];
            $birthReg_num=$docums_data[0]['BIRTHREG_SERIAL'];
            //$this->familyRelation($motherId);
            $human = Human::with(['addressBirth.adresComp'])
                ->where('rid', '=', $rid)//first()
                ->whereColumn('rid', 'pid') //
                ->orderBy('data_scan', 'desc')->first();
            $relation = $this->birthfamilyRelation($rid);
            return [$human, $docums_data, $relation];
        }

        return null;
    }

    private function birthfamilyRelation($rid): array
    {
        $motherFather=[];
        $humans=[];
        //get parents
        $parents = Relative::where('first_person','=',$rid)->get(['second_person']);

        if(isset($parents)) {
            foreach ($parents as $parent) {
                $motherFather[] = $parent['second_person'];
            }
        }
        foreach ($motherFather as $human){
            $humans[]=$this->queryHuman($human); //the correct
        }
        return $humans;
    }

}
