<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\OLDLMS\User;
use App\Models\OLDLMS\UserDetail;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Linksehat\Transformers\User\ShowProfileResource;
use Modules\Linksehat\Transformers\User\UserProfileResource;


class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $id)
    {
        $user = User::with(['detail'])->where('nID', $id)->get()->first();

        return Helper::responseJson(new ShowProfileResource($user));
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('linksehat::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('linksehat::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('linksehat::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'first_name' => 'required',
            'last_name' => 'required',
            'date_of_birth' => 'required',
            // 'email' => 'required',
        ]);
    

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

        $user = User::find($request->id);
        $userDetail = UserDetail::where('nIDUser', $request->id)->first();
        // Array asosiatif yang menghubungkan field dengan nama kolom di tabel
        $userFields = [
            'first_name' => 'sFirstName',
            'last_name' => 'sLastName',
            'phone' => 'sPhone',
            'email' => 'sEmail',
            'relationship' => 'nIDHubunganKeluarga',
        ];

        $userDetailFields = [
            'date_of_birth' => 'dTanggalLahir',
            'gender' => 'nIDJenisKelamin',
            'blood_type' => 'nIDGolonganDarah',
            'marital_status' => 'sMartialStatus',
            'weight' => 'sWeight',
            'height' => 'sHeight',
        ];

        // Update user data
        foreach ($userFields as $requestField => $column) {
            if ($request->filled($requestField)) {
                $user->update([$column => $request->$requestField]);
            }
        }

        // Update user detail
        if($userDetail){
            foreach ($userDetailFields as $requestField => $column) {
                if ($request->filled($requestField)) {
                    $userDetail->update([$column => $request->$requestField]);
                }
            }
        } else {
            UserDetail::create([
                'nIDUser' => $request->id,
                'dTanggalLahir' => $request->date_of_birth,
                'nIDJenisKelamin' => $request->gender,
                'nIDGolonganDarah' => $request->blood_type,
                'sMartialStatus' => $request->marital_status,
                'sWeight' => $request->weight,
                'sHeight' => $request->height,
            ]);
        }


        // poto profile
        // if ($request->hasFile('avatar')) {
        //     $pathFileAvatar = File::storeFile('photo_profile_lms', $newCorporate->id, $request->file('avatar'));
        //     $newCorporate->files()->updateOrCreate([
        //         'type' => 'photo_profile_lms',
        //         'name' => File::getFileName('photo_profile_lms', $newCorporate->id, $request->file('avatar')),
        //         'extension' => $request->file('avatar')->getClientOriginalExtension(),
        //         'path' => $pathFileAvatar,
        //         'created_by' => auth()->user()->id,
        //         'updated_by' => auth()->user()->id,
        //     ]);
        // }

        $data['data'] = [
            'status' => 200,
            'message' => 'data berhasil di edit',
            'error' => 'false'

        ];

          
        return response()->json($data);
        

    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public function changeProfile($id){
        $user = User::with('detail')
        ->where('nID', $id)
        ->first();
        return Helper::responseJson(
            data: [
                // 'token' => $user->createToken('app')->plainTextToken,
                'user' => UserProfileResource::make($user),
            ],
            message: 'Selamat Datang'
        );
    }
}
