<?php

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

$language = "fa";

$persona = null;
$type = null;


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

$code = convertPersianToEnglish($codeFirst);

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

$beforeImage = "https://nikaatmint.ir/files/appIcons/pregBefore.png";
$afterImage = "https://nikaatmint.ir/files/appIcons/pregAfter.png";
$beforeText = "امروز";
$afterText = "شش ماه بعد";
$description = "96.5 درصد از کاربران اپلیکیشن مینت، بارداریشون رو در سلامت کامل به پایان رسوندن";
$payCounter = "null";
$headerType = "lottie";

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

$isLazy = "false";

$fitnessPlans = null;

$discount = "0";

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

$withoutProcessCodes = array("prevent");

$gender = "none";

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

$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($row_persona["type"]);
        $type = $row_persona["type"];
        if ($persona == "prevent"){
            $headerType = "counter";
            $payCounter = "518342";
            $description = getTextFromTid("description_payment_count" , $language);
        }
        else {
            switch ($persona){
                case "pregnant":
//                    $result_preg = $conn_mint->query("SELECT * FROM preg_cycle WHERE `phone`='$phone' ORDER BY id");
//                    if ($result_preg->num_rows > 0) {
//                        while ($row_preg = $result_preg->fetch_assoc()) {
//                            $endYear = $row_preg["endYear"];
//                            $endMonth = $row_preg["endMonth"];
//                            $endDay = $row_preg["endDay"];
//                            $endTs = shamsiToTs($endYear , $endMonth , $endDay);
//                            $zaimanDate = getPlanDate($endTs , $language);
//                        }
//                    }
                    $beforeImage = "https://nikaatmint.ir/files/appIcons/pregBefore.png";
                    $afterImage = "https://nikaatmint.ir/files/appIcons/pregAfter.png";
                    $description = getTextFromTid("description_payment_pregcount" , $language);
                    $beforeText = "";
                    $afterText = "";
                    break;

                case "ovary":

                    $beforeImage = "https://nikaatmint.ir/files/appIcons/ovaryBefore.png";
                    $afterImage = "https://nikaatmint.ir/files/appIcons/ovaryAfter.png";
                    $description = getTextFromTid("description_payment_ovary" , $language);
                    $beforeText = getTextFromTid("today" , $language);
                    $afterText = getTextFromTid("two_month_later" , $language);
                    break;

                case "desire":

                    $beforeImage = "https://nikaatmint.ir/files/appIcons/desireBefore.png";
                    $afterImage = "https://nikaatmint.ir/files/appIcons/desireAfter.png";
                    $description = getTextFromTid("description_payment_desire" , $language);
                    $beforeText = getTextFromTid("today" , $language);
                    $afterText = getTextFromTid("two_month_later" , $language);
                    break;

                case "prepregnant":

                    $result_gender = $conn->query("SELECT * FROM process WHERE `code`='$code' AND `aid`='e8.1'");
                    if ($result_gender->num_rows > 0) {
                        $gender = "boy";
                    }
                    else{
                        $result_gender = $conn->query("SELECT * FROM process WHERE `code`='$code' AND `aid`='e8.2'");
                        if ($result_gender->num_rows > 0) {
                            $gender = "girl";
                        }
                    }
                    $result_lazy = $conn->query("SELECT * FROM process WHERE `code`='$code' AND `aid`='e4.1'");
                    if ($result_lazy->num_rows > 0) {
                        $isLazy = "true";
                        //$conn_fit->query("UPDATE program SET `program_type`='workout' WHERE `process_id`='$code'");
                    }

                    $beforeImage = "https://nikaatmint.ir/files/appIcons/PrePreg1.png";
                    $afterImage = "https://nikaatmint.ir/files/appIcons/PrePreg2.png";
                    $description = getTextFromTid("description_payment_prepregnant" , $language);
                    $beforeText = getTextFromTid("today" , $language);
                    $afterText = getTextFromTid("six_month_later" , $language);
                    break;

                case "fitness":
                {
                    $programType = "both";

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

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

                            if ($ranswer == "FchaleshBasan1" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_basan","fitness_nut_workout","fitness_workout","fitness_nut");
                                $addChallenge = "true";
                                $beforeImage = "https://nikaatmint.ir/files/appIcons/basanBefore.png";
                                $afterImage = "https://nikaatmint.ir/files/appIcons/basanAfter.png";
                                $description = "میانگین مدت زمانی که کاربران اپلیکیشن مینت، ۵ سانت افزایش دور باسن رو تجربه کردن";
                                $beforeText = "امروز";
                                $afterText = "دو ماه بعد";
                            }
                            else if ($ranswer == "FchaleshShekam1" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_shekam","fitness_nut_workout","fitness_workout","fitness_nut");
                                $addChallenge = "true";
                                $beforeImage = "https://nikaatmint.ir/files/appIcons/fitBefore.png";
                                $afterImage = "https://nikaatmint.ir/files/appIcons/fitAfter.png";
                                $description = "میانگین مدت زمانی که کاربران اپلیکیشن مینت، ۳ سایز کاهش دور کمر رو تجربه کردن";
                                $beforeText = "امروز";
                                $afterText = "دو ماه بعد";
                            }
                            else if ($ranswer == "rejimdarmani1.B" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_kabed");
                                $beforeImage = "https://nikaatmint.ir/files/appIcons/kabedBefore.png";
                                $afterImage = "https://nikaatmint.ir/files/appIcons/kabedAfter.png";
                                $description = "میانگین مدت زمانی که کاربران اپلیکیشن مینت، کبد چربشون رو کاملا بهبود دادن";
                                $beforeText = "امروز";
                                $afterText = "سه ماه بعد";
                            }
                            else if ($ranswer == "rejimdarmani1.A" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_diabet");
                                $headerType = "counter";
                                $payCounter = "302977";
                                $description = "تعداد نفراتی که از برنامه های تناسب اندام اپلیکیشن مینت استفاده کردن";
                            }

                            else if ($ranswer == "F1.D" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_eslahi");
                                $headerType = "counter";
                                $payCounter = "302977";
                                $description = "تعداد نفراتی که از برنامه های تناسب اندام اپلیکیشن مینت استفاده کردن";
                            }

                            else if ($ranswer == "F1.B" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_nut_workout","fitness_workout","fitness_nut");
                                $beforeImage = "https://nikaatmint.ir/files/appIcons/basanBefore.png";
                                $afterImage = "https://nikaatmint.ir/files/appIcons/basanAfter.png";
                                $description = "میزان افزایش وزنی که کاربران اپلیکیشن مینت در مدت زمان یک ماه تجربه کردن";
                                $beforeText = "";
                                $afterText = "";
                            }

                            else if ($ranswer == "F1.A" and in_array($ranswer , $userAnswers)){
                                $findPlan = true;
                                $fitnessPlans = array("fitness_nut_workout","fitness_workout","fitness_nut");
                                $beforeImage = "https://nikaatmint.ir/files/appIcons/fitBefore.png";
                                $afterImage = "https://nikaatmint.ir/files/appIcons/fitAfter.png";
                                $description = "میزان کاهش وزنی که کاربران اپلیکیشن مینت در مدت زمان یک ماه تجربه کردن";
                                $beforeText = "";
                                $afterText = "";
                            }

                        }
                        if ($findPlan == false){
                            $fitnessPlans = array("fitness_nut_workout","fitness_workout","fitness_nut");
                            $headerType = "counter";
                            $payCounter = "302977";
                            $description = "تعداد نفراتی که از برنامه های تناسب اندام اپلیکیشن مینت استفاده کردن";
                        }
                    }
                }


            }

        }//ok

    }
}

$paymentHeader = array(
    "beforeImage"=>$beforeImage,
    "afterImage"=>$afterImage,
    "beforeText"=>$beforeText,
    "afterText"=>$afterText,
    "description"=>$description,
    "counter"=>(string)$payCounter
);

$result_comment = $conn->query("SELECT * FROM comment WHERE `persona`='$persona' AND `visible`='true' AND `language`='fa' ORDER BY priority");
if ($result_comment->num_rows > 0) {
    while($row_comment = $result_comment->fetch_assoc()) {
        $res_comment["text"] = $row_comment["text"];
        $res_comment["link"] = $row_comment["link"];
        $res_comment["type"] = $row_comment["type"];
        array_push($comments , $res_comment);
    }
}

$result_faq = $conn->query("SELECT * FROM faq WHERE `persona`='$persona' AND `language`='fa' 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"];
        $res_faq["image"] = $row_faq["image"];
        array_push($faqs , $res_faq);
    }
}

//add plans
$counter = 0;
$index = "0";
if ($persona == "fitness"){
    for ($i = 0; $i < sizeof($fitnessPlans); $i++){
        $result = $conn->query("SELECT * FROM plans WHERE `persona`='$persona' AND `plan_id`='$fitnessPlans[$i]' AND `language`='fa' ORDER BY priority");
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $discountPrice = "";
                $perPrice = $row["per_price"];

                $res["planId"] = $row["plan_id"];
                $res["title"] = $row["title"];
                $res["description"] = $row["description"];
                $res["price"] = $perPrice;
                $res["length"] = $row["length"];
                $res["discountPrice"] = $discountPrice;
                $res["buttonTitle"] = $row["button_title"];
                $timeUnit = $row["time_unit"];
                if ($timeUnit == "month"){
                    $timeUnit = "ماهانه";
                }
                else {
                    $timeUnit = "سالانه";
                }
                $res["timeUnit"] = $timeUnit;
                array_push($plans , $res);
            }
        }
    }
}
else{
    $result = $conn->query("SELECT * FROM plans WHERE `persona`='$persona' AND `language`='fa' ORDER BY priority");
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $perPrice = $row["per_price"];
            $discountPrice = "";

            $planId = $row["plan_id"];
            $res["planId"] = $row["plan_id"];
            $res["title"] = $row["title"];
            $res["description"] = $row["description"];
            $res["price"] = $perPrice;
            $res["length"] = $row["length"];
            $res["discountPrice"] = $discountPrice;
            $res["buttonTitle"] = $row["button_title"];
            $timeUnit = $row["time_unit"];
            if ($timeUnit == "month"){
                $timeUnit = "ماهانه";
            }
            else {
                $timeUnit = "سالانه";
            }
            $res["timeUnit"] = $timeUnit;
            $isSelected = $row["is_selected"];
            if ($isSelected == "true"){
                $index = $counter;
            }
            $counter++;
            array_push($plans , $res);
        }
    }
}

$response['success'] = 'true';
$response['message'] = '200';
$response['result'] =
    array(
        "videoLink"=>(string)getVideoLink(),
        "videoText"=>getVideoText(),
        "type"=>$headerType,
        "paymentHeader"=>$paymentHeader,
        "index"=>(string)$index,
        "plans"=>$plans,
        "faq"=>$faqs,
        "comments"=>$comments
    );
$json_response = json_encode($response);
echo $json_response;
die();

$conn->close();


function getVideoLink(){
    global $conn;
    global $persona;
    global $type;
    global $code;
    global $token;
    global $videoBaseLink;
    $link = null;
    $userAnswers = array();

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

    if ($type == "eghdam"){

        $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);
            }
        }
        $result_result = $conn->query("SELECT * FROM resultsV2 WHERE `type`='$type'");
        if ($result_result->num_rows > 0) {
            while($row_result = $result_result->fetch_assoc()) {
                $resultAnswers = array();
                $ranswer = $row_result["answers"];
                $resultAnswers = explode("," , $ranswer);
                $containsAllValues = !array_diff($resultAnswers, $userAnswers);
                if ($containsAllValues){
                    $resultLink = $row_result["result"];
                    $link = $videoBaseLink.$resultLink.".mp4";
                    return $link;
                }
            }
        }
    }
    else if ($type == "Preg"){
//        $result_weight = $conn->query("SELECT * FROM users WHERE `token`='$token'");
//        if ($result_weight->num_rows > 0) {
//            while($row_weight = $result_weight->fetch_assoc()) {
//                $weightStatus = $row_weight["weight_status"];
//                if ($weightStatus == "high"){
//                    $link = $videoBaseLink."ezafebardari".".mp4";
//                    return $link;
//                }
//                else if ($weightStatus == "low"){
//                    $link = $videoBaseLink."kamboodbardari".".mp4";
//                    return $link;
//                }
//                else if ($weightStatus == "normal"){
//                    $link = $videoBaseLink."tanasobbardari".".mp4";
//                    return $link;
//                }
//                else{
//                    return "";
//                }
//            }
//        }

        return "";
    }
    else if ($type == "PageFitness"){
        $result_weight = $conn->query("SELECT * FROM users WHERE `token`='$token'");
        if ($result_weight->num_rows > 0) {
            while($row_weight = $result_weight->fetch_assoc()) {
                $weight = $row_weight["weight"];
                $height = $row_weight["height"];
                if ($weight - ($height - 105) > 5){
                    $weightStatus = "high";
                }
                else if ($weight - ($height - 105) < -5){
                    $weightStatus = "low";
                }
                else {
                    return "";
                }
                $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);
                    }
                }
                $result_result = $conn->query("SELECT * FROM resultsV2 WHERE `type`='$type' AND `weight`='$weightStatus'");
                if ($result_result->num_rows > 0) {
                    while($row_result = $result_result->fetch_assoc()) {
                        $resultAnswers = array();
                        $ranswer = $row_result["answers"];
                        $resultAnswers = explode("," , $ranswer);
                        $containsAllValues = !array_diff($resultAnswers, $userAnswers);
                        if ($containsAllValues){
                            $resultLink = $row_result["result"];
                            $link = $videoBaseLink.$resultLink.".mp4";
                            return $link;
                        }
                    }
                }
            }
        }
    }
    else{
        return "";
    }

}

function getVideoText(){
    global $type;
    if ($type == "PageFitness"){
        return "تحلیل شرایط شما توسط احمد نوازنده، مربی فدراسیون";
    }
    else {
        return "تحلیل شرایط شما توسط دکتر شهبازی";
    }
}

?>
