<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Carbon\Carbon;
use App\Mail\OtpMail;
use App\Mail\PasswordResetMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    public function login_send_otp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'data'    => null,
                'message' => 'Validation failed',
                'code'    => 422,
                'errors'  => $validator->errors()
            ], 422);
        }
        $user = User::where('email', $request->input('email'))->first();
        if ($user) {
            $otp = rand(100000, 999999);
            $user->otp = Crypt::encryptString($otp);
            $user->otp_expires_at = Carbon::now()->addMinutes(5);
            $user->otp_verified = false;
            $user->save();
            try {
                Log::info('Attempting to send OTP to: ' . $user->email);
                Mail::to($user->email)->send(new OtpMail($otp));
                Log::info('OTP sent to: ' . $user->email);

                return response()->json([
                    'status'  => 'success',
                    'data'    => null,
                    'message' => 'OTP has been sent to your email.',
                    'code'    => 200
                ], 200);
            } catch (\Exception $e) {
                Log::error('Failed to send OTP: ' . $e->getMessage());

                return response()->json([
                    'status'  => 'error',
                    'data'    => null,
                    'message' => 'Failed to send OTP.',
                    'code'    => 500
                ], 500);
            }
        }
        return response()->json([
            'status' => 'error',
            'data' => null,
            'message' => 'User not found',
            'code' => 404
        ], 404);
    }

    public function login_verify_otp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'    => 'required|email',
            'send_otp' => 'required|numeric',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'data'    => null,
                'message' => 'Validation failed',
                'code'    => 422,
                'errors'  => $validator->errors()
            ], 422);
        }
        $user = User::where('email', $request->input('email'))->first();
        if ($user && Carbon::now()->lessThan($user->otp_expires_at)) {
            $decryptedOtp = Crypt::decryptString($user->otp);
            if ($request->input('send_otp') == $decryptedOtp) {
                $user->otp_verified = true;

                $user->save();
                Auth::login($user);
                $token = $user->createToken('YourAppName')->plainTextToken;
                return response()->json([
                    'status' => 'success',
                    'data'   => [
                        'user' => [
                            'id'           => $user->id,
                            'email'        => $user->email,
                            'otp_verified' => $user->otp_verified,
                            'token'        => $token,
                        ],
                    ],
                    'message' => 'OTP verified and logged in successfully.',
                    'code'    => 200
                ], 200);
            }
        }
        return response()->json([
            'status'  => 'error',
            'data'    => null,
            'message' => 'Invalid or expired OTP.',
            'code'    => 400
        ], 400);
    }
    public function handleResetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'password' => ['required', 'string', 'min:8'],
            'new_pwd'  => ['required', 'string', 'min:8', 'confirmed', 'regex:/[!@#$%^&*(),.?":{}|<>]/'],
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation errors occurred.',
                'errors'  => $validator->errors(),
                'code'    => 422,
            ], 422);
        }
        $user = Auth::user();
        if (!Hash::check($request->input('password'), $user->password)) {
            return response()->json([
                'status'  => 'error',
                'message' => 'The old password is incorrect.',
                'code'    => 400,
            ], 400);
        }
        $user->password = Hash::make($request->input('new_pwd'));
        $user->save();
        return response()->json([
            'status'  => 'success',
            'message' => 'Password has been updated successfully.',
            'code'    => 200,
        ], 200);
    }

}

