<?php

namespace App\Http\Controllers\Api\Auth;

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

class AuthenticateUserController 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 login(Request $request, $role)
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'string', 'email', 'max:255'],
            'password' => ['required'],
        ]);

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

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();
            $data = [
                'token' => [
                    'type' => "Bearer",
                    'value' => $user->createToken('API Token')->plainTextToken,
                ],
                'user' => [
                    'id' => $user->id,
                    'name' => $user->nama,
                    'email' => $user->email,
                    'id_desa' => $user->desa ? $user->desa->id : null,
                    'desa_name' => $user->desa ? $user->desa->name : null,
                    'id_posyandu' => $user->posyandu ? $user->posyandu->id : null,
                    'posyandu_name' => $user->posyandu ? $user->posyandu->nama : null,
                    'role' => $user->role->role,
                    'status' => $user->status // Fixed typo: $seur to $user
                ],
            ];

            if ($user->role->role != $role) {
                return $this->errorValidationResponse("periksa kembali email dan password");
            }
            return $this->successResponse("berhasil login", $data);
        }

        return $this->errorValidationResponse("periksa kembali email dan password");
    }

    public function loginbaru(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'string', 'email', 'max:255'],
            'password' => ['required'],
        ]);

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

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();
            $data = [
                'token' => [
                    'type' => "Bearer",
                    'value' => $user->createToken('API Token')->plainTextToken,
                ],
                'user' => [
                    'id' => $user->id,
                    'name' => $user->nama,
                    'email' => $user->email,
                    'id_desa' => $user->desa ? $user->desa->id : null,
                    'desa_name' => $user->desa ? $user->desa->name : null,
                    'id_posyandu' => $user->posyandu ? $user->posyandu->id : null,
                    'posyandu_name' => $user->posyandu ? $user->posyandu->nama : null,
                    'role' => $user->role->role,
                    'status' => $user->status
                ],
            ];

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

        return $this->errorValidationResponse("periksa kembali email dan password");
    }

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

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

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

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

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

    /**
     * Update the authenticated user's profile.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateProfile(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return $this->errorUnauthorizedResponse("Unauthenticated");
        }

        $validator = Validator::make($request->all(), [
            'nama' => ['required', 'string', 'max:255'], // Added validation for nama
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
            'password_confirmation' => ['nullable', 'required_with:password', 'same:password'],
        ]);

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

        try {
            $user->nama = $request->nama;

            // Update password only if provided
            if ($request->filled('password')) {
                $user->password = Hash::make($request->password);
            }

            $user->save();

            $data = [
                'user' => [
                    'id' => $user->id,
                    'name' => $user->nama,
                    'email' => $user->email,
                    'id_desa' => $user->desa ? $user->desa->id : null, // Fixed potential null reference
                    'id_posyandu' => $user->posyandu ? $user->posyandu->id : null, // Fixed potential null reference
                    'role' => $user->role->role
                ],
            ];

            return $this->successResponse("Profil berhasil diperbarui", $data);
        } catch (\Exception $e) {
            \Log::error("Error updating profile: " . $e->getMessage());
            return $this->errorValidationResponse("Gagal memperbarui profil", [$e->getMessage()]);
        }
    }

    public function getProfile()
    {
        $user = Auth::user();
        if (!$user) {
            return $this->errorUnauthorizedResponse("Unauthenticated");
        }

        try {
            $data = [
                'user' => [
                    'name' => $user->nama,
                ],
            ];

            return $this->successResponse("Profil berhasil diambil", $data);
        } catch (\Exception $e) {
            \Log::error("Error fetching profile: " . $e->getMessage());
            return $this->errorValidationResponse("Gagal mengambil profil", [$e->getMessage()]);
        }
    }
}