<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Models\Person;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class DataController extends Controller
{
    public function show($id)
    {
        try {
            $data = Person::findOrFail($id);
            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Member not found'], 404);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $data = Person::findOrFail($id);
            $data->update($request->all());

            return response()->json(['message' => 'Data updated successfully']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to update data'], 500);
        }
    }

    public function updateFamily(Request $request)
    {
        try {
            // Ambil data keluarga dari payload
            $familyData = $request->json()->all();

            // Loop melalui data keluarga
            foreach ($familyData as $familyMember) {
                // Ambil ID anggota keluarga dari payload
                $person_id = $familyMember['person_id'];

                // Perbarui data anggota keluarga sesuai dengan payload
                Member::where('person_id', $person_id)->update([
                    'name' => $familyMember['name'],
                    'email' => $familyMember['email'],
                    'relation_with_principal' => $familyMember['relation_with_principal'],
                    'birth_date' => $familyMember['birth_date'],
                ]);

                Person::where('id', $person_id)->update([
                    'name' => $familyMember['name'],
                    'email' => $familyMember['email'],
                    'phone' => $familyMember['phone'],
                    'birth_date' => $familyMember['birth_date']
                ]);
            }

            // Respon sukses jika pembaruan berhasil
            return response()->json([$person_id => 'Data keluarga berhasil diperbarui'], 200);
        } catch (\Exception $e) {
            // Tangani kesalahan jika ada yang terjadi
            return response()->json(['error' => 'Gagal memperbarui data keluarga: ' . $e->getMessage()], 500);
        }
    }
}
