<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once("../../backend/vendor/PHPMailer/Exception.php");
require_once("../../backend/vendor/PHPMailer/PHPMailer.php");
require_once("../../backend/vendor/PHPMailer/SMTP.php");
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
$id_map = (int)$_POST['id_map'];
$type = strip_tags($_POST['type']);
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : '';
$settings_auth = sml_get_viewer_auth_settings($id_map);
if((int)$settings_auth['viewer_auth_mode']<=0 || $type!='forgot') {
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>_("Error, retry later")));
    exit;
}
if(isset($_POST['language'])) {
    $language = strip_tags($_POST['language']);
}
$settings = get_settings();
if(!$settings['smtp_valid']) {
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>_("Error, retry later")));
    exit;
}
if(isset($language)) {
    set_language($language,$settings['language_domain']);
} else {
    set_language($settings['language'],$settings['language_domain']);
}
$id_user = 0;
$username = '';
$query = "SELECT id,username FROM sml_users WHERE email=? LIMIT 1;";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('s', $email);
    $result = $smt->execute();
    if($result) {
        $result = get_result($smt);
        if(count($result)==1) {
            $row = array_shift($result);
            $id_user = $row['id'];
            $username = $row['username'];
        } else {
            ob_end_clean();
            echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
            exit;
        }
    } else {
        ob_end_clean();
        echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
        exit;
    }
} else {
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
    exit;
}
$code_map = '';
$query_map = "SELECT code FROM sml_maps WHERE id=? LIMIT 1;";
if($smt_map = $mysqli->prepare($query_map)) {
    $smt_map->bind_param('i',$id_map);
    if($smt_map->execute()) {
        $result_map = get_result($smt_map);
        if(count($result_map)==1) {
            $row_map = array_shift($result_map);
            $code_map = $row_map['code'];
        }
    }
}
if(empty($code_map)) {
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>_("Error, retry later")));
    exit;
}
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$verification_code = '';
for($i=0;$i<16;$i++) {
    $verification_code .= $characters[random_int(0, strlen($characters) - 1)];
}
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
$hostName = $_SERVER['HTTP_HOST'];
if (is_ssl()) { $protocol = 'https'; } else { $protocol = 'http'; }
$url = $protocol."://".$hostName.$pathInfo['dirname'];
$url = str_replace("/ajax","",$url)."/index.php?code=".urlencode($code_map)."&forgot=1&email=".urlencode($email)."&verification_code=".urlencode($verification_code);
$subject = $settings['mail_forgot_subject'];
$body = $settings['mail_forgot_body'];
$body = str_replace("%LINK%","<a href='$url'>$url</a>",$body);
$body = str_replace("%VERIFICATION_CODE%",$verification_code,$body);
$body = str_replace("%USER_NAME%",$username,$body);
$body = str_replace('<p><br></p>','<br>',$body);
$body = str_replace('<p>','<p style="padding:0;margin:0;">',$body);
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->CharSet = 'UTF-8';
    $mail->Timeout = 10;
    $mail->Host = $settings['smtp_server'];
    $mail->SMTPAuth = $settings['smtp_auth'];
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    $mail->Username = $settings['smtp_username'];
    $mail->Password = $settings['smtp_password'];
    switch($settings['smtp_secure']) {
        case 'ssl':
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            break;
        case 'tls':
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            break;
    }
    $mail->Port = $settings['smtp_port'];
    $mail->setFrom($settings['smtp_from_email'], $settings['smtp_from_name']);
    $mail->addAddress($email);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->send();
    $query = "UPDATE sml_users SET forgot_code=? WHERE id=?;";
    if($smt = $mysqli->prepare($query)) {
        $smt->bind_param('si',$verification_code,$id_user);
        $smt->execute();
    }
    ob_end_clean();
    echo json_encode(array("status"=>"ok"));
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>$mail->ErrorInfo));
}
