<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\File;
use App\Models\Person;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Modules\Linksehat\Http\Requests\PersonRequest;
use Modules\Linksehat\Transformers\Person\PersonResource;
use Symfony\Component\HttpFoundation\Response;

class PersonController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $user = Auth::user();
        $user->load(['person', 'person.families', 'person.avatar']);

        $families = $user->person->families;
        $currentUserPerson = $user->person;
        unset($currentUserPerson->families);
        $families->prepend($currentUserPerson);

        return Helper::responseJson(PersonResource::collection($families));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(PersonRequest $request)
    {
        $personData = $request->only([
            'owner_user_id',
            'nik',
            'name_prefix',
            'name',
            'name_suffix',
            'phone',
            'email',
            'gender',
            'birth_date',
            'birth_place',
            'citizenship',
            'current_employment',
            'last_education',
            'religion',
            'blood_type',
            'is_deceased',
            'deceased_at',
            'marital_status',
            'main_address_id',
            'domicile_address_id',
        ]);
        $personData['last_weight_kg'] = $request->weight ?? null;
        $personData['last_height_cm'] = $request->height ?? null;
        $personData = array_merge($personData, [
            'owner_user_id' => auth()->user()->id,
        ]);

        $person = Person::query()->create($personData);
        auth()->user()->person->families()->attach($person, [
            'relation_with_owner' => $request->relation_with_owner
        ]);

        return Helper::responseJson(['persons' => new PersonResource($person)], Response::HTTP_CREATED, 'Data berhasil di buat');
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show(Person $person)
    {
        return Helper::responseJson(data: new PersonResource($person), message: 'Data Person dengan nama ' . $person->name . ' berhasil di ambil');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(PersonRequest $request, Person $family)
    {
        if (Gate::forUser(auth()->user())->allows('update-person', $family)) {
            $personData = $request->only([
                'owner_user_id',
                'nik',
                'name_prefix',
                'name',
                'name_suffix',
                'phone',
                'email',
                'birth_date',
                'birth_place',
                'citizenship',
                'current_employment',
                'last_education',
                'religion',
                'blood_type',
                'is_deceased',
                'deceased_at',
                'marital_status',
                'main_address_id',
                'domicile_address_id',
            ]);
            $personData['last_weight_kg'] = $request->weight ?? null;
            $personData['last_height_cm'] = $request->height ?? null;
            $personData['gender'] = $request->has('gender') ? ($request->gender == 'P' ? 'M' : ($request->gender == 'W' ? 'F' : null)) : null;

            $family->fill($personData);
            $family->save();

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

            if ($request->hasFile('verification_file')) {
                $pathFileVerification = File::storeFile('dataDiri', $family->id, $request->file('verification_file'));
                $family->files()->updateOrCreate([
                    'type' => 'dataDiri',
                    'name' => File::getFileName('dataDiri', $family->id, $request->file('verification_file')),
                    'extension' => $request->file('verification_file')->getClientOriginalExtension(),
                    'path' => $pathFileVerification,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }

            if ($request->has('relation_with_owner') && auth()->user()->person_id != $family->id) {
                $family->familyOwner()->updateOrCreate([
                    'owner_id' => auth()->user()->person_id,
                    'person_id' => $family->id,
                ], [
                    'owner_id' => auth()->user()->person_id,
                    'relation_with_owner' => $request->relation_with_owner,
                    'person_id' => $family->id,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }

            return Helper::responseJson(data: ['persons' => PersonResource::make($family)], message: 'Data Berhasil di update');
        } elseif (Gate::forUser(auth()->user())->denies('update-person', $family)) {
            abort(Response::HTTP_FORBIDDEN, 'Tidak bisa update karena bukan pemilik!');
        }
    }

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