<?php
// yalda_payload.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';

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

$token = $_GET["userToken"];
$phone = "wait";
if (isset($_GET["userId"])) {
  $phone = $_GET["userId"];
}

$tamdidToken = getUniqueToken();
$planId = $_GET["planId"];

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

$redirect = $_GET["redirect"];




$result_plans = $conn->query("SELECT * FROM plansV2 WHERE `plan_id`='$planId'");
if ($result_plans->num_rows > 0) {
  while ($row = $result_plans->fetch_assoc()) {
    $payment = $row["discountPrice"];
    
    if ($payment == ""){
      $payment = $row["per_price"];
    }
    if (substr($redirect, 0, 3) == "ref"){
        $payment = $row["referral_price"];
    }
  }
}

if ($token == "47cd74d90b05722eab206af56db5d576ec725b23d2b56d4e9b1fcd516ac5c0b209aa611cc65ea193a8f90ed8ef66717e"){ 
    $payment = 2;
}


if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName` , `camp`)
    VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , $payment , $payment , '$token' , '$currentTime' , 'tamdid' , '' , 'yalda')")) {
}

$payment = $payment * 1000;


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' , 'fit' , '' , '$payment' , 'myfit' , '$time' , '$currentTime' , '$token' , '$year' , '$month' , '$day' , '$startTs' , '$endTs' , '' , '$redirect' , 'matcha' , '$callBack')")) {


  $res["phone"] = $rowUser["phone"];
  $res["persona"] = $rowUser["persona"];
  $res["userToken"] = $token;
  $res["paymentURL"] = 'https://api.matchadiet.com/gateway/irsrv17/jibit/index.php?id=' . $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;
}