<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Person;
use Crypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Modules\Internal\Emails\SendVerifyEmail;
use Modules\Internal\Events\ForgetPassword;
use App\Helpers\Helper;
use Validator;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required'
        ]);

        $user = User::query()
                ->where(function ($query) use ($request) {
                    $query->where('email', $request->email)
                        ->orWhere('username', $request->email);
                })
                ->first();


        if (!$user) {
            return response(['message' => 'User Tidak Ditemukan'], 404);
        }

        if (!Hash::check($request->password, $user->password)) {
            return response(['message' => 'Password Salah'], 403);
        }

        return response([
            'message' => 'Selamat Datang',
            'user' => $user,
            'token' => $user->createToken('app')->plainTextToken
        ]);
    }

    public function logout(Request $request)
    {
        $token = $request->bearerToken();
        Auth::user()->tokens()->where('id', $token)->delete();

        return response(['message' => 'Berhasil Logout.']);
    }

    public function resetPassword(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'old_password' => 'required',
            'new_password' => 'required',
            'confirm_new_password' => 'required'
        ]);

        if (!Hash::check($request['old_password'], $user->password)) {
            return response(['message' => 'Password Salah'], 403);
        }

        if ($request["new_password"] != $request["confirm_new_password"]) {
            return response([
                'message' => "Password Tidak Sama"
            ]);
        }

        $user->update([
            'password' => Hash::make($request->confirm_new_password),
        ]);
        return response()->json($user);
    }

    public function verifyEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $user = User::query()
            ->where('email', $request->email)
            ->first();

        if (!$user) {
            return response(['message' => 'User Tidak Ditemukan'], 404);
        }

        Event(new ForgetPassword($user));

        Mail::to($user->email)->send(new SendVerifyEmail($user));

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

    public function forgetPassword(Request $request)
    {
        $request->validate([
            'new_password' => 'required',
            'confirm_new_password' => 'required'
        ]);

        $token = Crypt::decryptString($request->token);
        $email = explode('|', $token)[0];

        $user = User::query()
            ->where('email', $email)
            ->first();

        if (!$user) {
            return response(['message' => 'User Tidak Ditemukan'], 404);
        }

        if ($request["new_password"] != $request["confirm_new_password"]) {
            return response([
                'message' => "Password Tidak Sama"
            ], 404);
        }

        $user->update([
            'password' => Hash::make($request->confirm_new_password),
        ]);
        return response()->json($user);
    }

    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email',
            'username' => 'required|unique:users,username',
            'name' => 'required',
            'password' => [
                'required',
                'min:5',
                // 'regex:/.*[0-9].*/',
                // 'regex:/.*[a-z].*/',
                // 'regex:/.*[A-Z].*/',
            ]
        ], [
            // 'password.regex' => "Password harus minimal 8 karakter, kombinasi huruf besar kecil dan angka"
        ])->validate();
        
        try {
            $user = User::create([
                'email' => $request->email,
                'username' => $request->username,
                'password' => Hash::make($request->password),
            ]);

            $person = Person::updateOrCreate(
                [
                    'id' => $user->person_id
                ],
                [
                    'name' => $request->name ?? null
                ]
            );
            $user->person_id = $person->id;
            $user->save();
            return response()->json($user);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Terjadi masalah ketika mendaftar'
            ]);
        }
    }

}
