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

if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 1000');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        // may also be using PUT, PATCH, HEAD etc
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    }

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
        header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization");
    }
    exit(0);
}

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

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


$startTime = time();
$startTimeInDate = date('Y/m/d H:i:s', $startTime);
$timeLeft = 0;

$programLength = "";
$redirect = "";


$rand = rand(10001, 99999);

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

if ($_GET["test"] == "true") {
    $json_string = json_encode($_GET);
    $file_handle = fopen('testResCOCO.json', 'w');
    fwrite($file_handle, $json_string);
    fclose($file_handle);
}

$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'] = 'لطفا آدرس ایمیل را کامل وارد کنید. مثال: matcha@gmail.com';

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

$plan_id = convertPersianToEnglish($plan_idFirst);
$code = convertPersianToEnglish($codeFirst);
$project = convertPersianToEnglish($projectFirst);
$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";
}
$errorPage = 'https://api.matchadiet.com/gateway/irsrv17/error.php';
$zarinpal = 'https://api.matchadiet.com/gateway/irsrv17/index.php?id=' . $payCode;
$paykan = 'https://api.matchadiet.com/gateway/irsrv17/paykan/index.php?id=' . $payCode;
$shenaseh = 'https://e-nik.ir/payment/mint/landing/index.php?id=' . $payCode;
$jibit = 'https://api.matchadiet.com/gateway/irsrv17/jibit/index.php?id=' . $payCode;

$gatewayLink = $zarinpal; 

if ($code == "Dea9aebfa239f3de") {
    $gatewayLink = $paykan;
}

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

$allAnswers = array();
$description = "";
$resultAllAnswers = $conn->query("SELECT * FROM process WHERE `code`='$code'");
if ($resultAllAnswers->num_rows > 0) {
    while ($row_aa = $resultAllAnswers->fetch_assoc()) {
        $answer_aa = $row_aa["aid"];
        $type = $row_aa["type"];
        $answer_aa = str_replace("_ge", "", $answer_aa);
        $answer_aa = str_replace("_ad", "", $answer_aa);
        array_push($allAnswers, $answer_aa);
    }
}
if (in_array("ov1.1", $allAnswers)) {
    $description = " - اقدام از تنبلی";
}

if ($type == "eghdam_ad") {
    $description = " - گوگل اد";
}
if ($type == "eghdam_ge") {
    $description = " - تعیین جنسیت";
}
if (in_array("ov1.1", $allAnswers)) {
    $description = " - اقدام از تنبلی";
}


$resultUser = $conn->query("SELECT * FROM users WHERE `token`='$token'");
if ($resultUser->num_rows > 0) {
    while ($rowUser = $resultUser->fetch_assoc()) {
        $programLength = $rowUser['programLength'];
        $redirect = $rowUser['redirect'];
    }
}



$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 = 349;
        $length = $row["length"];
        $payment = $per_price;
        $planId = $plan_id;
        
        $discountPrice = "";
        
        
    if ($planId == "fit" or $planId == "fastfit" or $planId == "gym" or $planId == "inc"){
        $discountPrice =  round($perPrice * $programLength);

        if ($discountPrice > 649) {
            $discountPrice = 649;
        }
        if ($discountPrice < 549) {
            $discountPrice = 549;
        }
        
           
    }
    if ($planId == "fit_vip" or $planId == "fastfit_vip" or $planId == "gym_vip" or $planId == "inc_vip"){
        $discountPrice =  round(($perPrice + 49) * $programLength);
        
        if ($discountPrice > 749) {
            $discountPrice = 749;
        }
        if ($discountPrice < 649) {
            $discountPrice = 649;
        }
        
  
    } 
    
    
        $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 ($token == "ad79c5c8fcbc2176749c8262123a6f7316b99609f7aeb431a8ccc526d46f269085cc106e3400962f100f7e0ff26e1ff9") {
            //            $resultLink = 'https://mintdoctor.ir/gateway/np/index.php?id='.$payCode;
            $payment = "7000";
        }
        
        






        if ($conn->query("INSERT IGNORE INTO payment(`phone` , `persona` , `process_id` , `payment` , `plan_id` , `time` , `created_at` , `code` , `year` , `month` , `day` , `startTs` , `endTs` , `description` , `redirect` , `project`) VALUES ('$phone' , '$persona' , '$code' , '$payment' , '$plan_id' , '$time' , '$currentTime' , '$payCode' , '$year' , '$month' , '$day' , '$startTs' , '$endTs' , '$description' , '$redirect' , '$project')")) {
            $timeLeft = time() - $startTime;



            $response1['success'] = 'true';
            $response1['message'] = '200';
            $response1['result'] = array(
                'phoneNumber' => $phone,
                'token' => $token,
                'resultLink' => $resultLink,
            );

            $response1['data'] = array(
                'phoneNumber' => $phone,
                'token' => $token,
                'resultLink' => $resultLink,
                'title' => "شماره موبایل رو وارد کنید",
                'placeholder' => "محل وارد کردن شماره موبایل",
                'description' => "نام کاربری، شماره موبایل شما خواهد بود و برای دریافت برنامه باید با یکی از این موارد، وارد ماچا بشید.",
                'button' => array(
                    'text' => "دریافت برنامه",
                    'link' => "",
                    'bgColor' => "#f87691",
                    'color' => "white",
                )

            );

            $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();
