<?php
session_start();
include_once("config/web_mysqlconnect.php");

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

$emailid = isset($_REQUEST['emailid']) ? trim($_REQUEST['emailid']) : '';
$otp     = isset($_REQUEST['otp']) ? trim($_REQUEST['otp']) : '';

if (empty($emailid)) {
    echo json_encode(array(
        'status' => false,
        'message' => 'Email ID is required'
    ));
    exit;
}

if (!filter_var($emailid, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(array(
        'status' => false,
        'message' => 'Invalid Email ID'
    ));
    exit;
}

if (empty($otp)) {
    echo json_encode(array(
        'status' => false,
        'message' => 'OTP is required'
    ));
    exit;
}

$subject = "OTP Verification";

$body = '
<html>
<head>
<meta charset="utf-8">
</head>
<body>
    <p>Dear User,</p>

    <p>Your One Time Password (OTP) is:</p>

    <h2 style="color:#0066cc;">'.$otp.'</h2>

    <p>This OTP is valid for a limited time.</p>

    <p>Please do not share this OTP with anyone.</p>

    <br>

    <p>Regards,<br>
    Support Team</p>
</body>
</html>
';

$data = array(
    'Mail'       => $emailid,
    'V_Subject'  => $subject,
    'V_Content'  => $body,
    'V_rule'     => 'OTP_VERIFICATION',
    'I_Status'   => '1'
);

/* Insert into email queue */
insert_emailinformationout($data);

echo json_encode(array(
    'status' => true,
    'message' => 'OTP email queued successfully',
    'email' => $emailid
));

exit;


/*Aarti-23-11-23
this function for insert email out record in web_email_information_out*/
function insert_emailinformationout($data){
    global $link,$db;

    if(empty($db)){
        $db = 'ensembler';
    }

    $from_email = "singhkewalsingh1986@gmail.com";
    $todaytime  = date("Y-m-d H:i:s");

    $Mail       = mysqli_real_escape_string($link,$data['Mail']);
    $from       = mysqli_real_escape_string($link,$from_email);
    $V_Subject  = mysqli_real_escape_string($link,$data['V_Subject']);
    $V_Content  = mysqli_real_escape_string($link,$data['V_Content']);
    $V_rule     = mysqli_real_escape_string($link,$data['V_rule']);

    $sql = "
        INSERT INTO $db.web_email_information_out
        (
            v_toemail,
            v_fromemail,
            v_subject,
            v_body,
            V_rule,
            d_email_date,
            email_type,
            I_Status
        )
        VALUES
        (
            '$Mail',
            '$from',
            '$V_Subject',
            '$V_Content',
            '$V_rule',
            '$todaytime',
            'OUT',
            '1'
        )
    ";

    $result = mysqli_query($link,$sql);

    if(!$result){
        error_log("Email Queue Insert Error : ".mysqli_error($link));
        return false;
    }

    return mysqli_insert_id($link);
}
?>
