<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\ApiBaseController;
use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterUserController extends ApiBaseController
{
    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  String  $role
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    private function register(Request $request, $role)
    {
        $rules = [
            'nama' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6'],
            'alamat' => ['sometimes', 'string', 'max:255'],
            'id_desa' => ['required', 'exists:data_desa,id'],
            'status' => ['nullable', 'boolean'],
        ];

        // Make id_posyandu optional for TENAGA_KESEHATAN
        if ($role !== 'TENAGA_KESEHATAN') {
            $rules['id_posyandu'] = ['required', 'exists:data_posyandu,id'];
        } else {
            $rules['id_posyandu'] = ['nullable', 'exists:data_posyandu,id'];
        }

        $validator = Validator::make($request->all(), $rules);

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

        $roleModel = Role::where('role', $role)->first();

        if (!$roleModel) {
            return $this->errorValidationResponse("Role tidak ditemukan");
        }

        try {
            $user = User::create([
                'nama' => $request->nama,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'alamat' => $request->alamat ?? null,
                'id_desa' => $request->id_desa,
                'id_posyandu' => $request->id_posyandu,
                'status' => $request->has('status') ? $request->status : 0,
            ]);

            $user->role()->associate($roleModel);
            $user->push();

            return $this->successResponse("registrasi berhasil, silahkan log in");
        } catch (\Exception $e) {
            \Log::error("Error registering user: " . $e->getMessage());
            return $this->errorResponse("Gagal registrasi", [$e->getMessage()], 500);
        }
    }

    /**
     * Update an existing user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUser(Request $request, $id)
    {
        $user = User::find($id);

        if (!$user) {
            return $this->errorResponse("User tidak ditemukan", [], 404);
        }

        $rules = [
            'nama' => ['sometimes', 'string', 'max:255'],
            'email' => ['sometimes', 'string', 'email', 'max:255', 'unique:users,email,' . $id],
            'password' => ['sometimes', 'string', 'min:6'],
            'alamat' => ['sometimes', 'string', 'max:255'],
            'id_desa' => ['sometimes', 'exists:data_desa,id'],
            'status' => ['sometimes', 'boolean'],
        ];

        // Make id_posyandu optional for TENAGA_KESEHATAN during update
        if ($user->role->role !== 'TENAGA_KESEHATAN') {
            $rules['id_posyandu'] = ['sometimes', 'required', 'exists:data_posyandu,id'];
        } else {
            $rules['id_posyandu'] = ['sometimes', 'nullable', 'exists:data_posyandu,id'];
        }

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return $this->errorValidationResponse("Gagal memperbarui user", $validator->errors());
        }

        try {
            // Update user fields
            $updateData = [];
            if ($request->has('nama')) {
                $updateData['nama'] = $request->nama;
            }
            if ($request->has('email')) {
                $updateData['email'] = $request->email;
            }
            if ($request->has('password')) {
                $updateData['password'] = Hash::make($request->password);
            }
            if ($request->has('alamat')) {
                $updateData['alamat'] = $request->alamat;
            }
            if ($request->has('id_desa')) {
                $updateData['id_desa'] = $request->id_desa;
            }
            if ($request->has('id_posyandu')) {
                $updateData['id_posyandu'] = $request->id_posyandu;
            } elseif ($request->has('id_posyandu') && $request->id_posyandu === null && $user->role->role === 'TENAGA_KESEHATAN') {
                $updateData['id_posyandu'] = null;
            }
            if ($request->has('status')) {
                $updateData['status'] = $request->status;
            }

            $user->update($updateData);

            return $this->successResponse("User berhasil diperbarui");
        } catch (\Exception $e) {
            \Log::error("Error updating user: " . $e->getMessage());
            return $this->errorResponse("Gagal memperbarui user", [$e->getMessage()], 500);
        }
    }

    /**
     * Soft delete a user.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteUser($id)
    {
        $user = User::find($id);

        if (!$user) {
            return $this->errorResponse("User tidak ditemukan", [], 404);
        }

        try {
            $user->delete();

            return $this->successResponse("User berhasil dihapus");
        } catch (\Exception $e) {
            \Log::error("Error deleting user: " . $e->getMessage());
            return $this->errorResponse("Gagal menghapus user", [$e->getMessage()], 500);
        }
    }

    public function registerOrangTua(Request $request)
    {
        return $this->register($request, "ORANG_TUA");
    }

    public function registerKaderPosyandu(Request $request)
    {
        return $this->register($request, "KADER_POSYANDU");
    }

    public function registerDesa(Request $request)
    {
        return $this->register($request, "DESA");
    }

    public function registerTenagaKesehatan(Request $request)
    {
        return $this->register($request, "TENAGA_KESEHATAN");
    }

    public function registerAdmin(Request $request)
    {
        return $this->register($request, "ADMIN");
    }
}