<?php
/****************************
 * File : explore.php
 * Author : Cygnusa
 * @2018
 ****************************/

//SECURITY
if (!defined('APPLICATION_PATH')) {
    exit('No direct script access allowed');
}

//FUNCTION LISTS

class explore
{
    public function __construct($parent)
    {
        //GET PAGE MESSAGE
        $this->page_data = globalfunc::getMessage($parent, $parent->lang, 'explore');
        if (count($parent->params) == 0) {
            $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
        } else {
            $qry_params = explode("?", $parent->params[0]);
            $parameter_val = strtolower($qry_params[0]);

            switch ($parameter_val) {
                case "model":
                case "images360":
                case "newimages360":
                case "comparison":
                case "salesprocess":
                case "variant":
                case "enquiry":
                case "customer":
                case "customerfeedback":
                case "customerenquiry":
                case "accessories_riders":
                case "accessories_bikes":
                case "smpindetails":
                case "contentlist":

                    $this->$parameter_val($parent);
                    break;

            }

        }
        $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
    }

    // GET SMPIN Number of CE
    private function smpindetails($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        globalfunc::checkParamCount($parent, 1);

        $dealer_code = $parent->current_user_data->dealer_code;

        $query_userarr = $parent->selectQuery(TABLE_USER . " u JOIN " . DMS_EMPLOYEE . " as e ON e.smpin=u.smpin ", " u.`userid`,u.`smpin`,u.`emp_code`,u. `fname`,u. `lname` ", "u.is_deleted=0 AND u.status=1 AND u.dealer_code = '" . $dealer_code . "' AND u.role>7 AND u.role NOT IN (14,16,17) AND e.segment=1 ORDER BY u.created_on ASC", "");
        if (!$query_userarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $parent->response(array('response' => 'success', 'data' => $query_userarr['result'], 'message' => $this->page_data['success1']), 200);
    }

    //GET MODEL ALL MODEL EXLPORE FRONT PAGE
    private function model($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));
        $cond = '';

        //ROLE WISE CONDITION
        switch ($parent->current_user_role) {
            case '0':
            case 'guest':
                $cond = " AND model_type='" . $parent->exp_model_type . "'";
                break;
            case '15':
                $cond = " AND model_type='1'";
                break;
            case '16':
                $cond = " AND model_type='0' AND is_experience=1 ";
                break;
            case '17':
                $cond = " AND is_experience=1 ";
                break;
            default:
                $cond = " AND model_type='0'";
                break;
        }

        if (count($parent->params) != 1) {
            globalfunc::checkParamCount($parent, 2);
            $model_id = escape_str($parent->params['1']);
            $cond .= " AND model_id='" . $model_id . "'";
        } else {

            globalfunc::checkParamCount($parent, 1);
            $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);

            if (isset($filter_arr) && isset($filter_arr['model'])) {
                $model_type = escape_str($filter_arr['model']);
                switch ($filter_arr['model']) {
                    case 'big':
                        $cond .= " AND model_type='1'";
                        break;
                    case 'normal':
                        $cond .= " AND model_type='0'";
                        break;
                    default:
                        $cond .= " AND model_type='0'";
                        break;
                }
                $cond .= '';
            }
        }

        $append_url = SITE_URL . "explore_assets/model/" . strtolower($parent->device_type) . "/";
        $brochure_url = SITE_URL . "explore_assets/model/";
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,`title`,`description`, `model_name`, CASE WHEN model_image!='' THEN CONCAT('" . $append_url . "',model_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_image_url', CASE WHEN model_brochure!='' THEN CONCAT('" . $brochure_url . "',model_brochure) ELSE '' END AS 'model_brochure',CASE WHEN model_banner_image!='' THEN CONCAT('" . $append_url . "',model_banner_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_banner_image_url' , CASE WHEN model_brochure_image!='' THEN CONCAT('" . $append_url . "',model_brochure_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_brochure_image_url' ", "is_deleted=0 AND is_other=0 " . $cond . " ORDER BY position ASC,model_id ASC", "");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        //LOG
        $logstr = 'EXPLORE MODEL';
        globalfunc::insertUserLog($parent, $logstr);
        if (count($parent->params) == 1) {
            $parent->response(array('response' => 'success', 'data' => $query_modelarr['result'], 'message' => $this->page_data['success1']), 200);
        } else {
            $parent->response(array('response' => 'success', 'data' => $query_modelarr['result'][0], 'message' => $this->page_data['success1']), 200);
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //GET 360 IMAGES AND ZIP OF MODEL
    private function images360($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $model_id = escape_str($parent->params['1']);
        //COMPARE MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, "*", "model_id='" . $model_id . "' AND is_other=0", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }
        //ASSETS VERSION
        $query_verarr = $parent->selectQuery(TABLE_MODEL_360ASSETS_VERSION, "*", "model_id='" . $model_id . "' ORDER BY file_version DESC", "1");
        if (!$query_verarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        if (!file_exists('../../explore_assets/360/' . $model_id . '/')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }
        $append_url = SITE_URL . "explore_assets/360/" . $model_id . '/';
        $version = $query_verarr['result'][0]->file_version;
        // GET 360 MODEL
        $query_filearr = $parent->selectQuery(TABLE_MODEL_360IMAGE, "*,CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url' ", "model_id='" . $model_id . "' AND is_deleted=0 ORDER BY position ASC", "");

        if (file_exists('../../explore_assets/360/' . $model_id . '/' . $version . '.zip')) {
            //FILE ALREDY EXIST;

            if ($query_filearr['nr'] > 0) {
                $path_arr = @explode('services\_api', APPLICATION_PATH);
                $path_arr[0] = str_replace('\\', '/', realpath($path_arr[0]));
                $root_path = $path_arr[0];

                foreach ($query_filearr['result'] as $key => $res_val) {
                    //GET POINTS
                    $query_hotspotarr = $parent->selectQuery(TABLE_MODEL_360IMAGE_HOTSPOT . " h LEFT JOIN " . TABLE_HOTSPOT_CONTENT . " c ON h.contentid=c.id", "h.*,c.`title`, c.`description`, c.`file`,CASE WHEN c.`file`!='' THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) ELSE '' END AS   file_url , c.`file_type`,CASE WHEN (c.`file_type` IN (2)  ) THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`thumb_image`) ELSE CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) END AS thumb_image_url", "h.image_id='" . $res_val->id . "' AND h.is_deleted=0", "");
                    $query_filearr['result'][$key]->hotspot = array();
                    if ($query_hotspotarr['nr'] > 0) {
                        foreach ($query_hotspotarr['result'] as $m => $res_p) {
                            $query_hotspotarr['result'][$m]->point_arr = json_decode($res_p->pointvalue);
                        }
                        $query_filearr['result'][$key]->hotspot = $query_hotspotarr['result'];
                    }
                }
            } else {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
            }
        } else {
            $file_arr = array();
            $missingfile_arr = array();

            if ($query_filearr['nr'] > 0) {
                // print_r(APPLICATION_PATH);
                $path_arr = @explode('services' . DIRECTORY_SEPARATOR . '_api', APPLICATION_PATH);

                //  print_r($path_arr);
                $path_arr[0] = str_replace('\\', '/', realpath($path_arr[0]));
                $root_path = $path_arr[0];

                foreach ($query_filearr['result'] as $key => $res_val) {
                    if (file_exists('../../explore_assets/360/' . $model_id . '/' . $res_val->image)) {
                        $file_arr[] = $root_path . '/explore_assets/360/' . $model_id . '/' . $res_val->image;
                    } else {
                        $missingfile_arr[] = 'explore_assets/360/' . $model_id . '/' . $res_val->image;
                    }

                    //GET POINTS
                    $query_hotspotarr = $parent->selectQuery(TABLE_MODEL_360IMAGE_HOTSPOT . " h LEFT JOIN " . TABLE_HOTSPOT_CONTENT . " c ON h.contentid=c.id", "h.*,c.`title`, c.`description`, c.`file`,CASE WHEN c.`file`!='' THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) ELSE '' END AS   file_url ,CASE WHEN (c.`file_type` IN (2)  ) THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`thumb_image`) ELSE CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) END AS thumb_image_url, c.`file_type`", "h.image_id='" . $res_val->id . "' AND h.is_deleted=0", "");
                    $query_filearr['result'][$key]->hotspot = array();
                    if ($query_hotspotarr['nr'] > 0) {
                        foreach ($query_hotspotarr['result'] as $m => $res_p) {
                            $query_hotspotarr['result'][$m]->point_arr = json_decode($res_p->pointvalue);
                        }

                        $query_filearr['result'][$key]->hotspot = $query_hotspotarr['result'];
                    }
                }

                if (count($missingfile_arr) > 0) {
                    $parent->response(array('response' => 'failed', 'data' => $missingfile_arr, 'message' => $this->page_data["error2"]), 406);
                }
                $returnzip = $this->zipFile($parent, '../../explore_assets/360/' . $model_id . '/', '../../explore_assets/360/' . $model_id . '/' . $version . '.zip', true, $version, $file_arr);
            } else {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
            }
        }

        //LOG
        $logstr = 'EXPLORE 360MODEL';
        globalfunc::insertUserLog($parent, $logstr);

        $data_arr = array('version' => $query_verarr['result'][0]->file_version, 'zip' => SITE_URL . 'explore_assets/360/' . $model_id . '/' . $version . '.zip', 'imagelist' => $query_filearr['result']);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //ZIP FILE GENERATE
    private function zipFile($parent, $source, $destination, $flag = '', $version, $file_arr)
    {
        if (!extension_loaded('zip') || !file_exists($source)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        $source = str_replace('\\', '/', realpath($source));

        if (is_dir($source) === true) {

            $i = 0;
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            //print_r($file_arr);
            foreach ($files as $file) {

                $file = str_replace('\\', '/', realpath($file));
                //echo $file;
                // print_r($file);
                // print_r($file_arr);
                if (in_array($file, $file_arr)) {
                    // echo $file;
                    if (is_dir($file) === true) {
                        //$zip->addEmptyDir(str_replace($source . '/', '', $flag.$file . '/'));
                    } else if (is_file($file) === true) {

                        $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                    }
                }
                $i++;
            }
        } else if (is_file($source) === true) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "1"), 406);
        } else {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "2"), 406);
        }

        $zip->close();
        chmod($destination, 0777);
        return $destination;
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //GET NEW 360 IMAGES AND ZIP OF MODEL
    private function newimages360($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $model_id = escape_str($parent->params['1']);
        //COMPARE MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, "*", "model_id='" . $model_id . "' AND is_other=0", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        //COMPARE MODEL VARIANT
        $query_model_variantarr = $parent->selectQuery(TABLE_MODEL_360VARIANT, "*", "model_id='" . $model_id . "' ", "");
        if (!$query_model_variantarr['nr'] > 0) {

            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error4"]), 406);
        }

        //VARAIANT LOOP
        foreach ($query_model_variantarr['result'] as $res_var) {

            $variant_id = $res_var->id;
            //ASSETS VERSION
            $query_verarr = $parent->selectQuery(TABLE_MODEL_360ASSETS_VERSION, "*", "model_id='" . $model_id . "' AND variant_id='" . $variant_id . "' ORDER BY file_version DESC", "1");
            if (!$query_verarr['nr'] > 0) {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "3"), 406);
            }

            if (!file_exists('../../explore_assets/360/' . $model_id . '/' . $variant_id . '/')) {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "4"), 406);
            } else {
                chmod('../../explore_assets/360/' . $model_id . '/' . $variant_id . '/', 0777);
            }
        }

        $path_arr = @explode('services' . DIRECTORY_SEPARATOR . '_api', APPLICATION_PATH);
        $path_arr[0] = str_replace('\\', '/', realpath($path_arr[0]));
        $root_path = $path_arr[0];

        foreach ($query_model_variantarr['result'] as $vkey => $res_var) {
            $variant_id = $res_var->id;
            $append_url = SITE_URL . "explore_assets/360/" . $model_id . '/' . $variant_id . '/';
            $version = $query_verarr['result'][0]->file_version;
            // GET 360 MODEL
            $query_filearr = $parent->selectQuery(TABLE_MODEL_360IMAGE, "*,CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url' ", "model_id='" . $model_id . "' AND variant_id='" . $variant_id . "' AND is_deleted=0 ORDER BY position ASC", "");

            if (file_exists('../../explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $version . '.zip')) {
                //FILE ALREDY EXIST;

                if ($query_filearr['nr'] > 0) {
                    //$path_arr=@explode('services\_api',APPLICATION_PATH);
                    //$path_arr[0] = str_replace('\\', '/', realpath($path_arr[0]));
                    //$root_path=$path_arr[0];

                    foreach ($query_filearr['result'] as $key => $res_val) {
                        //GET POINTS
                        $query_hotspotarr = $parent->selectQuery(TABLE_MODEL_360IMAGE_HOTSPOT . " h LEFT JOIN " . TABLE_HOTSPOT_CONTENT . " c ON h.contentid=c.id", "h.*,c.`title`, c.`description`, c.`file`,CASE WHEN c.`file`!='' THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) ELSE '' END AS   file_url , c.`file_type`,CASE WHEN (c.`file_type` IN (2)  ) THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`thumb_image`) ELSE CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) END AS thumb_image_url", "h.image_id='" . $res_val->id . "' AND h.is_deleted=0", "");
                        $query_filearr['result'][$key]->hotspot = array();
                        if ($query_hotspotarr['nr'] > 0) {
                            foreach ($query_hotspotarr['result'] as $m => $res_p) {
                                $query_hotspotarr['result'][$m]->point_arr = json_decode($res_p->pointvalue);
                            }
                            $query_filearr['result'][$key]->hotspot = $query_hotspotarr['result'];
                        }
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "5"), 406);
                }
            } else {

                $file_arr = array();
                $missingfile_arr = array();

                if ($query_filearr['nr'] > 0) {
                    // print_r(APPLICATION_PATH);

                    foreach ($query_filearr['result'] as $key => $res_val) {
                        if (file_exists('../../explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $res_val->image)) {
                            $file_arr[] = $root_path . '/explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $res_val->image;
                        } else {
                            $missingfile_arr[] = 'explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $res_val->image;
                        }

                        //GET POINTS
                        $query_hotspotarr = $parent->selectQuery(TABLE_MODEL_360IMAGE_HOTSPOT . " h LEFT JOIN " . TABLE_HOTSPOT_CONTENT . " c ON h.contentid=c.id", "h.*,c.`title`, c.`description`, c.`file`,CASE WHEN c.`file`!='' THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) ELSE '' END AS   file_url ,CASE WHEN (c.`file_type` IN (2)  ) THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`thumb_image`) ELSE CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) END AS thumb_image_url, c.`file_type`", "h.image_id='" . $res_val->id . "' AND h.is_deleted=0", "");
                        $query_filearr['result'][$key]->hotspot = array();
                        if ($query_hotspotarr['nr'] > 0) {
                            foreach ($query_hotspotarr['result'] as $m => $res_p) {
                                $query_hotspotarr['result'][$m]->point_arr = json_decode($res_p->pointvalue);
                            }

                            $query_filearr['result'][$key]->hotspot = $query_hotspotarr['result'];
                        }
                    }

                    if (count($missingfile_arr) > 0) {
                        $parent->response(array('response' => 'failed', 'data' => $missingfile_arr, 'message' => $this->page_data["error2"], "type" => "6"), 406);
                    }

                    $returnzip = $this->zipFile($parent, '../../explore_assets/360/' . $model_id . '/' . $variant_id . '/', '../../explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $version . '.zip', true, $version, $file_arr);
                } else {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"], "type" => "7"), 406);
                }
            }
            $query_model_variantarr['result'][$vkey]->version = $version;
            $query_model_variantarr['result'][$vkey]->zip = SITE_URL . 'explore_assets/360/' . $model_id . '/' . $variant_id . '/' . $version . '.zip';
            $query_model_variantarr['result'][$vkey]->imagelist = $query_filearr['result'];
        }
        //LOG
        $logstr = 'EXPLORE 360MODEL';
        globalfunc::insertUserLog($parent, $logstr);

        //$data_arr= array('version'=>$query_verarr['result'][0]->file_version,'zip'=>SITE_URL.'explore_assets/360/'.$model_id.'/'.$version.'.zip','imagelist'=>$query_filearr['result']);
        $parent->response(array('response' => 'success', 'data' => $query_model_variantarr['result'], 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODEL COMPARISON
    private function comparison($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));
        $append_url = SITE_URL . "explore_assets/model/web/"; // DUE IMAGE CONFILCT IN Comparison

        $model_id = escape_str($parent->params['1']);

        //GET MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,`title`,`description`, `model_name`, CASE WHEN model_image!='' THEN CONCAT('" . $append_url . "',model_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_image_url' ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        if ($parent->current_user_role == 0 && $parent->current_user_id == 'guest') {
            $cond = " AND model_type='" . $parent->exp_model_type . "'";
        } else {
            //GET COMPARE CATEGORY
            $cond = ($parent->current_user_role == '15') ? " AND model_type='1'" : " AND model_type='0'";
        }
        $append_url = SITE_URL . "explore_assets/model/" . strtolower($parent->device_type) . "/";

        $cat_id_arr = array();
        $query_catgrouparr = $parent->selectQuery(TABLE_COMPARE_FIELDS, "cat_id", "is_deleted='0' AND id IN (SELECT field_id FROM " . TABLE_COMPARE_VALUE . " WHERE model_id='" . $model_id . "' ) GROUP BY cat_id", "");
        if ($query_catgrouparr['nr'] > 0) {
            foreach ($query_catgrouparr['result'] as $res) {
                $cat_id_arr[] = $res->cat_id;
            }
            $cond .= " AND id in (" . @implode(",", $cat_id_arr) . ")";
        }

        $query_catarr = $parent->selectQuery(TABLE_COMPARE_CATEGORY, "id,cat_title as title", "is_deleted='0' " . $cond . " ORDER BY cat_pos,id ASC", "");

        $check_arr = array();
        $category_arr = array();
        if ($query_catarr['nr'] > 0) {
            foreach ($query_catarr['result'] as $m => $res_cat) {
                //COMPARE FIELDS
                $query_fieldarr = $parent->selectQuery(TABLE_COMPARE_FIELDS, "id,title", "is_deleted='0' AND cat_id='" . $res_cat->id . "' AND id IN (SELECT field_id FROM " . TABLE_COMPARE_VALUE . " WHERE model_id='" . $model_id . "' ) ORDER BY position,id ASC", "");
                if ($query_fieldarr['nr'] > 0) {
                    foreach ($query_fieldarr['result'] as $n => $res_field) {
                        //COMPARE VALUE
                        $query_fieldvaluearr = $parent->selectQuery(TABLE_COMPARE_VALUE, "cvalue", "is_deleted='0' AND field_id='" . $res_field->id . "' AND model_id='" . $model_id . "'", "1");
                        $query_fieldarr['result'][$n]->value = ($query_fieldvaluearr['nr']) ? $query_fieldvaluearr['result'][0]->cvalue : "";
                        $check_arr[$res_field->id] = $query_fieldarr['result'][$n]->value;
                    }
                }

                $query_catarr['result'][$m]->fields = ($query_fieldarr['nr'] > 0) ? $query_fieldarr['result'] : array();
                $category_arr[] = (array) $query_catarr['result'][$m];
            }

            // $category_arr=$query_catarr['result'];
        }

        //COMPARE MODEL
        $compare_model_arr = array();
        $query_othmodelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,`title`,`description`, `model_name`, CASE WHEN model_image!='' THEN CONCAT('" . $append_url . "',model_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_image_url' ", " is_other='1' AND FIND_IN_SET('" . $model_id . "',compare_model) AND is_deleted='0' ORDER BY position ASC,model_id ASC  ", "");

        if ($query_othmodelarr['nr'] > 0) {
            foreach ($query_othmodelarr['result'] as $val => $res_oth) {
                $comp_check_arr = array();
                //CATEGORY
                $comp_category_arr = array();
                if ($query_catarr['nr'] > 0) {
                    foreach ($query_catarr['result'] as $m => $res_cat) {
                        //COMPARE FIELDS
                        $query_fieldarr = $parent->selectQuery(TABLE_COMPARE_FIELDS, "id,title", "is_deleted='0' AND cat_id='" . $res_cat->id . "' AND id IN (SELECT field_id FROM " . TABLE_COMPARE_VALUE . " WHERE model_id='" . $model_id . "' )  ORDER BY position,id ASC", "");
                        if ($query_fieldarr['nr'] > 0) {
                            foreach ($query_fieldarr['result'] as $n => $res_field) {
                                $query_fieldarr['result'][$n]->is_equal = 0;
                                // echo "is_deleted='0' AND field_id='".$res_field->id."' AND model_id='".$res_oth->model_id."'";
                                $query_fieldvaluearr = $parent->selectQuery(TABLE_COMPARE_VALUE, "cvalue", "is_deleted='0' AND field_id='" . $res_field->id . "' AND model_id='" . $res_oth->model_id . "' ", "1");
                                $query_fieldarr['result'][$n]->value = ($query_fieldvaluearr['nr']) ? $query_fieldvaluearr['result'][0]->cvalue : "";
                                $comp_check_arr[$res_field->id] = $query_fieldarr['result'][$n]->value;

                                $query_fieldarr['result'][$n]->is_equal = (isset($check_arr[$res_field->id]) && trim($check_arr[$res_field->id]) == ($comp_check_arr[$res_field->id])) ? "1" : "0";
                            }
                        }

                        $query_catarr['result'][$m]->fields = ($query_fieldarr['nr'] > 0) ? $query_fieldarr['result'] : array();
                        $comp_category_arr[] = (array) $query_catarr['result'][$m];
                    }
                }
                $compare_model_arr[] = array('model' => $res_oth, 'category' => $comp_category_arr);
            }
        }

        //LOG
        $logstr = 'EXPLORE COMPARISON';
        globalfunc::insertUserLog($parent, $logstr);
        //print_r($category_arr);
        $data_arr = array('model' => $query_modelarr['result'][0], 'category' => $category_arr, 'compare_model' => $compare_model_arr);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODELS SALES PROCESS
    private function salesprocess($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $model_id = escape_str($parent->params['1']);
        //CHECK MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`  ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        //GET MASTER VIEW TYPE
        $query_typearr = $parent->selectQuery(TABLE_IMAGE_VIEW_TYPE, "id,title", "is_deleted='0' AND id IN (SELECT view_id FROM " . TABLE_MODEL_IMAGE_VIEW . " WHERE model_id='" . $model_id . "') ORDER BY position,id ASC ", "");
        $append_url = SITE_URL . "explore_assets/sales/";
        $data_arr = array();
        if ($query_typearr['nr'] > 0) {
            foreach ($query_typearr['result'] as $m => $res_type) {
                //GET MASTER VIEW TYPE IMAGES
                $query_typearr['result'][$m]->image = new stdClass();
                $query_model_imagearr = $parent->selectQuery(TABLE_MODEL_IMAGE_VIEW, "*,CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url'", "is_deleted=0 AND model_id='" . $model_id . "' AND view_id='" . $res_type->id . "'", "1");
                if ($query_model_imagearr['nr'] > 0) {

                    foreach ($query_model_imagearr['result'] as $n => $res_model) {

                        $query_model_imagearr['result'][$n]->hotspot = array();
                        //HOTSPOT IMAGES AND CONTENT
                        $query_hotspotarr = $parent->selectQuery(TABLE_MODEL_VIEW_HOTSPOT . " h LEFT JOIN " . TABLE_HOTSPOT_CONTENT . " c ON h.contentid=c.id", "h.*,c.`title`, c.`description`, c.`file`,CASE WHEN c.`file`!='' THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) ELSE '' END AS  file_url ,CASE WHEN (c.`file_type` IN (2)  ) THEN CONCAT('" . SITE_URL . "explore_assets/content/',c.`thumb_image`) ELSE CONCAT('" . SITE_URL . "explore_assets/content/',c.`file`) END AS thumb_image_url, c.`file_type`", "h.view_id='" . $res_model->id . "' AND h.is_deleted=0", "");
                        if ($query_hotspotarr['nr'] > 0) {
                            foreach ($query_hotspotarr['result'] as $k => $res_p) {
                                $query_hotspotarr['result'][$k]->point_arr = json_decode($res_p->pointvalue);
                            }
                            $query_model_imagearr['result'][$n]->hotspot = $query_hotspotarr['result'];
                        }

                    }
                    $query_typearr['result'][$m]->image = (array) $query_model_imagearr['result'][0];
                }
            }
            $data_arr = $query_typearr['result'];
        }
        //LOG
        $logstr = 'EXPLORE SALEPROCESS';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODELS VARIANT
    private function variant($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $model_id = escape_str($parent->params['1']);

        //CHECK MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id` ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }
        $append_url = SITE_URL . "explore_assets/variant/";
        $data_arr = array();
        //GET MODEL VARIANT
        $query_variantarr = $parent->selectQuery(TABLE_MODEL_VARIANT, "`id`, `model_id`, `title`,`position`", "model_id='" . $model_id . "' AND is_deleted=0 ORDER BY position,id ", "");
        if ($query_variantarr['nr'] > 0) {
            foreach ($query_variantarr['result'] as $m => $res_var) {
                $query_variantarr['result'][$m]->color = array();
                //GET MODEL VARIANT COLOR
                $query_colorarr = $parent->selectQuery(TABLE_MODEL_VARIANT_COLOR, "*, CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url'", "variant_id='" . $res_var->id . "' AND is_deleted=0 ORDER BY position,id ", "");
                if ($query_colorarr['nr'] > 0) {
                    $query_variantarr['result'][$m]->color = $query_colorarr['result'];
                }
            }
            $data_arr = $query_variantarr['result'];
        }
        //LOG
        $logstr = 'EXPLORE VARIANT';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODELS ENQUIRY
    private function enquiry($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $model_id = escape_str($parent->params['1']);
        //CHECK MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,model_type ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $REQUEST_KEYS = array('variant_id' => 'integer', 'name' => 'string', 'mobile' => 'string', 'email' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $variant_id = escape_str($parent->_request['variant_id']);
        $name = escape_str($parent->_request['name']);
        $mobile = escape_str($parent->_request['mobile']);
        $email = escape_str($parent->_request['email']);
        $is_brochure = escape_str($parent->_request['is_brochure']);
        $is_brochure = ($is_brochure == '1') ? "1" : "0";

        $token = ($query_modelarr['result'][0]->model_type == '1') ? MODE_TWO_TOKEN : MODE_ONE_TOKEN;
        $explore_url = SITE_URL . "#/download_brouchure/" . $model_id . "/" . $variant_id . "/" . $token;

        $insert_str = "INSERT INTO " . TABLE_EXPLORE_ENQUIRY . " (  `user_id`, `model_id`, `variant_id`, `name`, `mobile`, `email`, `is_brochure`, `created_on`, `modified_on`) VALUES ( '" . $parent->current_user_id . "', '" . $model_id . "', '" . $variant_id . "', '" . $name . "', '" . $mobile . "', '" . $email . "', '" . $is_brochure . "','" . NOW . "','" . NOW . "')";
        $insertquery = $parent->executeQuery($insert_str);

        $query_dealerarr = $parent->selectQuery(DMS_DEALER, " *", "dealer_code='" . $parent->current_user_data->dealer_code . "'", "1");
        if ($query_dealerarr['nr'] > 0) {
            $dealer_details_str = $query_dealerarr['result'][0]->dealer_name;
            $dealer_details_str .= ($query_dealerarr['result'][0]->address != '') ? '<br>' . trim($query_dealerarr['result'][0]->address) : '';
            $dealer_details_str .= ($query_dealerarr['result'][0]->phone != '') ? '<br>Mob : ' . trim($query_dealerarr['result'][0]->phone) : '';
            $dealer_details_str .= ($query_dealerarr['result'][0]->email != '') ? '<br>Email : ' . trim($query_dealerarr['result'][0]->email) : '';
        } else {
            $dealer_details_str = 'HYPER-M';
        }
        //"16", "17"
        $cond_mail_str1 = (in_array($parent->current_user_role, array("16"))) ? "Thank you for showing your interest in HYPER-M and visiting Dealership." : "Thank you for showing your interest in HYPER-M.";
        $cond_mail_str2 = (in_array($parent->current_user_role, array("16", "17"))) ? "We hope you had a great experience in exploring our range of students." : "We hope you had a great experience in exploring our range of students";

        $email_link = ($is_brochure == '1') ? '<a href="' . $explore_url . '" style="font-weight:bold " >Click Here</a> to download the product e-brochure for your reference.<br>' : "";

        //MAIL AND SMS TRIGGER
        $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
  <tbody>
    <tr>
      <td>
        <table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
          <tbody>
            <tr>
              <td bgcolor="#2d2d2d" height="36" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#e4e4e4;	text-align:left;	font-weight:bold; padding-left:14px; border-bottom:2px solid black">HYPER-M</td>
            </tr>
            <tr>
              <td>
                <table width="85%" align="center">
                  <tbody>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;">
                        <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Dear ' . $name . ',</div>
                      </td>
                    </tr>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;">
                        <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Greetings of the Day..!<br>
                        ' . $cond_mail_str1 . '<br>
' . $cond_mail_str2 . '<br><br>
' . $email_link . '
Thank you again for your visit and we look forward to see you soon.
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">
                      <p  >With regards </p>
					<p  >' . $dealer_details_str . '</p><br>
Visit us at: <a href="">click here<a><br>
Toll Free Number: 1800-121-7996 (Mon-Sat 9AM - 5:30PM)</p>
<p>This is a system generated e-mail, please do not reply to this mail. </p>
                </div>
                      </td>
                    </tr>

                  </tbody>
                </table>
              </td>
            </tr>
            <tr>
              <td style="padding-top:0px; padding-bottom:10px;"></td>
            </tr>
            <tr>
              <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:20px;  border-bottom:2px solid black">
                 &nbsp;
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>';
        $obj = array();
        $obj['from'] = CUSTOMER_EXPERIENCE_EMAIL;
        $obj['FromName'] = 'Customer Experience App';
        //$obj['replayto']=SUPPORT_EMAIL;
        $obj['to'] = $email;
        $obj['subject'] = "THANK YOU FOR ENQUIRY - HYPER-M";
        $obj['message'] = $message;
        // globalfunc::sendMai($parent, $obj);

        //LOG
        $logstr = 'EXPLORE ENQUIRY';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //CUSTOMER
    private function customer($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        //globalfunc::checkAuthrozation($parent,array('type'=>'explore'));

        $smpin = escape_str($parent->_request['smpin']);
        $emp_code = escape_str($parent->_request['emp_code']);

        if (!($smpin != '' || $emp_code != '')) {
            $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
        }

        $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND  smpin='" . $smpin . "' AND emp_code='" . $emp_code . "' LIMIT 1";
        $user_value = $parent->getQueryValue($user_qry_str);

        if (!count($user_value) > 0) {
            $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
        }

        $parent->current_user_data = $user_value[0];
        $parent->current_user_id = $user_value[0]->userid;
        $parent->current_user_role = $user_value[0]->role;
        $parent->current_smpin = $user_value[0]->smpin;
        $parent->current_emp_code = $user_value[0]->emp_code;

        $REQUEST_KEYS = array('customer_data' => 'array');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $customer_data = escape_str($parent->_request['customer_data']);

        $mobile = escape_str($parent->_request['mobile']);

        $is_exist = 0;
        $model_data = new stdClass();

        if ($mobile) {
            $startdate = date('Y-m-d', strtotime('-30 day', strtotime(NOW)));
            $query_checkarr = $parent->selectQuery(TABLE__CUSTOMEREXP . " as ce JOIN " . TABLE_EXPLORE_ENQUIRY . " e ON ce.id=e.customerid ", "e.model_id,e.variant_id ", "ce.mobile='" . $mobile . "' AND ce.created_on>='" . $startdate . " 00:00:00' ORDER BY e.id DESC", "1");
            if ($query_checkarr['nr'] > 0) {

                $append_url = SITE_URL . "explore_assets/model/" . strtolower($parent->device_type) . "/";
                $modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,`title`,`description`, `model_name`, CASE WHEN model_image!='' THEN CONCAT('" . $append_url . "',model_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_image_url', CASE WHEN model_banner_image!='' THEN CONCAT('" . $append_url . "',model_banner_image) ELSE '" . NOIMAGE_URL . "' END AS 'model_banner_image_url'", " model_id='" . $query_checkarr['result'][0]->model_id . "'", "1");
                if ($modelarr['nr'] > 0) {
                    $query_variantarr = $parent->selectQuery(TABLE_MODEL_VARIANT, "`id`, `model_id`, `title`,`position`", "id='" . $query_checkarr['result'][0]->variant_id . "'  ", "1");
                    $is_exist = 1;
                    $modelarr['result'][0]->variant = ($query_variantarr['nr'] > 0) ? $query_variantarr['result'][0] : '';
                    $model_data = $modelarr['result'][0];
                }
            }
        }
        $insert_arr = array();
        if (count($customer_data) > 0) {
            //VALIDATE
            foreach ($customer_data as $res) {
                $salutation = escape_str($res['salutation']);
                $firstname = escape_str($res['firstname']);
                $lastname = escape_str($res['lastname']);
                $email = escape_str($res['email']);
                $mobile = escape_str($res['mobile']);
                $age = escape_str($res['age']);
                $uid = escape_str($res['uid']);
                $smpin = escape_str($res['smpin']);
                $dsename = escape_str($res['dsename']);

                if (!($salutation != '' && $firstname != '' && $mobile != '' && $age != '' && $uid != '')) {
                    $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
                }
                $insert_arr[] = " ('" . $salutation . "', '" . $firstname . "', '" . $lastname . "', '" . $email . "','" . $mobile . "', '" . $age . "','" . $smpin . "', '" . $dsename . "', '" . $parent->current_user_id . "','" . $uid . "','" . NOW . "')";
            }
            $parent->executeQuery("INSERT INTO " . TABLE__CUSTOMEREXP . " ( `salutation`, `firstname`, `lastname`, `email`, `mobile`, `age`, `smpin`, `dsename`, `userid`,`uid`,`created_on`) VALUES " . @implode(",", $insert_arr));

        } else {
            $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
        }

//        $REQUEST_KEYS=array('salutation'=>'string','firstname'=>'string' ,'age'=>'string','mobile'=>'number');
        //        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        //
        //        $salutation=escape_str($parent->_request['salutation']);
        //        $firstname=escape_str($parent->_request['firstname']);
        //        $lastname=escape_str($parent->_request['lastname']);
        //        $email=escape_str($parent->_request['email']);
        //        $mobile=escape_str($parent->_request['mobile']);
        //        $age=escape_str($parent->_request['age']);
        //
        //        $insert_str = "INSERT INTO ".TABLE__CUSTOMEREXP." ( `salutation`, `firstname`, `lastname`, `email`, `mobile`, `age`, `userid`, `created_on`) VALUES ('".$salutation."', '".$firstname."', '".$lastname."', '".$email."','".$mobile."', '".$age."', '".$parent->current_user_id."', '".NOW."')";
        //        $insertquery = $parent->executeQuery($insert_str);
        //
        //        $ins_id=$parent->lastInsertId();
        //
        //LOG
        $logstr = 'EXPLORE CUSTOMER';
        globalfunc::insertUserLog($parent, $logstr);
//
        //        $get_str = "SELECT *  FROM ".TABLE__CUSTOMEREXP." WHERE id='".$ins_id."' LIMIT 1";
        //        $get_arr=$parent->getQueryValue($get_str);

        $parent->response(array('response' => 'success', 'is_exist' => $is_exist, 'model_data' => $model_data, 'message' => $this->page_data['success1']), 200);
    }

    //CUSTOMER
    private function customerfeedback($parent)
    {
        //
        globalfunc::checkMethodType($parent, array('GET', 'POST'));
        switch ($parent->get_request_method()) {
            case "GET": //GET FEEDBACK QUESTION
                globalfunc::checkAuthrozation($parent, array('type' => 'explore'));
                // $sarr=array('Poor','Average','Good','Very Good','Excellent');
                /*$sarr=array('1','2','3','4','5');
                $i=1;
                foreach($sarr as $sval)
                {
                $val=new stdClass();
                $val->id=$i++;
                $val->score=$val->id;
                $val->rating_text=$sval;
                $survey_arr[]=$val;
                }*/
                $sarr = array('5', '4', '3', '2', '1');
                $i = 1;
                foreach ($sarr as $sval) {
                    $val = new stdClass();
                    $val->id = $sval;
                    $val->score = $sval;
                    $val->rating_text = $sval;
                    $survey_arr[] = $val;
                }
                $ques_str = "SELECT  q.id as qid,  q.`questiontypeid`, q.`questiontext`, q.`qimage`, q.`qvideo`  FROM " . TABLE__EXPQUESTION . " as q  WHERE q.status=1 " . $econd;
                $ques_arr = $parent->getQueryValue($ques_str);
                $question_arr = array();

                if (count($ques_arr) > 0) {
                    $s3 = awsfileserver::connectS3();
                    foreach ($ques_arr as $key => $res_ques) {
                        $res_ques->rating_options = array();

                        //QUESTION IMAGE
                        $res_ques->qimage_url = '';
                        if ($res_ques->qimage != '') {
                            $res_ques->qimage_url = awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_QUESTION_URL . $res_ques->qimage);
                        }

                        //QUESTION VIDEO
                        $res_ques->qvideo_url = '';
                        if ($res_ques->qvideo != '') {
                            $res_ques->qvideo_url = awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_QUESTION_URL . $res_ques->qvideo);
                        }

                        //RATING QUESTION
                        $res_ques->rating_options = array();
                        $res_ques->options = array();
                        if ($res_ques->questiontypeid == '7') {
                            $res_ques->rating_options = $survey_arr;

                        } else if ($res_ques->questiontypeid == '9' || $res_ques->questiontypeid == '10') {
                            //CHOICE
                            $chocie_arr = array();
                            //WEB NEED selected

                            $quesoption_str = "SELECT optid,opttext  FROM " . TABLE__EXPQUESTIONOPTION . " WHERE qid='" . $res_ques->qid . "'";
                            $quesoption_arr = $parent->getQueryValue($quesoption_str);
                            $res_ques->options = $quesoption_arr;
                        }
                        $question_arr[] = $res_ques;
                    }
                }
                //LOG
                $logstr = 'EXPLORE QUESTION';
                globalfunc::insertUserLog($parent, $logstr);
                $parent->response(array('response' => 'success', 'data' => $question_arr, 'total' => count($question_arr), 'message' => $this->page_data['success1']), 200);

                break;
            case "POST": //POST FEEDBACK SUBMIT

                $smpin = escape_str($parent->_request['smpin']);
                $emp_code = escape_str($parent->_request['emp_code']);

                if (!($smpin != '' || $emp_code != '')) {
                    $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
                }

                $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND  smpin='" . $smpin . "' AND emp_code='" . $emp_code . "' LIMIT 1";
                $user_value = $parent->getQueryValue($user_qry_str);

                if (!count($user_value) > 0) {
                    $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
                }

                $parent->current_user_data = $user_value[0];
                $parent->current_user_id = $user_value[0]->userid;
                $parent->current_user_role = $user_value[0]->role;
                $parent->current_smpin = $user_value[0]->smpin;
                $parent->current_emp_code = $user_value[0]->emp_code;

                $REQUEST_KEYS = array('customer_data' => 'array');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                $customer_data = escape_str($parent->_request['customer_data']);
                if (count($customer_data) > 0) {
                    //VALIDATION
                    foreach ($customer_data as $key => $res) {
                        $uid = $res['uid'];
                        $ans_arr = $res['ans_arr'];
                        //$ans_arr = json_decode($ans_str);

                        if (!(isset($res['ans_arr']) && is_array($ans_arr) && count($ans_arr) > 0)) {
                            $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
                        }

                        $customer_str = "SELECT id  FROM " . TABLE__CUSTOMEREXP . " WHERE uid='" . $uid . "' LIMIT 1";
                        $customer_arr = $parent->getQueryValue($customer_str);

                        if (!count($customer_arr) > 0) {
                            $parent->response(array('response' => 'failed', 'message' => 'INVALID USER'), 406);
                        }
                        $customer_data[$key]['customerid'] = $customer_arr[0]->id;

                    }

                    foreach ($customer_data as $res) {
                        $uid = $res['uid'];
                        $ans_arr = $res['ans_arr'];

                        $customerid = $res['customerid'];

                        $userid = $parent->current_user_id;
                        //RESULT INSERT
                        $parent->executeQuery("INSERT INTO " . TABLE__FEEDBACKUSER . " ( `customerid`, `creatorid`, `created_on`, `modified_on`)VALUES('" . $customerid . "','" . $userid . "','" . NOW . "','" . NOW . "')");
                        $arid = $parent->lastInsertId();

                        //INSERT OPTIONS
                        $insert_result_arr = array();
                        for ($mid = 0; $mid < count($ans_arr); $mid++) {

//                            $qid = $ans_arr[$mid]->qid;
                            //                            $survey_rating = (isset($ans_arr[$mid]->survey_rating))?$ans_arr[$mid]->survey_rating:0;
                            //                            $survey_text=(isset($ans_arr[$mid]->survey_text) && is_string($ans_arr[$mid]->survey_text))?$ans_arr[$mid]->survey_text:'';
                            //                            $options_arr =(isset($ans_arr[$mid]->options))?$ans_arr[$mid]->options:array();
                            $qid = $ans_arr[$mid]['qid'];
                            $survey_rating = (isset($ans_arr[$mid]['survey_rating'])) ? $ans_arr[$mid]['survey_rating'] : 0;
                            $survey_text = (isset($ans_arr[$mid]['survey_text']) && is_string($ans_arr[$mid]['survey_text'])) ? $ans_arr[$mid]['survey_text'] : '';
                            $options_arr = (isset($ans_arr[$mid]['options'])) ? $ans_arr[$mid]['options'] : array();

                            if (is_array($options_arr) && count($options_arr) > 0) {
                                for ($nid = 0; $nid < count($options_arr); $nid++) {
                                    $option_id = $options_arr[$nid];
                                    $insert_result_arr[] = " ('" . $arid . "', '" . $customerid . "', '" . $qid . "','" . $survey_rating . "','" . $survey_text . "','" . $option_id . "','" . NOW . "','" . NOW . "')";
                                }
                            } else {
                                $insert_result_arr[] = " ('" . $arid . "', '" . $customerid . "', '" . $qid . "','" . $survey_rating . "','" . $survey_text . "','','" . NOW . "','" . NOW . "')";
                            }

                        }

                        if (count($insert_result_arr) > 0) {
                            $parent->executeQuery("INSERT INTO " . TABLE__FEEDBACKRESULT . " (arid, customerid, qid,survey_rating,survey_text,choiseid,created_on,modified_on)VALUES " . @implode(',', $insert_result_arr) . "");
                        } else {
                            $parent->response(array('response' => 'failed', 'message' => $this->page_data["explore"]), 406);
                        }
                    }

                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
                }

                //LOG
                $logstr = 'EXPLORE FEEDBACK SUBMIT';
                globalfunc::insertUserLog($parent, $logstr);
                //$parent->response(array('response'=>'success', 'message'=>$this->page_data['success1']),200);
                $parent->response(array('response' => 'success', 'message' => 'Thank you for your Feedback'), 200);

                break;
        }

    }

    //MODELS ENQUIRY
    private function customerenquiry($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        //globalfunc::checkAuthrozation($parent,array('type'=>'explore'));

        $smpin = escape_str($parent->_request['smpin']);
        $emp_code = escape_str($parent->_request['emp_code']);

        if (!($smpin != '' || $emp_code != '')) {
            $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
        }

        $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND  smpin='" . $smpin . "' AND emp_code='" . $emp_code . "' LIMIT 1";
        $user_value = $parent->getQueryValue($user_qry_str);

        if (!count($user_value) > 0) {
            $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
        }

        $parent->current_user_data = $user_value[0];
        $parent->current_user_id = $user_value[0]->userid;
        $parent->current_user_role = $user_value[0]->role;
        $parent->current_smpin = $user_value[0]->smpin;
        $parent->current_emp_code = $user_value[0]->emp_code;

        $REQUEST_KEYS = array('customer_data' => 'array');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $customer_data = escape_str($parent->_request['customer_data']);

        if (count($customer_data) > 0) {
            //VALIDATION
            foreach ($customer_data as $key => $res) {
                //$REQUEST_KEYS=array('variant_id'=>'integer','name'=>'string','mobile'=>'string','email'=>'string');
                //globalfunc::mandatoryKey($parent,$REQUEST_KEYS);

                $model_id = escape_str($res['model_id']);
                $uid = escape_str($res['uid']);

                $variant_id = escape_str($res['variant_id']);
                $name = escape_str($res['name']);
                $mobile = escape_str($res['mobile']);
                $email = escape_str($res['email']);
                $is_brochure = escape_str($res['is_brochure']);

                if (!($variant_id != '' && $model_id != '' && $name != '' && $mobile != '' && $email != '')) {
                    $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
                }

                if ($uid != '') {
                    $customer_str = "SELECT id  FROM " . TABLE__CUSTOMEREXP . " WHERE uid='" . $uid . "' LIMIT 1";
                    $customer_arr = $parent->getQueryValue($customer_str);

                    if (!count($customer_arr) > 0) {
                        $parent->response(array('response' => 'failed', 'message' => 'INVALID USER'), 406);
                    }
                    $customer_data[$key]['customerid'] = $customer_arr[0]->id;
                } else {
                    $customer_data[$key]['customerid'] = 0;
                }

                //CHECK MODEL
                $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`,model_type ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
                if (!$query_modelarr['nr'] > 0) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
                }
                $token = ($query_modelarr['result'][0]->model_type == '1') ? MODE_TWO_TOKEN : MODE_ONE_TOKEN;
                $customer_data[$key]['token'] = $token;
            }

            foreach ($customer_data as $res) {
                //$REQUEST_KEYS=array('variant_id'=>'integer','name'=>'string','mobile'=>'string','email'=>'string');
                //globalfunc::mandatoryKey($parent,$REQUEST_KEYS);

                $model_id = escape_str($res['model_id']);
                $variant_id = escape_str($res['variant_id']);
                $name = escape_str($res['name']);
                $mobile = escape_str($res['mobile']);
                $email = escape_str($res['email']);
                $is_brochure = escape_str($res['is_brochure']);
                $is_brochure = ($is_brochure == '1') ? "1" : "0";
                $customerid = $res['customerid'];
                $token = $res['token'];

                $explore_url = SITE_URL . "#/download_brouchure/" . $model_id . "/" . $variant_id . "/" . $token;

                $insert_str = "INSERT INTO " . TABLE_EXPLORE_ENQUIRY . " (  `user_id`, `model_id`, `variant_id`, `name`, `mobile`, `email`, `customerid`, `is_brochure`, `created_on`, `modified_on`) VALUES ( '" . $parent->current_user_id . "', '" . $model_id . "', '" . $variant_id . "', '" . $name . "', '" . $mobile . "', '" . $email . "','" . $customerid . "', '" . $is_brochure . "','" . NOW . "','" . NOW . "')";
                $insertquery = $parent->executeQuery($insert_str);

                $query_dealerarr = $parent->selectQuery(DMS_DEALER, " *", "dealer_code='" . $parent->current_user_data->dealer_code . "'", "1");
                if ($query_dealerarr['nr'] > 0) {
                    $dealer_details_str = $query_dealerarr['result'][0]->dealer_name;
                    $dealer_details_str .= ($query_dealerarr['result'][0]->address != '') ? '<br>' . trim($query_dealerarr['result'][0]->address) : '';
                    $dealer_details_str .= ($query_dealerarr['result'][0]->phone != '') ? '<br>Mob : ' . trim($query_dealerarr['result'][0]->phone) : '';
                    $dealer_details_str .= ($query_dealerarr['result'][0]->email != '') ? '<br>Email : ' . trim($query_dealerarr['result'][0]->email) : '';
                } else {
                    $dealer_details_str = 'HYPER-M';
                }

                $cond_mail_str1 = (in_array($parent->current_user_role, array("16"))) ? "Thank you for showing your interest in HYPER-M and visiting Dealership." : "Thank you for showing your interest in HYPER-M.";
                $cond_mail_str2 = (in_array($parent->current_user_role, array("16", "17"))) ? "We hope you had a great experience in exploring our range of students." : "We hope you had a great experience in exploring our range of students";

                $email_link = ($is_brochure == '1') ? '<a href="' . $explore_url . '" style="font-weight:bold " >Click Here</a> to download the product e-brochure for your reference.<br>' : "";

                //MAIL AND SMS TRIGGER
                $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
  <tbody>
    <tr>
      <td>
        <table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
          <tbody>
            <tr>
              <td bgcolor="#2d2d2d" height="36" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#e4e4e4;	text-align:left;	font-weight:bold; padding-left:14px; border-bottom:2px solid black">HYPER-M</td>
            </tr>
            <tr>
              <td>
                <table width="85%" align="center">
                  <tbody>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;">
                        <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Dear ' . $name . ',</div>
                      </td>
                    </tr>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;">
                        <div style="font-family:arial; color:#333; font-size:12px; padding:5px;">Greetings of the Day..!<br>
                        ' . $cond_mail_str1 . '<br>
' . $cond_mail_str2 . '<br><br>
' . $email_link . '
Thank you again for your visit and we look forward to see you soon.
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
                    line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">
                      <p  >With regards </p>
					<p  >' . $dealer_details_str . '</p><br>
Visit us at: <a href="">click here<a><br>
Toll Free Number: 1800-121-7996 (Mon-Sat 9AM - 5:30PM)</p>
<p>This is a system generated e-mail, please do not reply to this mail. </p>
                </div>

                      </td>
                    </tr>

                  </tbody>
                </table>
              </td>
            </tr>
            <tr>
              <td style="padding-top:0px; padding-bottom:10px;"></td>
            </tr>
            <tr>
              <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:20px;  border-bottom:2px solid black">
                 &nbsp;
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>';
                $obj = array();
                $obj['from'] = CUSTOMER_EXPERIENCE_EMAIL;
                $obj['FromName'] = 'Customer Experience App';

                //$obj['replayto']=SUPPORT_EMAIL;
                $obj['to'] = $email;
                $obj['subject'] = "THANK YOU FOR ENQUIRY - HYPER-M";
                $obj['message'] = $message;
                // globalfunc::sendMai($parent, $obj);

            }
        } else {
            $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA'), 406);
        }

        //LOG
        $logstr = 'EXPLORE ENQUIRY';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODEL ACCESSORIES RIDERS
    private function accessories_riders($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));
        $append_url = SITE_URL . "explore_assets/accessories/";

        $data_arr = array('category' => array(), 'data' => array());

        $cat_data = array();
        //GET ACCESSORIES
        $query_arr = $parent->selectQuery(TABLE_EXPLORE_ACCESSORIES, "*, CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url' ", "type='2' AND is_deleted=0 ", "");
        if ($query_arr['nr'] > 0) {
            foreach ($query_arr['result'] as $res) {
                $cat_data[$res->cat_id][] = $res;
            }

            $cat_query_arr = $parent->selectQuery(TABLE_EXPLORE_ACCESSORIES_CATEGORY, "*", "is_deleted=0 AND id IN (SELECT cat_id FROM " . TABLE_EXPLORE_ACCESSORIES . " WHERE type='2' AND is_deleted=0 ) ORDER BY cat_pos ASC", "");
            if ($cat_query_arr['nr']) {
                foreach ($cat_query_arr['result'] as $key => $val) {
                    $cat_query_arr['result'][$key]->data = $cat_data[$val->id];
                }
            }

            $data_arr = array('category' => $cat_query_arr['result'], 'data' => $query_arr['result']);
        }

        //LOG
        $logstr = 'EXPLORE ACCESSORIES RIDERS';
        globalfunc::insertUserLog($parent, $logstr);

        // $data_arr= array('model'=>$query_modelarr['result'][0],'category'=>$category_arr,'compare_model'=>$compare_model_arr);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODEL ACCESSORIES BIKES
    private function accessories_bikes($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));
        $append_url = SITE_URL . "explore_assets/accessories/";

        $model_id = escape_str($parent->params['1']);
        $data_arr = array('category' => array(), 'data' => array());
        //GET ACCESSORIES
        $query_arr = $parent->selectQuery(TABLE_EXPLORE_ACCESSORIES, "*, CASE WHEN image!='' THEN CONCAT('" . $append_url . "',image) ELSE '" . NOIMAGE_URL . "' END AS 'image_url' ", "type='1' AND is_deleted=0 AND model_id='" . $model_id . "' ", "");
        if ($query_arr['nr'] > 0) {
            $cat_query_arr = $parent->selectQuery(TABLE_EXPLORE_ACCESSORIES_CATEGORY, "*", "is_deleted=0 AND id IN (SELECT cat_id FROM " . TABLE_EXPLORE_ACCESSORIES . " WHERE type='1' AND is_deleted=0 AND model_id='" . $model_id . "' ) ORDER BY cat_pos ASC", "");
            $data_arr = array('category' => $cat_query_arr['result'], 'data' => $query_arr['result']);
        }

        //LOG
        $logstr = 'EXPLORE ACCESSORIES BIKES';
        globalfunc::insertUserLog($parent, $logstr);

        // $data_arr= array('model'=>$query_modelarr['result'][0],'category'=>$category_arr,'compare_model'=>$compare_model_arr);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    //MODELS CONTENT
    private function contentlist($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'explore'));

        $url_data = escape_str($parent->params['1']);
        //PAGINATION SETTINGS
        $limit_cond = '';
        $data_arr = array();
        $limit_str = globalfunc::setPageLimit($parent, $url_data);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $url_data_arr = @explode('?', $url_data);
        $model_id = $url_data_arr[0];
        //CHECK MODEL
        $query_modelarr = $parent->selectQuery(TABLE_COMPARE_MODEL, " `model_id`  ", "model_id='" . $model_id . "' AND is_other=0 ", "1");
        if (!$query_modelarr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }
        //S3_CUS_CONTENT_URL

        $model_content_arr = $parent->selectQuery(TABLE_EXPLORE_CONTENT . " c JOIN " . TABLE_EXPLORE_FILE . " f on c.contentid=f.contentid", "SQL_CALC_FOUND_ROWS c.contentid,c.title,c.description,c.uploaddate,c.version,c.uploaddate,f.filepath,f.thumbpath", " c.status='1' AND c.is_deleted='0' AND c.model_id='" . $model_id . "'  ORDER BY c.contentid ASC " . $limit_cond, "");

        $customer_arr = $parent->getQueryValue("select FOUND_ROWS() as total_records");

        if ($model_content_arr['nr']) {
            //CONNECT S3
            $s3 = awsfileserver::connectS3();
            foreach ($model_content_arr['result'] as $key => $res) {
                $model_content_arr['result'][$key]->file_url = ($res->filepath != '') ? awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_CUS_CONTENT_URL . $res->filepath) : NOIMAGE_URL;
                $model_content_arr['result'][$key]->thumb_url = ($res->thumbpath != '') ? awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_CUS_CONTENT_URL . $res->thumbpath) : NOIMAGE_URL;

                $data_arr[] = $model_content_arr['result'][$key];
            }
        }

        //GET COUNT
        $total = (count($customer_arr) > 0) ? $customer_arr[0]->total_records : 0;

        //LOG
        $logstr = 'CUSTOMER EXPERIENCE MODELS CONTENT';
        globalfunc::insertUserLog($parent, $logstr, $cateid);

        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

}
