<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Posyandu;
use App\Models\User;

class PosyanduController extends ApiBaseController
{
    public function index(Request $request)
    {
        $posyandu = Posyandu::all();

        return $this->successResponse("data posyandu", $posyandu);
    }

    public function store(Request $request)
    {
        $validator = validator($request->all(), [
            'id_desa' => ['exists:data_desa,id', 'required'],
            'nama' => ['string', 'required'],
            'alamat' => ['string', 'required'],
            'latitude' => ['string'],
            'longitude' => ['string'],
        ]);

        if ($validator->fails()) {
            return $this->errorValidationResponse("gagal input data posyandu", $validator->errors());
        }

        $posyandu = Posyandu::make([
            'nama' => $request->nama,
            'alamat' => $request->alamat,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
        ]);

        $posyandu->desa()->associate($request->id_desa);

        if (!($posyandu->save())) {
            return $this->errorValidationResponse("gagal create data Posyandu");
        }

        return $this->successResponse("success");
    }

    public function show($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }

    public function showKaderPosyandu()
    {
        try {
            $kaderPosyandu = User::whereHas('role', function ($query) {
                $query->where('role', 'KADER_POSYANDU');
            })->with(['role', 'desa', 'posyandu'])->get();

            if ($kaderPosyandu->isEmpty()) {
                return $this->successResponse("Tidak ada Kader Posyandu yang terdaftar", []);
            }

            return $this->successResponse("Daftar Kader Posyandu", $kaderPosyandu);
        } catch (\Exception $e) {
            return $this->errorResponse("Gagal mengambil data Kader Posyandu: " . $e->getMessage(), 500);
        }
    }

    public function showTenagaKesehatan()
    {
        try {
            $tenagaKesehatan = User::whereHas('role', function ($query) {
                $query->where('role', 'TENAGA_KESEHATAN');
            })->with(['role', 'desa', 'posyandu'])->get();

            if ($tenagaKesehatan->isEmpty()) {
                return $this->successResponse("Tidak ada Tenaga Kesehatan yang terdaftar", []);
            }

            return $this->successResponse("Daftar Tenaga Kesehatan", $tenagaKesehatan);
        } catch (\Exception $e) {
            return $this->errorResponse("Gagal mengambil data Tenaga Kesehatan: " . $e->getMessage(), 500);
        }
    }

    public function destroy($id)
    {
        try {
            $posyandu = Posyandu::withCount('anak')->find($id);
    
            if (!$posyandu) {
                return $this->errorNotFound("Posyandu tidak ditemukan");
            }
    
            if ($posyandu->anak_count > 0) {
                return $this->errorValidationResponse("Tidak bisa menghapus posyandu karena masih memiliki data anak.");
            }
    
            $posyandu->delete();
    
            return $this->successResponse("Posyandu berhasil dihapus");
        } catch (\Exception $e) {
            return $this->errorValidationResponse("Gagal menghapus Posyandu", $e->getMessage());
        }
    }


    public function deleteKaderPosyandu($userId)
    {
        try {
            $user = User::whereHas('role', function ($query) {
                $query->where('role', 'KADER_POSYANDU');
            })->find($userId);

            if (!$user) {
                return $this->errorNotFound("Kader Posyandu tidak ditemukan");
            }

            $user->delete();

            return $this->successResponse("Success Delete Kader Posyandu");
        } catch (\Exception $e) {
            return $this->errorResponse("Gagal menghapus Kader Posyandu: " . $e->getMessage(), 500);
        }
    }

    public function deleteTenagaKesehatan($userId)
    {
        try {
            $user = User::whereHas('role', function ($query) {
                $query->where('role', 'TENAGA_KESEHATAN');
            })->find($userId);

            if (!$user) {
                return $this->errorNotFound("Tenaga Kesehatan tidak ditemukan");
            }

            $user->delete();

            return $this->successResponse("Success Delete Tenaga Kesehatan");
        } catch (\Exception $e) {
            return $this->errorResponse("Gagal menghapus Tenaga Kesehatan: " . $e->getMessage(), 500);
        }
    }
}