<?php

/**
 * @desc This report lets you make split test of your pages and gives you an overview of wich one works the best.
 */
$reports["_SURVEYS"] = array(
    "ClassName" => "Surveys",
    "Category" => "_VISITOR_DETAILS",
    "icon" => "images/icons/32x32/surveys.png",
    "Options" => "daterangeField,columnSelector",
    "Filename" => "surveys",
    "Distribution" => "Premium",
    "Order" => 1,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => false,
    "Update" => false,
    "canAggregate" => false
);

class Surveys extends Report
{

    function Settings()
    {
        global $db;

        $this->remove_outputmodes = array("all");

        $this->columnDefinitions[] = array("Label" => _ANSWERS);
        $this->columnDefinitions[] = array("Label" => _UNIQUE_VISITORS);
        $this->columnDefinitions[] = array("Label" => "Responses", "disable_line" => true);

        $this->surveytablename = $this->profile->tablename . "_surveys";
        $this->surveytablename_questions = $this->profile->tablename . "_surveyquestions";
        $this->surveytablename_results = $this->profile->tablename . "_surveyresults";

        if (!isset($this->surveyid)) {
            $this->surveyid = 0;
        } else {
            if (!is_numeric($this->surveyid)) {
                $this->surveyid = 0;
            }
        }

        $this->fileNameExpension .= ".{$this->surveyid}";

        $this->SurveyTables();
    }

    function SurveyTables()
    {
        global $db;

        $db->Execute(
            "CREATE OR REPLACE TABLE {$this->surveytablename} (id int(11) NOT NULL auto_increment,surveyname varchar(255) NOT NULL default 'New Survey',
			surveydesc text, surveyoptions text,
			status int(1) default '1' , PRIMARY KEY (id) ) ENGINE=MyISAM  CHARSET=utf8"
        );


        $db->Execute(
            "CREATE OR REPLACE TABLE {$this->surveytablename_questions} (id int(11) NOT NULL auto_increment, surveyid int(11) NOT NULL default '0',
			question blob,
			question_rule blob,
			question_type varchar(255),
			question_order int(3),
			answer_rule blob, PRIMARY KEY  (id) ) ENGINE=MyISAM  CHARSET=utf8"
        );

        $db->Execute(
            "CREATE OR REPLACE TABLE  {$this->surveytablename_results} (id int(11) NOT NULL auto_increment,
			surveyid int(10) NOT NULL default '0',
			visitorid varchar(32) NOT NULL default '0',
			timestamp int(11) NOT NULL default '0',
			questionid int(10) NOT NULL default '0',
			answer varchar(255) NOT NULL default '0' , PRIMARY KEY  (id) ) ENGINE=MyISAM  CHARSET=utf8"
        );
        $db->Execute(
            "ALTER TABLE {$this->surveytablename_results} ADD INDEX {$this->surveytablename_results}_answer (answer)"
        );
        $db->Execute(
            "ALTER TABLE {$this->surveytablename_results} ADD INDEX {$this->surveytablename_results}_timestamp (timestamp)"
        );
        $db->Execute(
            "ALTER TABLE {$this->surveytablename_results} ADD INDEX {$this->surveytablename_results}_surveyid (surveyid)"
        );
    }

    function DisplayCustomForm()
    {
        global $db, $session;

        $q = $db->Execute("select * from {$this->surveytablename} order by id asc");
        echo "<div class='form-group'>";
        echo "<label>" . _SELECT . "</label>";
        echo "<select class='report_option_field form-control' name='surveyid'>";
        while (($q) && ($data = $q->FetchRow())) {
            if (!empty($this->surveyid) && $this->surveyid == $data["id"]) {
                $selected = "selected='selected'";
            } else {
                $selected = "";
            }
            echo "<option $selected value='{$data["id"]}' >{$data["surveyname"]}</option>";
        }
        echo "</select>";

        if ($session->canEditProfiles()) {
            echo "<a data-title='" . _CREATE_EDIT_SURVEY . "' href='definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS' target='_blank' class='optionlink open_iframe_window'>" . _CREATE_EDIT_SURVEY . "</a><br/>";
        }
        echo "</div>";
    }

    function DisplayReport()
    {
        $data = $this->GetReportData();
        $this->addlabel = $this->GetSurveyName();
        $this->displayReportButtons = false;
        $this->ReportHeader();


        $this->displayHeader = false;
        $this->displayReportButtons = false;

        $id = "S" . md5(time() . rand(0, 100));
        if (empty($data)) {
            echoNotice($this->SettingsButton() . _NO_DATA_TO_DISPLAY, "margin-left:15px;");
        } else {
            if (empty($this->visitorid)) {
                $this->SurveyStats($id);
            } else {
                echoNotice("Displaying answers for visitor id: $this->visitorid");
            }
        }


        //$this->columnDefinitions = [];
        $this->columnDefinitions[0]["Label"] = "_ANSWERS";
        // $this->columnDefinitions[1]["Label"] = "_UNIQUE_VISITORS";
        // unset($this->columnDefinitions[0]["actionmenu"]);
        // $this->columnDefinitions[1]["bchart"] = true;


        $r = 0;
        foreach ($data as $question => $answers) {
            $d = [];
            $i = 0;
            foreach ($answers as $k => $v) {
                if ($k != "type") {
                    $d[$i][0] = $k;
                    $d[$i][1] = $v["unique_visitors"];
                    $d[$i][2] = $v["visitors"];
                    $i++;
                }
            }
            //dump($question);
            //dump($d);

            echo "<div class='survey_div {$id}'>";
            echo "<h2 class='survey_table_header' rel='$r'>" . ucwords(_QUESTION) . ": $question</h2>";
            echo "<div class='st survey_table$r'>";

            if ($answers["type"] == "single") {
                $this->Pie($d);
            }
            if ($answers["type"] == "multiple") {
                $this->Table($d);
            }
            if ($answers["type"] == "open" || $answers["type"] == "input") {
                $this->Table($d);
            }
            echo "</div>";
            echo "</div>";
            $r++;
        }
        echo "<div style='clear:both;'></div>";
        if (empty($this->visitorid)) {
            $this->SurveyParticipants($id);
        }
        ?>
        <style>
            .survey_table_header {
                border-bottom: 1px solid #e3e3e3;
                color: #000;
                cursor: pointer;
                font-size: 15px;
                line-height: 28px;
                margin: 10px 0;
                padding: 0 4px;
            }

            .survey_div {
                float: left;
                width: 100%;
            }

            .st table tr td:first-child {
                white-space: pre-wrap !important;
                font-size: 12px;
                padding: 4px !important;
            }
        </style>
        <script type="text/javascript">
            $(".<?php echo $id; ?> .survey_table_header").on("click", function () {
                $(this).next(".survey_table" + $(this).attr('rel')).toggle();
            });
        </script><?php
    }

    function GetReportData()
    {
        global $db;

        $import = [];
        if (empty($this->surveyid)) {
            $q = $db->Execute("select id from {$this->surveytablename} order by id asc limit 1");
            while (($q) && ($data = $q->FetchRow())) {
                $this->surveyid = $data["id"];
            }
            if (empty($this->surveyid)) {
                $this->surveyid = 0;
            }
        }
        $q = $db->Execute(
            "select * from {$this->surveytablename_questions} where surveyid=" . $db->Quote(
                $this->surveyid
            ) . " order by question_order"
        );

        $onlythis = "";
        if (!empty($this->visitorid)) {
            $onlythis = " and r.visitorid=" . $db->Quote($this->visitorid);
        }

        while (($q) && ($data = $q->FetchRow())) {
            $query = "select q.question, q.question_type as type, r.answer, count(distinct r.visitorid) as v, count(r.visitorid) as r from {$this->surveytablename_results} as r, {$this->surveytablename_questions} as q where r.surveyid=" . $db->quote(
                    $this->surveyid
                ) . " and (timestamp >=" . $db->quote($this->from) . " and timestamp <=" . $db->Quote(
                    $this->to
                ) . ") and q.id=r.questionid and r.questionid=" . $db->quote(
                    $data["id"]
                ) . " $onlythis group by r.answer order by r desc";

            $q2 = $db->Execute($query);
            $i = 0;
            while (($q2) && ($data2 = $q2->FetchRow())) {
                $import[$data2["question"]]["type"] = $data2["type"];
                $import[$data2["question"]][$data2["answer"]]["unique_visitors"] = $data2["v"];
                $import[$data2["question"]][$data2["answer"]]["visitors"] = $data2["r"];
            }
        }

        return $import;
    }

    function GetSurveyName()
    {
        global $db;
        $q = $db->Execute("select id,surveyname from {$this->surveytablename} where id={$this->surveyid}");
        $data = $q->FetchRow();
        return $data[1] ?? 0;
    }

    function SurveyStats($id)
    {
        global $db;

        $q = $db->Execute(
            "select count(distinct visitorid) from {$this->surveytablename_results} where surveyid=" . $db->Quote(
                $this->surveyid
            ) . " and timestamp between " . $db->Quote($this->from) . " and " . $db->Quote($this->to) . ""
        );
        if ($data = $q->FetchRow()) {
            $total = $data[0];
        }

        $q = $db->Execute(
            "select FROM_UNIXTIME(timestamp, '%d-%b-%Y %a') AS days, count(distinct visitorid),count(*) from {$this->surveytablename_results} where surveyid=" . $db->Quote(
                $this->surveyid
            ) . " and timestamp between " . $db->Quote($this->from) . " and " . $db->Quote(
                $this->to
            ) . " group by days order by timestamp"
        );

        $data = [];
        $i = 0;
        while ($row = $q->FetchRow()) {
            $data[$i][0] = $row[0];
            $data[$i][1] = $row[1];
            $data[$i][2] = $row[2];
            $i++;
        }

        $this->DisplayModes = "barchart, linechart,table";
        $this->columnDefinitions[0]["Label"] = "_DATE";

        echo "<div class='survey_div {$id}'>";
        echo "<h2 class='survey_table_header' rel='Stats'>In this period $total unique visitors participated</h2>";
        echo "<div class='survey_tableStats'>";

        $this->BarChart($data);

        echo "</div>";
        echo "</div>";
        echo "<div style='clear:both;'></div>";
    }

    function SurveyParticipants($id)
    {
        global $db;

        $this->columnDefinitions = [];
        $this->columnDefinitions[] = ["Label" => "_IP_NUMBER"];
        $this->columnDefinitions[] = ["Label" => "_DATE"];
        $this->columnDefinitions[] = ["Label" => "Responses"];
        $this->columnDefinitions[] = ["Label" => "Answers"];
        if (isset($this->options['showColumn2'])) {
            $this->options['showColumn3'] = true;
        }
        $this->setupColumnDefinitions();

        $q = $db->Execute(
            "select IF(v.ipnumber IS NULL,a.visitorid,concat(v.ipnumber,'##',v.visitorid,'##',v.customlabel)) as ip,FROM_UNIXTIME(timestamp, '%d-%b-%Y %a') AS days, count(*) from {$this->surveytablename_results} as a LEFT JOIN {$this->profile->tablename_visitorids} as v on a.visitorid=v.visitorid where surveyid=" . $db->Quote(
                $this->surveyid
            ) . " and timestamp between " . $db->Quote($this->from) . " and " . $db->Quote(
                $this->to
            ) . " group by a.visitorid order by timestamp"
        );

        $button = "<a class='open_in_new_dialog btn btn-sm btn-default' type='_SURVEYS' href=\"reports.php?labels=_SURVEYS&conf={$this->profile->profilename}&from={$this->from}&to={$this->to}&surveyid={$this->surveyid}&visitorid=%VID%\">View Answers</a>";

        $ndata = [];
        $i = 0;
        while ($row = $q->FetchRow()) {
            $ndata[$i][0] = $row[0];
            $ndata[$i][1] = $row[1];
            $ndata[$i][2] = $row[2];
            if (strpos($row[0], '##') !== false) {
                $vid = explode("##", $row[0]);
                $vid = $vid[1];
            } else {
                $vid = $row[0];
            }
            $ndata[$i][3] = str_replace("%VID%", $vid, $button);
            $i++;
        }
        if (empty($ndata)) {
            return;
        }

        echo "<div class='survey_div {$id}'>";
        echo "<h2 class='survey_table_header' rel='Stats'>All Participants</h2>";
        echo "<div class='survey_tableStats'>";

        $this->Table($ndata);
        echo "</div>";
        echo "</div>";
        echo "<div style='clear:both;'></div>";
    }

    function DefineReport()
    {
        if (empty($this->action)) {
            $this->action = "surveyoverview";
        }
        $this->Jscript();

        if ($this->action == "saveSurvey") {
            $this->Save();
            $this->edit = 0;
        } else {
            if ($this->action == "savequestion") {
                $this->RewriteAnswerRules();
                $this->RewriteQuestionRules();
                $this->Save();
                $this->edit = 0;
            }
        }

        $this->Toppanel();

        echo "<div class='col-xs-12'>";
        switch ($this->action) {
            case "surveyoverview":
                $this->ListSurveys();
                break;
            case "cleardata":
                $this->ClearData();
                $this->ListSurveys();
                break;

            case "orderlist":
                $this->ReorderQuestions(stdToAssoc(json_decode($_REQUEST['orderlist'])));
                break;

            case "createsurvey":
                $this->CreateSurvey();
                break;

            case "deletesurvey":
                $this->DeleteSurvey();
                break;

            case "saveSurvey":
            case "savequestion":
            case "createquestion":
                $this->CreateQuestion();
                break;

            case "editsurvey":
                $this->edit = 1;
                $this->CreateSurvey();
                break;

            case "editquestion":
                $this->edit = 1;
                $this->CreateQuestion();
                break;

            case "deletequestion":
                $this->DeleteQuestion();
                $this->ListQuestions();
                break;

            case "questionsoverview":
                $this->ListQuestions();
                break;

            case "preview":
                $this->SurveyDialog();
                break;

            case "publish":
                $this->Publish();
                break;
        }
        echo "</div>";
    }

    function Jscript()
    {
        ?>
        <script type="text/javascript">
            $(document).ready(function () {
                var action = "<?php echo $this->action; ?>";
                $(".nav-tabs-custom li[data-action='" + action + "']").addClass("active");


                $("#define-_SURVEYS").on({
                    mouseenter: function () {
                        $(".surveys").css("display", "block");
                    },
                    mouseleave: function () {
                        $(".surveys").css("display", "none");
                        $("#define-_SURVEYS").on({
                            mouseenter: function () {
                                $(".surveys").css("display", "block");
                            },
                            mouseleave: function () {
                                $(".surveys").css("display", "none");
                            }
                        }, ".surveys");
                    }
                }, ".surveysBtn");

                $("#define-_SURVEYS").on({
                    mouseenter: function () {
                        $(".questions").css("display", "block");
                    },
                    mouseleave: function () {
                        $(".questions").css("display", "none");
                        $("#define-_SURVEYS").on({
                            mouseenter: function () {
                                $(".questions").css("display", "block");
                            },
                            mouseleave: function () {
                                $(".questions").css("display", "none");
                            }
                        }, ".questions");
                    }
                }, ".questionsBtn");


                $("#define-_SURVEYS #answer_type").on("change", function () {
                    type = $(this).val();
                    if (type != "open" && type != "input") {
                        $("#answersrow").css("display", "");
                    } else {
                        $("#answersrow").css("display", "none");
                    }
                    if (type == "single") {
                        $(".answersetttings").css("display", "");
                    } else {
                        $(".answersetttings").css("display", "none");
                    }
                });

                $("#define-_SURVEYS").on("click", ".answersetttings", function () {
                    $("#settingsform").modal('show');


                    $(".settingsform_selector").attr("rel", $(this).attr("rel"));
                    $(".settingsform_input").attr("rel", $(this).attr("rel"));
                    $(".add_other_field").attr("rel", $(this).attr("rel"));

                    var labl = '<?php echo _ANSWER_X_SETTINGS; ?>';
                    labl = labl.replace('%X%', $(this).attr("rel"));

                    $(".settingsform_header").html(labl);

                    if ($(this).attr("value").indexOf("url:") !== -1) {
                        $("#linkquestions").css("display", "none");
                        $('.settingsform_selector option')[1].selected = true;
                        $(".settingsform_input").css("display", "block");
                        set_url = $(this).attr("value").replace("url:", "");
                        $(".settingsform_input").attr("value", set_url);
                    }
                    if ($(this).attr("value").indexOf("url:") !== -1) {
                        $("#linkquestions").css("display", "none");
                        $('.settingsform_selector option')[1].selected = true;
                        $(".settingsform_input").css("display", "block");
                        set_url = $(this).attr("value").replace("url:", "");
                        $(".settingsform_input").attr("value", set_url);

                    } else if ($(this).attr("value").indexOf("link (") !== -1) {
                        $(".settingsform_input").css("display", "none");
                        $('.settingsform_selector option')[2].selected = true;
                        $("#linkquestions").css("display", "block");
                        set_opt = $(this).attr("value").replace("link (", "");
                        set_opt = set_opt.split(")");
                        $("#linkquestions option").each(function () {
                            if ($(this).attr("rel") == set_opt[0]) {
                                $(this).attr("selected", "selected");
                            }
                        });
                    } else if ($(this).attr("value").indexOf("default") !== -1) {
                        $(".settingsform_input").css("display", "none");
                        $("#linkquestions").css("display", "none");
                        $('.settingsform_selector option')[0].selected = true;
                    }


                    if ($("#addtext" + $(this).attr("rel")).attr("value") == "block") {
                        $(".add_other_field").attr('checked', true);
                    } else {
                        $(".add_other_field").attr("checked", false);
                    }
                });

                $("#define-_SURVEYS").on("click", ".settingsform_close", function () {
                    $("#settingsform").css("display", "none");
                });

                $("#define-_SURVEYS").on("change", ".settingsform_selector", function () {
                    sel = $(".settingsform_selector option:selected").attr("name");

                    var i = $(".settingsform_selector").attr("rel");

                    if (sel == "url") {
                        $(".settingsform_input").css("display", "block");
                        $("#settings" + i).attr("value", "url: ");
                    } else {
                        $(".settingsform_input").css("display", "none");
                    }
                    if (sel == "default") {
                        $("#settings" + i).attr("value", "default");
                    }
                    if (sel == "end") {
                        $("#settings" + i).attr("value", "<?php echo _DONE; ?>");
                    }
                    if (sel == "link") {
                        linkid = $("#linkquestions option:selected").attr("rel");
                        linkval = $("#linkquestions").val();
                        $("#linkquestions").css("display", "block");

                        linkval = linkval.slice(0, 7) + "...";

                        $("#settings" + i).attr("value", "link (" + linkid + ") " + linkval);

                    } else {
                        $("#linkquestions").css("display", "none");
                    }
                });

                $(".settingsform_input").keyup(function (event) {
                    c = $(this).attr("rel");
                    v = $(this).val();
                    $("#settings" + c).attr("value", "url: " + v);
                });

                $("#define-_SURVEYS").on("change", "#linkquestions", function () {
                    linkid = $("#linkquestions option:selected").attr("rel");
                    linkval = $("#linkquestions").val("value");
                    $("#settings" + $(".settingsform_selector").attr("rel")).attr("value", "link (" + linkid + ") " + linkval);
                });

                $("#define-_SURVEYS").on("click", ".add_other_field", function () {
                    if ($(this).is(":checked") == true) {
                        $("#addtext" + $(this).attr("rel")).attr("value", "block");
                    } else {
                        $("#addtext" + $(this).attr("rel")).attr("value", "none");
                    }
                });
            });
        </script><?php
    }

    function Save()
    {
        global $db;
        if (empty($_REQUEST["surveyid"])) {
            $cd = time();
            $ar["closingmsg"] = $_REQUEST["closingmsg"];
            $ar["only_once"] = $_REQUEST["only_once"];
            $_REQUEST["surveyoptions"] = json_encode($ar);

            $db->Execute(
                "insert into {$this->surveytablename} (surveyname, surveydesc, surveyoptions) values ('" . $_REQUEST["surveyname"] . "','" . $_REQUEST["surveydesc"] . "','" . $_REQUEST["surveyoptions"] . "')"
            );
            $this->surveyid = $db->Insert_ID();
            return $this->surveyid;
        } else {
            if (isset($_REQUEST["edit"]) && !empty($_REQUEST["questionid"])) {
                $db->Execute(
                    "update {$this->surveytablename_questions} set question=\"" . $_REQUEST["question"] . "\", question_order=\"" . $_REQUEST["question_order"] . "\", question_type=\"" . $_REQUEST["answer_type"] . "\", question_rule=\"" . addslashes(
                        $_REQUEST["question_rule"]
                    ) . "\", answer_rule=\"" . addslashes(
                        $_REQUEST["answer_rule"]
                    ) . "\", surveyid=\"{$this->surveyid}\" where id=\"" . $_REQUEST["questionid"] . "\""
                ) or die ($db->ErrorMsg());
            } else {
                if (isset($_REQUEST["edit"]) && empty($_REQUEST["questionid"])) {
                    $ar["closingmsg"] = addslashes($_REQUEST["closingmsg"]);
                    $ar["only_once"] = $_REQUEST["only_once"];
                    $_REQUEST["surveyoptions"] = json_encode($ar);

                    $db->Execute(
                        "update {$this->surveytablename} set surveyname='" . $_REQUEST["surveyname"] . "',surveydesc='" . $_REQUEST["surveydesc"] . "',surveyoptions='" . $_REQUEST["surveyoptions"] . "' where id='{$this->surveyid}'"
                    ) or die ($db->ErrorMsg());
                } else {
                    // this is where we'll save a question.
                    $db->Execute(
                        "insert into {$this->surveytablename_questions} set question=\"" . $_REQUEST["question"] . "\", question_order=\"" . $_REQUEST["question_order"] . "\", question_type=\"" . $_REQUEST["answer_type"] . "\", question_rule=\"" . addslashes(
                            $_REQUEST["question_rule"]
                        ) . "\", answer_rule=\"" . addslashes(
                            $_REQUEST["answer_rule"]
                        ) . "\", surveyid=\"{$this->surveyid}\""
                    ) or die ($db->ErrorMsg());
                }
            }
        }
    }

    function RewriteAnswerRules()
    {
        $rules = [];

        foreach ($_REQUEST as $k => $v) {
            $a = strpos($k, 'cvalue');
            if ($a !== false) {
                $i = intval(substr($k, 6));

                $rules[$i]["answer"] = $v;
            }
            $o = strpos($k, 'addtext');
            if ($o !== false) {
                $i = intval(substr($k, 7));

                $rules[$i]["otherBox"] = $v;
            }
            $s = strpos($k, 'settings');
            if ($s !== false) {
                $i = intval(substr($k, 8));

                $rules[$i]["otherBox"] = "";
                $rules[$i]["default"] = "";
                $rules[$i]["url"] = "";
                $rules[$i]["link"] = "";
                $rules[$i]["end"] = "";
                $rules[$i]["code"] = "";


                if (strpos($v, 'default') !== false) {
                    $rules[$i]["default"] = 1;
                }
                if (strpos($v, "End") !== false || strpos($v, _DONE) !== false) {
                    $rules[$i]["end"] = 1;
                }
                if (strpos($v, 'url:') !== false) {
                    $v = str_replace("url: ", "", $v);
                    $rules[$i]["url"] = $v;
                }
                if (strpos($v, 'link (') !== false) {
                    $v = str_replace("link (", "", $v);
                    $v = explode(")", $v);
                    $v = $v[0];
                    $rules[$i]["link"] = intval($v);
                }
                if (strpos($v, 'code:') !== false) {
                    $v = str_replace("code:", "", $v);
                    $rules[$i]["code"] = $v;
                }
            }
        }

        if ($_REQUEST['answer_type'] == "single") {
            $_REQUEST["answer_rule"] = json_encode($rules);
        } else {
            $_REQUEST["answer_rule"] = "[]";
        }
    }

    function RewriteQuestionRules()
    {
        $answers = [];
        $options = [];

        foreach ($_REQUEST as $k => $v) {
            $cv = strpos($k, 'cvalue');
            $ad = strpos($k, 'addtext');

            if ($cv !== false) {
                $answers[] = $v;
            } else {
                if ($ad !== false) {
                    $options[] = $v;
                }
            }
        }
        $_REQUEST["question_rule"] = json_encode(
            array("answers" => $answers, "options" => $options, "a_type" => $_REQUEST["answer_type"])
        );
    }

    function Toppanel()
    {
        global $db;
        if (CheckIfTableExists($this->surveytablename)) {
            $q = $db->Execute("select id,surveyname from {$this->surveytablename} where status=1");
        }
        if (!$q) {
            // Probably no table.  When we create a test, we'll create the table.
        }

        $link = "definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS";


        echo "<div class='nav-tabs-custom'>";
        echo "<ul class='nav nav-tabs'>";
        echo "<li data-action='surveyoverview'><a class='surveysBtn' href='{$link}&action=surveyoverview'>" . _SURVEYS . " <span class='caret'></span></a></li>";
        echo "<li data-action='createsurvey'><a href='{$link}&action=createsurvey'>" . _ADD_SURVEY . "</a></li>";

        if (!empty($this->surveyid)) {
            echo "<li data-action='questionsoverview'><a class='questionsBtn' href='{$link}&action=questionsoverview&surveyid={$this->surveyid}'>" . _QUESTIONS . " <span class='caret'></span></a></li>";
            echo "<li data-action='createquestion'><a href='{$link}&action=createquestion&surveyid={$this->surveyid}'>" . _ADD_QUESTION . "</a></li>";
            echo "<li data-action='preview'><a href='{$link}&action=preview&surveyid={$this->surveyid}'>" . _PREVIEW . "</a></li>";
            echo "<li data-action='publish'><a href='{$link}&action=publish&surveyid={$this->surveyid}'>" . _PUBLISH . "</a></li>";
        }
        if (!empty($this->surveyid)) {
            echo "<li class='pull-right'><a href='{$link}&action=deletesurvey&surveyid=" . $this->surveyid . "' onclick=\"return confirm('" . _LAST_CHANCE_TO_CANCEL . "')\"><i class='fa fa-trash'></i></a></li>";
            echo "<li class='pull-right'><a href='{$link}&action=editsurvey&surveyid=" . $this->surveyid . "'><i class='fa fa-edit'></i></a></li>";
        }
        echo "</ul>";
        echo "</div>";

        if (!empty($this->surveyid)) {
            echo "<h4>" . $this->GetSurveyName() . "</h4>";
        }

        echo "<ul class='surveys dropdown-menu'>";
        $i = 0;
        while (($q) && ($data = $q->FetchRow())) {
            # ignore this in the menu if the survey is going to be deleted
            if ($this->action == "deletesurvey" && $data['id'] == $this->surveyid) {
                continue;
            }
            echo "<li><a href='definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS&surveyid=" . $data['id'] . "&action=questionsoverview'>({$data['id']}) {$data["surveyname"]}</a></li>";
            $i++;
        }
        if ($i == 0) {
            echo "<li><a>" . _NONE . "</a></li>";
        }
        echo "</ul>";

        if (!empty($this->surveyid)) {
            $q = $db->Execute(
                "select id, question from {$this->surveytablename_questions} where surveyid = {$this->surveyid} order by question_order, id"
            );
            echo "<ul class='questions dropdown-menu'>";
            $i = 0;
            while (($q) && ($data = $data ?? $q->FetchRow())) {
                $label = (strlen($data['question']) > 25) ? substr(
                        $data['question'],
                        0,
                        25
                    ) . "..." : $data['question'];

                echo "<li><a title='{$data['question']}' href='definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS&questionid=" . $data['id'] . "&action=editquestion&surveyid={$this->surveyid}'>({$data['id']}) {$label}</a></li>";
                $i++;
            }
            if ($i == 0) {
                echo "<li><a>" . _NONE . "</a></li>";
            }
            echo "</ul>";
        }
    }

    function ListSurveys()
    {
        global $db;
        $q = $db->Execute("select * from {$this->surveytablename} order by id");
        $i = 0;
        echo "<h3>" . _SURVEYS . ":</h3>";
        echo "<table class='table'>";
        echo "<tr class='overview'><td>ID</td><td>" . _NAME . "</td><td>" . _DESCRIPTION . "</td><td>" . _EDIT . "</td><td>" . _DELETE_DATA . "</td><td>" . _DELETE . "</td></tr>";

        while (($q) && ($data = $data ?? $q->FetchRow())) {
            $link = "definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS&surveyid={$data['id']}";

            echo "<tr class='overview'>
				<td>{$data['id']}</td>
				<td><a href='{$link}&action=questionsoverview'>" . $data['surveyname'] . "</a></td>
				<td>{$data['surveydesc']}</td>
				<td><a href='{$link}&action=editsurvey'><i class='fa fa-edit'></i></a></td>
				<td><a href='{$link}&action=cleardata'><i class='fa fa-eraser'></i></a></td>
				<td><a href='{$link}&action=deletesurvey' onclick=\"return confirm('" . _LAST_CHANCE_TO_CANCEL . "')\"><i class='fa fa-trash'></i></a></td>
			</tr>";
            $i++;
        }

        if ($i == 0) {
            echo "<tr class='overview'><td></td><td>" . _NO_SURVEYS_FOUND . "</td><td></td><td></td></tr>";
        }
        echo "</table>";
    }

    function ClearData()
    {
        global $db;
        $db->Execute(
            "delete from {$this->surveytablename_results} where surveyid=" . $db->Quote($this->surveyid)
        ) or die ($db->ErrorMsg());
        echoNotice(_SURVEY_CLEARED_DATA);
    }

    function ReorderQuestions($new_orderlist = [])
    {
        global $db;

        foreach ($new_orderlist as $key => $val) {
            $query = "UPDATE {$this->surveytablename_questions} SET question_order = {$key} WHERE id = {$val}";
            echo $query . "<br/>";
            $db->Execute($query);
        }
    }

    function CreateSurvey()
    {
        if ($this->action == "editsurvey") {
            $data = $this->getSurveyData();
            $opts = json_decode($data["surveyoptions"], true);
            $data["closingmsg"] = $opts["closingmsg"];
            $data["only_once"] = $data["only_once"] ?? $opts["only_once"];
        }
        echo "<div class='col-xs-12'>";
        echo "<font size='3'><b>" . _CREATE_NEW_SURVEY . "</b></font>";
        echo "<ul><li>" . _NEW_SURVEY_STEP_1 . "</li><li>" . _NEW_SURVEY_STEP_2 . "</li><li>" . _NEW_SURVEY_STEP_3 . "</li></ul>";
        echo _LETS_START_SURVEY . "<hr noshade size=1>";
        echo "</div>";

        echo "<form method='POST' action='definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS'>";

        echo "<div class='form-group'>
				<label>" . _SURVEY_NAME . "</label>
				<input placeholder=\"" . _SURVEY_NAME_DESC . "\" class='form-control' type='text' size='35' name='surveyname' maxval='255' value='" . isset($data["surveyname"]) . "' />
			</div>";

        echo "<div class='form-group'>
				<label>" . _SURVEY_DESCRIPTION . "</label>
				<textarea placeholder=\"" . _SURVEY_DESCRIPTION_DESC . "\" class='form-control' name='surveydesc' cols='30' rows='5' maxval='255'>" . isset($data["surveydesc"]) . "</textarea>
			</div>";

        echo "<div class='form-group'>
				<label>" . _SURVEY_CLOSE_MESSAGE . "</label>	
				<textarea placeholder=\"" . _SURVEY_CLOSE_MESSAGE_DESC . "\" class=\"form-control\" cols='30' rows='5' id='closingmsg' name='closingmsg'>" . isset($data["closingmsg"]) . "</textarea>
			</div>";

        $one = "";
        $many = "";
        if (!empty($data['only_once'])) {
            $one = "selected";
        } else {
            $many = "selected";
        }
        echo "<div class='form-group'>
				<label>People can take this survey</label>	
				<select name='only_once' class='form-control'>
					<option value='true' $one>Only Once</option>
					<option value='' $many>As many times as they like</option>
				</select>
			</div>";


        if (!empty($this->edit) && $this->edit == 1) {
            echo "<input type=hidden name=edit value='1'>";
            echo "<input type=hidden name=surveyid value='{$this->surveyid}'>";
        } else {
            echo "<input type=hidden name=surveyid value='0'>";
        }
        echo "<input class='btn btn-primary' type='submit' value=" . _SAVE . ">";
        echo "<input type='hidden' name='action' value='saveSurvey'>";
        echo "<input type='hidden' name='conf' value='{$this->profile->profilename}'>";
        echo "</form>";
    }

    function getSurveyData()
    {
        global $db;
        $q = $db->Execute("select * from {$this->surveytablename} where id='{$this->surveyid}'");
        while (($q) && ($data = $q->FetchRow())) {
            return $data;
        }
    }

    function DeleteSurvey()
    {
        global $db;
        $db->Execute(
            "delete from {$this->surveytablename} where id=" . $db->Quote($this->surveyid)
        ) or die ($db->ErrorMsg());
        $db->Execute(
            "delete from {$this->surveytablename_questions} where surveyid=" . $db->Quote($this->surveyid)
        ) or die ($db->ErrorMsg());
        $db->Execute(
            "delete from {$this->surveytablename_results} where surveyid=" . $db->Quote($this->surveyid)
        ) or die ($db->ErrorMsg());
        echoNotice(_SURVEY_DELETED_INFO . " ..");
        echoNotice(_SURVEY_DELETED_QUESTIONS . " ..");
        echoNotice(_SURVEY_DELETED_RESULTS . " ..");
        echoNotice(_SURVEY_DELETED_FINISHED . "!");
        $this->surveyid = "";
    }

    function CreateQuestion()
    {
        global $db;

        $data["a_type"] = "single";
        if ($this->action == "editquestion") {
            $data = $this->getQuestionData();
            $data["answer_rule"] = json_decode($data["answer_rule"], true);
        }
        if (empty($data["question_order"])) {
            $q = $db->Execute(
                "SELECT COUNT(*) AS amount_of_questions FROM {$this->surveytablename_questions} WHERE surveyid = {$this->surveyid}"
            );
            $amount = $q->FetchRow();

            $data["question_order"] = $amount[0] + 1;
        }
        $selected = "";

        echo "<form name='editor' method=POST action='definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS&surveyid={$this->surveyid}'>";
        echo "<h3>" . _ADD_QUESTION_TO . ": " . $this->GetSurveyName() . "</h3>";
        echo "<span>" . _ADD_QUESTION_TO_DESC . "</span>";

        echo "<div class='form-group'>";
        echo "<label>" . _QUESTION . "</label>";
        echo "<input class='form-control' type='text' name='question' size='60' value=\"" . isset($data["question"]) . "\">";
        echo "</div>";

        echo "<div class='form-group'>";
        echo "<label>" . _QUESTION_ORDER . "</label>";
        echo "<input class='form-control' type='text' name='question_order' size='3' value=\"" . isset($data["question_order"]) . "\">";
        echo "</div>";

        $options = array(
            "single" => _SINGLE_ANSWER,
            "input" => "Single Input",
            "multiple" => _MULTIPLE_ANSWERS,
            "open" => _OPEN_ANSWERS
        );

        echo "<div class='form-group'>";
        echo "<label>" . _TYPE . "</label>";
        echo "<select class='form-control' id='answer_type' name='answer_type'>";
        foreach ($options as $k => $v) {
            if ($data["a_type"] == $k) {
                $selected = "selected='selected'";
            } else {
                $selected = "";
            }
            echo "<option name='{$k}' value='{$k}' {$selected}>{$v}</option>";
        }
        echo "</select>";
        echo "</div>";


        if ($data["a_type"] == "open" || $data["a_type"] == "input") {
            $style = "style='display:none;'";
        } else {
            $style = "";
        }
        echo "<div id='answersrow' {$style}>";
        echo "<span>" . _ANSWERS . ":</span>";

        $condition_options = [];
        if (!empty($data["answers"])) {
            foreach ($data["answers"] as $option => $val) {
                $condition_options['cvalue'][] = $val;
            }
        }
        $form_id = md5(time());
        $form = "<script type='text/javascript'>plusMinusForm('{$form_id}','cvalue','settings','addtext', undefined , 0);</script>";
        echo "<div id='{$form_id}' class='report-options form-group'>";
        if (count($condition_options) == 0) {
            $form .= "<div class='conditions_row'>
							<div class='input-group'>
									<input type='hidden' id='addtext0' name='addtext0' rel='0' value='' />
		                            <input class='form-control' src='cvalue' rel='0' name='cvalue0' id='cvalue0' autocomplete='off'>
		                            <div class='input-group-btn'>
		                                <a class='btn btn-default plus_btn'>+</a>
		                                <a class='btn btn-default min_btn' disabled='disabled'>-</a>
		                                <input type='text' readonly src='settings' id='settings0' name='settings0' class='btn btn-info answersetttings' value='default' rel='0' />
		                            </div>
		                        </div>
							</div>	
						</div>";
        } else {
            for ($c = 0; $c < count($condition_options['cvalue']); $c++) {
                $set = "default";
                if (!empty($data["answer_rule"][$c]["url"])) {
                    $set = "url: " . $data["answer_rule"][$c]["url"];
                }
                if (!empty($data["answer_rule"][$c]["link"])) {
                    $set = "link (" . $data["answer_rule"][$c]["link"] . ")";
                }
                if (!empty($data["answer_rule"][$c]["end"])) {
                    $set = _DONE;
                }

                if ($data["a_type"] != "single") {
                    $d = "style='display:none;'";
                } else {
                    $d = "";
                }
                if ($c == 0) {
                    $mh = "disabled='disabled'";
                } else {
                    $mh = "";
                }

                $form .= "<div class='conditions_row'>
								<div class='input-group'>
									<input type='hidden' src='addtext' id='addtext" . $c . "' name='addtext" . $c . "' rel='" . $c . "' value='" . isset($data["options"][$c]) . "' />
		                            <input class='form-control' src='cvalue' rel='" . $c . "' name='cvalue" . $c . "' id='cvalue" . $c . "' value=\"" . stripslashes(
                        $condition_options['cvalue'][$c]
                    ) . "\" autocomplete='off'>
		                            <div class='input-group-btn'>
		                                <a class='btn btn-default plus_btn'>+</a>
		                                <a class='btn btn-default min_btn' {$mh}>-</a>
		                                <input type='text' readonly src='settings' id='settings" . $c . "' name='settings" . $c . "' class='btn btn-info answersetttings' rel='" . $c . "' {$d} value='{$set}' />
		                            </div>
		                        </div>
							</div>";
            }
        }
        echo $form;
        echo "</div>";

        if (!empty($this->edit) && $this->edit == 1) {
            echo "<input type='hidden' name='edit' value='1' />";
            echo "<input type='hidden' name='questionid' value='{$this->questionid}' />";
        }

        echo "<input type=hidden name=surveyid value=\"{$this->surveyid}\" />";
        echo "<input type=hidden name=surveyname value=\"" . $this->GetSurveyName() . "\" />";
        echo "<input type=hidden name=action value=\"savequestion\" />";
        echo "<input type=hidden name=conf value=\"{$this->profile->profilename}\" />";

        echo "</div>";
        echo "<div class='form-group'>";
        echo "<input class='btn btn-primary' type='submit' value='" . _SAVE_QUESTION . "'>";
        echo "</div>";
        echo "</form>";
        $this->aSettings();
    }

    function getQuestionData()
    {
        global $db;
        $q = $db->Execute("select * from {$this->surveytablename_questions} where id={$_REQUEST['questionid']}");
        while (($q) && ($data = $q->FetchRow())) {
            if (!empty($data["question_rule"])) {
                $d = json_decode($data["question_rule"], true);
                $data["answers"] = $d['answers'];
                $data["options"] = $d['options'];
                $data["a_type"] = $d['a_type'];
            }
            return $data;
        }
    }

    function aSettings()
    {
        global $db;
        echo "<div id='settingsform' class='modal' role='dialog'>";
        echo "<div class='modal-dialog'>";
        echo "<div class='modal-content'>";
        echo "<div class='modal-header'>";
        echo "<button type='button' class='close' data-dismiss='modal'>&times;</button>";
        echo "<h4 class='modal-title settingsform_header'></h4>";
        echo "</div>";
        echo "<div class='modal-body'>";
        echo "<div class='form-group'>";
        echo "<select class='settingsform_selector form-control'><option name='default'>" . _NEXT_QUESTION . " (" . _DEFAULT . ")</option><option name='url'>" . _LINK_TO_URL . "</option><option name='link'>" . _LINK_TO_QUESTION . "</option><option name='end'>" . _LINK_TO_END . "</option></select>";
        echo "</div>";

        echo "<div class='form-group'>";
        echo "<input class='form-control settingsform_input' style='display:none;' />";

        echo "<select class='form-control' id='linkquestions' style='display:none;'>";
        $q = $db->Execute(
            "SELECT id,question FROM {$this->surveytablename_questions} where surveyid={$this->surveyid} order by question_order, id"
        );
        while (($q) && ($data = $q->FetchRow())) {
            if ($this->questionid != $data["id"]) {
                echo "<option rel='{$data["id"]}'>{$data["question"]}</option>";
            }
        }
        echo "</select>";
        echo "</div>";

        echo "</div>";
        echo "<div class='modal-footer'>";
        echo "<button class='btn btn-default' data-dismiss='modal'>" . _CLOSE . "</button>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
    }

    function DeleteQuestion()
    {
        global $db;
        $db->Execute(
            "delete from {$this->surveytablename_questions} where id=" . $db->Quote($_REQUEST['questionid'])
        ) or die ($db->ErrorMsg());
    }

    function ListQuestions()
    {
        global $db, $profile;
        if (CheckIfTableExists($this->surveytablename_questions) && isset($this->surveyid)) {
            $q = $db->Execute(
                "select id,question from {$this->surveytablename_questions} where surveyid={$this->surveyid} order by question_order, id"
            );
        }
        $i = 0;
        echo "<h3>" . _QUESTIONS . ":</h3>";
        echo "<table id='surveyquestions' class='table'>";
        echo "<tr class='overview'><td>ID</td><td>" . _QUESTION . "</td><td>" . _EDIT . "</td><td>" . _DELETE . "</td></tr>";
        while (($q) && ($data = $data ?? $q->FetchRow())) {
            $link = "definereport.php?conf={$this->profile->profilename}&labels=_SURVEYS&questionid={$data['id']}&surveyid={$this->surveyid}";

            echo "<tr class='overview'>
				<td>{$data['id']}</td>
				<td>{$data['question']}</td>
				<td><a href='{$link}&action=editquestion'><i class='fa fa-edit'></i></a></td>
				<td><a href='{$link}&action=deletequestion'><i class='fa fa-trash'></i></a></td>
			</tr>";
            $i++;
        }
        if ($i == 0) {
            echo "<tr class='overview'><td></td><td>" . _NONE . "</td><td></td><td></td></tr>";
        }
        echo "</table>";
    }

    function SurveyDialog()
    {
        $w_path = $_SERVER['PHP_SELF'];
        $wpath = dirname($w_path);
        echo "<div style='margin:10px;'><!-- /* Logaholic Web Analytics Code */ -->
			<link type=\"text/css\" rel=\"stylesheet\" href=\"" . Logaholic_URL() . "/survey.css\">
			<script type=\"text/javascript\">
			if (document.location.protocol==\"https:\") { var ptcl = \"https:\" } else { var ptcl = \"http:\" }
			var lwa_profile = \"{$this->profile->profilename}\";
			var lwa_server = ptcl + \"//{$_SERVER['HTTP_HOST']}{$wpath}/\";";
        if (!empty($_SESSION['dbid'])) {
            echo "var lwa_dbid = {$_SESSION['dbid']};";
        }
        echo ">
			var lwa_survey = LwaSurvey({$this->surveyid})
			</script></div>";
    }

    function Publish()
    {
        global $db, $lang;
        $q = $db->Execute("SELECT * FROM {$this->surveytablename} WHERE id='{$this->surveyid}'");
        while (($q) && ($data = $q->FetchRow())) {
            $opts = json_decode($data["surveyoptions"], true);
            echo "<h3>" . _PUBLISH . "</h3>";
            echo "<p>" . _PUBLISH_SURVEY_DESC . "</p>";
            echo "<div class='copy_tracking_div col-xs-12'>";
            $w_path = $_SERVER['PHP_SELF'];
            $wpath = dirname($w_path);
            echo "<pre>&lt;!-- /* Logaholic Web Analytics Code */ --&gt;
&lt;link type=\"text/css\" rel=\"stylesheet\" href=\"" . Logaholic_URL() . "/survey.css\"&gt;
&lt;script type=\"text/javascript\"&gt;
if (document.location.protocol==\"https:\") { var ptcl = \"https:\" } else { var ptcl = \"http:\" }
var lwa_profile = \"{$this->profile->profilename}\";
var lwa_server = ptcl + \"//{$_SERVER['HTTP_HOST']}{$wpath}/\";";
            if (!empty($_SESSION['dbid'])) {
                echo "var lwa_dbid = {$_SESSION['dbid']};";
            }
            echo "document.write(unescape(\"%3Cscript type='text/javascript' src='\" + lwa_server + \"survey.js'%3E%3C/script%3E\"));
&lt;/script&gt;
&lt;script type=\"text/javascript\"&gt;
var lwa_survey = LwaSurvey({$this->surveyid});
&lt;/script&gt;</pre>";
            echo "</div>";
        }
    }

    function UpdateStats($from = '', $to = '', $print = 2)
    {
        return false;
    }
}