<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Student;
use App\Models\StudentPasswordReset;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;
use Illuminate\Mail\Message;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;

class PasswordResetController extends Controller
{
    // Reset Password => Send Email
    public function forgotPassword(Request $request)
    {
        try {
            // Validation rules
            $validation = Validator::make($request->all(), [
                'email' => 'required|email|exists:students,email',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            $email = $request->email;

            // Check if a reset token already exists for this email and delete it
            StudentPasswordReset::where('email', $email)->delete();

            // Generate Token
            $token = mt_rand(100000, 999999);
            $now = Carbon::now();
            StudentPasswordReset::create([
                'email' => $email,
                'token' => $token,
                'created_at' => $now,
                'updated_at' => $now,
            ]);

            // $link = "http://localhost:5173/student/forgot-password/reset-password/" . $email . "/" . $token;

            $link = env('APP_LINK') . "student/forgot-password/reset-password/" . $email . "/" . $token;
            $img_link = env('APP_LINK');

            Mail::send('resetPassword', ['token' => $token, 'link' => $link, 'img_link' => $img_link], function (Message $message) use ($email) {
                $message->subject('Reset Your Password');
                $message->to($email);
                $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
            });

            return response()->json([
                'response_message' => ['token_sent' => ['An OTP has been sent on your email for password reset.']],
                'response_status' => 200,
                // 'token' => ['token' => $token]
            ], 200);

        } catch (Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    // Verify Email and Token
    public function resetEmailCodeVerify(Request $request)
    {
        try {
            // Validation rules
            $validation = Validator::make($request->all(), [
                'email' => 'required|email|exists:student_password_reset_tokens,email',
                'token' => 'required|digits:6',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            $email = $request->email;
            $token = $request->token;
            $passwordReset = StudentPasswordReset::where('email', $email)->where('token', $token)->first();

            if ($passwordReset) {
                return response()->json([
                    'response_message' => ['Valid' => ['OTP Verification Successful!']],
                    'response_status' => 200,
                    'data' => ['token_verify' => $passwordReset],
                ], 200);
            } else {
                return response()->json([
                    'validation_errors' => ['Invalid' => ['OTP Verification Failed!']],
                    'response_status' => 400,
                ], 200);
            }

        } catch (Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }

    // Change Password Request
    public function resetChangedPassword(Request $request)
    {
        try {
            // Reset Token Expire after 10 Minutes
            $formatted = Carbon::now()->subMinutes(10)->toDateTimeString();
            StudentPasswordReset::where('created_at', '<=', $formatted)->delete();

            // Validation rules
            $validation = Validator::make($request->all(), [
                'email' => 'required|email|exists:students,email',
                'token' => 'required|digits:6',
                'password' => 'required|confirmed|min:8',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Reset token is invalid
            $email = $request->email;
            $token = $request->token;
            $passwordReset = StudentPasswordReset::where('email', $email)->where('token', $token)->first();

            if (!$passwordReset) {
                return response()->json([
                    'validation_errors' => ['Invalid' => ['The OTP You have Entered is Invalid Or Expired!']],
                    'response_status' => 400,
                ], 200);
            }

            $student = Student::where('email', $passwordReset->email)->first();

            if (!$student) {
                return response()->json([
                    'validation_errors' => ['not_find' => ['Email address Does Not Exist!']],
                    'response_status' => 400,
                ], 200);
            }

            $student->password = Hash::make($request->password);
            $student->save();

            // Delete the token after resetting the password
            StudentPasswordReset::where('email', $student->email)->delete();

            return response()->json([
                'response_message' => ['success' => ['Password Updated Successfully!']],
                'response_status' => 200,
            ], 200);

        } catch (Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
