<?php
header('Access-Control-Allow-Origin: *');
header("Content-type: application/json; charset=utf-8");

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

// $err = "\n" . "**********" . "\n" . $_GET['phoneNumber'] . "\n" . $_GET['code']  . "\n" . time()  . "\n" . "**********";
// $error_message = $err;
// $log_file = "./setPhone.log";
// error_log($error_message, 3, $log_file);

$allPostFields = implode('', $_GET);
$err = "\n" . "**********" . "\n" . $_GET['phoneNumber'] . "\n" . $_GET['test']  . "\n" . $allPostFields  . "\n" . time()  . "\n" . "**********";
$error_message = $err;
$log_file = "./setPhone.log";
error_log($error_message, 3, $log_file);

$needVerify = "true";


$rand = rand(10001, 99999);

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

$phone = convertPersianToEnglish($phoneFirst);
$phone = str_replace(" ", "", $phone);

if (substr($phone, 0, 3) == "009") {

    $phone = str_replace("009", "09", $phone);
}

//$phone = str_replace(" " , "" , $phone);
if (is_numeric($phone)) {
    $phone = phoneFormatter($phone);
} else {


    $response['success'] = 'false';
    $response['message'] = 'لطفا شماره را به طور صحیح وارد کنید';

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

    // if ($phone == "direct"){

    // }
    // else {
    //     if(strpos($phone, '@') !== false){
    //         $phone = "gg".$phone;
    //     }
    //     else {
    //         $response['success'] = 'false';
    //         $response['message'] = 'لطفا آدرس ایمیل را کامل وارد کنید. مثال: matcha@gmail.com';

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

if ($phone == "989031346086") {
    $needVerify = "true";
}

$payCode = convertPersianToEnglish($codeFirst);
$payCode = str_replace(" ", "", $payCode);
$persona = null;
$payment = null;

$code = "";

$currentTime = time();
$token = null;
$headers = apache_request_headers();

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname_process);
mysqli_set_charset($conn, "utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$checkMobile = false;


if ($phone != "direct") {
    $result1 = $conn->query("SELECT * FROM payment WHERE `code`='$payCode'");
    if (mysqli_num_rows($result1) > 0) {
        while ($row1 = $result1->fetch_assoc()) {
            $code = $row1["process_id"];
        }
    }

    // else {
    //     $response['success'] = 'false';
    //     $response['message'] = 'تراکنش یافت نشد';

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

if ($needVerify == "true") {


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

    //The data you want to send via POST
    $fields = [
        'receptor' => $phone,
        'token' => $rand,
        'sender' => '200060600600',
        'template' => 'GMatchaSendCode',
    ];

    //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['data'] = array(
                'verifySubtitle' => "کد 5 رقمی به شماره " . $phone . " ارسال شده است.",
                'needVerify' => $needVerify,
                'phoneNumber' => $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['data'] = array(
                'resultLink' => "https://api.matchadiet.com/gateway/irsrv17/resultLink.php?id=" . $code,
                'needVerify' => $needVerify,
                'phoneNumber' => $phone,
                'verifySubtitle' => "کد 5 رقمی به شماره " . $phone . " ارسال شده است.",
            );

            $json_response = json_encode($response);
            echo $json_response;
            die();
        }
    } else {

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

    $conn->query("UPDATE payment SET `phone`='$phone' WHERE `code`='$payCode'");

    $data_sk = array(
        'id' => null
    );
    $post_data = json_encode($data_sk);

    // Prepare new cURL resource
    $crl = curl_init('https://api.matchadiet.com/process/payment/confirmpay.php' . '?id=' . $payCode . '&ref=');
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($crl, CURLINFO_HEADER_OUT, true);
    curl_setopt($crl, CURLOPT_POST, true);
    curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data);

    // Set HTTP Header for POST request
    curl_setopt(
        $crl,
        CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );

    // Submit the POST request
    $result_uid = curl_exec($crl);


    $data_sk = json_decode($result_uid, true);

    if ($data_sk["success"] == 'true') {

        $response1['success'] = 'true';
        $response1['message'] = '200';
        $response1['result'] = array(
            'resultLink' => "https://api.matchadiet.com/gateway/irsrv17/resultLink.php?id=" . $code,
        );
        $response1['data'] = array(
            'resultLink' => "https://api.matchadiet.com/gateway/irsrv17/resultLink.php?id=" . $code,
            'needVerify' => $needVerify
        );
        $json_response = json_encode($response1);
        echo $json_response;
        die();
    } else {
        $response1['success'] = 'true';
        $response1['message'] = $data_sk['message'];

        $json_response = json_encode($response1);
        echo $json_response;
        die();
    }
}

$conn->close();
