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

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

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

$currentTime = time();

$token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
$phone = "wait";
$redirect = "";
if (isset($_GET["redirect"])){
  $redirect = $_GET["redirect"];
}
$tamdidToken = getUniqueToken();
if (isset($_GET["phone"])){
  $phone = $_GET["phone"];
  
    if ($conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName` , `camp` , `redirect`)
        VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , 2899 , 799 , '$token' , '$currentTime' , 'tamdid' , '' , 'yalda' , '$redirect')")) {
    }
}




// Build the payload as a PHP associative array
$data = [
  "version" => "yalda-1",
  "userToken" => $token,
  "banner" => [
    "src" => "/yalda-banner-2.webp",
    "width" => 327,
    "height" => 157,
  ],
  "features" => [
    [
      "id" => "doctors",
      "text" => "رژیم تخصصی ماچا، طراحی‌شده توسط واحد علمی و پزشکان تغذیه",
      "mainImage" => [
        "src" => "/yalda-doctor.webp",
        "width" => 99,
        "height" => 259,
      ],

      "alignment" => "right",
      "badges" => [
        [
          "id" => "1",
          "text" => "بدون ریزش مو",
          "textColor" => "#A550A7",
          "bgColor" => "#A550A71A",
        ],
        [
          "id" => "2",
          "text" => "بدون افتادگی پوست",
          "textColor" => "#FF5257",
          "bgColor" => "#FF52571A",
        ],
        [
          "id" => "3",
          "text" => "بدون دارو",
          "textColor" => "#3377FF",
          "bgColor" => "#3377FF1A",
        ],
      ],
    ],
    [
      "id" => "support",
      "text" => "هر هفته تا شب یلدا، کارشناس تغذیه مورد تأیید ماچا با شما تماس می‌گیرد و شرایطتان را پیگیری می‌کند",
      "mainImage" => [
        "src" => "/yalda-support.webp",
        "width" => 99,
        "height" => 275,
      ],
      "alignment" => "left",
    ],
    [
      "id" => "bot",
      "text" => "مقایسه و تحلیل کامل وضعیت شما با افراد مشابه در بانک اطلاعاتی ماچا (بیش از ۲۵۰,۰۰۰ کاربر) و ارائه مؤثرترین رژیم اختصاصی.",
      "mainImage" => [
        "src" => "/yalda-bot.webp",
        "width" => 99,
        "height" => 237,
      ],

      "alignment" => "right",
    ],
    [
      "id" => "diet",
      "text" => "با ماچا رژیم ساده و اقتصادی با غذاهای سفره خانواده اجرا میشه، هر غذایی رو هم می تونید راحت جایگزین کنید، فقط مقدار مصرف مهمه",
      "mainImage" => [
        "src" => "/yalda-food.webp",
        "width" => 100,
        "height" => 100,
      ],
      "alignment" => "left",
    ],
  ],
  "midSection" => [
    "title" => "ورزش در خانه یا باشگاه؛",
    "subtitle" => "با آموزش ویدئویی قدم‌به‌قدم",
    "image" => [
      "src" => "/yalda-video-preview.webp",
      "width" => 325,
      "height" => 161,
    ],
    "items" => [
      [
        "id" => "enamad",
        "image" => [
          "src" => "/yalda-enamad.webp",
          "width" => 93,
          "height" => 93,
        ],
        "text" => "اینماد و مجوزهای قانونی",
      ],
      [
        "id" => "guarantee",
        "image" => [
          "src" => "/yalda-guarantee.webp",
          "width" => 93,
          "height" => 93,
        ],
        "text" => "گارانتی بازگشت وجه در صورت عدم نتیجه",
      ],
      [
        "id" => "suggestion",
        "image" => [
          "src" => "/yalda-suggestion.webp",
          "width" => 93,
          "height" => 80,
        ],
        "text" => "توصیه و رضایت هزاران مشتری موفق",
      ],
    ],
    "bubbleText" => "ماچا‌دایت فقط یک رژیم نیست؛ سرمایه‌گذاری روی سلامت و حال خوب شماست.",
    "endingText" => "امسال شـــب‌یـــلدا بدرخشید",
  ],
  "plans" => [
    [
      "title" => "پکیج کامل تا یلدا (پیشنهاد ماچا)",
      "planId" => "yaldaFeatured",
      "price" => [
        "isDiscount" => true,
        "regular" => 2899,
        "discounted" => 879,
        "discountPercent" => 30,
        "preUnit" => "هزار",
        "unit" => "تومان",
      ],
      "buttonText" => "فرصت را از دست نده!",
      "isFeatured" => true,
      "image" => [
        "src" => "/yalda-matcha-gold.webp",
        "width" => 48,
        "height" => 48,
      ],
      "features" => [
        [
          "id" => "1",
          "status" => "positive",
          "text" => "پشتیبانی تلفنی + آنلاین",
        ],
        [
          "id" => "2",
          "status" => "positive",
          "text" => "برنامه ورزشی",
        ],
        [
          "id" => "3",
          "status" => "positive",
          "text" => "امکان پرداخت در 4 قسط (۳ قسط ۴۷۹ تومنی دیگر)",
        ],
      ],
    ],
    [
      "title" => "پکیج اقتصادی تا یلدا",
      "planId" => "yaldaEco",
      "price" => [
        "isDiscount" => false,
        "regular" => 2599,
        "discounted" => null,
        "discountPercent" => null,
        "preUnit" => "هزار",
        "unit" => "تومان",
      ],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        [
          "id" => "1",
          "status" => "positive",
          "text" => "فقط پشتیبانی آنلاین",
        ],
      ],
    ],
    [
      "title" => "پکیج پایه تا یلدا",
      "planId" => "yaldaBase",
      "price" => [
        "isDiscount" => false,
        "regular" => 1399,
        "discounted" => null,
        "discountPercent" => null,
        "preUnit" => "هزار",
        "unit" => "تومان",
      ],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        [
          "id" => "1",
          "status" => "negative",
          "text" => "پشتیبانی ندارد",
        ],
      ],
    ],
  ],
  "footer" => [
    "items" => [
      [
        "id" => "iran-address",
        "text" => "آدرس دفتر ایران : تهران، ناحیه نوآوری شریف، ساختمان گسترش، واحد 9",
      ],
      [
        "id" => "britain-address",
        "text" => "دفتر بریتانیا : انگستان، تانتون، کریدول اُرچارد، واحد 5",
      ],
      [
        "id" => "email",
        "text" => "MatchaSupp@gmail.com",
      ],
    ],
    "images" => [
      [
        "id" => "senfi",
        "src" => "yalda-footer-senfi.webp",
        "link" => "",
      ],
      [
        "id" => "enamad",
        "src" => "yalda-footer-enamad.webp",
        "link" => "",
      ],
      [
        "id" => "behpardakht",
        "src" => "yalda-footer-behpardakht.webp",
        "link" => "",
      ],
      [
        "id" => "satra",
        "src" => "yalda-footer-satra.webp",
        "link" => "",
      ],
      [
        "id" => "e",
        "src" => "yalda-footer-e.webp",
        "link" => "",
      ],
    ],
  ],
];

$response['success'] = 'true';
$response['message'] = '200';
$response['result'] = $data;
$json_response = json_encode($response);
echo $json_response;
die();

// Echo JSON (pretty for readability; remove JSON_PRETTY_PRINT in production if you prefer compact)
// echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);


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