<?php

/**
 * @desc This report allows a user to set a goal
 */

$reports["_GOALS"] = array(
    "ClassName" => "Goals",
    "Category" => "_PERFORMANCE",
    "canAggregate" => false,
    "icon" => "images/icons/32x32/goals.png",
    "Options" => "daterangeField,profileselector,trafficsource",
    "Filename" => "goals",
    "Distribution" => "Premium",
    "Order" => 11,
    "hidden" => 0,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 3.0,
    "EmailAlerts" => false,
    "Update" => false
);

class Goals extends Report
{

    function Settings()
    {
        global $db;
        $this->help = _GOALS_EXPLANATION;
        $this->reportButtons = 0;
        $this->displayReportButtons = false;
        $this->remove_outputmodes = array("xml", "csv", "mail");


        $db->Execute(
            "CREATE OR REPLACE TABLE  `" . TBL_GOALS . "` (
				`goalID` int(11) NOT NULL AUTO_INCREMENT,
				`goalName` varchar(100) DEFAULT NULL,
				`timeunit` varchar(100) DEFAULT NULL,
				`targetValue` varchar(11) DEFAULT NULL,
				`metric` varchar(50) DEFAULT NULL,
				`conditions` text,
				`graphType` varchar(50) DEFAULT 'speed',
				`profileID` int(11) DEFAULT NULL,
				`inverse` int(1) DEFAULT NULL,
				`kpi` varchar(100) DEFAULT NULL,
				PRIMARY KEY (`goalID`)
			) ENGINE=MyISAM  CHARSET=utf8"
        );
    }

    function DisplayReport()
    {
        $q = $this->DefineQuery();
        if (empty($q)) {
            $this->Welcome();
            return false;
        }

        $data = $this->GetReportData();

        if (empty($data)) {
            $this->ReportHeader();
            echoWarning(_NO_DATA_TO_DISPLAY, "margin:5px;");
            return false;
        }

        $this->goal['inverse'] = 0; // We need to change this once we implement bouncerate

        $this->ReportHeader();

        if (($data['trend'] > 0 && $this->goal['inverse'] == 1) || ($data['trend'] < 0 && $this->goal['inverse'] == 0)) {
            $direction = "down";
            $trend_plus_minus = '';
        } elseif (($data['trend'] > 0 && $this->goal['inverse'] == 0) || ($data['trend'] < 0 && $this->goal['inverse'] == 1)) {
            $direction = "up";
            $trend_plus_minus = '+';
        } else {
            $direction = "even";
            $trend_plus_minus = '';
        }

        if ($data['currentValue'] != 0) {
            $risen_trend = $data['trend'];
        } else {
            $risen_trend = 0;
        }

        if ($risen_trend > 0) {
            $risen_trend = "+" . number_format($risen_trend, 0);
            $risen_color = "green";
        } else {
            $risen_color = "red";
        }

        if ($data['currentValue'] != 0) {
            $percentage = number_format((($data['currentValue'] / $this->goal['targetValue']) * 100), 2, ".", "");
        } else {
            $percentage = 0;
        }

        switch ($percentage) {
            case ($percentage >= number_format(500, 2, ".", "")) :
                $icon = "smile-flat";
                $color = "red";
                break;
            case ($percentage >= number_format(110, 2, ".", "") && $percentage < number_format(500, 2, ".", "")) :
                $icon = "smile-relax";
                $color = "green";
                break;
            case ($percentage >= number_format(100, 2, ".", "") && $percentage < number_format(110, 2, ".", "")) :
                $icon = "smile";
                $color = "green";
                break;
            case ($percentage >= number_format(90, 2, ".", "") && $percentage < number_format(100, 2, ".", "")) :
                $icon = "smile-fast";
                $color = "orange";
                break;
            case ($percentage >= number_format(50, 2, ".", "") && $percentage < number_format(90, 2, ".", "")) :
                $icon = "smile";
                $color = "black";
                break;
            case ($percentage > number_format(10, 2, ".", "") && $percentage <= number_format(50, 2, ".", "")) :
                $icon = "smile-flat2";
                $color = "black";
                break;
            case ($percentage <= number_format(10, 2, ".", "")) :
                $icon = "smile-shame";
                $color = "red";
                break;
            default:
                $icon = "smile";
                $color = "black";
        }

        $md5_time = md5(time()) . rand(1, 1000);

        switch ($this->goal['timeunit']) {
            case 'years':
                $timeunit_label = _PER_YEAR;
                break;
            case 'months':
                $timeunit_label = _PER_MONTH;
                break;
            case 'weeks':
                $timeunit_label = _PER_WEEK;
                break;
            default:
                $timeunit_label = _PER_DAY;
                break;
        }


        echo "<h2 style='text-align: center; color: #333; margin: 5px 0 0; font-size: 14px;'>{$this->goal['goalName']} ({$timeunit_label})</h2>";

        if ($data['currentValue'] >= $this->goal['targetValue']) {
            echo "<h2 style='text-align: center; color: green; margin-top: 5px; margin-bottom: 0; font-size: 12px;'>" . _CONGRATS_EXCEEDED_GOAL . " " . (ceil(
                        (($data['currentValue'] / $this->goal['targetValue']) * 100)
                    ) - 100) . "%!</h2>";
        }
        echo "<div class='graph_area' style='margin-top: 0;'>
			<div id='{$md5_time}' class='graphcontainer' style='width: 350px; height: " . round(350 / (5 / 3)) . "px; margin: 0 auto;'></div>
		</div>";

        $gauge_label = "<div style='width: 100%; text-align: center; color: #333; margin-bottom: 5px;'>";
        if ($this->goal['metric'] == 'conversion') {
            $gauge_label .= "<span style='color: {$color}; line-height: 22px;'><img style='vertical-align: middle;' src='images/{$icon}.gif' />" . _YOU_HAVE . " <strong>{$data['currentValue']}%</strong> " . _OF_THE . " " . _NEEDED . " <strong>{$this->goal['targetValue']}%</strong> {$this->goal['metric']}.</span><br/>";
        } else {
            $gauge_label .= "<span style='color: {$color}; line-height: 22px;'><img style='vertical-align: middle;' src='images/{$icon}.gif' />" . _YOU_HAVE . " <strong>{$data['currentValue']}</strong> " . _OF_THE . " <strong>{$this->goal['targetValue']}</strong> " . _NEEDED . " {$this->goal['metric']}.</span><br/>";
        }
        $gauge_label .= "<span style='color: {$risen_color}; line-height: 16px;'>" . _PROGRESS_TOWARDS_GOAL_IS_GOING . " {$direction}! ({$trend_plus_minus}{$data['trend']} " . _DAILY_TREND . ") </span>";
        $gauge_label .= "</div>";

        echo "<script type='text/javascript'>createGauge('{$md5_time}','',{$data['currentValue']},{$this->goal['targetValue']})</script>";

        echo $gauge_label;

        return;
    }

    function DefineQuery()
    {
        global $db;

        $this->getGoalData();

        if (!isset($this->goal['conditions'])) {
            $this->goal['conditions'] = "";
        }
        if ($this->goal['conditions'] == " AND") {
            $this->goal['conditions'] = "";
        }
        $additional_tables = "";
        $join_condition = "";

        if (empty($this->goal['timeunit'])) {
            $this->goal['timeunit'] = 'days';
        }
        if (is_numeric(strpos($this->goal['conditions'], 'url'))) {
            $additional_tables .= ", {$this->profile->tablename_urls} AS u";
            $join_condition .= " AND a.url = u.id";
        }
        if (is_numeric(strpos($this->goal['conditions'], 'up.params'))) {
            $additional_tables .= ", {$this->profile->tablename_urlparams} AS up";
            $join_condition .= " AND a.params = up.id";
        }
        if (is_numeric(strpos($this->goal['conditions'], 'referrer'))) {
            $additional_tables .= ", {$this->profile->tablename_referrers} AS r";
            $join_condition .= " AND a.referrer = r.id";
        }
        if (is_numeric(strpos($this->goal['conditions'], 'refparams'))) {
            $additional_tables .= ", {$this->profile->tablename_urlparams} AS rp";
            $join_condition .= " AND a.refparams = rp.id";
        }

        $nice_conditions = "";
        $tmp_conditions = [];
        $exploded_conditions = $this->breaksql($this->goal['conditions']);

        foreach ($exploded_conditions as $cond_key => $cond) {
            $c = 0;
            foreach ($cond as $cnd) {
                $tmp_conditions[$c][$cond_key] = $cnd;
                $c++;
            }
        }

        $c = 0;
        foreach ($tmp_conditions as $cond) {
            if (count($tmp_conditions) > 1 && $c != 0) {
                $nice_conditions .= " and ";
            }
            $nice_conditions .= "{$cond['field']} {$cond['condition']} {$cond['cvalue']}";
            $c++;
        }
        if (empty($this->goal['metric'])) {
            return false;
        }
        switch ($this->goal['metric']) {
            case "visitors":
                $this->addlabel .= _CONDITIONS . ": {$nice_conditions}";
                $query = "SELECT COUNT(DISTINCT(visitorid)) AS visitors, FROM_UNIXTIME(timestamp,'%d-%b-%Y %a') AS days FROM {$this->profile->tablename} AS a{$additional_tables} WHERE timestamp >= " . $db->Quote(
                        $this->from
                    ) . " AND timestamp <= " . $db->Quote(
                        $this->to
                    ) . "" . $this->goal['conditions'] . $join_condition . " AND (status = 200 or status = 302) GROUP BY days ORDER BY timestamp";
                break;
            case "pageviews":
                $this->addlabel .= _CONDITIONS . ": {$nice_conditions}";
                $query = "SELECT COUNT(*) AS pages, FROM_UNIXTIME(timestamp,'%d-%b-%Y %a') AS days FROM {$this->profile->tablename} AS a{$additional_tables} WHERE timestamp >= " . $db->Quote(
                        $this->from
                    ) . " AND timestamp <= " . $db->Quote(
                        $this->to
                    ) . "" . $this->goal['conditions'] . $join_condition . " AND (status = 200 or status = 302) GROUP BY days ORDER BY timestamp";
                break;
            case "conversion":
                $this->addlabel .= "KPI: {$this->goal['kpi']}";
                $query = "SELECT COUNT(DISTINCT(visitorid)) AS visitors, FROM_UNIXTIME(timestamp,'%d-%b-%Y %a') AS days FROM {$this->profile->tablename} WHERE timestamp >= " . $db->Quote(
                        $this->from
                    ) . " AND timestamp <= " . $db->Quote(
                        $this->to
                    ) . " AND (status = 200 or status = 302) GROUP BY days ORDER BY timestamp";
                $q = $db->Execute("SELECT avg(a.visitors) AS av FROM ($query) as a");

                $row = $q->FetchRow();
                $avg_visitors = $row['av'];

                $query = "SELECT (((COUNT(DISTINCT(visitorid))*1.00)/{$avg_visitors})*100) AS conversion, FROM_UNIXTIME(timestamp,'%d-%b-%Y %a') AS days FROM {$this->profile->tablename_conversions} WHERE timestamp >= " . $db->Quote(
                        $this->from
                    ) . " AND timestamp <= " . $db->Quote($this->to) . " AND url = " . getID(
                        $this->goal['kpi'],
                        'urls'
                    ) . " GROUP BY days ORDER BY timestamp";
                break;
            case "bouncerate":


                break;
            default:
                return false;
        }
        return $query;
    }

    function getGoalData()
    {
        global $db;
        if (!empty($this->goal_id)) {
            $q = $db->Execute(
                "SELECT * FROM " . TBL_GOALS . " WHERE profileID = {$this->profile->profileid} AND goalID = " . $db->Quote(
                    $this->goal_id
                )
            );
            $row = $q->FetchRow();
            if (!$row) {
                $row = [];
            }
            foreach ($row as $k => $v) {
                if (is_numeric($k)) {
                    unset($row[$k]);
                }
            }
            $this->goal = $row;
            return $row;
        } else {
            return false;
        }
    }

    function breaksql($sqlstring)
    {
        if (strpos($sqlstring, " AND ") !== false) {
            $rows = explode(" AND ", $sqlstring);
            $andor = "AND";
        } else {
            if (strpos($sqlstring, " OR ") !== false) {
                $rows = explode(" OR ", $sqlstring);
                $andor = "OR";
            } else {
                $rows[0] = $sqlstring;
                $andor = "AND";
            }
        }

        $conditions = [];
        $i = 0;

        if (empty($rows[$i])) {
            $i++;
        }
        while (isset($rows[$i]) != "") {
            if (strpos($rows[$i], " NOT LIKE ") != false) {
                $rsplit = explode(" NOT LIKE ", $rows[$i]);
                $conditions['condition'][$i] = "nocontain";
                $conditions['field'][$i] = str_replace(
                    "r.",
                    "",
                    str_replace(
                        "rp.",
                        "",
                        str_replace(
                            "u.",
                            "",
                            str_replace("up.", "", trim($rsplit[0]))
                        )
                    )
                );
                if (substr($rsplit[1], 0, 2) != "'%") {
                    $conditions['condition'][$i] = "nostart";
                    $conditions['cvalue'][$i] = substr($rsplit[1], 1, -2);
                } else {
                    $conditions['cvalue'][$i] = substr($rsplit[1], 2, -2);
                }
            } elseif (strpos($rows[$i], " LIKE ") != false) {
                $rsplit = explode(" LIKE ", $rows[$i]);
                $conditions['field'][$i] = str_replace(
                    "r.",
                    "",
                    str_replace(
                        "rp.",
                        "",
                        str_replace(
                            "u.",
                            "",
                            str_replace("up.", "", trim($rsplit[0]))
                        )
                    )
                );

                if (substr($rsplit[1], 0, 2) == "'%") {
                    $conditions['condition'][$i] = "end";
                    $conditions['cvalue'][$i] = substr($rsplit[1], 2, -1);
                }
                if (substr($rsplit[1], -2) == "%'") {
                    if (isset($conditions['condition'][$i]) == "") {
                        $conditions['condition'][$i] = "start";
                        $conditions['cvalue'][$i] = substr($rsplit[1], 1, -2);
                    } else {
                        $conditions['condition'][$i] = "contains";
                        $conditions['cvalue'][$i] = substr($rsplit[1], 2, -2);
                    }
                }
            } elseif (strpos($rows[$i], "!=") != false) {
                $rsplit = explode("!=", $rows[$i]);
                $conditions['condition'][$i] = "isnot";
                $conditions['field'][$i] = str_replace(
                    "r.",
                    "",
                    str_replace(
                        "rp.",
                        "",
                        str_replace(
                            "u.",
                            "",
                            str_replace("up.", "", trim($rsplit[0]))
                        )
                    )
                );
                $conditions['cvalue'][$i] = substr($rsplit[1], 1, -1);
            } elseif (strpos($rows[$i], "=") !== false) {
                $rsplit = strpos($rows[$i], "=");
                $conditions['condition'][$i] = "is";
                $conditions['field'][$i] = str_replace(
                    "r.",
                    "",
                    str_replace(
                        "rp.",
                        "",
                        str_replace(
                            "u.",
                            "",
                            str_replace(
                                "up.",
                                "",
                                trim(
                                    substr(
                                        $rows[$i],
                                        0,
                                        $rsplit
                                    )
                                )
                            )
                        )
                    )
                );
                $conditions['cvalue'][$i] = substr($rows[$i], ($rsplit + 2), -1);
            }
            $i++;
        }

        return $conditions;
    }

    function Welcome()
    {
        $this->ReportHeader();
        //echo _SELECT_GOAL_FROM_OPTIONS;
        echoNotice($this->SettingsButton() . _SELECT_GOAL_FROM_OPTIONS);
    }

    function GetReportData()
    {
        global $db;

        $query = $this->DefineQuery();
        if (empty($query)) {
            return false;
        }
        $q = $db->Execute(subsetDataToSourceID($query, $this->trafficsource));

        switch ($this->goal['metric']) {
            case "visitors":
                $metricValue = 'visitors';
                break;
            case "pageviews":
                $metricValue = 'pages';
                break;
            case "conversion":
                $metricValue = 'conversion';
                break;
            case "bouncerate":
                $metricValue = 'bouncerate';
                break;
            default:
                return false;
        }

        $avg_data = [];
        while ($row = $q->FetchRow()) {
            foreach ($row as $k => $v) {
                if (is_numeric($k)) {
                    unset($row[$k]);
                }
            }
            $data[] = $row;
            $avg_data[$row['days']] = $row[$metricValue];
        }

        $goaldata['goalName'] = $this->goal['goalName'];
        $goaldata['metric'] = $this->goal['metric'];
        $goaldata['targetValue'] = $this->goal['targetValue'];

        $goaldata['currentValue'] = getAverage($avg_data);

        switch ($this->goal['timeunit']) {
            case "years":
                $goaldata['currentValue'] = round($goaldata['currentValue'] * 365);
                break;
            case "months":
                $goaldata['currentValue'] = round($goaldata['currentValue'] * 30.5);
                break;
            case "weeks":
                $goaldata['currentValue'] = round($goaldata['currentValue'] * 7);
                break;
            default:
                $goaldata['currentValue'] = $goaldata['currentValue'];
                break;
        }

        switch ($this->goal['metric']) {
            case "visitors":
                $goaldata['currentValue'] = floor($goaldata['currentValue']);
                break;
            case "pageviews":
                $goaldata['currentValue'] = floor($goaldata['currentValue']);
                break;
            case "conversion":
                $goaldata['currentValue'] = number_format($goaldata['currentValue'], 2);
                break;
            case "bouncerate":

                break;
            default:
                return false;
        }


        $x = 0;
        foreach ($data as $k => $v) {
            $trenddata[$x][0] = $v['days'];
            $trenddata[$x][1] = $v[$metricValue];
            $x++;
        }

        $tmp_data = []; // do a little zerofill
        for ($c = 0; $c < count($trenddata); $c++) {
            if (!empty($trenddata[$c][1])) {
                $tmp_data[$c] = $trenddata[$c][1];
            } else {
                $tmp_data[$c] = 0;
            }
        }

        $goaldata['trend'] = getTrend($tmp_data);

        return $goaldata;
    }

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

        echo "<div class='form-group'>";
        if ($q = $db->Execute(
            "SELECT goalID, goalName FROM " . TBL_GOALS . " WHERE profileID = {$this->profile->profileid} ORDER BY goalName ASC"
        )) {
            echo "<label for='goal_id'>" . _PICK_A_GOAL . ":</label>";
            echo "<select id='goal_id' name='goal_id' class='report_option_field form-control'>";
            while ($data = $q->FetchRow()) {
                if ($this->goal_id == $data['goalID']) {
                    $selected = " selected='selected'";
                } else {
                    $selected = "";
                }
                echo "<option{$selected} value='{$data['goalID']}'>{$data['goalName']}</option>";
            }
            echo "</select>";
        }

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

    function DefineReport()
    {
        if (empty($this->goal_id) && empty($this->goal_action)) {
            # Nothing to do..
        } elseif ($this->goal_action == "save") {
            $message = $this->SaveGoal();
            $this->goal_action = "manage";
            if (isset($this->goal_id)) {
                $this->goal_action = "edit";
            }
        } else {
            if ($this->goal_action == "delete") {
                $message = $this->DeleteGoal();
                $this->goal_action = "manage";
            }
        }

        $this->Toppanel();

        if (isset($message)) {
            echo $message;
        }
        echo "<div class='goals-content'>";

        if (empty($this->goal_id) && empty($this->goal_action)) {
            $this->goal_action = "manage";
            $this->ManageGoals();
        } else {
            if ($this->goal_action == "create" || $this->goal_action == "edit") {
                $this->EditGoal();
            } else {
                if ($this->goal_action == "manage") {
                    $this->ManageGoals();
                } else {
                    if ($this->goal_action == "report") {
                        if (!$this->goal_id) {
                            $this->ManageGoals();
                        }
                    }
                }
            }
        }
        echo "</div>";
    }

    function SaveGoal()
    {
        global $db;

        $this->inverse = 0;

        $condition_options = [];
        foreach ($this->options as $option => $val) {
            if (substr($option, 0, 5) == 'field') {
                $condition_options['field'][] = $val;
            } elseif (substr($option, 0, 9) == 'condition') {
                $condition_options['condition'][] = $val;
            } elseif (substr($option, 0, 6) == 'cvalue') {
                $condition_options['cvalue'][] = $val;
            }
        }

        $mode = "and";

        if (!empty($condition_options)) {
            $this->conditions = $this->makesql($condition_options, $mode);
        } else {
            $this->conditions = "";
        }

        if (!empty($this->goal_id)) {
            $sql = "UPDATE " . TBL_GOALS . " SET goalName = " . $db->Quote(
                    $this->goalname
                ) . ", timeunit = " . $db->Quote($this->timeunit) . ", targetValue = " . $db->Quote(
                    $this->targetval
                ) . ", metric = " . $db->Quote(
                    $this->metrics
                ) . ", inverse = {$this->inverse}, conditions = " . $db->Quote(
                    $this->conditions
                ) . ", profileID = " . $db->Quote(
                    $this->profile->profileid
                ) . ", graphType = 'speed', kpi = " . $db->Quote(trim($this->kpi)) . " WHERE goalID = {$this->goal_id}";
        } else {
            $sql = "INSERT INTO " . TBL_GOALS . " (goalName,timeunit,targetValue,metric,inverse,conditions,profileID,graphType,kpi) VALUES (" . $db->Quote(
                    $this->goalname
                ) . "," . $db->Quote($this->timeunit) . "," . $db->Quote($this->targetval) . "," . $db->Quote(
                    $this->metrics
                ) . ",{$this->inverse}," . $db->Quote($this->conditions) . "," . $db->Quote(
                    $this->profile->profileid
                ) . ",'speed'," . $db->Quote($this->kpi) . ") ON DUPLICATE KEY UPDATE goalID = goalID";
        }

        if ($db->Execute($sql)) {
            return Notice("{$this->goalname} " . _HAS_BEEN_SAVED . "!");
        } else {
            return Warning(_SOMETHING_WENT_WRONG_PLEASE_TRY_AGAIN . ".");
        }
    }

    function makesql($urls, $mode)
    {
        $i = 0;
        switch ($mode) {
            case "or":
                $andor = " OR";
                break;
            default:
                $andor = " AND";
        }

        $sqlstring = "";

        while ($i < count($urls)) {
            $cvalue = "";
            $cvalue = $cvalue ?? $urls['cvalue'][$i];
            if ($cvalue != "") {
                $field = $field ?? $urls["field"][$i];
                if ($field == "") {
                    return false;
                }
                $condition = $conditio ?? $urls["condition"][$i];
                if ($field == "keywords") {
                    $cvalue = urlencode($cvalue);
                }
                if ($field == "refparams" || $field == "params") {
                    $cvalue = str_replace(" ", "+", $cvalue);
                }

                if ($condition == "contains") {
                    $op = "{$field} LIKE '%{$cvalue}%'";
                } else {
                    if ($condition == "nocontain") {
                        $op = "{$field} NOT LIKE '%{$cvalue}%'";
                    } else {
                        if ($condition == "start") {
                            $op = "{$field} LIKE '{$cvalue}%'";
                        } else {
                            if ($condition == "end") {
                                $op = "{$field} LIKE '%{$cvalue}'";
                            } else {
                                if ($condition == "is") {
                                    $op = "{$field} ='{$cvalue}'";
                                } else {
                                    if ($condition == "isnot") {
                                        $op = "{$field} !='{$cvalue}'";
                                    }
                                }
                            }
                        }
                    }
                }
                if ($i == 0) {
                    $sqlstring = " {$op}";
                } else {
                    $sqlstring .= " {$andor} {$op}";
                }
            }
            $i++;
        }
        $filter = 1;

        $joincond = "";
        $addtables = "";
        if (!empty($sqlstring)) {
            if (strpos("  " . $sqlstring, " url ") != false) {
                $sqlstring = str_replace("url =", "u.url=", $sqlstring);
                $sqlstring = str_replace("url !=", "u.url!=", $sqlstring);
                $sqlstring = str_replace("url LIKE", "u.url LIKE", $sqlstring);
                $sqlstring = str_replace("url NOT LIKE", "u.url NOT LIKE", $sqlstring);
                $addtables = ",{$this->profile->tablename_urls} as u";
                $joincond = "and a.url=u.id";
            }

            if (strpos("  " . $sqlstring, " params ") != false) {
                $sqlstring = str_replace("params =", "up.params=", $sqlstring);
                $sqlstring = str_replace("params !=", "up.params!=", $sqlstring);
                $sqlstring = str_replace("params LIKE", "up.params LIKE", $sqlstring);
                $sqlstring = str_replace("params NOT LIKE", "up.params NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_urlparams} as up";
                $joincond .= " and a.params=up.id";
            }

            if (strpos("  " . $sqlstring, " referrer ") != false) {
                $sqlstring = str_replace("referrer =", "r.referrer=", $sqlstring);
                $sqlstring = str_replace("referrer !=", "r.referrer!=", $sqlstring);
                $sqlstring = str_replace("referrer LIKE", "r.referrer LIKE", $sqlstring);
                $sqlstring = str_replace("referrer NOT LIKE", "r.referrer NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_referrers} as r";
                $joincond .= " and a.referrer=r.id";
            }

            if (strpos("  " . $sqlstring, " refparams ") != false) {
                $sqlstring = str_replace("refparams =", "rp.params=", $sqlstring);
                $sqlstring = str_replace("refparams !=", "rp.params!=", $sqlstring);
                $sqlstring = str_replace("refparams LIKE", "rp.params LIKE", $sqlstring);
                $sqlstring = str_replace("refparams NOT LIKE", "rp.params NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_refparams} as rp";
                $joincond .= " and a.refparams=rp.id";
            }

            if (strpos("  " . $sqlstring, " keywords ") != false) {
                $sqlstring = str_replace("keywords =", "k.keywords=", $sqlstring);
                $sqlstring = str_replace("keywords !=", "k.keywords!=", $sqlstring);
                $sqlstring = str_replace("keywords LIKE", "k.keywords LIKE", $sqlstring);
                $sqlstring = str_replace("keywords NOT LIKE", "k.keywords NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_keywords} as k";
                $joincond .= " and a.keywords=k.id";
            }
            if (strpos("  " . $sqlstring, " ipnumber ") != false) {
                $sqlstring = str_replace("ipnumber =", "v.ipnumber=", $sqlstring);
                $sqlstring = str_replace("ipnumber !=", "v.ipnumber!=", $sqlstring);
                $sqlstring = str_replace("ipnumber LIKE", "v.ipnumber LIKE", $sqlstring);
                $sqlstring = str_replace("ipnumber NOT LIKE", "v.ipnumber NOT LIKE", $sqlstring);
            }
            if (strpos("  " . $sqlstring, " useragent ") != false) {
                $sqlstring = str_replace("useragent =", "AGENTS.name=", $sqlstring);
                $sqlstring = str_replace("useragent !=", "AGENTS.name!=", $sqlstring);
                $sqlstring = str_replace("useragent LIKE", "AGENTS.name LIKE", $sqlstring);
                $sqlstring = str_replace("useragent NOT LIKE", "AGENTS.name NOT LIKE", $sqlstring);
            }
        }

        return " AND" . $sqlstring;
    }

    function DeleteGoal()
    {
        global $db;
        $db->Execute("DELETE FROM " . TBL_GOALS . " WHERE goalID={$this->goal_id}") or die ($db->ErrorMsg());

        return Notice(_DELETED_GOAL . "!");
    }

    function Toppanel()
    {
        $link = "definereport.php?conf={$this->profile->profilename}&labels=_GOALS";
        echo '<div class="nav-tabs-custom"><ul class="nav nav-tabs">';
        if (empty($this->goal_action) || $this->goal_action == "manage") {
            echo "<li class='active'><a href='{$link}&goal_action=manage'>Manage Goals</a></li><li><a href='{$link}&goal_action=create'>" . _CREATE_A_NEW_GOAL . "</a></li>";
        } else {
            echo "<li><a href='{$link}&goal_action=manage'>Manage Goals</a></li><li class='active'><a href='{$link}&goal_action=create'>" . _CREATE_A_NEW_GOAL . "</a></li>";
        }
        echo '</ul></div>';
    }

    function ManageGoals()
    {
        global $db;
        if (CheckIfTableExists(TBL_GOALS) && CheckIfTableExists($this->profile->profileid)) {
            $q = $db->Execute(
                "select goalID, goalName from " . TBL_GOALS . " where profileID = {$this->profile->profileid}"
            );
        }
        echo "<table class='table'>";
        if (!$q) {
            echo "<tr><td>" . _NO_DATA_TO_DISPLAY . "</td><td></td><td></td></tr>";
        } else {
            while ($data = $q->FetchRow()) {
                $link = "definereport.php?labels=_GOALS&conf={$this->profile->profilename}&goal_id=" . $data['goalID'];
                echo "<tr>
					<td>{$data['goalName']}</td>
					<td><a href=\"{$link}&goal_action=edit\">" . _EDIT . "</a></td>
					<td><a href=\"{$link}&goal_action=delete\">" . _DELETE . "</a></td>
				</tr>";
            }
        }
        echo "</table>";
    }

    function EditGoal()
    {
        global $db;

        if (!empty($this->goal_id)) {
            $data = $this->getGoalData();
        } else {
            $data = array(
                "kpi" => ""
            );
        }
        ?>
        <form id='goalform' action="<?php
        echo "?conf={$this->profile->profilename}&labels={$this->label_constant}"; ?>" method='post'>
            <h3><?php
                echo $this->goal_action == "edit" ? _EDIT_GOAL . ": {$data['goalName']}" : _CREATE_A_NEW_GOAL; ?></h3>

            <?php
            echo _GOALS_INTRO; ?>

            <div class="form-group">
                <label><?php
                    echo _NAME_OF_GOAL; ?>:</label>
                <input class="form-control" placeholder="<?php
                echo _ENTER_GOAL_NAME; ?>" type="text" id="goalname" name="goalname" value='<?php
                echo htmlentities(isset($data['goalName']), ENT_QUOTES); ?>'/>
            </div>

            <div class="form-group">
                <label title="<?php
                echo _CHOOSE_TIME_UNIT; ?>."><?php
                    echo _TIME_UNIT; ?>:</label>
                <select class="form-control" id="timeunit" name="timeunit">
                    <option value=''>-- <?php
                        echo _SELECT_A_TIME_UNIT; ?> --
                    </option>
                    <option value='days'<?php
                    if (isset($data['timeunit']) == "days") {
                        echo " selected";
                    } ?>><?php
                        echo _DAYS; ?></option>
                    <option value='weeks'<?php
                    if (isset($data['timeunit']) == "weeks") {
                        echo " selected";
                    } ?>><?php
                        echo _WEEKS; ?></option>
                    <option value='months'<?php
                    if (isset($data['timeunit']) == "months") {
                        echo " selected";
                    } ?>><?php
                        echo _MONTHS; ?></option>
                    <option value='years'<?php
                    if (isset($data['timeunit']) == "years") {
                        echo " selected";
                    } ?>><?php
                        echo _YEARS; ?></option>
                </select>
            </div>

            <div class="form-group">
                <label title="<?php
                echo _CHOOSE_GOAL_TYPE; ?>."><?php
                    echo _GOAL_TYPE; ?>:</label>
                <select class="form-control" id="metrics" name="metrics">
                    <option value=''>-- <?php
                        echo _SELECT_A_METRIC; ?> --
                    </option>
                    <option value='visitors'<?php
                    if (isset($data['metric']) == 'visitors') {
                        echo " selected";
                    } ?>><?php
                        echo _UNIQUE_VISITORS; ?></option>
                    <option value='pageviews'<?php
                    if (isset($data['metric']) == 'pageviews') {
                        echo " selected";
                    } ?>><?php
                        echo _PAGEVIEWS; ?></option>
                    <option value='conversion'<?php
                    if (isset($data['metric']) == 'conversion') {
                        echo " selected";
                    } ?>><?php
                        echo _CONVERSION; ?></option>
                </select>
            </div>

            <div class="form-group">
                <label><?php
                    echo _VALUE; ?>:</label>
                <input class="form-control" placeholder="<?php
                echo _ENTER_GOAL_VALUE; ?>" type='text' id='targetval' name='targetval' value='<?php
                echo isset($data['targetValue']); ?>'/>
            </div>

            <div class="kpiSelector form-group">
                <label title="<?php
                echo _KEY_PERFORMANCE_INDICATOR; ?>" for='kpi'><?php
                    echo _KPI; ?>:</label>
                <?php
                $kpis = explode(",", $this->profile->targetfiles);

                echo "<select  class='form-control' name='kpi' id='kpi'>";
                foreach ($kpis as $kpi) {
                    $kpi = trim($kpi);
                    $selected = "";

                    if (trim($data['kpi']) == $kpi) {
                        $selected = " selected";
                    }
                    echo "<option{$selected} value='{$kpi}'>{$kpi}</option>";
                }
                echo "</select>";
                ?>
            </div>


            <?php
            $condition_options = [];
            if (!empty($data['conditions'])) {
                $data['conditions'] = substr($data['conditions'], 4);
                $condition_options = $this->breaksql($data['conditions']);
            }

            if (isset($condition_options['condition']) && count($condition_options['condition']) > 1) {
                echo "<div class='andor_selector'>";
                echo "<span style='float: left; margin-right: 20px;'>Mode: </span>";
                if (empty($this->andor) || $this->andor == "AND") {
                    echo "<label style='float: left;'>AND</label><input type='radio' style='width: 25px; float: left;' class='noTextInput' name='andor' value='AND' checked />";
                } else {
                    echo "<label style='float: left;'>AND</label><input type='radio' style='width: 25px; float: left;' class='noTextInput' name='andor' value='AND' />";
                }
                if (!empty($this->andor) && $this->andor == "OR") {
                    echo "<label style='float: left;'>OR</label><input type='radio' style='width: 25px; float: left;' class='noTextInput' name='andor' value='OR' checked />";
                } else {
                    echo "<label style='float: left;'>OR</label><input type='radio' style='width: 25px; float: left;' class='noTextInput' name='andor' value='OR' />";
                }
                echo "</div>";
                echo "<div class='clear'></div>";
            }


            $form_id = md5(time());
            echo "<div id='{$form_id}' class='conditions report-options'>";
            echo "<label>" . _PICK_GOAL_CONDITIONS . "</label>";
            echo "<table class='table'>";
            echo "<tr><td>" . _FIELD . "</td><td>" . _CONDITION . "</td><td>" . _VALUE . "</td><td></td></tr>";
            if (count($condition_options) == 0) {
                echo "<tr class='conditions_row'>
							<td><select src='field' class='form-control' id='field1' name='field1'>
								<option></option>
								<option value='url'>" . _URL . "</option>
								<option value='params'>" . _URLPARAMS . "</option>
								<option value='referrer'>" . _REFERRER . "</option>
								<option value='refparams'>" . _REFPARAMS . "</option>
							</select></td>
							<td><select src='condition' class='form-control' id='condition1' name='condition1'>
								<option></option>
								<option value='is'>" . _SELECT_IS . "</option>
								<option value='contains'>" . _CONTAINS . "</option>
								<option value='nocontain'>" . _NOT_CONTAINS . "</option>
								<option value='start'>" . _STARTS_WITH . "</option>
								<option value='end'>" . _ENDS_WITH . "</option>
								<option value='isnot'>" . _SELECT_IS_NOT . "</option>
							</select></td>
							<td>
								<input class='form-control qbuilderhelp' src='cvalue' rel='1' name='cvalue1' id='cvalue1' value='" . isset($condition_options['cvalue'][1]) . "' autocomplete='off'>
							</td>
							<td><div class='btn-group'>
								<button class='btn btn-default plus_btn' type='button' />+</button>
								<button class='btn btn-default min_btn' type='button'  disabled='disabled' />-</button>
							</div></td>
						</tr>";
            } else {
                for ($c = 0; $c < count($condition_options['condition']); $c++) {
                    for ($c = 0; $c < count($condition_options['condition']); $c++) {
                        if (!empty($condition_options['field'][$c])) {
                            $fieldselect = "<option value='{$condition_options['field'][$c]}'>{$condition_options['field'][$c]}</option>";
                            $fieldselect .= "<option></option>";
                        } else {
                            $fieldselect = "<option></option>";
                        }

                        $fieldselect .= "<option value='url'>" . _URL . "</option>";
                        $fieldselect .= "<option value='params'>" . _URLPARAMS . "</option>";
                        $fieldselect .= "<option value='referrer'>" . _REFERRER . "</option>";
                        $fieldselect .= "<option value='refparams'>" . _REFPARAMS . "</option>";
                        $fieldselect = SelectField($fieldselect, isset($condition_options['field'][$c]));

                        echo "<tr class='conditions_row'>
									<td><select class='form-control' src='field' id='field" . ($c + 1) . "' name='field" . ($c + 1) . "'>{$fieldselect}</select></td>
									<td><select class='form-control' src='condition' id='condition" . ($c + 1) . "' name='condition" . ($c + 1) . "'>
										<option value=\"" . isset($condition_options['condition'][$c]) . "\" selected>" . isset($condition_options['condition'][$c]) . "
										<option></option>
										<option value='is'>" . _SELECT_IS . "</option>
										<option value='contains'>" . _CONTAINS . "</option>
										<option value='nocontain'>" . _NOT_CONTAINS . "</option>
										<option value='start'>" . _STARTS_WITH . "</option>
										<option value='end'>" . _ENDS_WITH . "</option>
										<option value='isnot'>" . _SELECT_IS_NOT . "</option>
									</select></td>
									<td>
										<input class='form-control qbuilderhelp' src='cvalue' rel='" . ($c + 1) . "' name='cvalue" . ($c + 1) . "' id='cvalue" . ($c + 1) . "' value='" . isset($condition_options['cvalue'][$c]) . "' autocomplete='off'>
									</td>	
									<td><div class='btn-group'>
										<button class='btn btn-default plus_btn' type='button' /> + </button>
										<button class='btn btn-default min_btn' type='button' /> - </button>
									</div></td>
								</tr>";
                    }
                }
            }
            echo "</table>";
            echo "<script type='text/javascript'>plusMinusForm('{$form_id}', 'field', 'condition', 'cvalue');</script>";
            echo "</div>";
            ?>

            <input type='hidden' name='goal_action' value='save'/>
            <input type='hidden' name='conf' value='<?php
            echo $this->profile->profilename; ?>'/>
            <?php
            echo $this->goal_action == 'edit' ? "<input type='hidden' name='goal_id' value='{$this->goal_id}'/>" : ""; ?>

            <input type="submit" class="btn btn-primary" style="" value="<?php
            echo _SAVE; ?>"/>

        </form>
        <script type='text/javascript'>
            conf_name = "<?php echo $this->profile->profilename; ?>";
            from_date = <?php echo $this->from; ?>;
            to_date = <?php echo $this->to; ?>;
            $(document).ready(function () {

                /* Open a query builder drop down */
                $(".conditions").on("keyup", ".qbuilderhelp", function (event) {
                    QBuilderHelpForms($(this).val(), event, $(this).val() + '@' + 'cvalue' + $(this).attr('rel') + '@' + $("#field" + $(this).attr('rel')).val(), 'forminput');
                });

                /* Open a query builder drop down */
                $(".conditions").on("click", ".qbuilderhelp", function (event) {
                    QBuilderHelpForms($(this).val(), event, $(this).val() + '@' + 'cvalue' + $(this).attr('rel') + '@' + $("#field" + $(this).attr('rel')).val(), 'forminput');
                });

                $("select#metrics").change(function () {
                    if ($(this).val() !== "") {
                        var metric = $(this).val();
                        metric = metric.substr(0, 1).toUpperCase() + metric.substr(1);
                        $("select#inverse option[value=0]").html(metric + " <?php echo _INCREASE;?>");
                        $("select#inverse option[value=1]").html(metric + " <?php echo _DECREASE;?>");
                    } else {
                        $("select#inverse option[value=0]").html("<?php echo _SELECTED_METRIC_INCREASES;?>");
                        $("select#inverse option[value=1]").html("<?php echo _SELECTED_METRIC_DECREASES;?>");
                    }
                    if ($(this).val() == "conversion") {
                        $(".kpiSelector").show();
                        $(".conditions").hide();
                    } else {
                        $(".kpiSelector").hide();
                        $(".conditions").show();
                    }
                });

                $("select#metrics").change();
            });
        </script>
        <?php
    }

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

?>