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

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


$allAnswers = array();
$type = "";

$scaleList = array("چاقی مفرط", "اضافه وزن", "نرمال", "کمبود وزن");

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

$code = convertPersianToEnglish($codeFirst);

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

$ts = time();
$currntMonth = tsToShamsiMonth($ts);
$currntMonthName = monthNumberToMonthName($currntMonth);
$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);
$ts4MonthLater = monthNumberToMonthName($currntMonth + 4);
$ts3MonthLater = monthNumberToMonthName($currntMonth + 3);
$ts2MonthLater = monthNumberToMonthName($currntMonth + 2);

$fitState = "";
$target = "";
$regimeType = "";
$gender = "null";
$height = "";
$weightCurrent = "";
$weightGoal = "";
$barrier = "";
$rhyme = "";
$rhymeColor = "";
$barrierSecond = "
سایز فولیکول بالا
</br>
ذخایر تخمدان بالا
</br>
کیفیت اسپرم بالا
";

$percentage = rand(90, 98);
$percentage = (string) $percentage;
$percentageText = "احتمال موفقیت در برنامه تناسب اندام و رسیدن به وزن هدف";


// 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"];
        $weightCurrent = $rowUser["weight"];
        $weightGoal = $rowUser["weight_goal"];
        $height = $rowUser["height"];
    }

    //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 == "eghdam") {

    $title = "وضعیت باروری شما پس از پایان برنامه";
    $regimeType = "تقویت قدرت باروری";

    $target = "بارداری در " . $ts3MonthLater;
    $lineBarTitle1 = "قدرت باروری فعلی";
    $lineBarTitle2 = "قدرت باروری بعد از پایان برنامه";
    $lineBarLabel = "قدرت باروری شما ";
    $warningTitle = "هشدار قدرت باروری";
    $warningDescription = "سبک زندگی و تغذیه شما برای اقدام به بارداری مناسب نیست و در ریسک بارداری دیر هنگام قرار دارین.";
    $summeryTitle = "خلاصه وضعیت باروری شما";
    $borderImage1 = "https://mint-family.com/api/files/v2/before.png";
    $borderImage2 = "https://mint-family.com/api/files/v2/after.png";

    $scaleList = array("ضعیف", "متوسط", "قوی", "خیلی قوی");
} else if ($type == "fit" or $type == "gym" or $type == "inc") {


    $regimeType = "Healthy Life Style + Caloric Density";
    $title = "وضعیت تناسب اندام شما پس از پایان برنامه";
    $summeryTitle = "خلاصه وضعیت تناسب اندام شما";

    $lineBarTitle1 = "وضعیت تناسب اندام فعلی";
    $lineBarTitle2 = "وضعیت تناسب اندام بعد از پایان برنامه";
    $lineBarLabel = "وضعیت BMI";

    if ($gender == "male") {
        $borderImage1 = "https://api.matchadiet.com/files/v2/beforeMatchaMan.png";
        $borderImage2 = "https://api.matchadiet.com/files/v2/afterMatchaMan.png";
    } else {
        $borderImage1 = "https://api.matchadiet.com/files/v2/beforeMatchaWomanAI.png";
        $borderImage2 = "https://api.matchadiet.com/files/v2/afterMatchaWomanAI.png";
    }

    $beforeBMI = $weightCurrent / ($height * $height / 10000);
    $afterBMI = $weightGoal / ($height * $height / 10000);

    if ($type == "fit" or $type == "fastfit" or $type == "gym") {
        if ($gender == "male") {
            if ($beforeBMI >= 30) {
                $borderImage1 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-man-upper30-before.png";
                $borderImage2 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-man-upper30-after.png";
            } else {
                $borderImage1 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-man-under30-before.png";
                $borderImage2 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-man-under30-after.png";
            }
        } else {
            if ($afterBMI >= 30) {
                $borderImage1 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-woman-upper30-before.png";
                $borderImage2 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-woman-upper30-after.png";
            } else {
                $borderImage1 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-woman-under30-before.png";
                $borderImage2 = "https://api.matchadiet.com/files/v2/precheckout_ba/fit-woman-under30-after.png";
            }
        }
    }

    if ($beforeBMI < 18.5) {
        $lowerLineBar = rand(91, 99);
    } else if ($beforeBMI > 25) {
        $lowerLineBar = rand(1, 15);
    } else {
        $lowerLineBar = rand(50, 60);
    }

    if ($afterBMI < 18.5) {
        $upperLineBar = rand(3, 15);
    } else if ($afterBMI > 25) {
        $upperLineBar = rand(60, 70);
    } else {
        $upperLineBar = rand(20, 55);
    }


    if ($beforeBMI >= 30) {
        $fitState = "اضافه وزن شدید";
        $fitStateColor = "#fc0505";
        $lifeStyle = "خطرناک";
        $lifeStyleColor = "#fc0505";
        $metabol = "خیلی پایین";
        $metabolColor = "#fc0505";
        $warningTitle = "هشدار سبک زندگی بسیار ناسالم";
        $warningDescription = "سبک زندگی شما خیلی ناسالمه و در ریسک فشار خون بالا، سکته قلبی، دیابت نوع دو و مشکلات مفصلی و کمری قرار دارین.";
    } else if ($beforeBMI >= 25 and $beforeBMI < 30) {
        $fitState = "اضافه وزن";
        $fitStateColor = "#fc0505";
        $lifeStyle = "ناسالم";
        $lifeStyleColor = "#fc0505";
        $metabol = "پایین";
        $metabolColor = "#fc0505";
        $warningTitle = "هشدار سبک زندگی ناسالم";
        $warningDescription = "سبک زندگی شما ناسالمه و در ریسک فشار خون بالا، سکته قلبی، دیابت نوع دو و مشکلات مفصلی و کمری قرار دارین.";
    } else if ($beforeBMI >= 18 and $beforeBMI < 25) {
        $fitState = "خوب";
        $fitStateColor = "#000000";
        $lifeStyle = "خوب";
        $lifeStyleColor = "#000000";
        $warningTitle = "BMI سالم";
        $metabol = "متوسط";
        $metabolColor = "#000000";
        $warningDescription = "وزنت در بازه خوبی قرار داره و وقتشه که تخصصی تر کار کنی تا به یه بدن حرفه‌ای برسی.";
    } else if ($beforeBMI < 18) {
        $fitState = "کمبود وزن";
        $fitStateColor = "#fc0505";
        $lifeStyle = "ناسالم";
        $lifeStyleColor = "#fc0505";
        $warningTitle = "هشدار سبک زندگی ناسالم";
        $metabol = "پایین";
        $metabolColor = "#fc0505";
        $warningDescription = "کمبود وزن داری و باید هرچه سریعتر سبک زندگیت رو تغییر بدی تا به وزن نرمال برسی";
    }

    $strings = array(
        'A',
        'B',
        'C',
        'D',
    );
    $key = array_rand($strings);
    $prof = $strings[$key];

    $lowerLineBar = (int)$lowerLineBar;
    $lowerLineBar = (string)$lowerLineBar;

    $upperLineBar = (int)$upperLineBar;
    $upperLineBar = (string)$upperLineBar;
}

$itemsBefore = array();
$itemsAfter = array();

if ($type == "fit" or $type == "inc") {

    $itemBefore1 = array(

        "icon" => "",
        "title" => "وضعیت تناسب اندام:",
        "description" => $fitState,
        "descriptionColor" => $fitStateColor,
    );
    array_push($itemsBefore, $itemBefore1);
    $itemBefore2 = array(

        "icon" => "",
        "title" => "وضعیت سبک زندگی:",
        "description" => $lifeStyle,
        "descriptionColor" => $lifeStyleColor,
    );
    array_push($itemsBefore, $itemBefore2);

    $itemBefore3 = array(

        "icon" => "",
        "title" => "متابولسیم بدن:",
        "description" => $metabol,
        "descriptionColor" => $metabolColor,
    );
    array_push($itemsBefore, $itemBefore3);
    $itemBefore4 = array(

        "icon" => "",
        "title" => "پروفایل رفتاری:",
        "description" => $prof,
        "descriptionColor" => "#000000",
    );
    array_push($itemsBefore, $itemBefore4);


    $itemAfter1 = array(

        "icon" => "",
        "title" => "وضعیت تناسب اندام:",
        "description" => "بسیار خوب",
        "descriptionColor" => "#12db04",
    );
    array_push($itemsAfter, $itemAfter1);

    $itemAfter2 = array(

        "icon" => "",
        "title" => "وضعیت سبک زندگی:",
        "description" => "سالم",
        "descriptionColor" => "#000000",
    );
    array_push($itemsAfter, $itemAfter2);

    $itemAfter3 = array(

        "icon" => "",
        "title" => "متابولسیم بدن:",
        "description" => "استاندارد",
        "descriptionColor" => "#12db04",
    );
    array_push($itemsAfter, $itemAfter3);

    $itemAfter4 = array(
        "icon" => "",
        "title" => "پروفایل رفتاری:",
        "description" => $prof,
        "descriptionColor" => "#000000",
    );
    array_push($itemsAfter, $itemAfter4);
}

if ($type == "gym") {

    $bodyType = "";
    if (in_array("gymg43.3", $allAnswers)) {
        $bodyType = "دایره (سیب)";
    }
    if (in_array("gymg43.2", $allAnswers)) {
        $bodyType = "مستطیلی";
    }
    if (in_array("gymg43.1", $allAnswers)) {
        $bodyType = "مثلث (گلابی)";
    }
    if (in_array("gymg43.4", $allAnswers)) {
        $bodyType = "ساعت شنی";
    }
    if (in_array("gymg43.5", $allAnswers)) {
        $bodyType = "مثلث معکوس";
    }
    if (in_array("gymg43.6", $allAnswers)) {
        $bodyType = "-";
    }

    $itemBefore1 = array(

        "icon" => "",
        "title" => "وضعیت تناسب اندام:",
        "description" => $fitState,
        "descriptionColor" => $fitStateColor,
    );
    array_push($itemsBefore, $itemBefore1);
    $itemBefore2 = array(

        "icon" => "",
        "title" => "وضعیت سبک زندگی:",
        "description" => $lifeStyle,
        "descriptionColor" => $lifeStyleColor,
    );
    array_push($itemsBefore, $itemBefore2);

    $itemBefore3 = array(

        "icon" => "",
        "title" => "متابولسیم بدن:",
        "description" => $metabol,
        "descriptionColor" => $metabolColor,
    );
    array_push($itemsBefore, $itemBefore3);
    $itemBefore4 = array(

        "icon" => "",
        "title" => "پروفایل عضلانی:",
        "description" => $prof,
        "descriptionColor" => "#000000",
    );
    array_push($itemsBefore, $itemBefore4);

    $itemBefore5 = array(

        "icon" => "",
        "title" => "تیپ بدنی:",
        "description" => $bodyType,
        "descriptionColor" => "#000000",
    );
    array_push($itemsBefore, $itemBefore5);


    $itemAfter1 = array(

        "icon" => "",
        "title" => "وضعیت تناسب اندام:",
        "description" => "بسیار خوب",
        "descriptionColor" => "#12db04",
    );
    array_push($itemsAfter, $itemAfter1);

    $itemAfter2 = array(

        "icon" => "",
        "title" => "وضعیت سبک زندگی:",
        "description" => "سالم",
        "descriptionColor" => "#000000",
    );
    array_push($itemsAfter, $itemAfter2);

    $itemAfter3 = array(

        "icon" => "",
        "title" => "متابولسیم بدن:",
        "description" => "استاندارد",
        "descriptionColor" => "#12db04",
    );
    array_push($itemsAfter, $itemAfter3);

    $itemAfter4 = array(
        "icon" => "",
        "title" => "پروفایل عضلانی:",
        "description" => $prof,
        "descriptionColor" => "#000000",
    );
    array_push($itemsAfter, $itemAfter4);

    $itemAfter4 = array(

        "icon" => "",
        "title" => "تیپ بدنی:",
        "description" => "فرم ورزشکاری",
        "descriptionColor" => "#000000",
    );
    array_push($itemsAfter, $itemAfter4);
}

$response['success'] = 'true';
$response['message'] = '200';
$response['result'] =
    array(
        "token" => $token,
        "code" => $code,
        "header" => array(
            "color" => "#ffffff",
            "bgColor" => "#3cd5af",
            "image" => "https://api.matchadiet.com/files/v2/banners/header1.png",
            "text" => "نتایج تحلیل شرایط شما",
        ),
        "summery" => array(
            "title" => $summeryTitle,
            "video" => array(
                "link" => null,
                "text" => ""
            ),
            "lineBar" => array(
                "title" => $lineBarTitle1,
                "value" => (string) ($lowerLineBar),
                "label" => $lineBarLabel,
                "warningTitle" => $warningTitle,
                "warningDescription" => $warningDescription,
                "scaleList" => $scaleList,
            ),
            "borderImage" => $borderImage1,
            "items" => $itemsBefore,
        ),
        "highlight" => array(
            "title" => $title,
            "lineBar" => array(
                "title" => $lineBarTitle2,
                "value" => (string) ($upperLineBar),
                "label" => $lineBarLabel,
                "scaleList" => $scaleList,
            ),
            "borderImage" => $borderImage2,
            "items" => $itemsAfter,
            "percentage" => array(
                "value" => $percentage,
                "description" => $percentageText,
            ),
        ),
    );

$response['data'] =
    array(
        "token" => $token,
        "code" => $code,
        "isResult" => "true",
        "header" => array(
            "color" => "#ffffff",
            "bgColor" => "#3cd5af",
            "image" => "https://api.matchadiet.com/files/v2/banners/header1.png",
            "text" => "نتایج تحلیل شرایط شما",
        ),
        "button" => array(
            "text" => "دریافت برنامه",
            "link" => "/checkout",
            "bgColor" => "#4ed09a",
            "color" => "#ffffff",
        ),
        "summery" => array(
            "title" => $summeryTitle,
            "video" => array(
                "link" => null,
                "text" => ""
            ),
            "lineBar" => array(
                "title" => $lineBarTitle1,
                "value" => (string) ($lowerLineBar),
                "label" => $lineBarLabel,
                "warningTitle" => $warningTitle,
                "warningDescription" => $warningDescription,
                "scaleList" => $scaleList,
            ),
            "borderImage" => $borderImage1,
            "items" => $itemsBefore,
        ),
        "highlight" => array(
            "title" => $title,
            "lineBar" => array(
                "title" => $lineBarTitle2,
                "value" => (string) ($upperLineBar),
                "label" => $lineBarLabel,
                "scaleList" => $scaleList,
            ),
            "borderImage" => $borderImage2,
            "items" => $itemsAfter,
            "percentage" => array(
                "value" => $percentage,
                "description" => $percentageText,
            ),
        ),
    );

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

function getVideoLink()
{

    $videoBaseLink = "https://file.mintapp.ir/Persona/";
    global $type;
    global $conn;
    global $code;
    global $token;

    $userAnswers = array();

    $link = "";

    if ($type == "eghdam" or $type == "eghdam_ge" or $type == "eghdam_ad") {

        $result_answers = $conn->query("SELECT * FROM process WHERE `code`='$code' AND `token`='$token'");
        if ($result_answers->num_rows > 0) {
            while ($row_answers = $result_answers->fetch_assoc()) {
                $answer = $row_answers["aid"];
                array_push($userAnswers, $answer);
            }
        }

        $typeTemp = $type;
        if ($type == "eghdam_ad" or $type == "eghdam_ge") {
            $typeTemp = "eghdam";
        }

        $result_result = $conn->query("SELECT * FROM resultsV2 WHERE `type`='$typeTemp'");
        if ($result_result->num_rows > 0) {
            while ($row_result = $result_result->fetch_assoc()) {
                $resultAnswers = array();
                $ranswer = $row_result["answers"];
                $resultAnswers = explode(",", $ranswer);


                if ($type == "eghdam_ge") {
                    for ($i = 0; $i < sizeof($resultAnswers); $i++) {
                        $resultAnswers[$i] = $resultAnswers[$i] . "_ge";
                    }
                }

                if ($type == "eghdam_ad") {
                    for ($i = 0; $i < sizeof($resultAnswers); $i++) {
                        $resultAnswers[$i] = $resultAnswers[$i] . "_ad";
                    }
                }

                $containsAllValues = !array_diff($resultAnswers, $userAnswers);
                if ($containsAllValues) {
                    $resultLink = $row_result["result"];
                    $link = $videoBaseLink . $resultLink . ".mp4";
                    return $link;
                }
            }
        }
    }
}


function ovaryCount()
{
    global $allAnswers;
    $ovaryCount = 0;
    $ovarySymList = array("ov4.1", "ov6.1", "ov8.1", "ov9.1", "ov16.1", "ov17.1", "ov21.1", "ov23.1", "ov25.2");
    for ($i = 0; $i < sizeof($ovarySymList); $i++) {
        if (in_array($ovarySymList[$i], $allAnswers)) {
            $ovaryCount++;
        }
    }
    return $ovaryCount;
}
