<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use App\Mail\EmailVerification;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid credentials!'], 401);
        }

        if ($user->double_auth) {
            $this->sendVerificationCodeDef($user->id , 'Confim your email to Login');

            return response()->json(['message' => 'Code sent successfully.' , 'success' => true], 200);
        } else {
            $token = $user->createToken('authToken')->plainTextToken;

            return response()->json([
                'message' => 'User logged in successfully.',
                'user' => $user,
                'token' => $token,
            ], 200);
        }
    }

    public function forgetPassKey(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json(['message' => 'Email Invalid !!'], 404);
        }

        $this->sendVerificationCodeDef($user->id , 'Confim your email to reset your password');

        return response()->json(['message' => 'Code sent successfully.'], 200);
    }

    public function verifyCodeforgetPassKey(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'code' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user || $user->verify_code !== $request->code) {
            return response()->json(['message' => 'Invalid code or email!'], 400);
        }

        $user->forget_password = true;
        $user->save();

        return response()->json(['message' => 'Code verified successfully.'], 200);
    }

    public function loginAndVerifyCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
            'code' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Invalid email or password!'], 401);
        }

        if ($user->verify_code !== $request->code) {
            return response()->json(['message' => 'Invalid verification code!'], 400);
        }

        $token = $user->createToken('authToken')->plainTextToken;

        return response()->json([
            'message' => 'User logged in successfully.',
            'user' => $user,
            'token' => $token,
        ], 200);
    }

    public function changePasswordForget(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'NewPassword' => 'required|min:8',
            'code' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        $user = User::where('email', $request->email)->first();
        if (!$user || !$user->forget_password) {
            return response()->json(['message' => 'Unauthorized!'], 403);
        }

        if ($user->verify_code !== $request->code) {
            return response()->json(['message' => 'Invalid verification code!'], 400);
        }

        $user->password = Hash::make($request->NewPassword);
        $user->forget_password = false;
        $user->save();

        return response()->json(['message' => 'Password changed successfully.'], 200);
    }

    private function sendVerificationCodeDef($id , $text)
    {
        $verificationCode = random_int(100000, 999999);
        $user = User::findOrFail($id);

        $data = [
            'fullName' => $user->fullName,
            'email' => $user->email,
            'code' => $verificationCode,
            'text' => $text
        ];

        Mail::to($user->email)->send(new EmailVerification($data));
        $user->verify_code =  $verificationCode;
        $user->save();
    }

    public function getCurrentUser(Request $request)
    {
        return response()->json(['user' => $request->user()->load('role')], 200);
    }
}
