<?php
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '1');
require_once '../../includes/config.php';

function rancode() {
	$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	srand((double)microtime()*1000000);
	$i = 0;
	while ($i <= 8)
	{
		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$pwd = $pwd . $tmp;
		$i++;
	}
	return $pwd;
}

if(!isset($_GET['uid']) || empty($_GET['uid'])){
	echo '<script>alert("Error");</script>';
	$db->RedirectToURL($db->base_url());
	exit;	
}else{
	$uid = $_GET['uid'];
	
    $sql = $db->sql_query("SELECT user_name, user_email, user_2fa_duration, user_2fa_otp FROM users WHERE user_2fa_id = '$uid'");					
    $row = $db->sql_fetchrow($sql);
    				
    if($row['user_2fa_duration'] == 0){
        $email = $row['user_email'];
        $username = $row['user_name'];
        $code = rancode();
        $otpid = rancode();
        $qryotp = $db->sql_query("UPDATE users SET user_2fa_otp='$code', user_2fa_id='$otpid', user_2fa_duration='600' WHERE user_email = '$email'");
            							
        $msgz = "Hello " . $username . ",\r\n\r\n";
        $msgz .= "Copy the confirmation code given below and paste it in confirmation page. \r\n \r\n";
        $msgz .= "Confirmation Code: ".$code . "\r\n \r\n";
        $msgz .= "Regards, \r\n";
        $msgz .= "Security Department\r\n";
        $subject = $db->sitename . ' - Account Confirmation';
                            			
        #set email headers  to aviod spam filters
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        //$headers .= "From: ".$db->siteTitle." <no-reply@".$db->sitename.">".$eol;
        $headers = 'From: support@no-reply.net' . "\r\n" .
        'Reply-To: support@no-reply.net' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
                            			
        mail($email, $subject, $msgz, $headers);	
        			
        if($qryotp){
            $success_message = 'Confirmation code have been sent. Please check your email.';
            $values['response'] = 1;
            $values['msg'] = $success_message;
            $values['id'] = $otpid;
        }else{
            $error_message = 'Sorry! invalid transaction!';
            $values['response'] = 2;
            $values['msg'] = $error_message;
        }
    }else{
        $error_message = 'Sorry! invalid transaction!';
        $values['response'] = 2;
        $values['msg'] = $error_message;
    }
    
    echo json_encode($values);
}
?>