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

error_reporting(0);

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


$nextPage = "payment";

// echo $currency;

$pureVIP = "";
$pureNormal = "";

$language = "fa";

$fasteasyTarget = "q48";

$languageFirst = $_POST["language"];
$codeFirst = $_POST['code'];
$userIpAddress = $_POST['userIpAddress'];
if (sizeof($_POST) == 0) {
  $codeFirst = $_GET['code'];
  $languageFirst = $_GET['language'];
  $userIpAddress = $_GET['userIpAddress'];
}
$currency = getCurrencyFromIP($userIpAddress);
$language = strtolower($languageFirst);
if ($language == "it") {
  $currency = "EUR";
}
$unitSymbol = getSymbolFromCurrency($currency);
$symbol = "";


$bodyFatPercentage = 28;
$bodyFatPercentageFinalValue = "25-31%";

$metabolismBefore = 0;
$metabolismAfter = 0;

$bodyFatPercentageGoal = 17;
$bodyFatPercentageGoalFinalValue = "14-20%";
$summery = array();

$borderImage1 = "";
$borderImage2 = "";

$ts = time();
$currntMonth = tsToShamsiMonth($ts);
$currntMonthName = monthNumberToMonthName($currntMonth, $language);
$ts5MonthLaterNum = $currntMonth + 5;
$ts4MonthLaterNum = $currntMonth + 4;
$ts3MonthLaterNum = $currntMonth + 3;
$ts2MonthLaterNum = $currntMonth + 2;
if ($ts5MonthLaterNum > 12) {
  $ts5MonthLaterNum = $ts5MonthLaterNum - 12;
}
if ($ts4MonthLaterNum > 12) {
  $ts4MonthLaterNum = $ts4MonthLaterNum - 12;
}
if ($ts3MonthLaterNum > 12) {
  $ts3MonthLaterNum = $ts3MonthLaterNum - 12;
}
if ($ts2MonthLaterNum > 12) {
  $ts2MonthLaterNum = $ts2MonthLaterNum - 12;
}
$ts5MonthLater = monthNumberToMonthName(($currntMonth + 5), $language);
$ts4MonthLater = monthNumberToMonthName(($currntMonth + 4), $language);
$ts3MonthLater = monthNumberToMonthName(($currntMonth + 3), $language);
$ts2MonthLater = monthNumberToMonthName(($currntMonth + 2), $language);



$token = null;
$code = null;
$headers = apache_request_headers();

$bannerImage = "";

$persona = null;
$type = null;

$guaranteeTitle = "";
$guaranteeDescription = "";

$target = "";
$regimeType = "";

$code = convertPersianToEnglish($codeFirst);

$plans = array();
$faqs = array();
$comments = array();
$horizontalComments = array();

$gender = "female";
$height = "";
$weightCurrent = "";
$weightGoal = "";
$programLength = "";
$diffWeight = "";
$weightUnit = "kg";

$domain = "https://api.matchadiet.com";


$description = "96.5 درصد از کاربران اپلیکیشن مینت، بارداریشون رو در سلامت کامل به پایان رسوندن";
$payCounter = "null";
$headerType = "lottie";

$headerSection = array();
$BMI = 25;


$todayDate = getPlanDate(time());
$zaimanDate = "";

$isLazy = "false";

$fitnessPlans = null;

$discount = "0";

$normalPlan = "";
$normalPlan2 = "";
$normalPlan3 = "";
$vipPlan = "";

$videoBaseLink = "https://file.mintapp.ir/Persona/";

$withoutProcessCodes = array("prevent");


$allAnswers = array();
$wyg = array();

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);
// Check connection
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}


$resultAllAnswers = $conn->query("SELECT * FROM process WHERE `code`='$code' ORDER BY id");
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);
  }
}


$redirect = "";
$resultUser = $conn->query("SELECT * FROM users WHERE `token`='$token'");
if ($resultUser->num_rows > 0) {
  while ($rowUser = $resultUser->fetch_assoc()) {
    $redirect = $rowUser["redirect"];
    $gender = $rowUser["gender"];
    if ($gender != "male") {
      $gender = "female";
    }
    $metabolismBefore = $rowUser["beforeMetaLevel"];
    $metabolismAfter = $rowUser["afterMetaLevel"];
    $weightCurrent = $rowUser["weight"];
    $weightGoal = $rowUser["weight_goal"];
    $weightUnit = $rowUser["weight_unit"];
    $heightUnit = $rowUser["height_unit"];
    $height = $rowUser["height"];
    $midAge = $rowUser["midAge"];
    $programLength = $rowUser["programLength"];
    $regimeType = $rowUser["regimeType"];
    $fastingMotivation = $rowUser["fastingMotivation"];
    if ($fastingMotivation == "q53") {
      $fasteasyTarget = "q47";
    }
    if ($fastingMotivation == "q54") {
      $fasteasyTarget = "q48";
    }
    if ($fastingMotivation == "q55") {
      $fasteasyTarget = "q56";
    }

    //calculate BMI
    $weightForBMI = $weightCurrent;
    $weightGoalForBMI = $weightGoal;
    $heightForBMI = $height;
    if ($weightUnit == "lbs") {
      $weightForBMI = convertLbsToKg($weightCurrent);
      $weightGoalForBMI = convertLbsToKg($weightGoal);
    }
    //if ($heightUnit == "ft") {
    //  $heightForBMI = convertFootToCm($height);
    //}
    $BMI = $weightForBMI / ($heightForBMI * $heightForBMI / 10000);
    $BMIGoal = $weightGoalForBMI / ($heightForBMI * $heightForBMI / 10000);
    $bodyFatPercentage = bodyFatPercentage($gender, $BMI, $midAge);
    $bodyFatPercentageGoal = bodyFatPercentage($gender, $BMIGoal, $midAge);
    $bodyFatPercentageFinalValue = ($bodyFatPercentage - 3) . "-" . ($bodyFatPercentage + 3) . "%";
    $bodyFatPercentageGoalFinalValue = ($bodyFatPercentageGoal - 3) . "-" . ($bodyFatPercentageGoal + 3) . "%";

    if ($programLength > 6) {
      $programLength = 6;
      $conn->query("UPDATE users SET `currency`='$currency' , `programLength`='6' WHERE `token`='$token'");
    } else {
      $conn->query("UPDATE users SET `currency`='$currency' WHERE `token`='$token'");
    }

    if ($metabolismBefore == "0") {
      $metabolismBefore = rand(1, 2);
      $metabolismAfter = rand(4, 5);
      $conn->query("UPDATE users SET `beforeMetaLevel`='$metabolismBefore' , `afterMetaLevel`='$metabolismAfter' WHERE `token`='$token'");
    }

    $diffWeight = $weightCurrent - $weightGoal;
    if ($diffWeight < 0) {
      $diffWeight = $diffWeight * -1;
    }
  }

  //update Statistics
  $pageId = "preCheckout";
  $date = tsToShamsiYear(time(), "fa") . tsToShamsiMonth(time(), "fa") . tsToShamsiDay(time(), "fa");
  $resultStatistics = $conn->query("SELECT * FROM `statistics` WHERE `date`='$date' AND `page_id`='$pageId' AND `redirect`='$redirect' AND `type`='$type'");
  if ($resultStatistics->num_rows > 0) {
    $conn->query("UPDATE `statistics` SET `count`=`count`+1 WHERE `date`='$date' AND `page_id`='$pageId' AND `redirect`='$redirect' AND `type`='$type'");
  } else {
    $conn->query("INSERT INTO `statistics`(`page_id` , `date` , `count` , `redirect` , `type`) VALUES('$pageId' , '$date' , 1 , '$redirect' , '$type')");
  }
  //

}

if ($type == "fit" . $symbol) {

  $title = getTextFromId("ch1", $language);
  $underTitle = getTextFromId("ch2", $language);

  $guaranteeTitle = getTextFromId("ch27", $language);
  $guaranteeDescription = getTextFromId("ch28", $language);

  if ($regimeType == "") {
    $regimeType = getTextFromId("ch8", $language);
  }
  $secondPartOfTarget = getTextFromId("ch22_1", $language);

  // add for Italian language
  if ($programLength > 1) {
    $secondPartOfTarget = getTextFromId("ch22", $language);
  }
  $target = $diffWeight . " " . $weightUnit . " " . getTextFromId("ch51", $language) . $programLength . " " . $secondPartOfTarget;


  $ch5Title = $programLength  . getTextFromId("ch5_1", $language);
  if ($programLength > 1) {
    $ch5Title = $programLength  . getTextFromId("ch5", $language);
  }
  // add for Italian language
  if ($language == "it") {
    if ($programLength > 1) {
      $ch5Title = "Piano Alimentare per Dimagrimento di " . $programLength . " Mesi";
    } else {
      $ch5Title = "Piano Alimentare per Dimagrimento di 1 Mese";
    }
  }

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/plan.png";
  $res_aa["title"] = $ch5Title;
  $res_aa["description"] = getTextFromId("ch6", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/healthy.png";
  $res_aa["title"] = getTextFromId("ch7", $language);
  $res_aa["description"] = getTextFromId("ch10", $language) . " (" . $regimeType . ")";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/food.png";
  $res_aa["title"] = getTextFromId("ch11", $language);
  $res_aa["description"] = getTextFromId("ch12", $language);
  array_push($wyg, $res_aa);

  // $res_aa["icon"] = "https://matchadiet.com/files/v2/wyg/lifestyle.png";
  // $res_aa["title"] = "برنامه تمرینات ورزشی (اختیاری)";
  // $res_aa["description"] = "آموزش ویدیویی حرکات ورزشی در منزل/باشگاه برای بالا بردن سوخت و ساز بدن، چربی سوزی بیشتر و عضله سازی همزمان";
  // array_push($wyg , $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/lifestyle.png";
  $res_aa["title"] = getTextFromId("ch13", $language);
  $res_aa["description"] = getTextFromId("ch14", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/fire.png";
  $res_aa["title"] = getTextFromId("ch15", $language);
  $res_aa["description"] = getTextFromId("ch16", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/vip-card.png";
  $res_aa["title"] = getTextFromId("ch17", $language);
  $res_aa["description"] = getTextFromId("ch18", $language);
  array_push($wyg, $res_aa);
}

if ($type == "fastfit" . $symbol) {

  $title = getTextFromId("ch1", $language);
  $underTitle = getTextFromId("ch2", $language);

  $guaranteeTitle = getTextFromId("ch27", $language);
  $guaranteeDescription = getTextFromId("ch28", $language);

  //$regimeType = getTextFromId("ch52", $language);
  if ($regimeType == "") {
    $regimeType = getTextFromId("chV2_50", $language);
  }

  // $secondPartOfTarget = getTextFromId("ch22_1", $language);

  // // add for Italian language
  // if ($programLength > 1) {
  //   $secondPartOfTarget = getTextFromId("ch22", $language);
  // }
  // $target = getTextFromId("ch53", $language) .  $diffWeight . " " . $weightUnit;

  $target = $diffWeight . " کیلوگرم در " . $programLength . " ماه";

  $ch5Title = $programLength  . getTextFromId("ch5_1", $language);
  if ($programLength > 1) {
    $ch5Title = $programLength  . getTextFromId("ch5", $language);
  }
  // add for Italian language
  if ($language == "it") {
    if ($programLength > 1) {
      $ch5Title = "Piano Alimentare per Dimagrimento di " . "1-3" . " Mesi";
    }
  }

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/plan.png";
  $res_aa["title"] = $ch5Title;
  $res_aa["description"] = getTextFromId("ch6", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/healthy.png";
  $res_aa["title"] = getTextFromId("ch7", $language);
  $res_aa["description"] = getTextFromId("ch10", $language) . " " . $regimeType . "";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/food.png";
  $res_aa["title"] = getTextFromId("ch11", $language);
  $res_aa["description"] = getTextFromId("ch12", $language);
  array_push($wyg, $res_aa);

  // $res_aa["icon"] = "https://matchadiet.com/files/v2/wyg/lifestyle.png";
  // $res_aa["title"] = "برنامه تمرینات ورزشی (اختیاری)";
  // $res_aa["description"] = "آموزش ویدیویی حرکات ورزشی در منزل/باشگاه برای بالا بردن سوخت و ساز بدن، چربی سوزی بیشتر و عضله سازی همزمان";
  // array_push($wyg , $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/lifestyle.png";
  $res_aa["title"] = getTextFromId("ch13", $language);
  $res_aa["description"] = getTextFromId("ch14", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/fire.png";
  $res_aa["title"] = getTextFromId("ch15", $language);
  $res_aa["description"] = getTextFromId("ch16", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/vip-card.png";
  $res_aa["title"] = getTextFromId("ch17", $language);
  $res_aa["description"] = getTextFromId("ch18", $language);
  array_push($wyg, $res_aa);
}

if ($type == "inc" . $symbol) {

  $title = "افزایش وزن پایدار، بدون شکم پهلو و اصلاح سبک زندگی با ماچا";
  $underTitle = "به جمع هزاران نفری که به کمک ماچا، به اندام ایده آلشون رسیده‌اند، بپیوندید";

  $guaranteeTitle = "ضمانت افزایش وزن";
  $guaranteeDescription = "
    رژیم ها و نکات ماچا رو کاملا بر اساس مشخصاتت طراحی کردیم. با تمامی جزئیات رژیم رو رعایت کنی، مطمئنیم که به وزن ایده آلی که میخوای میرسی.
</br>
در نهایت اگر تا پایان اشتراکت به افزایش وزن نرسیدی، ماچا مبلغی رو که پرداخت کردی، عودت میده.
";

  $regimeType = "Healthy Life Style + Caloric Density";
  $target = $diffWeight . " کیلوگرم در " . $programLength . " ماه";

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/plan.png";
  $res_aa["title"] = $programLength . " ماه برنامه غذایی افزایش وزن";
  $res_aa["description"] = "برنامه غذایی کامل صبحانه، ناهار، شام و میان وعده به همراه مکمل های لازم";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/healthy.png";
  $res_aa["title"] = "استفاده از متدولوژی HLCD";
  $res_aa["description"] = "برنامه شما بر اساس روش (‌Healthy Life Style + Caloric Density) طراحی خواهد شد.";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/food.png";
  $res_aa["title"] = "وعده های غذایی راحت و در دسترس";
  $res_aa["description"] = "سفرتون از خونواده جدا نمیشه و به راحتی میتونید رژیم غذایی رو رعایت کنید.";
  array_push($wyg, $res_aa);

  // $res_aa["icon"] = "https://matchadiet.com/files/v2/wyg/lifestyle.png";
  // $res_aa["title"] = "برنامه تمرینات ورزشی (اختیاری)";
  // $res_aa["description"] = "آموزش ویدیویی حرکات ورزشی در منزل/باشگاه برای بالا بردن سوخت و ساز بدن، چربی سوزی بیشتر و عضله سازی همزمان";
  // array_push($wyg , $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/lifestyle.png";
  $res_aa["title"] = "اصلاح سبک زندگی";
  $res_aa["description"] = "اصلاح سبک زندگی و عادت های غذایی برای افزایش وزن سریعتر و دائمی";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/fire.png";
  $res_aa["title"] = "تنظیم سوخت و ساز بدن";
  $res_aa["description"] = "تنظیم سوخت و ساز بدن برای عضله سازی و افزایش وزن اصولی";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/vip-card.png";
  $res_aa["title"] = "پشتیبانی آنلاین هفتگی توسط متخصص HLCD (طرح VIP)";
  $res_aa["description"] = "متخصصان رژیم، ورزش و تناسب‌‌اندام ما هرروزِ هفته شبانه‌روزی و بدونِ تعطیلی با شما در ارتباطن تا روند انجام رژیم و مسائل انگیزشی شما رو پیگیری کنن";
  array_push($wyg, $res_aa);
}

if ($type == "gym" . $symbol) {

  $title = getTextFromId("ch29", $language);
  $underTitle = getTextFromId("ch30", $language);


  if ($weightGoal > $weightCurrent) {

    $guaranteeTitle = getTextFromId("ch47", $language);
    $guaranteeDescription = getTextFromId("ch48", $language);
  } else {

    $guaranteeTitle = getTextFromId("ch27", $language);
    $guaranteeDescription = getTextFromId("ch28", $language);
  }

  $regimeType = "Body Building Life Style + Caloric Density";

  $secondPartOfTarget = getTextFromId("ch22_1", $language);

  // add for Italian language
  if ($programLength > 1) {
    $secondPartOfTarget = getTextFromId("ch22", $language);
  }
  $target = getTextFromId("ch46", $language) . $programLength . $secondPartOfTarget;

  // add for Italian language
  $ch31Title = $programLength . " " . getTextFromId("ch31", $language);
  if ($language == "it") {
    if ($programLength > 1) {
      $ch31Title = "Programma di Bodybuilding di " . $programLength . " Mesi";
    } else {
      $ch31Title = "Programma di Bodybuilding di 1 Mese";
    }
  }

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/icon3.png";
  $res_aa["title"] = $ch31Title;
  $res_aa["description"] = getTextFromId("ch32", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/icon2.png";
  $res_aa["title"] = getTextFromId("ch33", $language);
  $res_aa["description"] = getTextFromId("ch34", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/icon1.png";
  $res_aa["title"] =  getTextFromId("ch35", $language);
  $res_aa["description"] = getTextFromId("ch36", $language);
  array_push($wyg, $res_aa);

  // add for Italian language
  $ch37Title = $programLength . " " . getTextFromId("ch37", $language);
  if ($language == "it") {
    if ($programLength > 1) {
      $ch37Title = $programLength . " Diete per il Bodybuilding";
    } else {
      $ch37Title = "1 Dieta per il Bodybuilding";
    }
  }

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/plan.png";
  $res_aa["title"] = $ch37Title;
  $res_aa["description"] = getTextFromId("ch38", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/healthy.png";
  $res_aa["title"] = getTextFromId("ch39", $language);
  $res_aa["description"] = getTextFromId("ch10", $language) . " (" . $regimeType . ")";
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/food.png";
  $res_aa["title"] = getTextFromId("ch40", $language);
  $res_aa["description"] = getTextFromId("ch41", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/fire.png";
  $res_aa["title"] = getTextFromId("ch42", $language);
  $res_aa["description"] = getTextFromId("ch43", $language);
  array_push($wyg, $res_aa);

  $res_aa["icon"] = "https://api.matchadiet.com/files/v2/wyg/vip-card.png";
  $res_aa["title"] = getTextFromId("ch44", $language);
  $res_aa["description"] = getTextFromId("ch45", $language);
  array_push($wyg, $res_aa);
}

if ($type == "fit" . $symbol or $type == "fastfit" . $symbol) {
  if ($gender == "male") {
    if ($BMI >= 30) {
      $borderImage1 = $domain . "/files/v2/precheckout_ba/fit-man-upper30-before.png";
      $borderImage2 = $domain . "/files/v2/precheckout_ba/fit-man-upper30-after.png";
    } else {
      $borderImage1 = $domain . "/files/v2/precheckout_ba/fit-man-under30-before.png";
      $borderImage2 = $domain . "/files/v2/precheckout_ba/fit-man-under30-after.png";
    }
  } else {
    if ($BMIGoal >= 30) {
      $borderImage1 = $domain . "/files/v2/precheckout_ba/fit-woman-upper30-before.png";
      $borderImage2 = $domain . "/files/v2/precheckout_ba/fit-woman-upper30-after.png";
    } else {
      $borderImage1 = $domain . "/files/v2/precheckout_ba/fit-woman-under30-before.png";
      $borderImage2 = $domain . "/files/v2/precheckout_ba/fit-woman-under30-after.png";
    }
  }
}

$result_persona = $conn->query("SELECT * FROM process WHERE `code`='$code' ORDER BY id DESC LIMIT 1");
if ($result_persona->num_rows > 0) {
  while ($row_persona = $result_persona->fetch_assoc()) {
    $persona = getPersonaFromType($type);
    $bannerType = str_replace($symbol, "",  $type);
    if ($bannerType == "fastfit") {
      $bannerType = "fit";
    }
    $bannerImage = "https://api.matchadiet.com/files/v2/banners/" . $bannerType . ".png";
  }
}

$paymentHeader = array(

  "description" => $description,
  "counter" => (string)$payCounter
);

$commentQuery = "SELECT * FROM comment WHERE `persona`='fit' AND `visible`='true' AND `language`='fa' AND `type`!='voice' ORDER BY priority";

$result_comment = $conn->query($commentQuery);
if ($result_comment->num_rows > 0) {
  while ($row_comment = $result_comment->fetch_assoc()) {
    $res_comment["profileName"] = $row_comment["profileName"];
    $res_comment["profileImage"] = $row_comment["profileImage"];
    $res_comment["date"] = $row_comment["date"];
    $res_comment["title"] = $row_comment["title"];
    $res_comment["text"] = $row_comment["text"];
    $res_comment["date"] = $row_comment["date"];
    $res_comment["rate"] = "5";
    $res_comment["voice"] = $row_comment["voiceLink"];
    $res_comment["image"] = $row_comment["link"];

    // if ($row_comment["type"] == "voice"){
    //     $res_comment["voice"] = $row_comment["voiceLink"];
    // }
    // else {
    //     $res_comment["image"] = $row_comment["link"];
    // }

    array_push($comments, $res_comment);
  }
}

$result_horizontal_comment = $conn->query("SELECT * FROM horizontal_comments WHERE MOD(id,2) = 1  ORDER BY id DESC LIMIT 25");
$mainURL = "https://api.matchadiet.com/files/v2/comments/horizontal/main/";
$profileURL = "https://api.matchadiet.com/files/v2/comments/horizontal/profile/";
$socialURL = "https://api.matchadiet.com/files/social/";

if ($result_horizontal_comment->num_rows > 0) {
  while ($row_horizontal_comment = $result_horizontal_comment->fetch_assoc()) {
    $res_horizontal_comment["name"] = $row_horizontal_comment["name"];
    $res_horizontal_comment["voice"] = $row_horizontal_comment["voiceLink"];
    $profileImageInDB = $row_horizontal_comment["profile_image"];
    if (strlen($profileImageInDB) < 6) {
      $res_horizontal_comment["profileImage"] = "https://api.matchadiet.com/files/v2/profile/ph.png";
    } else {
      $res_horizontal_comment["profileImage"] = $profileURL . $profileImageInDB;
    }
    $socialLogoInDB = $row_horizontal_comment["social_logo"];
    if (strlen($socialLogoInDB) < 4) {
      $res_horizontal_comment["socialLogo"] = "https://api.matchadiet.com/files/social/telegram.svg";
    } else {
      $res_horizontal_comment["socialLogo"] = $socialURL . $row_horizontal_comment["social_logo"] . ".svg";
    }
    if (strlen($row_horizontal_comment["main_image"]) > 4) {
      $res_horizontal_comment["mainImage"] = $mainURL . $row_horizontal_comment["main_image"];
    } else {
      $res_horizontal_comment["mainImage"] = "";
    }
    // $res_horizontal_comment["mainImage"] = "";

    $res_horizontal_comment["comment"] = $row_horizontal_comment["comment"];
    $res_horizontal_comment["date"] = $row_horizontal_comment["date"];

    array_push($horizontalComments, $res_horizontal_comment);
  }
}

$result_faq = $conn->query("SELECT * FROM faq WHERE `persona`='fit' AND `language`='$language' ORDER BY priority");
if ($result_faq->num_rows > 0) {
  while ($row_faq = $result_faq->fetch_assoc()) {
    $res_faq["question"] = $row_faq["question"];
    $res_faq["answer"] = $row_faq["answer"];
    array_push($faqs, $res_faq);
  }
}

$newPlans = array();
$newRes = array();

$planCounter = 0;
$result_plans = $conn->query("SELECT * FROM plansV2 WHERE `persona`='$persona' AND `language`='fa' ORDER BY priority");
if ($result_plans->num_rows > 0) {
  while ($row = $result_plans->fetch_assoc()) {
    $discountPrice = "";
    $perPrice = 299;
    //            $discountPrice = $perPrice - ($perPrice * 0.2);
    //            $discountPrice = (int) $discountPrice;
    //            $discountPrice = (string) $discountPrice;

    $planId = $row["plan_id"];
    $res["planId"] = $row["plan_id"];

    if ($persona == "fit" or $persona == "fastfit") {
      $res["title"] = $programLength . " " . $row["title"];
      $res["description"] = $row["description"];
      if ($planId == "fit" or $planId == "fastfit") {
        $discountPrice =  round($perPrice * $programLength);
        if ($discountPrice > 949) {
            $discountPrice = 949;
        }
      } else if ($planId == "fit_vip" or $planId == "fastfit_vip") {
        $discountPrice =  round(($perPrice + 49) * $programLength);
        if ($discountPrice > 999) {
            $discountPrice = 999;
        }
      }
     
      if ($discountPrice < 449) {
        if ($planId == "fit" or $planId == "fastfit") {
          $discountPrice = 449;
        }
        if ($planId == "fit_vip" or $planId == "fastfit_vip") {
          $discountPrice = 499;
        }
      }
    } else if ($persona == "gym") {
      $res["title"] = "برنامه " . $programLength . " " . $row["title"];
      $res["description"] = $row["description"];
      if ($planId == "gym") {
        $discountPrice =  round($perPrice * $programLength);
        if ($discountPrice > 949) {
            $discountPrice = 949;
        }
      } else if ($planId == "gym_vip") {
        $discountPrice =  round(($perPrice + 49) * $programLength);
        if ($discountPrice > 999) {
            $discountPrice = 999;
        }
      }
     
      if ($discountPrice < 449) {
        if ($planId == "gym") {
          $discountPrice = 449;
        }
        if ($planId == "gym_vip") {
          $discountPrice = 499;
        }
      }
    } else if ($persona == "inc") {
      $res["title"] = $programLength . " " . $row["title"];
      $res["description"] = $row["description"];
      if ($planId == "inc") {
        $discountPrice =  round($perPrice * $programLength);
        if ($discountPrice > 949) {
            $discountPrice = 949;
        }
      } else if ($planId == "inc_vip") {
        $discountPrice =  round(($perPrice + 49) * $programLength);
        if ($discountPrice > 999) {
            $discountPrice = 999;
        }
      }
      
      if ($discountPrice < 449) {
        if ($planId == "inc") {
          $discountPrice = 449;
        }
        if ($planId == "inc_vip") {
          $discountPrice = 499;
        }
      }
    }
    $purePrice = round($discountPrice * 1.2);
    $res["discountPrice"] = $discountPrice;
    $res["price"] = $purePrice;
    $res["length"] = $row["length"];
    $timeUnit = $row["time_unit"];
    if ($timeUnit == "month") {
      $timeUnit = "ماهانه";
    } else {
      $timeUnit = "سالانه";
    }
    $res["timeUnit"] = $timeUnit;
    array_push($plans, $res);

    //added in new version
    $featured = "false";
    if ($row['priority'] == "1") {
      $featured = "true";
    }
    $newRes['featured'] = $featured;
    $newRes['featuredTitle'] = "پیشنهاد ماچا";
    $newRes['price'] = array(
      "regular" => $purePrice,
      "discounted" => $discountPrice,
      "preUnit" => "هزار",
      "unit" => "تومان",
    );
    $newRes['planId'] = $row["plan_id"];
    $newRes['title'] = $programLength . " " . $row["title"];
    $newRes['description'] = $row["description"];
    $newRes['length'] = $row["length"];
    $newRes['timeUnit'] = $timeUnit;
    array_push($newPlans, $newRes);

    // *************
  }
}



$counter = 0;
$index = "0";

if ($persona == "fastfit") {

  $paymentModalInner = array(
    $normalPlan =>
    array(
      array(
        "title" => $target,
        "value" => array($pureNormal),
        "color" => "#000000",
        "availableOnDiscount" => "false"
      ),
      array(
        "title" => getTextFromId("ch49", $language),
        "value" => array($discountNormal),
        "color" => "#000000",
        "availableOnDiscount" => "true"
      ),
    ),
    $normalPlan2 =>
    array(
      array(
        "title" => $target,
        "value" => array($pureNormal2),
        "color" => "#000000",
        "availableOnDiscount" => "false"
      ),
      array(
        "title" => getTextFromId("ch49", $language),
        "value" => array($discountNormal2),
        "color" => "#000000",
        "availableOnDiscount" => "true"
      ),
    ),
    $normalPlan3 =>
    array(
      array(
        "title" => $target,
        "value" => array($pureNormal3),
        "color" => "#000000",
        "availableOnDiscount" => "false"
      ),
      array(
        "title" => getTextFromId("ch49", $language),
        "value" => array($discountNormal3),
        "color" => "#000000",
        "availableOnDiscount" => "true"
      ),
    ),
  );
} else {

  $paymentModalInner = array(
    $vipPlan =>
    array(
      array(
        "title" => $target,
        "value" => array($pureVIP),
        "color" => "#000000",
        "availableOnDiscount" => "false"
      ),
      array(
        "title" => getTextFromId("ch49", $language),
        "value" => array($discountVIP),
        "color" => "#000000",
        "availableOnDiscount" => "true"
      ),
    ),
    $normalPlan =>
    array(
      array(
        "title" => $target,
        "value" => array($pureNormal),
        "color" => "#000000",
        "availableOnDiscount" => "false"
      ),
      array(
        "title" => getTextFromId("ch49", $language),
        "value" => array($discountNormal),
        "color" => "#000000",
        "availableOnDiscount" => "true"
      ),
    ),
  );
}

// FastEasy model *************
$fastEasy = array();

$plansFE = array(
  "key" => "plans",
  "content" => array(
    "title" => getTextFromId("chV2_23", $language),
    "heroSection" => array(
      "backModal" => array(
        "title" => getTextFromId("chV2_34", $language),
        "descriptionUp" => getTextFromId("chV2_35", $language),
        "chartUrl" => $domain . "/files/v2/backmodal.png",
        "underChart" => getTextFromId("chV2_36", $language),
        "descriptionDown" => getTextFromId("chV2_37", $language),
        "buttonText" => getTextFromId("chV2_38", $language),
      ),
      "giftCard" => array(
        "image" => $domain . "/files/v2/gift.png",
        "text" => getTextFromId("chV2_39", $language),
      ),
      "credits" => array(
        "title" => getTextFromId("chV2_40", $language),
        "icon" => "",
        "items" => array($domain . "/files/v2/visa.png", $domain . "/files/v2/card.png", $domain . "/files/v2/paypal.png", $domain . "/files/v2/ssl.png"),
      ),
      "targetWeight" => array(
        "text" => getTextFromId("chV2_24", $language),
        "icon" => "",
        "value" => $weightGoal . " " . $weightUnit,
      ),
      "fastingLevel" => array(
        "text" => getTextFromId("chV2_25", $language),
        "icon" => "",
        "value" => getTextFromId($fasteasyTarget, $language),
      ),
      "plans" => $newPlans,
      "guarantee" => array(
        "text" => getTextFromId("chV2_27", $language),
        "link" => "",
      ),
      "button" => array(
        "text" => getTextFromId("chV2_28", $language),
        "link" => "",
      ),
      "hint" => getTextFromId("chV2_29", $language),
    ),
  ),

);

$beforeAfter = array(
  "key" => "after-before",
  "content" => array(
    "title" => getTextFromId("chV2_1", $language),
    "before" => array(
      "title" => getTextFromId("chV2_2", $language),
      "image" => $borderImage1,
      "param1" => array(
        "title" => getTextFromId("chV2_4", $language),
        "value" => getTextFromId("chV2_42", $language), //$bodyFatPercentageFinalValue
      ),
      "param2" => array(
        "title" => getTextFromId("chV2_5", $language),
        "value" => $metabolismBefore,
      ),
    ),
    "after" => array(
      "title" => getTextFromId("chV2_3", $language),
      "image" => $borderImage2,
      "param1" => array(
        "title" => getTextFromId("chV2_4", $language),
        "value" => getTextFromId("chV2_43", $language), //$bodyFatPercentageGoalFinalValue
      ),
      "param2" => array(
        "title" => getTextFromId("chV2_5", $language),
        "value" => $metabolismAfter,
      ),
    ),
    "hint" => getTextFromId("chV2_6", $language),
  )
);

$slider = array(
  "key" => "slider",
  "content" => array(
    "title" => getTextFromId("chV2_7", $language),
    "sliderImages" => array($domain . "/files/v2/screens/" . $language . "/screen1.png", $domain . "/files/v2/screens/" . $language . "/screen2.png", $domain . "/files/v2/screens/" . $language . "/screen3.png",),
    "callToAction" => array(
      "image" => $domain . "/files/v2/clock.webp",
      "numValue" => "6,600,000",
      "description" => getTextFromId("chV2_8", $language),
      "button" => array(
        "text" => getTextFromId("chV2_9", $language),
      ),
    ),
  ),
);

$whatYouGet = array(
  "key" => "what-you-get",
  "content" => array(
    "title" => getTextFromId("chV2_10", $language),
    "hero" => getTextFromId("chV2_11", $language),
    "callToAction" => array(
      "title" => getTextFromId("chV2_44", $language),
      "content" => array(array("icon" => "", "text" => "برنامه شما بر اساس روش (" . $regimeType . ") طراحی خواهد شد."), array("icon" => "", "text" => getTextFromId("chV2_13", $language)), array("icon" => "", "text" => getTextFromId("chV2_14", $language)), array("icon" => "", "text" => getTextFromId("chV2_15", $language))),
      "hint" => getTextFromId("chV2_16", $language),
      "image" => "", //$domain . "/files/v2/plan_mock.webp",
    ),
  ),
);

$successStories = array(
  "key" => "success-stories",
  "content" => array(
    "title" => getTextFromId("chV2_17", $language),
    "stories" => $horizontalComments,
  ),
);

$meetTheirGoals = array(
  "key" => "meet-their-goals",
  "content" => array(
    "title" => getTextFromId("chV2_18", $language),
    "image" => "https://api.matchadiet.com/files/v2/comment_" . $gender . ".png",
    "comments" => $comments,
    "message" => array(
      "title" => getTextFromId("chV2_19", $language),
      "description" => getTextFromId("chV2_20", $language),
    ),
  ),
);

$guarantee = array(
  "key" => "guarantee",
  "content" => array(
    "heroText" => getTextFromId("chV2_21", $language),
    "image" => $domain . "/files/v2/gaurantee.png",
    "callToAction" => array(
      "message" => getTextFromId("chV2_22", $language),
    ),
  ),
);

$FAQ = array(
  "key" => "FAQ",
  "content" => array(
    "title" => getTextFromId("chV2_41", $language),
    "questions" => $faqs,
  ),
);

array_push($fastEasy, $beforeAfter);
array_push($fastEasy, $plansFE);
array_push($fastEasy, $slider);
array_push($fastEasy, $whatYouGet);
array_push($fastEasy, $FAQ);
array_push($fastEasy, $successStories);
array_push($fastEasy, $meetTheirGoals);
array_push($fastEasy, $plansFE);
array_push($fastEasy, $guarantee);

//****************************//

$response['success'] = 'true';
$response['message'] = '200';

$response['data'] =
  array(
    "clientToken" => $clientToken,
    "currency" => $currency,
    "unitSymbol" => $unitSymbol,
    "token" => $token,
    "code" => $code,
    "offerLabel" => getTextFromId("ch24", $language),
    "isResult" => "true",
    "items" => $fastEasy,
    "banner" => array(
      "title" => $title,
      "image" => $bannerImage,
      "description" => $underTitle,
      "bgColor" => "#ffffff"
    ),
    "button" => array(
      "text" => getTextFromId("pre32", $language),
      "link" => "",
      "bgColor" => "#4ed09a",
      "color" => "#ffffff"
    ),

    "discountBar" => array(
      "title" => getTextFromId("ch3", $language),
      "time" => "600",
      "bgColor" => "#f87691",
      "titleColor" => "#ffffff",
      "timerColor" => "yellow"
    ),

    "wyg" => array(
      "sectionTitle" => getTextFromId("ch4", $language),
      "items" => $wyg
    ),


    "plans" => array(
      "sectionTitle" => getTextFromId("ch19", $language),
      "paymentModal" => $paymentModalInner,
      "target" => array(
        "title" => getTextFromId("ch20", $language),
        "description" => $target
      ),
      "regime" => array(
        "title" => getTextFromId("ch23", $language),
        "description" => $regimeType
      ),
      "items" => $newPlans,
    ),


    "comments" => array(
      "sectionTitle" => getTextFromId("ch25", $language),
      "items" => $comments
    ),
    "horizontalComments" => array(
      "sectionTitle" => getTextFromId("ch50", $language),
      "items" => $horizontalComments
    ),
    "faq" => array(
      "sectionTitle" => getTextFromId("ch26", $language),
      "items" => $faqs,
      "backgroundImage" => array(
        "right" => "https://api.matchadiet.com/files/avocado.png",
        "left" => "https://api.matchadiet.com/files/pepper.png",
      ),
    ),

    "nextPage" => $nextPage,
    "type" => $type,

    "guarantee" => array(
      "guaranteeTitle" => $guaranteeTitle,
      "guaranteeDescription" => $guaranteeDescription,
    ),

    "footer" => array(
      "title" => "",
//       "description" => "ما تشا لخدمات إدارة المشاريع شركة الشخص الواحد ذ.م.م
//       <br>
// M A T C H A FOR PROJECT MANAGEMENT SERVICES CO. L.L.C
// <br><br>
// Rigga Business Centre, Al Murqabat, Dubai"
      "description" => "قدرت‌ گرفته از شرکت بین‌المللی Matcha <br>  دفتر بریتانیا : انگلستان - تانتون - کریدول اُرچارد - واحد ۵ <br> دفتر ایران : تهران - ناحیه نوآوری شریف - باشگاه کسب‌وکارهای دانش‌بنیان - واحد ۳۹",



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

$conn->close();
