<?php

header("Content-type: application/json; charset=utf-8");

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

$year = tsToShamsiYear(time());
$month = tsToShamsiMonth(time());
$day = tsToShamsiDay(time());

$phoneFirst = $_POST['phoneNumber'];
$verificationFirst = $_POST['verification'];
$loginTypeFirst = $_POST['loginType'];
$plan_idFirst = $_POST['plan'];
$codeFirst = $_POST['code'];
if (sizeof($_POST) == 0){
    $phoneFirst = $_GET['phoneNumber'];
    $verificationFirst = $_GET['verification'];
    $plan_idFirst = $_GET['plan'];
    $loginTypeFirst = $_GET['loginType'];
    $codeFirst = $_GET['code'];
}

$phone = convertPersianToEnglish($phoneFirst);
$verification = convertPersianToEnglish($verificationFirst);
$loginType = convertPersianToEnglish($loginTypeFirst);
$phone = phoneFormatter($phone);

$plan_id = convertPersianToEnglish($plan_idFirst);
$code = convertPersianToEnglish($codeFirst);
$persona = null;
$payment = null;

$payCode = md5(uniqid(rand(), true)).md5(uniqid(rand(), true)).md5(uniqid(rand(), true));
if (substr($code, -3) == "AAD"){
    $payCode = $payCode."AAD";
}
$zarinpal = 'https://api.matchadiet.com/gateway/index.php?id='.$payCode;
$shenaseh = 'https://e-nik.ir/payment/mint/landing/index.php?id='.$payCode;
$gatewayLink = $zarinpal;

$resultLink = $gatewayLink;

$time = date("Y-m-d H:i:s");
$time = str_replace(" " , "T" , $time);

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

if(isset($headers['Authorization'])){

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

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

}

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

$result = $conn->query("SELECT * FROM mobiles WHERE `phone`='$phone'");

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $codeTime = $row["timestamp"];
        if($row["token"] != $verification){
            $response['success'] = 'false';
            $response['message'] = 'کد وارد شده اشتباه است';
            $json_response = json_encode($response);
            echo $json_response;
            die();
        }

        if ((($currentTime - $codeTime) / 60) > 3){
            $response['success'] = 'false';
            $response['message'] = 'کد ورود منقضی شده است';
            $json_response = json_encode($response);
            echo $json_response;
            die();
        }
    }
}
else {
    if ($loginType != "google"){
        $response['success'] = 'false';
        $response['message'] = 'خطا ثبت اطلاعات';

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

            $result1 = $conn->query("SELECT * FROM users WHERE `phone`='$phone'");
            if ($result1->num_rows > 0) {
                while($row1 = $result1->fetch_assoc()) {
                    $conn->query("UPDATE users SET `token`='$token', `updated_at`='$currentTime' WHERE `phone`='$phone'");
                }
            }
            else {
                $conn->query("UPDATE users SET `phone`='$phone', `updated_at`='$currentTime' WHERE `token`='$token'");
            }

            $result = $conn->query("SELECT * FROM plans WHERE `plan_id`='$plan_id'");
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $persona = $row["persona"];
                    $per_price = $row["per_price"];
                    $length = $row["length"];
                    $payment = $per_price * $length;
                    $payment = $payment * 1000;
                    $time_unit = $row["time_unit"];
                    if ($time_unit == "month"){
                        $lengthDay = $length * 31;
                    }
                    else if ($time_unit == "year"){
                        $lengthDay = $length * 366;
                    }
                    $startTs = currentTsToPaymentTs(time());
                    $endTs = $startTs + ($lengthDay*86400);

                    if ($conn->query("INSERT IGNORE INTO payment(`phone` , `persona` , `process_id` , `payment` , `plan_id` , `time` , `created_at` , `code` , `year` , `month` , `day` , `startTs` , `endTs`) VALUES ('$phone' , '$persona' , '$code' , '$payment' , '$plan_id' , '$time' , '$currentTime' , '$payCode' , '$year' , '$month' , '$day' , '$startTs' , '$endTs')")){
                        $response1['success'] = 'true';
                        $response1['message'] = '200';
                        $response1['result'] = array(
                            'phoneNumber' => $phone,
                            'token' => $token,
                            'resultLink' => $resultLink,
                        );
                        $json_response = json_encode($response1);
                        echo $json_response;
                        die();
                    }
                    else {
                        $response['success'] = 'false';
                        $response['message'] = 'مشکل در ثبت اطلاعات';

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


                }
            }






$conn->close();

?>
