<?php

namespace App\Http\Controllers;

use Intervention\Image\Facades\Image;
use Illuminate\Http\Request;
use App\Models\Anak;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;




class AnakController extends Controller
{
    public function index()
    {
        $anak = Anak::where('pengguna_id', Auth::id())->get();

        // Tambahkan URL lengkap untuk foto_profil
        $anak->transform(function ($item) {
            $item->foto_profil_url = $item->foto_profil
                ? asset('storage/' . $item->foto_profil)
                : null;
            return $item;
        });

        return response()->json($anak);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'tanggal_lahir' => 'required|date',
            'jenis_kelamin' => 'required|string|in:Laki-laki,Perempuan',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = null;

        if ($request->hasFile('foto')) {
            $foto = $request->file('foto');
            $filename = uniqid('anak_') . '.' . $foto->getClientOriginalExtension();

            $manager = new ImageManager(new Driver()); // ✅ Ini penting
            $image = $manager->read($foto)->cover(300, 300); // ✅ untuk resize
            $image->save(storage_path('app/public/foto-anak/' . $filename));

            $fotoPath = 'foto-anak/' . $filename;
        }

        $anak = Anak::create([
            'pengguna_id' => Auth::id(),
            'nama' => $validated['nama'],
            'tanggal_lahir' => $validated['tanggal_lahir'],
            'jenis_kelamin' => $validated['jenis_kelamin'],
            'foto_profil' => $fotoPath,
        ]);

        $anak->foto_profil_url = $anak->foto_profil
            ? asset('storage/' . $anak->foto_profil)
            : null;

        return response()->json($anak, 201);
    }


    public function show($id)
    {
        $anak = Anak::where('id', $id)->where('pengguna_id', Auth::id())->first();

        if (!$anak) {
            return response()->json(['message' => 'Data anak tidak ditemukan'], 404);
        }

        $anak->foto_profil_url = $anak->foto_profil
            ? asset('storage/' . $anak->foto_profil)
            : null;

        return response()->json($anak);
    }

    public function update(Request $request, $id)
    {
        $anak = Anak::where('id', $id)->where('pengguna_id', Auth::id())->first();
        if (!$anak) {
            return response()->json(['message' => 'Data anak tidak ditemukan'], 404);
        }

        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'tanggal_lahir' => 'required|date',
            'jenis_kelamin' => 'required|string|in:Laki-laki,Perempuan',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Handle foto baru (jika ada)
        if ($request->hasFile('foto')) {
            $foto = $request->file('foto');
            $filename = uniqid('anak_') . '.' . $foto->getClientOriginalExtension();

            $manager = new \Intervention\Image\ImageManager(new \Intervention\Image\Drivers\Gd\Driver());
            $image = $manager->read($foto)->cover(300, 300);
            $image->save(storage_path('app/public/foto-anak/' . $filename));

            // Hapus foto lama jika ada
            if ($anak->foto_profil) {
                Storage::delete('public/' . $anak->foto_profil);
            }


            $validated['foto_profil'] = 'foto-anak/' . $filename;
        }

        $anak->update($validated);

        $anak->foto_profil_url = $anak->foto_profil
            ? asset('storage/' . $anak->foto_profil)
            : null;

        return response()->json($anak);
    }

    public function destroy($id)
    {
        $anak = Anak::where('id', $id)->where('pengguna_id', Auth::id())->first();
        if (!$anak) {
            return response()->json(['message' => 'Data anak tidak ditemukan'], 404);
        }

        $anak->delete();
        return response()->json(['message' => 'Data anak berhasil dihapus']);
    }
}