<?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';


$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 (is_numeric($phone) ) {
    $phone = phoneFormatter($phone);
} else {

    if ($phone == "direct"){

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

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

$payCode = convertPersianToEnglish($codeFirst);
$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();
    }
}

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

// Prepare new cURL resource
$crl = curl_init('https://matchadiet.com/process/payment/confirmpay.php'.'?id='.$code . '&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://mintdoctor.ir/gateway/irsrv17/resultLink.php?code=".$code,
    );
    $json_response = json_encode($response1);
    echo $json_response;
    die();
}

//$conn->query("UPDATE users SET `phone`='$phone', `updated_at`='$currentTime' WHERE `token`='$token'");


$conn->close();

?>
