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

//die();

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);
}
$callBack = "tamdid";

// error_reporting(0);

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

$response1['success'] = 'false';
$response1['message'] = '500';

$isDiscount = true;
$redirect = "tamdid";

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

$conn = new mysqli($servername, $username, $password, $dbname_process);
// Check connection
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error); 
}
if (isset($_GET["id"])){
    $token = $_GET["id"];
}
else {
    $token = $_GET["userToken"];
}

$currentTime = time();
$startTs = currentTsToPaymentTs(time());
$endTs = $startTs + (30 * 86400);
$year = tsToShamsiYear(time());
$month = tsToShamsiMonth(time());
$day = tsToShamsiDay(time());
$time = date("Y-m-d H:i:s");
$time = str_replace(" ", "T", $time); 



$title = "برنامه ۱ ماهه اختصاصی شما";

if ($token == "tempTamdid" OR $token == "tempTamdid2" OR $token == "tempTamdid3" OR $token == "tempTamdid6" OR $token == null OR $token == "reserveTamdid1" OR $token == "reserveTamdid2" OR $token == "reserveTamdid3" OR $token == "reserveTamdid6") { 
    
    $redirect = "tamdidSeller";
    $tamdidPrice = '749';
    $tamdidPriceDis = '499';
    switch ($token){
        case "tempTamdid2":
            $title = "برنامه ۲ ماهه اختصاصی شما";
            $tamdidPrice = '975';
            $tamdidPriceDis = '599';
            break;
        case "tempTamdid3":
            $title = "برنامه ۳ ماهه اختصاصی شما";
            $tamdidPrice = '1250';
            $tamdidPriceDis = '637';
            break;
        case "tempTamdid6":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $tamdidPrice = '2050';
            $tamdidPriceDis = '997';
            break;
            
        case "reserveTamdid1":
            $title = "برنامه ۱ ماهه اختصاصی شما";
            $tamdidPrice = '499';
            $tamdidPriceDis = '450';
            break;
            
        case "reserveTamdid2":
            $title = "برنامه ۲ ماهه اختصاصی شما";
            $tamdidPrice = '599';
            $tamdidPriceDis = '550';
            break;
        
        case "reserveTamdid3":
            $title = "برنامه ۳ ماهه اختصاصی شما";
            $tamdidPrice = '637';
            $tamdidPriceDis = '588';
            break;
        
        case "reserveTamdid6":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $tamdidPrice = '997';
            $tamdidPriceDis = '948';
            break;
        
    }
    
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone="wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , $tamdidPrice , $tamdidPriceDis , '$token' , '$currentTime' , 'tamdid' , '')")) {
    }
}
if ($token == "tempNew" OR $token == "tempNew2" OR $token == "tempNew3" OR $token == "tempNew6" OR $token == null OR $token == "reserveNew1" OR $token == "reserveNew2" OR $token == "reserveNew3" OR $token == "reserveNew6"  OR $token == "tempNew6off") {
    
    $redirect = "newSeller";
    $newPrice = '945';
    $newPriceDis = '598';
    switch ($token){
        case "tempNew2":
            $title = "برنامه ۲ ماهه اختصاصی شما";
            $newPrice = '1175';
            $newPriceDis = '849';
            break;
        case "tempNew3":
            $title = "برنامه ۳ ماهه اختصاصی شما";
            $newPrice = '1250';
            $newPriceDis = '997';
            break;
        case "tempNew6":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $newPrice = '2150';
            $newPriceDis = '1579';
            break;
            
        case "tempNew6":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $newPrice = '2150';
            $newPriceDis = '1579';
            break;
            
        case "tempNew6off":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $newPrice = '2150';
            $newPriceDis = '1297';
            break;
            
        case "reserveNew1":
            $title = "برنامه ۱ ماهه اختصاصی شما";
            $newPrice = '598';
            $newPriceDis = '549';
            break;
            
        case "reserveNew2":
            $title = "برنامه ۲ ماهه اختصاصی شما";
            $newPrice = '849';
            $newPriceDis = '800';
            break;
            
        case "reserveNew3":
            $title = "برنامه ۳ ماهه اختصاصی شما";
            $newPrice = '997';
            $newPriceDis = '948';
            break;
            
        case "reserveNew6":
            $title = "برنامه ۶ ماهه اختصاصی شما";
            $newPrice = '1579';
            $newPriceDis = '1530';
            break;
            
    }
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone="wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , $newPrice , $newPriceDis , '$token' , '$currentTime' , 'new' , '')")) {
    }
}
if ($token == "tempNew2" or $token == null) {

    $redirect = "newSeller";
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone = "wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , '945' , '417' , '$token' , '$currentTime' , 'new' , '')")) {
    }
}
if ($token == "tempNew3" or $token == null) {

    $redirect = "newSeller";
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone = "wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , '945' , '299' , '$token' , '$currentTime' , 'new' , '')")) {
    }
}
if ($token == "tempNew3" or $token == null) {

    $redirect = "newSeller";
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone = "wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , '945' , '299' , '$token' , '$currentTime' , 'new' , '')")) {
    }
}
if ($token == "reserve" or $token == null) {

$callBack = "reserve";
    $redirect = "reserve";
    $tamdidToken = getUniqueToken();
    $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
    $phone = "wait";
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , '499' , '49' , '$token' , '$currentTime' , 'new' , '')")) {
    }
}
$resultUser = $conn->query("SELECT * FROM tamdid WHERE `tamdidToken`='$token' OR `token`='$token'");
while ($rowUser = $resultUser->fetch_assoc()) {
    $conn->query("UPDATE tamdid SET `isSeen`=1 WHERE `tamdidToken`='$token' OR `token`='$token'");
    
    $isInDrop = $rowUser["isInDrop"];
    if ($isInDrop == true){
       $conn->query("UPDATE tamdidDrop SET `isSeen`=1 WHERE `tamdidToken`='$token' OR `token`='$token'"); 
    }
    
    $phone = $rowUser["phone"]; 
    $persona = $rowUser["persona"]; 
    $price = $rowUser["price"]; 
    $disPrice = $rowUser["disPrice"]; 
    $disPercent = $rowUser["discountPercent"]; 
    $payment = $disPrice;
    $payCode = $rowUser["token"];
    if ($disPercent == 0){
        $isDiscount = false;
    }
    if (!$isDiscount){
        $payment = $price;
    }
    $payment = $payment * 1000;
    // switch ($persona){
    //     case "fit":
    //         $title = " رژیم کاهش وزن تخصصی یک ماهه + برنامه تمرینی + پشتیبانی آنلاین متخصص";
    //         break;
    //     case "gym":
    //         $title = " رژیم بدنسازی تخصصی یک ماهه + برنامه تمرینی + پشتیبانی آنلاین متخصص";
    //         break;
    //     case "inc":
    //         $title = " رژیم افزایش وزن تخصصی یک ماهه + برنامه تمرینی + پشتیبانی آنلاین متخصص";
    //         break;
    // }
    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`, `callBack`)
        VALUES ('$phone' , '$persona' , '' , '$payment' , 'myfit' , '$time' , '$currentTime' , '$payCode' , '$year' , '$month' , '$day' , '$startTs' , '$endTs' , '' , '$redirect' , 'matcha' , '$callBack')")) {
            
            
            $res["phone"] = $rowUser["phone"];
            $res["persona"] = $rowUser["persona"];
            $res["userToken"] = $rowUser["token"];
            $res["paymentURL"] = 'https://api.matchadiet.com/gateway/irsrv17/jibit/index.php?id=' . $rowUser["token"];
            $res["title"] = "انتخاب دوره";
            $res["thisPlan"] = array(
                "title" => $title,
                "price" => array(
                    "isDiscount" => $isDiscount,
                    "regular" => (int)$price,
                    "discounted" => (int)$disPrice,
                    "discountPercent" => (int)$disPercent, 
                    "preUnit" => "هزار",
                    "unit" => "تومان"
                    ),
                "planId" => "tamdid",  
                );
            $res["details"] = array(
                "title" => "پیشنهاد ویژه هوش مصنوعی ماچا برای تو!",
                "description"=> "براساس اطلاعاتی که بهم دادی، برنامه‌ات کاملاً شخصی‌سازی شده — چه بخوای وزن کم کنی، عضله بسازی، یا سبک زندگیتو تغییر بدی.<br>هم غذاها و هم تمرینات، دقیقاً مطابق شرایطت تنظیم شدن. هر قدم از مسیر، ما کنار تو هستیم.<br>پشتیبانی، یادآوری و انگیزه‌سازی هم همیشه فعاله."
                );
            
            $response1['success'] = 'true';
            $response1['message'] = '200';
            $response1['result'] = $res;
    }else {
            $response1['success'] = 'false';
            $response1['message'] = '500';
    }
}

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

function getUniqueToken($tokenLength = 8){
    $token = "";
    //Combination of character, number and special character...
    $combinationString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for($i=0;$i<$tokenLength;$i++){
        $token .= $combinationString[uniqueSecureHelper(0,strlen($combinationString))];
    }
    return $token;
}

/*
    This helper function will return unique and secure string...
*/
function uniqueSecureHelper($minVal, $maxVal) {
        $range = $maxVal - $minVal;
        if ($range < 0) return $minVal; // not so random...

        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1

        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $minVal + $rnd;
}