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

if (isset($_SERVER['HTTP_ORIGIN'])) {
  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'])) {
    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);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// ---------------------- Params & tokens ----------------------
$phone = isset($_GET["phone"]) ? $_GET["phone"] : "wait";
$redirect = isset($_GET["redirect"]) ? $_GET["redirect"] : "";
$referral = "false";
if ($_GET["referral"] == "true"){
    $referral = "true";
}



// اگر خودت توکن را می‌فرستی، از همان استفاده می‌شود؛
// در غیر این صورت، همان روش قدیمی برای ساخت توکن به‌صورت fallback اجرا می‌شود.
if (isset($_GET['token']) && is_string($_GET['token']) && $_GET['token'] !== '') {
  $token = $_GET['token'];
} else {
  // fallback به روش قبلی شما
  $token = md5(uniqid(rand(), true)) . md5(uniqid(rand(), true)) . md5(uniqid(rand(), true));
}

$tamdidToken = getUniqueToken();

$currentTime= time();

if (isset($_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' , 1999 , 647 , '$token' , '$currentTime' , 'tamdid' , '' , 'yalda' , '$redirect')")) {
    }
}

$plans = [
    [
      "title" => "پکیج کامل تا یلدا (پیشنهاد ماچا)",
      "planId" => "yaldaFeatured",
      "price" => ["isDiscount" => true,"regular" => 1999,"discounted" => 647,"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" => 1599,"discounted" => null,"discountPercent" => null,"preUnit" => "هزار","unit" => "تومان"],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        ["id" => "1","status" => "positive","text" => "فقط پشتیبانی آنلاین"]
      ]
    ],
    [
      "title" => "پکیج پایه تا یلدا",
      "planId" => "yaldaBase",
      "price" => ["isDiscount" => false,"regular" => 997,"discounted" => null,"discountPercent" => null,"preUnit" => "هزار","unit" => "تومان"],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        ["id" => "1","status" => "negative","text" => "پشتیبانی ندارد"]
      ]
    ]
  ];
  
if ($redirect == "yaldaconsent1"){
      $plans = [
    [
      "title" => "پکیج کامل تا یلدا (پیشنهاد ماچا)",
      "planId" => "yaldaFeatured",
      "price" => ["isDiscount" => true,"regular" => 2899,"discounted" => 2316,"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" => "برنامه ورزشی"],
      ]
    ],
    [
      "title" => "پکیج پایه تا یلدا",
      "planId" => "yaldaBase",
      "price" => ["isDiscount" => false,"regular" => 1399,"discounted" => null,"discountPercent" => null,"preUnit" => "هزار","unit" => "تومان"],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        ["id" => "1","status" => "negative","text" => "پشتیبانی ندارد"]
      ]
    ]
  ];
}

if ($referral == "true"){
    $plans = [
    [
      "title" => "پکیج کامل تا یلدا (ویژه دوستان)",
      "planId" => "yaldaFeatured",
      "price" => ["isReferral" => true, "isDiscount" => true,"regular" => 1999,"referral" => 547,"discounted" => 647,"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" => 1599,"discounted" => null,"discountPercent" => null,"preUnit" => "هزار","unit" => "تومان"],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        ["id" => "1","status" => "positive","text" => "فقط پشتیبانی آنلاین"]
      ]
    ],
    [
      "title" => "پکیج پایه تا یلدا",
      "planId" => "yaldaBase",
      "price" => ["isDiscount" => false,"regular" => 997,"discounted" => null,"discountPercent" => null,"preUnit" => "هزار","unit" => "تومان"],
      "buttonText" => "انتخاب",
      "isFeatured" => false,
      "features" => [
        ["id" => "1","status" => "negative","text" => "پشتیبانی ندارد"]
      ]
    ]
  ];
}

// اگر نیاز شد، این کوئری قبلی‌ات را آنکامنت کن و مقادیر قیمت/زمان را ست کن.
// $conn->query("INSERT IGNORE INTO tamdid(`phone` , `persona` , `tamdidToken` , `discountPercent` , `price` , `disPrice` , `token` , `createdAt` , `type` , `firstName` , `camp` , `redirect`)
//   VALUES ('$phone' , 'fit' , '$tamdidToken' , '30' , $tamdidPrice , $tamdidPriceDis , '$token' , '$currentTime' , 'tamdid' , '' , 'yalda' , '$redirect')");

// ---------------------- Payload ----------------------
$data = [
  "version"   => "yalda-2",
  "userToken" => $token,
  "banner" => [
    "src" => "/yalda-banner-long.webp",
    "width" => 327,
    "height" => 157
  ],
  "whatYouGet" => [
    "title" => "آنچه دریافت می‌کنید",
    "items" => [
      [
        "id" => "1",
        "image" => ["src" => "/yalda-wyg-1-v2.webp","width" => 57,"height" => 80],
        "text" => "پیگیری تلفنی هر هفته از سمت پشتیبانی"
      ],
      [
        "id" => "2",
        "image" => ["src" => "/yalda-wyg-2-v2.webp","width" => 56,"height" => 83],
        "text" => "5 تا 8 کیلو لاغری در هر ماه"
      ],
      [
        "id" => "3",
        "image" => ["src" => "/yalda-wyg-4-v2.webp","width" => 60,"height" => 82],
        "text" => "اسکن غذا و کالری‌شماری با اپلیکیشن ماچا"
      ],
      [
        "id" => "4",
        "image" => ["src" => "/yalda-wyg-3-v2.webp","width" => 46,"height" => 80],
        "text" => "مقایسه شما با ۲۵۰هزار کاربر و ارائه رژیم اختصاصی."
      ],
      [
        "id" => "5",
        "image" => ["src" => "/yalda-wyg-6-v2.webp","width" => 57,"height" => 68],
        "text" => "قابلیت جایگزینی غذا به صورت لحظه‌ای"
      ],
      [
        "id" => "6",
        "image" => ["src" => "/yalda-wyg-5-v2.webp","width" => 57,"height" => 80],
        "text" => "ارائه برنامه ورزشی تخصصی "
      ]
    ]
  ],
  "features" => [
    [
      "id" => "doctors",
      "text" => "رژیم تخصصی ماچا، طراحی‌شده توسط واحد علمی و پزشکان تغذیه",
      "mainImage" => ["src" => "/yalda-doctor-v2.webp","width" => 110,"height" => 224],
      "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-v2.webp","width" => 145,"height" => 174],
      "alignment" => "left"
    ],
    [
      "id" => "bot",
      "text" => "مقایسه و تحلیل کامل وضعیت شما با افراد مشابه در بانک اطلاعاتی ماچا (بیش از ۲۵۰,۰۰۰ کاربر) و ارائه مؤثرترین رژیم اختصاصی.",
      "mainImage" => ["src" => "/yalda-bot.webp","width" => 106,"height" => 217],
      "alignment" => "right"
    ],
    [
      "id" => "diet",
      "text" => "با ماچا رژیم ساده و اقتصادی با غذاهای سفره خانواده اجرا میشه، هر غذایی رو هم می تونید راحت جایگزین کنید، فقط مقدار مصرف مهمه",
      "mainImage" => ["src" => "/yalda-food.webp","width" => 100,"height" => 100],
      "alignment" => "left"
    ]
  ],
  "midSection" => [
    "title" => "اعتماد شما با پشتوانه مجوزهای رسمی",
    "items" => [
      ["id" => "enamad","image" => ["src" => "/yalda-enamadv2.webp","width" => 100,"height" => 100],"text" => "اینماد و مجوزهای قانونی"],
      ["id" => "guarantee","image" => ["src" => "/yalda-guarantee-v2.webp","width" => 100,"height" => 100],"text" => "گارانتی بازگشت وجه در صورت عدم نتیجه"],
      ["id" => "suggestion","image" => ["src" => "/yalda-suggestion-v2.webp","width" => 100,"height" => 100],"text" => "توصیه و رضایت هزاران مشتری موفق"]
    ],
    "beforeAfterCarousel" => [
      "title" => "نتیجه تغییرات شما",
      "items" => [
        ["id" => "scslide1","image" => ["src" => "/before-after-1.webp","width" => 327,"height" => 376]],
        ["id" => "scslide2","image" => ["src" => "/before-after-2.webp","width" => 327,"height" => 376]],
        ["id" => "scslide3","image" => ["src" => "/before-after-3.webp","width" => 327,"height" => 376]],
        ["id" => "scslide4","image" => ["src" => "/before-after-4.webp","width" => 327,"height" => 376]],
        ["id" => "scslide5","image" => ["src" => "/before-after-5.webp","width" => 327,"height" => 376]],
      ]
    ],
    "screenCarousel" => [
      "items" => [
        ["id" => "scslide1","image" => ["src" => "/yalda-slider-1-v2.webp","width" => 128,"height" => 258]],
        ["id" => "scslide2","image" => ["src" => "/yalda-slider-2-v2.webp","width" => 128,"height" => 258]],
        ["id" => "scslide3","image" => ["src" => "/yalda-slider-3-v2.webp","width" => 128,"height" => 258]],
        ["id" => "scslide4","image" => ["src" => "/yalda-slider-4-v2.webp","width" => 128,"height" => 258]]
      ]
    ],
    "contentCarousel" => [
      "items" => [
        ["key" => "comment_default_1","name" => ".","description" => "در طول ۲۵ روز ۶.۵ کیلو کم کردم اینقدر وزن کم کردن طبیعی هستش\r\n","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۱۰ شهریور","media" => ["image" => "/comment-1.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_2","name" => "Niayesh ","description" => "من اومدم بگم ۷۰ کیلو شدم برم تو ۴ ماه ۱۵ کیلو در طول روز اصلا احساس گرسنگی نمیکنم تازهههه تاثیر غذای مقوی و حذف قند رو درس خوندنم هم تاثیر مثبت گذاشته خواستم بگم خیلییییی خفنین","avatar" => "/nyayesh.jpg","socialIcon" => "/telegram.svg","date" => "۱۵ خرداد","media" => ["image" => "/comment-2.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_3","name" => "F","description" => "ميخواستم ديروز وزن بگيرم بعداز يك هفته ولي پريود شدم \r\nولي ميدونم حداقل نزديك يك و نيم تا دوكيلو رو حتما كم كردم\r\nخيليييي خوشحالم","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۱۳ مرداد","media" => ["image" => "/comment-3.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_4","name" => "فهیمه","description" => "دوره ۱ ماه من یکشنبه تموم میشه امروز وزن کردم خودمو با کمال ناباوری ۷۹ کیلو شدم اصلاً فکرشو نمی‌کردم بتونم تو یک ماه ۸ کیلو کم کنم در واقع هفته ۲ کیلو\r\n","avatar" => "/fahimeh.jpg","socialIcon" => "/telegram.svg","date" => "۲۸ مرداد","media" => ["image" => "/comment-4.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_5","name" => "فرهادی","description" => "من نود کیلو هستم الان دو روزه رژیم رو شروع کردم خیلی عالیه متنوع وهمونی که میخواستم اصلا احساس گرسنگی نمیکنم","avatar" => "/farhadi.jpg","socialIcon" => "/telegram.svg","date" => "۹خرداد","media" => ["image" => "/comment-5.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_6","name" => "Fahimeh","description" => "الهی که هر چی از خدا می خواهین بهتون بده \r\nدست گلت درد نکنه \r\nواقعاً با خونسردی جواب سوالات من و تغییر رژیم منو دادین \r\nخدا خیرتون بده","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۶ مرداد","media" => ["image" => "/comment-6.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_7","name" => "nargess","description" => "تعداد وعده‌ها عالیه واقعا اصلا احساس گرسنگی ندارم\r\n","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۵ تیر","media" => ["image" => "/comment-7.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_8","name" => "S","description" => "چقدر عالی که هستین \r\nاین انگیزه ی بزرگ ایجاد میکنه خیلی ممنونم","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۱ مهر","media" => ["image" => "/comment-8.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_9","name" => ".","description" => "عزیزم من تو یک ماه ۴کیلو کم کردم\r\n","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۲۹ اردیبهشت","media" => ["image" => "/comment-9.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_10","name" => "Amirhs","description" => "اول از همه میخوام ازتون تشکر ویژه کنم بابت هم پشتیبانی عالیتون هم برنامه کاهش وزن فوق العاده ای که در اختیارم گذاشتین واقعا ازتون ممنونم چون هرچی این سالها تلاش کرده بودم نتیجه ای نداشت ولی شما این مسئله رو عملی کردین هزاران بار سپاس خوشحالم که به مجموعه شما اعتماد کردم\r\n\r\n","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۲۷ شهریور","media" => ["image" => "/comment-10.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_11","name" => "Amir","description" => "پشتیبانی ۱۰۰/۱۰۰ خسته نباشید واقعا","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۲۱ اردیبهشت","media" => ["image" => "/comment-11.webp"],"button" => "نمایش تصویر"],
        ["key" => "comment_default_12","name" => "M","description" => "واقعا خوشحالم با گروه ماچا لاغری رو شروع کردم سپاس از برنامه و پشتیبانی خوب شما\r\n","avatar" => "/matcha-logo-with-bg.webp","socialIcon" => "/telegram.svg","date" => "۱۶ اردیبهشت","media" => ["image" => "/comment-12.webp"],"button" => "نمایش تصویر"]
      ]
    ],
    "yourVoices" => [
      "title" => "صدای شما",
      "items" => [
        ["key" => "voice_1","name" => "فخرالدین آذری زاده","media" => ["voice" => "/user-voice-1-fa.mp3"]],
        ["key" => "voice_1","name" => "حامد فاطمی","media" => ["voice" => "/user-voice-2-fa.mp3"]],
        ["key" => "voice_1","name" => "ساغر","media" => ["voice" => "/user-voice-3-fa.mp3"]]
      ]
    ],
    "bulletPoints" => [
      ["id" => "bullet1","image" => ["src" => "/yalda-bullets-1-v2.webp","width" => 32,"height" => 32],"text" => "قابلیت جایگزینی غذا در لحظه"],
      ["id" => "bullet2","image" => ["src" => "/yalda-bullets-2-v2.webp","width" => 32,"height" => 32],"text" => "قابلیت کالری شماری غذاها"],
      ["id" => "bullet3","image" => ["src" => "/yalda-bullets-3-v2.webp","width" => 32,"height" => 32],"text" => "برنامه غذایی شخصی سازی شده"],
      ["id" => "bullet4","image" => ["src" => "/yalda-bullets-4-v2.webp","width" => 32,"height" => 32],"text" => "اینماد و مجوزهای قانونی"],
      ["id" => "bullet5","image" => ["src" => "/yalda-bullets-5-v2.webp","width" => 32,"height" => 32],"text" => "اینماد و مجوزهای قانونی"],
      ["id" => "bullet6","image" => ["src" => "/yalda-bullets-6-v2.webp","width" => 32,"height" => 32],"text" => "اینماد و مجوزهای قانونی"]
    ],
    "bubbleText" => "",
    "midText" => ["part1" => "تا","part2" => "24","part3" => "کیلو کاهش وزن تا شب یلدا"],
    "endingText" => "امسال شـــب‌یـــلدا بدرخشید"
  ],
  "plans" => $plans,
  "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 wrapper ----------------------
$response = [
  "success" => "true",
  "message" => "200",
  "result"  => $data
];

echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;

// ---------------------- Helpers (حفظ‌شده از قبل) ----------------------
function getUniqueToken($tokenLength = 8)
{
  $token = "";
  $combinationString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for ($i = 0; $i < $tokenLength; $i++) {
    $token .= $combinationString[uniqueSecureHelper(0, strlen($combinationString))];
  }
  return $token;
}

function uniqueSecureHelper($minVal, $maxVal)
{
  $range = $maxVal - $minVal;
  if ($range < 0) return $minVal;

  $log = log($range, 2);
  $bytes = (int) ($log / 8) + 1;
  $bits = (int) $log + 1;
  $filter = (int) (1 << $bits) - 1;

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