<?php

namespace App\Http\Controllers\Admin;

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 handle(Request $request)
//     {
//         $action = $request->input('action');
//         if ($action === 'send_otp') {
//             return $this->sendOtp($request);
//         } elseif ($action === 'verify_otp') {
//             return $this->verifyOtp($request);
//         }
//         return redirect()->back()->with('errormessage', 'Invalid action.');
//     }

    //     public function sendOtp(Request $request)
//     {
//         $request->validate([
//             'email' => 'required|email',
//         ]);
//         $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 redirect()->back()->withInput()->with('successmessage', 'OTP has been sent to your email.');
//             } catch (\Exception $e) {
//                 Log::error('Failed to send OTP: ' . $e->getMessage());
//                 return redirect()->back()->withInput()->with('errormessage', 'Failed to send OTP.');
//             }
//         }
//         return redirect()->back()->withInput()->with('successmessage', 'User not found');
//     }
//     public function verifyOtp(Request $request)
//     {
//         $request->validate([
//             'email'    => 'required|email',
//             'send_otp' => 'required|numeric',
//         ]);
//         $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);
//                 return redirect()->route('dashboard')->with('successmessage', 'OTP verified and logged in successfully.');
//             }
//         }
//         return redirect()->back()->with('errormessage', 'Invalid or expired OTP.');
//     }

    public function handleResetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'password' => ['required', 'string', 'min:8'],
            'new_pwd' => ['required', 'string', 'min:8', 'confirmed', 'regex:/[!@#$%^&*(),.?":{}|<>]/'],
            'new_pwd_confirmation' => ['required', 'string', 'min:8'],
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $user = Auth::user();
        if (!Hash::check($request->input('password'), $user->password)) {
            return redirect()->back()
                ->withErrors(['password' => 'The old password is incorrect.'])
                ->withInput();
        }

        $user->password = Hash::make($request->input('new_pwd'));
        $user->save();

        return redirect()->route('dashboard')
            ->with('success', 'Password has been updated successfully.');
    }

    public function updateProfile(Request $request)
    {
        $validatedData = $request->validate([
            'user_id' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone_number' => 'required|regex:/^[0-9]{10}$/',
        ]);
        $user = auth()->user();
        if (!$user) {
            return redirect()->route('admin.login')->with('error', 'You need to be logged in to update your profile.');
        }

        if (!auth()->check()) {
            return redirect()->route('admin.login')->with('error', 'You need to be logged in to update your profile.');
        }
        $user->user_id = $request->user_id;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->phone_number = $request->phone_number;
        $user->save();
        return redirect()->route('profile')->with('success', 'Profile updated successfully!');
    }
    public function logout(Request $request)
    {

        Auth::logout();
        $request->session()->flush();
        $request->session()->regenerateToken();
        Log::info('User logged out successfully');
        return redirect()->route('admin.login');
    }

    // public function handle(Request $request)
    // {
    //     $action = $request->input('action');
    //     if ($action === 'send_otp') {
    //         return $this->sendOtp($request);
    //     } elseif ($action === 'verify_otp') {
    //         return $this->verifyOtp($request);
    //     }
    //     return response()->json(['status' => 'error', 'message' => 'Invalid action.']);
    // }
    public function handle(Request $request)
    {
        Log::info('hi');
        if ($request->action === 'send_otp') {
            return $this->sendOtp($request);
        } elseif ($request->action === 'verify_otp') {
            return $this->verifyOtp($request);
        }
        return response()->json(['status' => 'error', 'message' => 'Invalid action.']);
    }
   
    public function sendOtp(Request $request)
{
    
    $request->validate([
        'email' => 'required|email',
    ]);
    $user = User::where('email', $request->input('email'))->first();
    if (!$user) {
    
        return response()->json(['status' => 'error', 'message' => 'User not found']);
    }
    $otp = rand(100000, 999999);
    $user->otp = Crypt::encryptString($otp);
    $user->otp_expires_at = Carbon::now()->addMinutes(5);
    $user->otp_verified = false;

    Log::info('senotp');
    try {
        $user->save();
        Mail::to($user->email)->send(new OtpMail($otp));
        return response()->json(['status' => 'success', 'message' => 'Otp Sent Successfully']);
    } catch (\Exception $e) {
        return response()->json(['status' => 'error', 'message' => 'Error Occured']);

    }
}
// public function verifyOtp(Request $request)
// {
//     Log::info('verifyOtp');
//     $request->validate([
//         'email' => 'required|email',
//         'send_otp' => 'required|numeric',
//     ]);

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

//     Log::info($user);
//     if (!$user) {
//         return response()->json(['status' => 'error', 'message' => 'User not found.']);
//     }

//     if (Carbon::now()->greaterThan($user->otp_expires_at)) {
//         return response()->json(['status' => 'error', 'message' => 'OTP has expired.']);
//     }

//     $decryptedOtp = Crypt::decryptString($user->otp);

//     if ($request->input('send_otp') == $decryptedOtp) {
//         $user->otp_verified = true;
//         $user->save();
//         Auth::login($user);
//         Log::info('completed');
//         return response()->json(['status' => 'success', 'redirect_url' => route('dashboard')]);
//     }

//     return response()->json(['status' => 'error', 'message' => 'Invalid or expired OTP.']);
// }



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

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

        if (!$user) {
            return response()->json(['status' => 'error', 'message' => 'User not found.']);
        }

        if (Carbon::now()->greaterThan($user->otp_expires_at)) {
            return response()->json(['status' => 'error', 'message' => 'OTP has expired.']);
        }

        $decryptedOtp = Crypt::decryptString($user->otp);

        if ($request->input('send_otp') === $decryptedOtp) {
            $user->otp_verified = true;
            $user->save();
            Auth::login($user);

            return response()->json(['status' => 'success', 'redirect_url' => route('dashboard')]);
        } else {
            return response()->json(['status' => 'error', 'message' => 'Invalid or expired OTP.']);
        }
    } catch (\Exception $e) {
        Log::error('OTP Verification Error: ' . $e->getMessage());
        return response()->json(['status' => 'error', 'message' => 'An error occurred. Please try again.']);
    }
}


    // public function verifyOtp(Request $request)
    // {
    //     $request->validate([
    //         'email' => 'required|email',
    //         'send_otp' => 'required|numeric',
    //     ]);
    //     $user = User::where('email', $request->input('email'))->first();
    //     if (!$user) {
    //         return response()->json(['status' => 'error', 'message' => 'User not found.']);
    //     }
    //     if (Carbon::now()->greaterThan($user->otp_expires_at)) {
    //         return response()->json(['status' => 'error', 'message' => 'OTP has expired.']);
    //     }
    //     $decryptedOtp = Crypt::decryptString($user->otp);
    //     if ($request->input('send_otp') == $decryptedOtp) {
    //         $user->otp_verified = true;
    //         $user->save();
    //         Auth::login($user);
    //         return redirect()->route('dashboard')->with('successmessage', 'OTP verified and logged in successfully.');

    //     }

    //     return redirect()->back()->with('errormessage', 'Invalid or expired OTP.');
    // }
}
