<?php

namespace App\Livewire\Search;

use App\Models\Docum;
use App\Models\Human;
use App\Models\IprsImg;
use App\Models\RegistrOffice;
use App\Models\Relative;
use App\Models\User;
use App\Traits\GetHumanIDTrait;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Component;
use Spatie\Permission\Models\Role;

class Resultsmodal extends Component
{
    use GetHumanIDTrait;

    public $role;
    public $isOpen = false;
    public $human=[];
    public $docums=[];
    public $placeissued=[];
    public $familyrelation;

    protected $listeners = ['openModal'];
    public $serialNum='';
    public $humanAllDocs=[];
    private $doc_num='';
    private $serial_num='';
    public $doctype='';
    public $photo;

    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.");
        }
    }

    #[On('openModal')]
    public function openModal($doc_num, $serial_num, $doctype): void
    {
        try {
            switch ($doctype){
                case 'ID':
                    $human_data = $this->getHuman($doc_num, $serial_num);
                break;
                case 'Birth':
                    $human_data = $this->getHumanBirth($doc_num,$serial_num);
                break;
            }
            //$human_data = $this->getHuman($doc_num, $serial_num);
            if ($human_data) {
                $this->human            = $human_data[0];
                $this->docums           = $human_data[1];
                $this->familyrelation   = $human_data[2];
                $this->humanAllDocs     = !empty($human_data[3]) ? $human_data[3] : '';
                //$this->photo            =$human_data[3];
                $this->doctype          = $doctype;
                $this->isOpen           = true; //open modal
                $this->serialNum        = $serial_num;
            } else {
                /*@TODO add a handler for this*/
                // Handle the case where no data is found
                //$this->dispatchBrowserEvent('notification', ['type' => 'error', 'message' => 'No data found']);
            }
        } catch (\Exception $e) {
            //@ToDo add a handler for this
            // Handle any errors that occur during data retrieval
           // $this->dispatchBrowserEvent('notification', ['type' => 'error', 'message' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    public function closeModal()
    {
       // $this->isOpen = false;
    }

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

    private function getHuman($docNumber, $serial_num=null)
    {
        //fetch id data
        $data = $this->getDetailedIDHuman($docNumber,$serial_num,'id');
        //get data from array
        $human        = $data['human'];
        $docums_data  = $data['docums'];
        $humanAllDocs = $data['all_docs'];
        $family       = $data['family'];

        return [$human, $docums_data, $family, $humanAllDocs];
    }

    public function placeholder()
    {
       return view('livewire.search.skeleton.resultsmodal');
    }

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

        if(isset($child_id[0])){
            $parents_id= Relative::where('second_person', '=', $child_id[0]['second_person'])->get(['first_person','type_rel']);
            foreach($child_id as $child){
                $children[] = $this->queryHuman($child['second_person']);
                foreach($parents_id as $parent){
                    $parents[]=$this->queryHuman($parent['first_person']);
                }
            }
            return ['parents'=>$parents,'children'=>$children];
        }
       return [];
    }
    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;
    }

    private function getPhoto($docnumber)
    {
        /*$human_photo = Human::whereNotNull('photo')->where('o_pid', '=', $docnumber)->first(['pid', 'photo']);
        //get blob file
        $photo_id= $human_photo['photo'];
        $photo = IprsImg::where('rid','=',$photo_id)->first();*/
       // dd($photo['img']);
        return true;
    }

    private function getHumanBirth($doc_num,$serial_num)
    {
        $docums_data=[];
        $relation=[];
        $parents=[];

        if(!empty($serial_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' => $serial_num]);
            //$human_rid = Docum::where('ser_num', '=', $serial_num)->value('rid_h');
            $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'];

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

}
