<?php

session_start();
include_once '../config/properties.php';
include_once "../resources/EncryptDecrypt.php";
include_once '../config/database.php';
include_once "../resources/otp.php";
//added for sendinblue
require_once('../vendor/autoload.php');

if (isset($_POST['mode'])) {
    include_once "../resources/manageusers.php";
    $object = new ManageUsers();

    $website_link_comp = "";

    if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {

        $mode = $_POST['mode'];

        if ($mode == 'password') {
            $mobile = $_POST['mobile'];
            $password = $out;
            $mcrypt = new MCrypt();
            $encrypted = $mcrypt->encrypt($password);
            $login_flag = '0';

            $query = $object->ForgotPassword($mobile);
            if ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                extract($row);
                if ($status != 'Active') {
                    echo json_encode(array("result1" => "failure", "result2" => _("LG0116")));
                } else {
                    if ($sms == "ON" || $email == "ON") {
                        if ($last_gen_pw_ts == "") {
                            $val2 = $object->UpdateUserPasword($user_id, $date_time, $encrypted, $login_flag);
                            if ($val2) {
                                if ($sms == "ON") {
                                    $first_name_sms = $first_name;
                                    if (strlen($first_name_sms) > 30) {
                                        $first_name_sms = substr($first_name_sms, 0, 30);
                                    }
                                    $msgbody = urlencode("Dear " . $first_name_sms . ", OTP for logging into K-nest LMS is: " . $password . ". 4EdgeIT Solutions");
                                    file_get_contents('http://www.smsjust.com/blank/sms/user/urlsms.php?username=haniballal01&pass=user@123&senderid=EDGEIT&dest_mobileno=' . $mobile_no . '&message=' . $msgbody.'&dltentityid=1201160450888723221&dlttempid=1607100000000336323&response=Y');
                                }
                                if ($email == "ON") {
                                    if ($email_id != "") {
                                        $email_id_user = $row['email_id'];
                                        $stmt_company = $object->UserCompanyDetails($user_id);
                                        if ($row_user = $stmt_company->fetch(PDO::FETCH_ASSOC)) {
                                            extract($row_user);
                                            if ($row_user['website_link'] != null) {
                                                $website_link_comp = $row_user['website_link'];
                                            }
                                            $logo_path = ADMIN_HTTP_PATH . $properties['jdbc.comp_image_folder'] . "/" . $row_user['logo_path'];
                                        }
                                        SendBlueEmail("forgot_password", $email_id_user, $first_name, $password, $api_key, $logo_path, $website_link_comp);
                                    }
                                }
                                unset($_SESSION['csrf_token']);
                                echo json_encode(array("result1" => "non_ecom", "result2" => _("LG0118")));
                            } else {
                                echo json_encode(array("result1" => "failure", "result2" => _("LG0105")));
                            }
                        } else {
                            $minutes_to_add = 3;
                            $time = new DateTime($last_gen_pw_ts);
                            $time->modify('+3 minutes');
                            $stamp = $time->format('Y-m-d H:i:s');
                            if ($stamp < $date_time) {
                                $val2 = $object->UpdateUserPasword($user_id, $date_time, $encrypted, $login_flag);
                                if ($val2) {
                                    if ($sms == "ON") {
                                        $first_name_sms = $first_name;
                                        if (strlen($first_name_sms) > 30) {
                                            $first_name_sms = substr($first_name_sms, 0, 30);
                                        }
                                        $msgbody = urlencode("Dear " . $first_name_sms . ", OTP for logging into K-nest LMS is: " . $password . ". 4EdgeIT Solutions");
//                                        file_get_contents('http://trans.kapsystem.com/api/v3/index.php?method=sms&api_key=A7cca971e58ac774dd98d2830c7aea569&to=' . $mobile_no . '&sender=EDGEIT&message=' . $msgbody);
                                         file_get_contents('http://www.smsjust.com/blank/sms/user/urlsms.php?username=haniballal01&pass=user@123&senderid=EDGEIT&dest_mobileno=' . $mobile_no . '&message=' . $msgbody.'&dltentityid=1201160450888723221&dlttempid=1607100000000336323&response=Y');
                                    }
                                    if ($email == "ON") {
                                        if ($email_id != "") {
                                            $email_id_user = $row['email_id'];
                                            $stmt_company = $object->UserCompanyDetails($user_id);
                                            if ($row_user = $stmt_company->fetch(PDO::FETCH_ASSOC)) {
                                                extract($row_user);
                                                if ($row_user['website_link'] != null) {
                                                    $website_link_comp = $row_user['website_link'];
                                                }
                                                $logo_path = ADMIN_HTTP_PATH . $properties['jdbc.comp_image_folder'] . "/" . $row_user['logo_path'];
                                            }
                                            SendBlueEmail("forgot_password", $email_id_user, $first_name, $password, $api_key, $logo_path, $website_link_comp);
                                        }
                                    }
                                    unset($_SESSION['csrf_token']);
                                    echo json_encode(array("result1" => "non_ecom", "result2" => _("LG0118")));
                                } else {
                                    echo json_encode(array("result1" => "failure", "result2" => _("LG0105")));
                                }
                            } else {
                                echo json_encode(array("result1" => "failure", "result2" => _("LG0106")));
                            }
                        }
                    } else {
                        echo json_encode(array("result1" => "failure", "result2" => _("LG0510")));
                    }
                }
            } else {
                echo json_encode(array("result1" => "failure", "result2" => _("LG0105")));
            }
        } else if ($mode == 'username') {
            $mobile = $_POST['mobile'];
            $yoursecret = "6LePCPoUAAAAAIZ7-HYiMOsQVuAoT8pav4cC8uw_";
            $response = getSslPage('https://www.google.com/recaptcha/api/siteverify?secret=' . $yoursecret . '&response=' . $_POST['captcha']);
            $googleobj = json_decode($response);
            $verified = $googleobj->success;
            if ($verified === true) {

                $query = $object->ForgotUsername($mobile);
                if ($row = $query->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    if ($status != 'Active') {
                        echo json_encode(array("result1" => "failure", "result2" => _("LG0116")));
                    } else {
                        if ($sms == "ON" || $email == "ON") {
                            if ($sms == "ON") {
                                if ($mobile_no != "") {
                                    if ($login_id != "") {
                                        $first_name_sms = $first_name;
                                        if (strlen($first_name_sms) > 30) {
                                            $first_name_sms = substr($first_name_sms, 0, 30);
                                        }
                                        $msgbody = urlencode("Dear " . $first_name_sms . ", Username for logging into K-nest LMS is: " . $login_id . " - 4EdgeIT Solutions");
//                                        file_get_contents('http://trans.kapsystem.com/api/v3/index.php?method=sms&api_key=A7cca971e58ac774dd98d2830c7aea569&to=' . $mobile_no . '&sender=EDGEIT&message=' . $msgbody);
                                         file_get_contents('http://www.smsjust.com/blank/sms/user/urlsms.php?username=haniballal01&pass=user@123&senderid=EDGEIT&dest_mobileno=' . $mobile_no . '&message=' . $msgbody.'&dltentityid=1201160450888723221&dlttempid=1607100000000126745&response=Y');
                                    }
                                }
                            }
                            if ($email == "ON") {
                                if ($email_id != "") {
                                    $email_id_user = $row['email_id'];
                                    if ($login_id != "" || $login_id == null) {
                                        $stmt_company = $object->UserCompanyDetails($user_id);
                                        if ($row_user = $stmt_company->fetch(PDO::FETCH_ASSOC)) {
                                            extract($row_user);
                                            if ($row_user['website_link'] != null) {
                                                $website_link_comp = $row_user['website_link'];
                                            }
                                            $logo_path = ADMIN_HTTP_PATH . $properties['jdbc.comp_image_folder'] . "/" . $row_user['logo_path'];
                                        }
                                        SendBlueEmail("forgot_username", $email_id_user, $first_name, $login_id, $api_key, $logo_path, $website_link_comp);
                                    }
                                }
                            }
                            if ($login_id == "" || $login_id == null) {
                                echo json_encode(array("result1" => "failure", "result2" => _("LG0503")));
                            } else {
                                unset($_SESSION['csrf_token']);
                                echo json_encode(array("result1" => "non_ecom", "result2" => _("LG0117")));
                            }
                        } else {
                            echo json_encode(array("result1" => "failure", "result2" => _("LG0510")));
                        }
                    }
                } else {
                    echo json_encode(array("result1" => "failure", "result2" => _("LG0105")));
                }
            } else {
                echo json_encode(array("result1" => "failure", "result2" => _("Please check I'm not a Robot")));
            }
        }
    } else {
        echo json_encode(array("result1" => 'failure', "result2" => "CSRF token validation failed."));
    }
}

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function SendBlueEmail($mode, $email_id, $first_name, $value, $api_key, $logo_path, $website_link) {
    $credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', $api_key);
    $apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(), $credentials);
    if ($mode === "forgot_username") {
        $sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
            'subject' => 'K-nest LMS',
            'sender' => ['name' => ' K-nest LMS', 'email' => 'donotreply@knestlms.com'],
            'to' => [['email' => $email_id]],
            'htmlContent' => '<html><div style="background-color:#f3f5f9;width:100%;padding:10px 50px 10px 10px;"><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:620px;padding:30px;">Dear ' . $first_name . ',<br/><br/>Username for logging into K-nest LMS is:  ' . $value . '<br/><br/>Regards,<br/>K-nest LMS Admin</div><div style="padding:30px;"><center><img src=' . $logo_path . ' /><br/>' . $website_link . '</center></div></div></html>',
        ]);
    } else {
        $sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
            'subject' => 'K-nest LMS',
            'sender' => ['name' => 'K-nest LMS', 'email' => 'donotreply@knestlms.com'],
            'to' => [['email' => $email_id]],
            'htmlContent' => '<html><div style="background-color:#f3f5f9;width:100%;padding:10px 50px 10px 10px;"><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:620px;padding:30px;">Dear ' . $first_name . ',<br/><br/>OTP for logging into K-nest LMS is: ' . $value . '.<br/><br/>Regards,<br/>K-nest LMS Admin</div><div style="padding:30px;"><center><img src=' . $logo_path . ' /><br/>' . $website_link . '</center></div></div></html>',
        ]);
    }
    try {
        $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
    } catch (Exception $e) {
        echo $e->getMessage(), PHP_EOL;
    }
}

?>