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

$token = null;
$headers = apache_request_headers();
$language = getLanguageFromHeader($headers);
$token = $headers['Authorization'];

$aidFirst = $_POST['aid'];
$codeFirst = $_POST['code'];
if (sizeof($_POST) == 0) {
  $aidFirst = $_GET['aid'];
  $codeFirst = $_GET['code'];
}

$aid = convertPersianToEnglish($aidFirst);
$code = convertPersianToEnglish($codeFirst);
$firstQid = "";
$res = null;
$answers = array();
$isResult = "false";
$allQuestions = 60;
$preAid = "main";

$parasiteElements = array();
$parasite = array();

$result_id = $conn->query("SELECT * FROM answersV2 WHERE `aid`='$aid'");
if ($result_id->num_rows > 0) {
  while ($row_id = $result_id->fetch_assoc()) {
    $firstQid = $row_id["qid"];
    $preAid = $row_id["prev_question"];
  }
}

$result = $conn->query("SELECT * FROM questionsV2 WHERE `qid`='$firstQid'");
if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $questionType = $row["questionType"];
    $currentQuestion = $row["questionNumber"];
    if ($questionType == "parasite") {
      $pid = $row["pid"];

      // start:  for develop
      if ($row["qid"] == "fitg59" and $_GET['version'] == "v3") {
        $pid = "fitg59_v3";
      }
      if ($row["qid"] == "fitg19" and $_GET['version'] == "v3") {
        $pid = "fitg19_v3";
      }
      if ($row["qid"] == "fitg36" and $_GET['version'] == "v3") {
        $pid = "fitg36_v3";
      }
      // end: for develop

      $res_parasiteOut["id"] = $row["pid"];
      $res_parasiteOut["aid"] = $row["parasiteAid"];
      $res_parasiteOut["bgColor"] = $row["bgColor"];
      $res_parasiteOut["textColor"] = $row["textColor"];

      $result_parasite = $conn->query("SELECT * FROM parasite WHERE `pid`='$pid' ORDER BY priority");
      if ($result_parasite->num_rows > 0) {
        while ($row_parasite = $result_parasite->fetch_assoc()) {

          $hasCode = $row_parasite["hasCode"];
          $hasCode2 = $row_parasite["hasCode2"];

          $res_parasite = null;
          $res_parasite["id"] = $row_parasite["pType"];
          if ($row_parasite["pType"] == "title") {
            $res_parasite["inputs"] = array(
              "text" => $row_parasite["titleText"],
              "textAlign" => $row_parasite["textAlign"],
              "textSize" => $row_parasite["textSize"],
            );
          }
          if ($row_parasite["pType"] == "description") {
            if ($hasCode == "true") {
              $res_parasite["inputs"] = array(
                "text" => $customText,
                "textAlign" => $row_parasite["textAlign"],
                "textSize" => $row_parasite["textSize"],
              );
            } else if ($hasCode2) {
              $res_parasite["inputs"] = array(
                "text" => $customText2,
                "textAlign" => $row_parasite["textAlign"],
                "textSize" => $row_parasite["textSize"],
              );
            } else {
              $res_parasite["inputs"] = array(
                "text" => $row_parasite["descriptionText"],
                "textAlign" => $row_parasite["textAlign"],
                "textSize" => $row_parasite["textSize"],
              );
            }
          }
          if ($row_parasite["pType"] == "titleFade") {
            if ($hasCode == "true") {
              $temp = explode(",", $customTitleFade);
              $res_parasite["inputs"] = array(
                "texts" => $temp
              );
            } else {
              $temp = explode(",", $row_parasite["titleFadeTexts"]);
              $res_parasite["inputs"] = array(
                "texts" => $temp
              );
            }
          }
          if ($row_parasite["pType"] == "transitionText") {
            if ($hasCode == "true") {
              $temp = explode(",", $customTransitionText);
              $res_parasite["inputs"] = array(
                "texts" => $temp
              );
            } else {
              $temp = explode(",", $row_parasite["transitionTexts"]);
              $res_parasite["inputs"] = array(
                "texts" => $temp
              );
            }
          }
          if ($row_parasite["pType"] == "image") {
            if ($hasCode == "true") {
              $res_parasite["inputs"] = array(
                "link" => $customImageLink,
                "textAlign" => "right"
              );
            } else {
              $res_parasite["inputs"] = array(
                "link" => $row_parasite["imageLink"],
                "textAlign" => "right"
              );
            }
          }
          if ($row_parasite["pType"] == "icon") {
            $res_parasite["inputs"] = array(
              "link" => $row_parasite["imageLink"],
              "textAlign" => "right"
            );
          }
          if ($row_parasite["pType"] == "video") {
            $res_parasite["inputs"] = array(
              "link" => $row_parasite["videoLink"],
            );
          }
          if ($row_parasite["pType"] == "loading") {
            $temp = "";
            if (strlen($row_parasite["loadingTexts"]) > 5) {
              $temp = explode(",", $row_parasite["loadingTexts"]);
            }
            $res_parasite["inputs"] = array(
              "type" => $row_parasite["loadingType"],
              "color" => $row_parasite["loadingColor"],
              "time" => $row_parasite["loadingTime"],
              "maxValue" => $row_parasite["loadingMaxValue"],
              "text" => $row_parasite["loadingText"],
              "texts" => $temp,
              "hasButton" => $row_parasite["loadingHasButton"],
              "delay" => $row_parasite["loadingDelay"],
            );
          }
          if ($row_parasite["pType"] == "multiLoading") {
            $temp = "";
            $tempInput = array();
            $loadingParts = $row_parasite["loadingParts"];
            for ($z = 0; $z < $loadingParts; $z++) {
              $res_input["type"] = "circle";
              $res_input["color"] = explode(",", $row_parasite["loadingColor"])[$z];
              $res_input["time"] = explode(",", $row_parasite["loadingTime"])[$z];
              $res_input["maxValue"] = explode(",", $row_parasite["loadingMaxValue"])[$z];
              $res_input["text"] = explode(",", $row_parasite["loadingText"])[$z];
              $res_input["texts"] = explode(",", $row_parasite["loadingTexts"])[$z];
              $res_input["hasButton"] = "false";
              $res_input["delay"] = explode(",", $row_parasite["loadingDelay"])[$z];

              array_push($tempInput, $res_input);
            }
            $res_parasite["inputs"] = $tempInput;
          }
          if ($row_parasite["pType"] == "diagram") {

            $res_parasite["type"] = $row_parasite["diagramType"];
            $diagramId = $row_parasite["diagramId"];
            $labels = array();
            $datasets = array();

            $result_diagram = $conn->query("SELECT * FROM diagram WHERE `did`='$diagramId' ORDER BY id");
            if ($result_diagram->num_rows > 0) {
              while ($row_diagram = $result_diagram->fetch_assoc()) {
                $label = $row_diagram["label"];
                $dataset = $row_diagram["dataset"];
                array_push($labels, $label);
                array_push($datasets, $dataset);
              }
            }
            $res_parasite["inputs"] = array(
              "color" => $row_parasite["diagramColor"],
              "label" => $row_parasite["diagramLabel"],
              "labels" => $labels,
              "datasets" => $datasets
            );
          }
          if ($row_parasite["pType"] == "button") {
            $res_parasite["inputs"] = array(
              "text" => $row_parasite["buttonText"],
              "bgColor" => $row_parasite["buttonBgColor"],
              "textColor" => $row_parasite["buttonTextColor"]
            );
          }
          //start: for develop
          if ($row_parasite["pType"] == "chart" and $pid == "fitg19_v3") {
            $res_parasite["inputs"] = array(
              "status" => "down",
              "current" => "اسفند ۱۴۰۲: ۷۰",
              "goal" => "خرداد ۱۴۰۳: ۵۵"
            );
          }
          if ($row_parasite["pType"] == "chart" and $pid == "fitg36_v3") {
            $res_parasite["inputs"] = array(
              "status" => "up",
              "current" => "اسفند ۱۴۰۲: 65",
              "goal" => "خرداد ۱۴۰۳: 80"
            );
          }
          //end: for develop
          array_push($parasiteElements, $res_parasite);
        }
        $res_parasiteOut["elements"] = $parasiteElements;
        $parasite = $res_parasiteOut;
      }
    }
    $qid = $row["qid"];
    //before test: $query_a = "SELECT * FROM answersV2 WHERE `qid`='$qid' AND `type`='$type' ORDER BY priority";
    $query_a = "SELECT * FROM answersV2 WHERE `qid`='$qid' ORDER BY priority";
    $result_a = $conn->query($query_a);
    if ($result_a->num_rows > 0) {
      while ($row_a = $result_a->fetch_assoc()) {
        $res_in["aid"] = $row_a["aid"];
        $res_in["text"] = $row_a['text'];
        $res_in["image"] = $row_a['image'];
        $res_in["description"] = $row_a['description'];
        $res_in["hint"] = array(
          "icon" => $row_a['hintIcon'],
          "title" => $row_a['hintTitle'],
          "description" => $row_a['hintDescription'],
        );
        $isResult = $row_a["is_result"];
        array_push($answers, $res_in);
      }
    }

    $res['token'] = $token;
    $res['code'] = $code;
    $res['redirect'] = $_GET["redirect"];
    $res['qid'] = $row['qid'];
    $res['preAid'] = $preAid;
    $res['nextPage'] = "";
    $res['allQuestions'] = $allQuestions;
    $res['currentQuestion'] = $currentQuestion;
    $res['type'] = $row['type'];
    $res['questionType'] = $row['questionType']; // singleSelect , multiSelect , inputQuestion , parasite
    $res['inputQuestion'] = $row['inputQuestion'];
    $res['video'] = $row['video'];
    $res['image'] = "";
    $res['borderImage'] = $row['image'];
    $res['diagram'] = $diagram;
    $res['parasite'] = $parasite;
    $res['text'] = $row['text'];
    $res['description'] = $row['description'];

    if ($aid == "fitg6.1" or $aid == "fitb6.1" or $aid == "incg6.1" or $aid == "incb6.1" or $aid == "gymg6.1" or $aid == "gymb6.1") {
      $res['description'] = $customDescription;
    }

    if ($aid == "fitg9.5" or $aid == "fitb9.5" or $aid == "incg9.5" or $aid == "incb9.5") {
      $currentYear = tsToShamsiYear(time());
      $nextYear = $currentYear + 1;
      $nextYear = $nextYear . "/01/01";
      $conn->query("UPDATE users SET `calendar`='$nextYear' , `celebration`='نوروز' WHERE `token`='$token'");
    }
    if ($aid == "fitg9.4" or $aid == "fitb9.4" or $aid == "incg9.4" or $aid == "incb9.4") {
      $currentYear = tsToShamsiYear(time());
      $currentYaldaTs = shamsiToTs($currentYear, "09", "30");
      $yalda = "";
      if (time() > $currentYaldaTs) {
        $yalda = ($currentYear + 1) . "/09/30";
      } else {
        $yalda = $currentYear . "/09/30";
      }
      $conn->query("UPDATE users SET `calendar`='$yalda' , `celebration`='یلدا' WHERE `token`='$token'");
    }

    if ($aid == "fitg9.1" or $aid == "fitg9.2" or $aid == "fitg9.6" or $aid == "fitg9.7" or $aid == "fitg9.8" or $aid == "fitb9.1" or $aid == "fitb9.2" or $aid == "fitb9.6" or $aid == "fitb9.7" or $aid == "fitb9.8" or $aid == "incg9.1" or $aid == "incg9.2" or $aid == "incg9.6" or $aid == "incg9.7" or $aid == "incg9.8" or $aid == "incb9.1" or $aid == "incb9.2" or $aid == "incb9.5" or $aid == "incb9.6" or $aid == "incb9.7" or $aid == "incb9.8") {
      $result_celeb = $conn->query("SELECT * FROM answersV2 WHERE `aid`='$aid'");
      if ($result_celeb->num_rows > 0) {
        while ($rowCeleb = $result_celeb->fetch_assoc()) {
          $celebText = $rowCeleb["text"];
          $conn->query("UPDATE users SET `celebration`='$celebText' WHERE `token`='$token'");
          $res['text'] = "تاریخ " . $celebText . " کیه؟!";
        }
      }
    }

    if ($aid == "fitg44.1" or $aid == "fitb44.1" or $aid == "incg44.1" or $aid == "incb44.1") {
      $result_thirdMonth = $conn->query("SELECT * FROM users WHERE `token`='$token'");
      if ($result_thirdMonth->num_rows > 0) {
        while ($rowCeleb = $result_thirdMonth->fetch_assoc()) {
          $thirdMonth = $rowCeleb["thirdMonth"];
          $thirdMonth = monthNumberToMonthName($thirdMonth);
          $res['text'] = "چقدر مطمئنی که در ماه " . $thirdMonth . " به هیکل ایده‌آلی که میخوای میرسی؟";
        }
      }
    }

    if ($aid == "gymg30.1" or $aid == "gymb30.1") {
      $result_thirdMonth = $conn->query("SELECT * FROM users WHERE `token`='$token'");
      if ($result_thirdMonth->num_rows > 0) {
        while ($rowCeleb = $result_thirdMonth->fetch_assoc()) {
          $thirdMonth = $rowCeleb["secondMonth"];
          $thirdMonth = monthNumberToMonthName($thirdMonth);
          $res['text'] = "چقدر مطمئنی که در ماه " . $thirdMonth . " به هیکل ایده‌آلی که میخوای میرسی؟";
        }
      }
    }

    $hint = $row['hint'];
    if (strlen($hint) < 5) {
      $hint = "";
    }
    $res['hint'] = array(
      "title" => "",
      "caption" => $hint
    );

    $res["isResult"] = (string)$isResult;
    $res['answers'] = $answers;
  }
}



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