<?php
// Suppress any output before JSON
ob_start();

include "connection.php";
include "SMTP.php";
include "PHPMailer.php";
include "Exception.php";

use PHPMailer\PHPMailer\PHPMailer;

// Clear any output buffer
ob_clean();

header("Content-Type: application/json");

$json = file_get_contents("php://input");
$data = json_decode($json, true);
    
$email = isset($data["email"]) ? trim($data["email"]) : "";

    $response = [
        "status" => false,
        "message" => ""
    ];

    if(!empty($email)){

        $UserEmail = $email;

        $rs = Database::search("SELECT * FROM `student` WHERE `email` = '".$email."' ");
        $num = $rs->num_rows;

        if($num == 1){

            $vcode = rand(10000,99999);
            Database::iud("UPDATE `student` SET `verification_code` = '".$vcode."' WHERE `email` = '".$email."' ");

            $mail = new PHPMailer;
            $mail->IsSMTP();
            $mail->Host = 'smtp.gmail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'team.eexam@gmail.com';
            $mail->Password = 'afvd brxt yglt csfs';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('team.eexam@gmail.com', 'Reset Password');
            $mail->addReplyTo('Ttam.eexam@gmail.com', 'Reset Password');
            $mail->addAddress($UserEmail);
            $mail->isHTML(true);
            $mail->Subject = 'e-Exam.lk Forgot password Verification Code.';
            $bodyContent = '<h1 style="color:#DC2626;">Your Verification Code Is <br/> '.$vcode.'</h1>';
            $mail->Body    = $bodyContent;

            if(!$mail->send()){
                $response["status"] = false;
                $response["message"] = "Verification Code Sending Faield!";
                
            }else{           
                $response["status"] = true;
                $response["message"] = "Email Sent Success! Please Check Your Email";
                
            }

        }else{
            $response["status"] = false;
            $response["message"] = "Invalid Email Address!";  
        }

    }else{
        $response["status"] = false;
        $response["message"] = "Please Enter Your Email and try again!";
 
    }

echo json_encode($response);
exit;