<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Person;
use App\Models\Corporate;
use App\Models\Member;
use App\Models\OLDLMS\User;
use App\Models\OLDLMS\UserInsurance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;
use Modules\Linksehat\Transformers\User\UserProfileResource;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\OLDLMS\MemberResource;
use App\Rules\NikRule;


class LinkingController extends Controller
{
    private $url;

    public function __construct() {
        $this->url = $_ENV['LMS_APP_URL'];
    }

    public function linkingValidate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'corporate_id' => 'required',
            'user_id' => 'required',
        ]);

         // $request->validate($validationRules);
         if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $corporate = Corporate::findOrFail($request->corporate_id);     
        // Make Validation from Linking Rules
        $linkingRulesArr = $corporate->linking_rules->toArray();

        $validationRules = [];
        foreach ($linkingRulesArr as $field) {
            $rules = ['required']; // Default is required if in the linking_rules
            if ($field == 'email') {
                $rules[] = 'email';
            }

            if ($field == 'nric') {
                $rules[] = new NikRule;
            }

            $validationRules[$field] = $rules;
        }

        $validator = Validator::make($request->all(),$validationRules);

        // $request->validate($validationRules);
        if ($validator->fails()) {
            return Helper::responseJson(data: [], message: 'Member Tidak ditemukan', statusCode: 422, status: 'error');
        }

        $member = Member::query()
            ->when(in_array('nric', $linkingRulesArr), function($q) use ($request) {
                $q->where('nric', $request->nric);
            })
            ->when(in_array('member_id', $linkingRulesArr), function($q) use ($request) {
                $q->where('member_id', $request->member_id);
            })
            ->when(in_array('name', $linkingRulesArr), function($q) use ($request) {
                $q->where('name', $request->name);
            })
            ->when(in_array('dob', $linkingRulesArr), function($q) use ($request) {
                $q->where('birth_date', $request->dob);
            })
            ->when(in_array('phone', $linkingRulesArr), function($q) use ($request) {
                $q->whereHas('person', function ($person) use ($request) {
                    $person->where('phone', $request->phone);
                });
            })
            ->when(in_array('email', $linkingRulesArr), function($q) use ($request) {
                $q->where('email', $request->email);
            })
            ->when(in_array('nik', $linkingRulesArr), function($q) use ($request) {
                $q->whereHas('employeds', function ($employed) use ($request) {
                    $employed->where('corporate_id', $request->corporate_id)
                        ->where('nik', $request->nik);
                });
            })

            ->with([
                'memberPlans' => function ($memberPlan) {
                    $memberPlan->latest();
                },

            ])

            ->first();

        if ($member) {
            // Insert into database linksehat
            $insurance = UserInsurance::updateOrCreate(
            [
                'nIDUser' => $request->user_id,
            ],
            [
                'nIDUser' => $request->user_id,
                '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;
            return Helper::responseJson(data: MemberResource::make($member), message: $message);
        }

        return Helper::responseJson(data: [], message: 'Member Tidak ditemukan', statusCode: 404, status: 'error');
    }

    public function card($member_id){
        $member = Member::where('member_id', $member_id)->get()->first();
        $message = $member->currentPolicy->corporate->welcome_message;
        return Helper::responseJson(data: MemberResource::make($member), message: $message);
    }
}
