<?php

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

include '../../utils/database.php';
include '../../utils/helper.php';
include '../../utils/tokens.php';

$rand=rand(10001,99999);

$currentTime = time();

$phoneFirst = $_POST['phoneNumber'];
if (sizeof($_POST) == 0){
    $phoneFirst = $_GET['phoneNumber'];
}

$token = null;
$phone = convertPersianToEnglish($phoneFirst);
$temp_phone = $phoneFirst;

$phone = phoneFormatter($phone);
$headers = apache_request_headers();

if(isset($headers['Authorization'])){
    $token = $headers['Authorization'];
}
else {
    $response['success'] = 'false';
    $response['message'] = '403';
    $json_response = json_encode($response);
    echo $json_response;
    die();
}

$conn = new mysqli($servername, $username, $password, $dbname_process);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$url = 'https://api.kavenegar.com/v1/'.$SMSTOKEN.'/verify/lookup.json';

//The data you want to send via POST
$fields = [
    'receptor'=> $phone,
    'token'=> $rand,
    'template'=> 'GMintSendCode',
    'token2'=> $AppCode
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
$result = json_decode($result);
if ($result->entries !== NULL) {
    $result1 = $conn->query("SELECT phone FROM mobiles WHERE `phone`='$phone'");

    if(mysqli_num_rows($result1) > 0){

        $conn->query("UPDATE mobiles SET `token`='$rand' , `timestamp`='$currentTime' WHERE `phone`='$phone'");

        $response['success'] = 'true';
        $response['message'] = '200';
        $response['result'] = array(

            'phoneNumber' => $temp_phone,
        );
        $json_response = json_encode($response);
        echo $json_response;
        die();
    }
    else{

        $conn->query("INSERT INTO mobiles
                (phone, token , timestamp)
                VALUES
                ('$phone', '$rand' , '$currentTime')");

        $response['success'] = 'true';
        $response['message'] = '200';
        $response['result'] = array(

            'phoneNumber' => $temp_phone,
        );

        $json_response = json_encode($response);
        echo $json_response;
        die();

    }
}
else{

    $response['success'] = 'false';
    $response['message'] = 'مشکل در ارسال پیامک. لطفا بعدا تلاش کنید';
    $response['result'] = array(
        'phoneNumber' => $temp_phone,
    );
    $json_response = json_encode($response);
    echo $json_response;
    die();
}

$conn->close();
