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

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

$gender = "null";
$height = "";
$weightCurrent = "";
$weightGoal = "";
$programLength = "";
$diffWeight = "";


$rand=rand(10001,99999);

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

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

$plan_id = convertPersianToEnglish($plan_idFirst);
$code = convertPersianToEnglish($codeFirst);
$discount = $discountFirst;
$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://matchadiet.com/gateway/irsrv17/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;

$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'");
}
else{
    $conn->query("INSERT INTO mobiles(phone, token , timestamp) VALUES ('$phone', '$rand' , '$currentTime')");
}

$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'");
}

$resultUser = $conn->query("SELECT * FROM users WHERE `token`='$token'");
if ($resultUser->num_rows > 0) {
    while ($rowUser = $resultUser->fetch_assoc()) {
        $gender = $rowUser["gender"];
        $weightCurrent = $rowUser["weight"];
        $weightGoal = $rowUser["weight_goal"];
        $height = $rowUser["height"];
        $programLength = $rowUser["programLength"];

        $diffWeight = $weightCurrent - $weightGoal;
    }
}

$result = $conn->query("SELECT * FROM plansV2 WHERE `plan_id`='$plan_id'");
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $persona = $row["persona"];
        
        $perPrice = 125;
//            $discountPrice = $perPrice - ($perPrice * 0.2);
//            $discountPrice = (int) $discountPrice;
//            $discountPrice = (string) $discountPrice;

            $planId = $row["plan_id"];
            $res["planId"] = $row["plan_id"];
            $res["title"] = $programLength . " " . $row["title"];
            $res["description"] = $row["description"];
            if ($planId == "fit"){
                $discountPrice =  round($perPrice * $programLength);
            }
            else if ($planId == "fit_vip"){
                $discountPrice =  round(($perPrice + 49) * $programLength);
                
            }
            if ($discountPrice > 999){
                $discountPrice = 999;
            }

            // if ($discountPrice < 179){
            //     $discountPrice = 179;
            // }
        $purePrice = round($discountPrice * 1.2);
        $payment = $purePrice;
        if ($discount == "true"){
            $payment = $discountPrice;
        }
        $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 ($phone == "989356292212" or $phone == "989015159799"){
//            $resultLink = 'https://mintdoctor.ir/gateway/np/index.php?id='.$payCode;
            $payment = "1000";
        }

        error_log("request no problem! time: " . time() . " IP: ". getUserIpAddr() . " phone: " . $phone . PHP_EOL, 3, "./my-errors.log");


        if ($conn->query("INSERT 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();

?>
