<?php

namespace Modules\Linksehat\Transformers\User;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\OLDLMS\User;
use App\Models\OLDLMS\UserDetail;
use App\Models\OLDLMS\UserInsurance;
use App\Models\Member;
use App\Models\Person;
use App\Models\CorporateEmployee;
use App\Models\Corporate;
use Illuminate\Support\Facades\Auth;

use DB;


class UserProfileResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */

    protected $connection = 'oldlms';

    public function toArray($request)
    {
        $memberProfile = User::with('detail')->where('nIDUser', $this->nID)->get()->toArray();
        $dataMemberProfile = [];

        $userInsurance = UserInsurance::where('nIDUser', $this->nID)->get()->first();
        $memberId = null;
        $linking = false;
        if($userInsurance){
            $memberId  = $userInsurance->sNoPolis;
            $linking = true;
        } else {
            $member = Member::where('email', $this->sEmail)->get()->first();
            $person = Person::where('phone', $this->sPhone)->get()->first();
            if ($member || $person){ // Autolinking
                $corporateEmployee = CorporateEmployee::where('member_id', $member->id)->get()->first(); // cek corporate id empolyee/member
                if ($corporateEmployee){
                    $corporate = Corporate::findOrFail($corporateEmployee->corporate_id)->automatic_linking; // cek autocomplete
                    if ($corporate){
                        if($member) {
                            // Insert into database linksehat
                            $insurance = UserInsurance::updateOrCreate(
                            [
                                'nIDUser' => $this->nID,
                            ],
                            [
                                'nIDUser' => $this->nID,
                                'nIDInsurance' => $_ENV['LINKSEHAT_ASO_INSURANCE_ID'],
                                'sNoPolis' => $member->member_id,
                                'sNamaPeserta' => $member->fullName,
                                'sKartuPeserta' => '',
                                'sLayanan' => 'RJ,TC',
                                'dStartDate' => $member->members_effective_date,
                                'dExpireDate' => $member->members_expire_date,
                                'dTanggalLahir' => $member->birth_date,
                                'nNoKTP' => $member->nric != '' ? $member->nric : 0 ,
                                'sIsConfrimed' => 1,
                                'sStatus' => 1,
                            ]);
                            $message = $member->currentPolicy->corporate->welcome_message;
                            $linking = true;

                            $memberId  = $member->member_id;
                        }
                    }
                }
            }
        };

        if (count($memberProfile) > 0){
            
            $urlAvatarDefault = $this->detail->nIDJenisKelamin == 1 ? 'https://linksehat.dev/assets/img/users/male-avatar.png' : 'https://linksehat.dev/assets/img/users/female-avatar.png';
            $avatarMember = $this->detail->sImage ?? $urlAvatarDefault;
            $relationship = DB::connection('oldlms')->table('tm_hubungan_keluarga')->where('nID', $this->nIDHubunganKeluarga)->first('sHubunganKeluarga');
            
            $dataUser = [
                'id' => $this->nID,
                'name' => $this->sFirstName . ' ' . $this->sLastName,
                'relationship' => $relationship ? $relationship->sHubunganKeluarga : '-',
                'avatar' => $avatarMember
            ];

            array_push($dataMemberProfile, $dataUser);

            foreach($memberProfile as $m){
                $urlAvatarDefault = $m['detail']['nIDJenisKelamin'] == 1 ? 'https://linksehat.dev/assets/img/users/male-avatar.png' : 'https://linksehat.dev/assets/img/users/female-avatar.png';
                $avatarMember = $m['detail']['sImage'] ?? $urlAvatarDefault;
                $relationship = DB::connection('oldlms')->table('tm_hubungan_keluarga')->where('nID', $m['nIDHubunganKeluarga'])->first('sHubunganKeluarga');
               
                $data = [
                    'id' => $m['nID'],
                    'name' => $m['full_name'],
                    'relationship' => $relationship ? $relationship->sHubunganKeluarga : '-',
                    'avatar' => $avatarMember,
                ];

                array_push( $dataMemberProfile, $data);
            }


        } else {
            $nID = $this->nIDUser ?  $this->nIDUser : $this->nID;
            if ($nID){
                $memberProfile = User::with('detail')->where('nIDUser', $nID)->get()->toArray();

                $dataMember = User::with('detail')->where('nID', $nID)->get()->first();
                                
                if ($this->detail){
                    $urlAvatarDefault = $this->detail->nIDJenisKelamin == 1 ? 'https://linksehat.dev/assets/img/users/male-avatar.png' : 'https://linksehat.dev/assets/img/users/female-avatar.png';
                } else {
                    $urlAvatarDefault =  'https://linksehat.dev/assets/img/users/male-avatar.png';
                }
                $avatar = $this->detail->sImage ?? $urlAvatarDefault;
        
                $avatarMember = $dataMember->detail->sImage ?? $urlAvatarDefault;
                $relationship = DB::connection('oldlms')->table('tm_hubungan_keluarga')->where('nID', $this->nIDHubunganKeluarga)->first('sHubunganKeluarga');
                
                $dataUser = [
                    'id' => $dataMember->nID,
                    'name' => $dataMember->sFirstName . ' ' . $dataMember->sLastName,
                    'relationship' => 'Me',
                    'avatar' => $avatarMember
                ];
                array_push($dataMemberProfile, $dataUser);

                if (count($memberProfile) > 0){
                    foreach($memberProfile as $m){
                        $urlAvatarDefault = $m['detail']['nIDJenisKelamin'] == 1 ? 'https://linksehat.dev/assets/img/users/male-avatar.png' : 'https://linksehat.dev/assets/img/users/female-avatar.png';
                        $avatarMember = $m['detail']['sImage'] ?? $urlAvatarDefault;
                        $relationship = DB::connection('oldlms')->table('tm_hubungan_keluarga')->where('nID', $m['nIDHubunganKeluarga'])->first('sHubunganKeluarga');
               
                        $data = [
                            'id' => $m['nID'],
                            'name' => $m['full_name'],
                            'relationship' => $relationship->sHubunganKeluarga,
                            'avatar' => $avatarMember,
                        ];
        
                        array_push( $dataMemberProfile, $data);
                    }
                }
            } else {

            }
        }

        // Principal
        if ($this->detail){
            $urlAvatarDefault = $this->detail->nIDJenisKelamin == 1 ? 'https://linksehat.dev/assets/img/users/male-avatar.png' : 'https://linksehat.dev/assets/img/users/female-avatar.png';
        } else {
            $urlAvatarDefault =  'https://linksehat.dev/assets/img/users/male-avatar.png';
        }
        $avatar = $this->detail->sImage ?? $urlAvatarDefault;


        return [
            'id' => $this->nID,
            'full_name' => $this->sFirstName . ' '. $this->sLastName,
            'avatar' => $avatar,
            'member_type' => $this->nIDUser ? 'Dependent' : 'Principal',
            'member_profile' => $dataMemberProfile,
            'member_id' => $memberId,
            'linking'  => $linking,
        ];
    }
}
