<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Teacher;
use App\Models\TeacherPasswordReset;
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:teachers,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
            TeacherPasswordReset::where('email', $email)->delete();

            // Generate Token
            $token = mt_rand(100000, 999999);
            $now = Carbon::now();
            TeacherPasswordReset::create([
                'email' => $email,
                'token' => $token,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
            // $link = "http://localhost:5173/teacher/forgot-password/reset-password/" . $email . "/" . $token;

            $link = env('APP_LINK') . "teacher/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);
        }
    }

    // Valid Email and Token Request
    public function resetEmailCodeVerify(Request $request)
    {
        try {
            // Validation rules
            $validation = Validator::make($request->all(), [
                'email' => 'required|email|exists:teacher_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;
            $password_reset = TeacherPasswordReset::where('email', $email)->where('token', $token)->first();

            if ($password_reset) {
                return response()->json([
                    'response_message' => ['Valid' => ['OTP Verification Successful!']],
                    'response_status' => 200,
                    'data' => ['token_verify' => $password_reset],
                ], 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
            $formated = Carbon::now()->subMinutes(10)->toDateTimeString();
            TeacherPasswordReset::where('created_at', '<=', $formated)->delete();

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

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

            // Check if token is valid
            $email = $request->email;
            $token = $request->token;
            $password_reset = TeacherPasswordReset::where('email', $email)->where('token', $token)->first();

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

            $teacher = Teacher::where('email', $password_reset->email)->first();
            if (!$teacher) {
                return response()->json([
                   'validation_errors' => ['not_find' => ['Email address Does Not Exist!']],
                    'response_status' => 400,
                ], 200);
            }

            if ($teacher) {
                $teacher->password = Hash::make($request->password);
                $teacher->save();

                // Delete the token after resetting the password
                TeacherPasswordReset::where('email', $teacher->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);
        }
    }
}
