<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\DesaResource;
use App\Models\Desa;
use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class DesaController extends ApiBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $desa = Desa::all();

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validasi input untuk desa dan akun
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        if ($validator->fails()) {
            return $this->errorValidationResponse("Gagal input data desa atau akun", $validator->errors());
        }

        // Normalisasi nama untuk email (huruf kecil, tanpa spasi)
        $namaDesa = $request->name;
        $email = Str::slug($namaDesa, '') . '@gmail.com';

        // Validasi email unik
        $emailValidator = Validator::make(['email' => $email], [
            'email' => ['required', 'email', 'unique:users,email'],
        ]);

        if ($emailValidator->fails()) {
            return $this->errorValidationResponse("Email {$email} sudah digunakan", $emailValidator->errors());
        }

        // Mulai transaksi database
        DB::beginTransaction();

        try {
            // Buat data desa
            $desa = Desa::create([
                'name' => $namaDesa,
            ]);

            if (!$desa) {
                throw new \Exception("Gagal menyimpan data desa");
            }

            // Cari role DESA
            $role = Role::where('role', 'DESA')->first();
            if (!$role) {
                throw new \Exception("Role DESA tidak ditemukan");
            }

            // Buat akun dengan role DESA
            $user = User::create([
                'nama' => $namaDesa,
                'email' => $email,
                'password' => bcrypt($request->password),
                'id_desa' => $desa->id,
                'status' => true,
            ]);

            // Kaitkan role DESA
            $user->role()->associate($role);
            $user->save();

            // Commit transaksi
            DB::commit();

            // Kembalikan respons sukses dengan data
            return $this->successResponse("Data desa dan akun berhasil dibuat", [
                'desa' => new DesaResource($desa),
                'user' => [
                    'email' => $email,
                    'role' => 'DESA',
                    'status' => true,
                ],
            ]);
        } catch (\Exception $e) {
            // Rollback transaksi jika gagal
            DB::rollBack();
            return $this->errorValidationResponse("Gagal membuat data desa dan akun: " . $e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Desa  $desa
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Desa  $desa
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Desa  $desa
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $desa = Desa::withCount(['posyandu', 'anak'])->find($id);
    
        if (!$desa) {
            return $this->errorNotFound("Desa tidak ditemukan");
        }
    
        if ($desa->posyandu_count > 0 || $desa->anak_count > 0) {
            return $this->errorValidationResponse("Tidak bisa menghapus desa karena memiliki data posyandu atau anak yang terkait.");
        }
    
        $desa->delete();
    
        return $this->successResponse("Desa berhasil dihapus");
    }

    public function getStatistikDesa($id)
    {
        $desa = Desa::find($id);
    
        if (empty($desa)) {
            return $this->errorNotFound("Desa tidak ditemukan");
        }
    
        $response = [];
        $all_posyandu = $desa->posyandu;
    
        // Inisialisasi total
        $total = [
            "id_posyandu" => null,
            "nama_posyandu" => "Total Semua Posyandu",
            "jumlah_anak" => 0,
            "berat_badan" => [
                'gemuk' => 0,
                'normal' => 0,
                'kurus' => 0,
                'sangat_kurus' => 0,
            ],
            "tinggi_badan" => [
                'tinggi' => 0,
                'normal' => 0,
                'pendek' => 0,
                'sangat_pendek' => 0,
            ],
            "lingkar_kepala" => [
                'makrosefali' => 0,
                'normal' => 0,
                'mikrosefali' => 0,
            ],
        ];
    
        foreach ($all_posyandu as $key => $posyandu) {
            $statistik = [
                "id_posyandu" => $posyandu->id,
                "nama_posyandu" => $posyandu->nama,
                "jumlah_anak" => 0,
                "berat_badan" => [
                    'gemuk' => 0,
                    'normal' => 0,
                    'kurus' => 0,
                    'sangat_kurus' => 0,
                ],
                "tinggi_badan" => [
                    'tinggi' => 0,
                    'normal' => 0,
                    'pendek' => 0,
                    'sangat_pendek' => 0,
                ],
                "lingkar_kepala" => [
                    'makrosefali' => 0,
                    'normal' => 0,
                    'mikrosefali' => 0,
                ],
            ];
    
            if (!empty($posyandu->anak)) {
                $allLatsStatistik = [];
                foreach ($posyandu->anak as $anak) {
                    $latestStatistik = DB::table('data_statistik_anak')->where('id_anak', $anak->id)->latest('created_at')->first();
                    if ($latestStatistik) {
                        $allLatsStatistik[] = $latestStatistik;
                    }
                }
    
                $statistik["jumlah_anak"] = $posyandu->jumlahAnak();
                $statistik["berat_badan"] = $posyandu->laporanBerat($allLatsStatistik);
                $statistik["tinggi_badan"] = $posyandu->laporanTinggi($allLatsStatistik);
                $statistik["lingkar_kepala"] = $posyandu->laporanLingkarKepala($allLatsStatistik);
    
                // Tambahkan ke total
                $total["jumlah_anak"] += $statistik["jumlah_anak"];
                foreach ($statistik["berat_badan"] as $keyBB => $val) {
                    $total["berat_badan"][$keyBB] += $val;
                }
                foreach ($statistik["tinggi_badan"] as $keyTB => $val) {
                    $total["tinggi_badan"][$keyTB] += $val;
                }
                foreach ($statistik["lingkar_kepala"] as $keyLK => $val) {
                    $total["lingkar_kepala"][$keyLK] += $val;
                }
            }
    
            $response[] = $statistik;
        }
    
        // Sisipkan total di paling atas
        array_unshift($response, $total);
    
        return $this->successResponse("Data Statistik Desa", $response);
    }

}