<?php
/****************************
 * File : enquiry.php
 * Author : Cygnusa
 * @2020
 ****************************/

//SECURITY
if (!defined('APPLICATION_PATH')) {
    exit('No direct script access allowed');
}
/* cSpell:disable */
//FUNCTION LISTS
function comparator($object1, $object2)
{
    return $object1->order > $object2->order;
}
class enquiry
{

    public function __construct($parent)
    {

        //GET PAGE MESSAGE
        $this->page_data = globalfunc::getMessage($parent, $parent->lang, 'enquiry');
        if (count($parent->params) == 0) {
            $this->enquirysubmit($parent);

        } else {
            $qry_params = explode("?", $parent->params[0]);
            $parameter_val = strtolower($qry_params[0]);

            switch ($parameter_val) {
                case "common":
                case "checkunsave":
                case "deleteunsave":
                case "otp":
                case "otpvalidate":
                case "dashboard":
                case "enquirysales":
                case "listdata":
                case "details":
                case "followup":
                case "stockavailability":
                case "sharebrochure": //NOT COMPLETED
                //case "followuphistory":
                case "quotation":
                case "sharequotation":
                // case "getquotation":
                case "pricelist":
                case "testride":
                case 'plannerlist':
                case 'plannersave':
                case 'plannerupdate':
                case 'plannerdelete':
                case "plannertimer":
                case "smpindealer":
                case "dealer":
                case "followupcommon":
                case "testrideupdate":
                case "testrideotp":
                    $this->$parameter_val($parent);
                    break;

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

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

    /* /////////////////////////////// COMMON //////////////////////////////////////////////// */
    private function common($parent)
    {

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

        //CHECK SMPIN OTP EXIST
        $buyertype_data = $parent->selectQuery(DMS_ENQUIRY_BUYERTYPE, "id,title,title_code", " status='1'", "");
        $title_data = $parent->selectQuery(DMS_ENQUIRY_TITLE, "id,title,title_code", " status='1'", "");
        $company_data = $parent->selectQuery(DMS_ENQUIRY_ORGANISATION, "id,title,title_code", " status='1'", "");
        $communicate_data = $parent->selectQuery(DMS_ENQUIRY_COMMUNICATE, "id,title,title_code", " status='1'", "");
        $action_data = $parent->selectQuery(DMS_ENQUIRY_ACTIONPLAN, "id,title,title_code", " status='1'", "");
        $purpose_data = $parent->selectQuery(DMS_ENQUIRY_PURPOSE, "id,title,title_code", " status='1'", ""); //STAGE SAME ONLY
        switch ($parent->current_user_data->segment) {
            case '0':$segmentcond = "";
                break;
            case '1':$segmentcond = " AND segment='1'";
                break;
            case '2':$segmentcond = " AND segment='2'";
                break;
        }

        $model_data = $parent->selectQuery(DMS_ENQUIRY_MODEL, "title,title_code", " status='1' AND enq_yn='Y' " . $segmentcond . " GROUP BY title_code", "");

        $profession_data = $parent->selectQuery(DMS_ENQUIRY_PROFESSION, "title,title_code", " status='1' ", "");
        $sdata = array();
        $dealer_code = $parent->current_user_data->dealer_code;
        $dealer_data = $parent->selectQuery(DMS_DEALER, "dealer_map_cd", "dealer_code='" . $dealer_code . "' AND status='1' AND is_deleted=0 AND dealer_map_cd!=''", "1");
        //dealer_map_cd
        if ($dealer_data['nr'] > 0) {
            $p_dealer = $dealer_data['result'][0]->dealer_map_cd;

            //GET SOURCE
            $url = SUZ_DMS_URL;
            $post = array("query" => "BEGIN pkg_smipl_star_app.sp_enquiry_source(:p_dealer, :list_cursor, :p_err_cd, :p_err_msg); END;", "params" => '[{"title":"p_dealer","value":"' . $p_dealer . '","type":""},{"title":"list_cursor","value":"","type":"cursor"},{"title":"p_err_cd","value":"0","type":""},{"title":"p_err_msg","value":"","type":""}]');
            $header = array('Authorization:Bearer ' . SUZ_TOKEN);

            //LOG
            $obj = new stdClass();
            $obj->type = 'callsource';
            $obj->apirequest = $post['params'];
            $log_id = projectfunc::cronLog($parent, $obj);

            // $ch = curl_init();
            // curl_setopt($ch, CURLOPT_URL, $url);
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
            // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            // $response = curl_exec($ch);
            // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            // curl_close($ch);
            $httpcode = '200';
            $response="";
            $error = 1;
            $count = 0;

            //REPSONSE SAVE
            $obj = new stdClass();
            $obj->id = $log_id;
            $obj->apiresponse = $response;
            projectfunc::updateCronLog($parent, $obj);

            if ($httpcode == '200' && $response != '') {
                $json = json_decode($response);
                if (isset($json->response) && $json->response == 'success' && isset($json->data) && count($json->data) > 0) {
                    foreach ($json->data as $res) {
                        $new = new stdClass();
                        $new->title = $res->ETYPE_DESC;
                        $new->title_code = $res->ETYPE_CD;
                        $sdata[] = $new;
                    }
                    $source_data['nr'] = count($sdata);
                    $source_data['result'] = $sdata;

                    //LOG UPDATE
                    $obj = new stdClass();
                    $obj->id = $log_id;
                    $obj->insert_count = $source_data['nr'];
                    $obj->status = 1;
                    projectfunc::updateCronLog($parent, $obj);
                }
            }
        }
        if (count($sdata) == 0) {
            $source_data = $parent->selectQuery(DMS_ENQUIRY_SOURCE, "title,title_code", " status='1' ", "");
        }

        $custtype_data = $parent->selectQuery(DMS_ENQUIRY_CUSTTYPE, "title,title_code", " status='1' ", "");
        $custage_data = $parent->selectQuery(DMS_ENQUIRY_CUSTAGE, "title,title_code", " status='1' ", "");
        $modeofcontact_data = $parent->selectQuery(DMS_ENQUIRY_MODE, "title,title_code", " status='1' ", "");

        $brochure_arr = array();
        $brochure_url = SITE_URL . "explore_assets/model/";
        $expmodel_data = $parent->selectQuery(TABLE_COMPARE_MODEL, "model_id,CASE WHEN model_brochure!='' THEN CONCAT('" . $brochure_url . "',model_brochure) ELSE '' END AS 'model_brochure', CASE WHEN model_image!='' THEN CONCAT('" . SITE_URL . "hypermupload/model/',model_image) ELSE '" . NOIMAGE_URL . "' END as model_image  ", "is_deleted=0 AND is_other=0  AND `model_type` = '0'", "");
        if ($expmodel_data['nr'] > 0) {
            $arr_id = array_column($expmodel_data['result'], 'model_id');
            $arr_name = array_column($expmodel_data['result'], 'model_brochure');
            $brochure_arr = array_combine($arr_id, $arr_name);
            $arr_image = array_column($expmodel_data['result'], 'model_image');
            $img_arr = array_combine($arr_id, $arr_image);
        }

        //MODEL DATA BUILD
        if ($model_data['nr'] > 0) {
            foreach ($model_data['result'] as $key => $res) {

                $variant_data = $parent->selectQuery(DMS_ENQUIRY_MODEL, "variant title,variant_code title_code", " status='1' AND title_code='" . $res->title_code . "'  AND enq_yn='Y' " . $segmentcond . " GROUP BY variant_code", "");
                if ($variant_data['nr'] > 0) {
                    foreach ($variant_data['result'] as $nkey => $resm) {
                        $color_data = $parent->selectQuery(DMS_ENQUIRY_MODEL, "color title,color_code title_code", " status='1' AND title_code='" . $res->title_code . "' AND variant_code='" . $resm->title_code . "' AND enq_yn='Y' " . $segmentcond . " GROUP BY color_code", "");
                        $variant_data['result'][$nkey]->color = ($color_data['nr'] > 0) ? $color_data['result'] : array();
                        $variant_data['result'][$nkey]->model_image = NOIMAGE_URL;
                        $brochure_url = '';
                        $model_image = NOIMAGE_URL;
                        switch ($res->title_code) {
                            case 'GSX': //GIXXER
                                $id = (strpos($resm->title_code, 'GSX250') !== false || strpos($resm->title, 'GIXXER 250') !== false) ? GIXXER_250_ID : GIXXER_ID;
                                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                                $model_image = isset($img_arr[$id]) ? $img_arr[$id] : NOIMAGE_URL;
                                break;
                            case 'GSXSF': //GIXXER SF
                                $id = (strpos($resm->title_code, 'GSXF250') !== false || strpos($resm->title, 'GIXXER SF 250') !== false) ? GIXXER_SF_250_ID : GIXXER_SF_ID;
                                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                                $model_image = isset($img_arr[$id]) ? $img_arr[$id] : NOIMAGE_URL;
                                break;
                            case 'GL': //INTRUDER
                                $id = INTRUDER_ID;
                                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                                $model_image = isset($img_arr[$id]) ? $img_arr[$id] : NOIMAGE_URL;
                                break;
                            case 'UB125': //BURGMAN
                                $id = BURGMAN_ID;
                                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                                $model_image = isset($img_arr[$id]) ? $img_arr[$id] : NOIMAGE_URL;
                                break;
                            case 'AC':
                            case 'ACZ':
                                $id = ACCESS_ID;
                                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                                $model_image = isset($img_arr[$id]) ? $img_arr[$id] : NOIMAGE_URL;
                                break;
                            default:
                                $brochure_url = '';
                                break;

                        }
                        $variant_data['result'][$nkey]->brochure = $brochure_url;
                        $variant_data['result'][$nkey]->model_image = $model_image;
                    }
                }

                $model_data['result'][$key]->variant = ($variant_data['nr'] > 0) ? $variant_data['result'] : array();
            }
        }

        $buyertype_arr = ($buyertype_data['nr'] > 0) ? $buyertype_data['result'] : array();
        $title_arr = ($title_data['nr'] > 0) ? $title_data['result'] : array();
        $company_arr = ($company_data['nr'] > 0) ? $company_data['result'] : array();
        $communicate_arr = ($communicate_data['nr'] > 0) ? $communicate_data['result'] : array();
        $action_arr = ($action_data['nr'] > 0) ? $action_data['result'] : array();
        $purpose_arr = ($purpose_data['nr'] > 0) ? $purpose_data['result'] : array();
        $model_arr = ($model_data['nr'] > 0) ? $model_data['result'] : array();

        $profession_arr = ($profession_data['nr'] > 0) ? $profession_data['result'] : array();
        $source_arr = ($source_data['nr'] > 0) ? $source_data['result'] : array();
        $custtype_arr = ($custtype_data['nr'] > 0) ? $custtype_data['result'] : array();
        $custage_arr = ($custage_data['nr'] > 0) ? $custage_data['result'] : array();
        $modeofcontact_arr = ($modeofcontact_data['nr'] > 0) ? $modeofcontact_data['result'] : array();

        $t_arr = array("00", "30");
        for ($i = 9; $i < 19; $i++) {
            $m = ($i < 10) ? "0" . $i : $i;
            foreach ($t_arr as $tstr) {
                //$t=($tstr<10)?"0".$tstr:$tstr;
                $tvalue = $m . ":" . $tstr;
                $time_arr[] = array('title' => $tvalue, 'title_code' => $tvalue);
            }
        }

        $gender = array(0 => array('title' => "Male", "title_code" => "M"), 1 => array('title' => "Female", "title_code" => "F"), 2 => array('title' => "Transgender", "title_code" => "T"));
        $data = array('gender' => $gender, 'buyertype' => $buyertype_arr, 'title' => $title_arr, 'company' => $company_arr, 'communicate' => $communicate_arr, 'actionplan' => $action_arr, 'purpose' => $purpose_arr, 'model' => $model_arr, 'profession' => $profession_arr, 'source' => $source_arr, 'custtype' => $custtype_arr, 'custage' => $custage_arr, 'time' => $time_arr, 'modeofcontact' => $modeofcontact_arr);
        //LOG
        $logstr = 'ENQUIRY COMMON';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECKUNSAVE //////////////////////////////////////////////// */
    private function checkunsave($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

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

        $smpin = $parent->current_user_data->smpin;
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", "save_level!=0 AND smpin='" . $smpin . "' AND is_starapp=1 AND is_dms=0 AND is_deleted=0 ", "1");

        $total = ($check_arr['nr'] > 0) ? 1 : 0;
//        $total_arr=$parent->getQueryValue("SELECT FOUND_ROWS() as total_record");
        //        $total=(count($total_arr)>0)?$total_arr[0]->total_record:0;

        //EXIST CHECK
        $is_exist = ($check_arr['nr'] > 0) ? 1 : 0;
        $data = new stdClass();
        $data->details = array();
        if ($is_exist == 1) {
            foreach ($check_arr['result'] as $res) {
                $data->details[] = $this->getEnquirydata($parent, $res->id);
            }
        }
        $data->is_exist = $is_exist;

        //LOG
        $logstr = 'ENQUIRY CHECKUNSAVE';
        globalfunc::insertUserLog($parent, $logstr);

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

    /* /////////////////////////////// DELETE UNSAVE //////////////////////////////////////////////// */
    private function deleteunsave($parent)
    {

        globalfunc::checkMethodType($parent, array('DELETE'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;
        $id = escape_str($parent->params[1]);

        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,is_deleted", " smpin='" . $smpin . "' AND is_dms=0 AND id='" . $id . "'  ", "1");

        if ($check_arr['nr'] == 1) {
            $update_str = "UPDATE  " . DMS_ENQUIRY_MASTER . " SET is_deleted=1 ,`modified_on`='" . NOW . "' WHERE id='" . $id . "'";
            $parent->executeQuery($update_str);

            //LOG
            $logstr = 'ENQUIRY UNSAVE DELETE';
            globalfunc::insertUserLog($parent, $logstr);
            $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
        } else {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// OTP //////////////////////////////////////////////// */
    private function otp($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $REQUEST_KEYS = array('mobile' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $mobile = escape_str($parent->_request['mobile']);
        $smpin = $parent->current_user_data->smpin;
        $otp_expiry = globalfunc::generateExpiryTime($parent, ENQUIRY_OTP_EXPIRY_MIN);
        $otp = globalfunc::generateOTP();

        //CHECK SMPIN OTP EXIST
        $query_arr = $parent->selectQuery(TABLE_ENQUIRY_OTP, "id", " smpin='" . $smpin . "' AND is_checked=0 AND mobile='" . $mobile . "'", "1");
        if ($query_arr['nr'] > 0) {
            $update_str = "UPDATE  " . TABLE_ENQUIRY_OTP . " SET  `otp`='" . $otp . "', otp_expiry='" . $otp_expiry . "',  `modified_on`='" . NOW . "' WHERE id='" . $query_arr['result'][0]->id . "'";
            $parent->executeQuery($update_str);
        } else {
            $insert_str = "INSERT INTO " . TABLE_ENQUIRY_OTP . " (  `smpin`, `mobile`, `otp`, `otp_expiry`, `created_on`, `modified_on`) VALUES ('" . $smpin . "', '" . $mobile . "', '" . $otp . "', '" . $otp_expiry . "', '" . NOW . "', '" . NOW . "')";
            $parent->executeQuery($insert_str);
        }
        $sms_message = "Your one time password is " . $otp;
        // globalfunc::sendSMS($parent, $mobile, $sms_message);

        $mobile_exist = 0;
        $enq_data = new stdClass();
        //AND dealer_code='".$parent->current_user_data->dealer_code."'
        $mobile_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER . " e JOIN " . DMS_EMPLOYEE . " p ON e.smpin=p.smpin JOIN " . DMS_ENQUIRY_MODEL . " m ON e.model1=m.title_code", "m.title as model,m.variant,m.color,e.newvechicledate", "e.mobile='" . $mobile . "' AND p.dealer_code='" . $parent->current_user_data->dealer_code . "' AND e.is_dms=1 AND e.is_deleted=0 ORDER BY e.newvechicledatatime DESC", "1");
        if ($mobile_arr['nr'] > 0) {
            $mobile_exist = 1;
            $enq_data = $mobile_arr['result'][0];
        }

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

    /* /////////////////////////////// OTP VALIDATE //////////////////////////////////////////////// */
    private function otpvalidate($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $REQUEST_KEYS = array('mobile' => 'string', 'otp' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $mobile = escape_str($parent->_request['mobile']);
        $otp = escape_str($parent->_request['otp']);
        $smpin = $parent->current_user_data->smpin;

        //CHECK SMPIN OTP EXIST
        $query_arr = $parent->selectQuery(TABLE_ENQUIRY_OTP, "*", " smpin='" . $smpin . "' AND mobile='" . $mobile . "' AND is_checked=0 ORDER BY id DESC", "1");
        if (!$query_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error2']), 406);
        }

        if ($query_arr['result'][0]->otp != $otp) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error3']), 406);
        }

        if (strtotime($query_arr['result'][0]->otp_expiry) < strtotime(NOW)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error4']), 406);
        }

        $parent->executeQuery("UPDATE " . TABLE_ENQUIRY_OTP . " SET is_checked=1 WHERE id='" . $query_arr['result'][0]->id . "'");

        /*
        $data_check=array();
        $check_arr=$parent->selectQuery(DMS_ENQUIRY_MASTER,"*"," mobile='".$mobile."'  ORDER BY id DESC","1");
        $enquiry_avaliable=0;
        if($check_arr['nr']>0)
        {
        $enquiry_avaliable=(strtolower($check_arr['result'][0]->status)=='lost' || strtolower($check_arr['result'][0]->enquiry_stage)=='invoiced')?"0":"1";
        $data=($enquiry_avaliable=='1')?$check_arr['result'][0]:new stdClass();
        }
         */
        $data = new stdClass();
        $data_check = array("enquiry_avaliable" => $enquiry_avaliable, 'data' => $data);

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

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// ENQUIRY SUBMIT //////////////////////////////////////////////// */
    private function getEnquirydata($parent, $id)
    {
        $data_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, " `id`, `enq_num`,   `transaction_id`, `enq_salesman_cd`, `smpin`, `mobile`, `email`, `buyer_type`, `title`, `first_name`, `middle_name`, `last_name`, `ind_sex`, `address1`, `address2`, `address3`, `city`, `state`, `ofc_address1`, `ofc_address2`, `ofc_address3`, `ofc_city`, `ofc_state`, `workplace_id`,  `company`, `work_place_name`, `communicate`,   `newvechicledatatime`, `newvechicletactionplan`,  `oldvechicledate`, `oldvechicletime`, `oldvechicletactionplan`,   `model1`, `variant1`, `color1`, `model2`, `variant2`, `color2`, `oldvechiclemaker`, `oldvechiclemodel`, `profession`, `source`, `custtype`, `custage`, `modeofcontact`, `enquiry_stage`, `lik_pur_days`, `followup_remark`, `status`, `save_level`, `is_dms`, `is_starapp`, `created_on`, `modified_on`,ind_sex as gender,DATE_FORMAT(newvechicledatatime, '%d-%m-%Y') newvechicledate,newvechicletime,enquiry_stage as newvechicletpurpose,is_starapp,license,license_expiry,is_testride ", "id='" . $id . "'", "1");

        $data_arr['result'][0]->model_image_url = NOIMAGE_URL;
        if ($data_arr['result'][0]->model1 != '' && $data_arr['result'][0]->variant1 != '') {

            $data_arr['result'][0]->license_expiry = ($data_arr['result'][0]->is_testride == 1 && $data_arr['result'][0]->license_expiry != '0000-00-00') ? date('d-m-Y', strtotime($data_arr['result'][0]->license_expiry)) : '';

            $res = $data_arr['result'][0];

            $model_arr = $parent->selectQuery(DMS_ENQUIRY_MODEL, "title as model_name,variant as variant_name,color as color_name", "title_code='" . $res->model1 . "' AND variant_code='" . $res->variant1 . "' AND color_code='" . $res->color1 . "'", "");

            $data_arr['result'][0]->model_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->model_name : $res->model1;
            $data_arr['result'][0]->variant_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->variant_name : $res->variant1;
            $data_arr['result'][0]->color_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->color_name : $res->color1;
            $data_arr['result'][0]->enq_through = ($res->is_starapp == 1) ? "HYPER-M App" : "DMS";
            $data_arr['result'][0]->newvechicledatatime_str = projectfunc::enqdatediff($parent, NOW, $res->newvechicledatatime);

            $obj = new stdClass();
            $obj->model = $data_arr['result'][0]->model1;
            $obj->variant = $data_arr['result'][0]->variant1;
            $obj->variantname = $data_arr['result'][0]->variant_name;
            $data_arr['result'][0]->model_image_url = projectfunc::modelimage($parent, $obj);

            //enquiry type, source,profession,age group
            $enquiry_arr = $parent->selectQuery(DMS_ENQUIRY_STAGETYPE, "title", "title_code='" . $res->enquiry_stage . "'", "1");
            $data_arr['result'][0]->enquiry_str = ($enquiry_arr['nr'] > 0) ? $enquiry_arr['result'][0]->title : '';

            $profession_arr = $parent->selectQuery(DMS_ENQUIRY_PROFESSION, "title", "title_code='" . $res->profession . "'", "1");
            $data_arr['result'][0]->profession_str = ($profession_arr['nr'] > 0) ? $profession_arr['result'][0]->title : '';

            $age_arr = $parent->selectQuery(DMS_ENQUIRY_CUSTAGE, "title", "title_code='" . $res->custage . "'", "1");
            $data_arr['result'][0]->agegroup_str = ($age_arr['nr'] > 0) ? $age_arr['result'][0]->title : '';

            $title_arr = $parent->selectQuery(DMS_ENQUIRY_TITLE, "title", "title_code='" . $res->title . "'", "1");
            $data_arr['result'][0]->title_str = ($title_arr['nr'] > 0) ? $title_arr['result'][0]->title : '';

            $source_arr = $parent->selectQuery(DMS_ENQUIRY_SOURCE, "title", "title_code='" . $res->source . "'", "1");
            $data_arr['result'][0]->source_str = ($source_arr['nr'] > 0) ? $source_arr['result'][0]->title : '';

            $status_arr = $parent->selectQuery(DMS_ENQUIRY_STATUS, "title", "title_code='" . $res->status . "'", "1");
            $data_arr['result'][0]->status_str = ($status_arr['nr'] > 0) ? $status_arr['result'][0]->title : '';

            $action_arr = $parent->selectQuery(DMS_ENQUIRY_ACTIONPLAN, "title", "title_code='" . $res->newvechicletactionplan . "'", "1");
            $data_arr['result'][0]->action_str = ($action_arr['nr'] > 0) ? $action_arr['result'][0]->title : '';

            $checkdate = date('Y-m-d', strtotime($res->newvechicledatatime));
            //0-overdue,1-current day,2-future
            switch (true) {
                case (strtotime($checkdate) < strtotime(CUR_DATE)): $data_arr['result'][0]->enq_date_type = 0;
                    break;
                case (strtotime($checkdate) == strtotime(CUR_DATE)): $data_arr['result'][0]->enq_date_type = 1;
                    break;
                case (strtotime($checkdate) > strtotime(CUR_DATE)): $data_arr['result'][0]->enq_date_type = 2;
                    break;
            }
            ///PENDING ENQUIRY MASTER
            if (strtoupper($res->enquiry_stage) == 'T') {
                $data_arr['result'][0]->icon_type = 1;
            } else if (strtoupper($res->modeofcontact) == 'S' || strtoupper($res->modeofcontact) == 'V') {
                $data_arr['result'][0]->icon_type = 2;
            } else if (in_array(strtoupper($res->modeofcontact), array('E', 'F', 'O', 'T'))) {
                $data_arr['result'][0]->icon_type = 3;
            } else {
                $data_arr['result'][0]->icon_type = 0;
            }
            //visit,call,testdrive
        }
        return ($data_arr['nr'] > 0) ? $data_arr['result'][0] : new stdClass();
    }

    /* /////////////////////////////// ENQUIRY SUBMIT //////////////////////////////////////////////// */
    private function enquirysave($parent, $save_level)
    {
        $smpin = $parent->current_user_data->smpin; //p_mspin
        $dealer_code = $parent->current_user_data->dealer_code; //p_mspin
        switch ($save_level) {
            case '1':
                $REQUEST_KEYS = array('buyer_type' => 'string', 'title' => 'string', 'first_name' => 'string', 'company' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                $id = escape_str($parent->_request['id']);
                $edit = 0;
                $econd = '';
                //CHECK EXITS
                if ($id != '') {
                    $edit = 1;
                }

                if ($edit == 1) {
                    $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", "  smpin='" . $smpin . "' AND id='" . $id . "' AND is_starapp=1 AND is_dms=0 AND is_deleted=0 ", "1");
                    if ($check_arr['nr'] == 0) {
                        $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
                    }

                    $econd = " AND id!='" . $id . "'";
                }

                //CHECK ALREDY EXIST
                $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", "smpin='" . $smpin . "' " . $econd . " AND is_starapp=1 AND is_dms=0 AND is_deleted=0 ", "1");
                if ($check_arr['nr'] > 0) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data['error7']), 406);
                }

                $buyer_type = escape_str($parent->_request['buyer_type']); //buyer_type
                $title = escape_str($parent->_request['title']); //p_title

                $first_name = escape_str($parent->_request['first_name']); //fname
                $middle_name = escape_str($parent->_request['middle_name']); //mid_name
                $last_name = escape_str($parent->_request['last_name']); //l_name
                $gender = ($parent->_request['gender']) ? escape_str($parent->_request['gender']) : ""; //gender
                $email = escape_str($parent->_request['email']); //p_email
                if ($email != '') {
                    if (!globalfunc::isValidEmail($email)) {
                        $parent->response(array('response' => 'failed', 'message' => $this->page_data['error12']), 406);
                    }

                }

                $address1 = escape_str($parent->_request['address1']); //address1
                $address1 = str_replace(array("\n", "\r"), ' ', $address1);
                $address2 = escape_str($parent->_request['address2']); //address2
                $address3 = escape_str($parent->_request['address3']); //address3

                $city = escape_str($parent->_request['city']); //city
                $state = escape_str($parent->_request['state']); //state

                //GET DEALER
                $getdealerarr = $parent->selectQuery(DMS_DEALER, "city_cd,state_cd", "dealer_code='" . $parent->current_user_data->dealer_code . "' ", "1");
                if ($getdealerarr['nr'] > 0) {
                    $city = ($getdealerarr['result'][0]->city_cd != '') ? $getdealerarr['result'][0]->city_cd : '';
                    $state = ($getdealerarr['result'][0]->state_cd != '') ? $getdealerarr['result'][0]->state_cd : '';
                }

                $company = escape_str($parent->_request['company']); //p_work_place_id
                $work_place_name = escape_str($parent->_request['work_place_name']); //p_work_place_name
                if ($edit == 0) {
                    $parent->executeQuery("INSERT INTO `" . DMS_ENQUIRY_MASTER . "` ( smpin, dealer_code, `buyer_type`, `title`, `first_name`, `middle_name`, `last_name`, `ind_sex`, `email`, `address1`, `address2`, `address3`, `city`, `state`,  `company`, `work_place_name`,save_level,is_dms,is_starapp ,`created_on`, `modified_on`) VALUES ('" . $smpin . "','" . $dealer_code . "','" . $buyer_type . "','" . $title . "','" . $first_name . "','" . $middle_name . "','" . $last_name . "','" . $gender . "','" . $email . "','" . $address1 . "','" . $address2 . "','" . $address3 . "','" . $city . "', '" . $state . "','" . $company . "','" . $work_place_name . "',1,0,1,'" . NOW . "', '" . NOW . "')");
                    $id = $parent->lastInsertId();
                } else {
                    $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET dealer_code='" . $dealer_code . "', `buyer_type`='" . $buyer_type . "', `title`='" . $title . "', `first_name`='" . $first_name . "', `middle_name`='" . $middle_name . "', `last_name`='" . $last_name . "', `ind_sex`='" . $gender . "', `email`='" . $email . "', `address1`='" . $address1 . "', `address2`='" . $address2 . "', `address3`='" . $address3 . "', `city`='" . $city . "', `state`='" . $state . "',  `company`='" . $company . "', `work_place_name`='" . $work_place_name . "' WHERE id='" . $id . "'");
                }
                //GET DATA
                $data_arr = $this->getEnquirydata($parent, $id);

                //LOG
                $logstr = 'ENQUIRY SAVE LEVEL 1';
                globalfunc::insertUserLog($parent, $logstr, $id);
                $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
                break;
            case '2':
                $REQUEST_KEYS = array('id' => 'number', 'mobile' => 'number', 'communicate' => 'string', 'model1' => 'string', 'variant1' => 'string', 'color1' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

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

                $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,save_level", " id='" . $id . "' AND save_level>=1 AND smpin='" . $smpin . "' AND is_starapp=1 AND is_dms=0 AND is_deleted=0", "1");
                if ($check_arr['nr'] != 1) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data['error8']), 406);
                }

                $query_arr = $parent->selectQuery(TABLE_ENQUIRY_OTP, "*", " smpin='" . $smpin . "' AND mobile='" . $mobile . "' AND is_checked=0 ORDER BY id DESC", "1");
                if ($query_arr['nr'] > 0) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data['error9']), 406);
                }

                $mobile = escape_str($parent->_request['mobile']); //mobile_no
                $communicate = escape_str($parent->_request['communicate']); //mod_of_com

                $model1 = escape_str($parent->_request['model1']); //model
                $variant1 = escape_str($parent->_request['variant1']); //variant
                $color1 = escape_str($parent->_request['color1']); //colour

                //IF ONLY Level one need to update
                if ($check_arr['result'][0]->save_level == 1) {
                    $updcond = ",save_level='2'";
                }
                $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET mobile='" . $mobile . "',`model1`='" . $model1 . "', `variant1`='" . $variant1 . "', `color1`='" . $color1 . "',`communicate`='" . $communicate . "' " . $updcond . "   WHERE id='" . $id . "'");

                //GET DATA
                $data_arr = $this->getEnquirydata($parent, $id);

                //LOG
                $logstr = 'ENQUIRY SAVE LEVEL 2';
                globalfunc::insertUserLog($parent, $logstr, $id);
                $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
                break;
            case '3':
                $REQUEST_KEYS = array('id' => 'number', 'source' => 'string', 'profession' => 'string', 'custtype' => 'string', 'custage' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                $id = escape_str($parent->_request['id']);

                $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,save_level", " id='" . $id . "' AND save_level>=2 AND smpin='" . $smpin . "' AND is_starapp=1 AND is_dms=0 AND is_deleted=0", "1");
                if ($check_arr['nr'] != 1) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data['error8']), 406);
                }

                $source = escape_str($parent->_request['source']); //enq_soruce
                $profession = escape_str($parent->_request['profession']); //occupation
                $custtype = escape_str($parent->_request['custtype']); //cust_type
                $custage = escape_str($parent->_request['custage']); //p_cust_age_group

                if ($check_arr['result'][0]->save_level == 2) {
                    $updcond = ",save_level='3'";
                }

                $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET `source`='" . $source . "', `profession`='" . $profession . "',  `custtype`='" . $custtype . "', `custage`='" . $custage . "' " . $updcond . " WHERE id='" . $id . "'");

                //GET DATA
                $data_arr = $this->getEnquirydata($parent, $id);

                //LOG
                $logstr = 'ENQUIRY SAVE LEVEL 3';
                globalfunc::insertUserLog($parent, $logstr, $id);
                $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
                break;

            default:
                $parent->response(array('response' => 'failed', 'message' => $this->page_data['error10']), 406);
                break;
        }

    }

    /* /////////////////////////////// ENQUIRY SUBMIT //////////////////////////////////////////////// */
    private function enquirysubmit($parent)
    {
        globalfunc::checkParamCount($parent, 0);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

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

        $dealer_code = $parent->current_user_data->dealer_code; //dealer
        $dealer_arr = $parent->selectQuery(DMS_DEALER, "*", "is_enquirymodule=1 AND dealer_code='" . $dealer_code . "'", "1");
        if (!$dealer_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error22']), 406);
        }

        $smpin = $parent->current_user_data->smpin; //p_mspin
        //$dealer_code = $parent->current_user_data->dealer_code;  //p_mspin
        $is_edit = 0;
        switch ($save_level) {
            case '1':
            case '2':
            case '3':

                $is_edit = 1; //FOR SAVE
                $this->enquirysave($parent, $save_level);
                break;
            case '4': //final level submit
                $REQUEST_KEYS = array('id' => 'number', 'newvechicledate' => 'date|d-m-Y', 'newvechicletime' => 'string', 'newvechicletactionplan' => 'string', 'newvechicletpurpose' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
//                $check_arr=$parent->selectQuery(DMS_ENQUIRY_MASTER ,"id","save_level>=3 AND smpin='".$smpin."' AND is_starapp=1 AND is_dms=0 AND is_deleted=0","1");
                //                if($check_arr['nr']>0) $parent->response(array('response'=>'failed','message'=>$this->page_data['error7']),406);
                $is_edit = 1;
                $is_submit = escape_str($parent->_request['is_submit']);
                $is_submit = ($is_submit == '1') ? 1 : 0;
                break;
            default: //do nothing //DIRECT SUBMIT

                $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", "save_level<=4 AND smpin='" . $smpin . "' AND is_dms=0 AND is_deleted=0", "1");
                $update_str = "UPDATE  " . DMS_ENQUIRY_MASTER . " SET is_deleted=1 ,`modified_on`='" . NOW . "' WHERE smpin='" . $smpin . "' AND id='" . $check_arr['result'][0]->id . "'";
                $parent->executeQuery($update_str);

                $REQUEST_KEYS = array('title' => 'string', 'first_name' => 'string', 'company' => 'string', 'communicate' => 'string', 'newvechicledate' => 'date|d-m-Y', 'newvechicletime' => 'string', 'custage' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                break;
        }

        $enq_salesman_cd = '';
        $p_enq = '';
        $mobile = escape_str($parent->_request['mobile']); //mobile_no
        if ($is_edit == 0) {
            $query_arr = $parent->selectQuery(TABLE_ENQUIRY_OTP, "*", " smpin='" . $smpin . "' AND mobile='" . $mobile . "'  ORDER BY id DESC", "1");
            if ($query_arr['nr'] == 0 || (isset($query_arr['result'][0]) && $query_arr['result'][0]->is_checked == 0)) {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data['error9']), 406);
            }

        }
        $newvechicletactionplan = escape_str($parent->_request['newvechicletactionplan']); //p_action

        $first_name = escape_str($parent->_request['first_name']); //fname
        $middle_name = escape_str($parent->_request['middle_name']); //mid_name
        $last_name = escape_str($parent->_request['last_name']); //l_name
        $gender = ($parent->_request['gender']) ? escape_str($parent->_request['gender']) : ""; //gender
        $profession = escape_str($parent->_request['profession']); //occupation
        $email = escape_str($parent->_request['email']); //p_email

        if ($is_edit == 0 && $email != '') {
            if (!globalfunc::isValidEmail($email)) {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data['error12']), 406);
            }

        }

        $address1 = escape_str($parent->_request['address1']); //address1
        $address1 = str_replace(array("\n", "\r"), ' ', $address1);
        $address2 = escape_str($parent->_request['address2']); //address2
        $address3 = escape_str($parent->_request['address3']); //address3

        $city = escape_str($parent->_request['city']); //city
        $state = escape_str($parent->_request['state']); //state

        //GET DEALER
        $getdealerarr = $parent->selectQuery(DMS_DEALER, "city_cd,state_cd", "dealer_code='" . $parent->current_user_data->dealer_code . "' ", "1");
        if ($getdealerarr['nr'] > 0) {
            $city = ($getdealerarr['result'][0]->city_cd != '') ? $getdealerarr['result'][0]->city_cd : '';
            $state = ($getdealerarr['result'][0]->state_cd != '') ? $getdealerarr['result'][0]->state_cd : '';
        }

        $ofc_address1 = escape_str($parent->_request['ofc_address1']); //ofc_address1
        $ofc_address2 = escape_str($parent->_request['ofc_address2']); //ofc_address2
        $ofc_address3 = escape_str($parent->_request['ofc_address3']); //ofc_address3
        $ofc_city = escape_str($parent->_request['ofc_city']); //ofc_city
        $ofc_state = escape_str($parent->_request['ofc_state']); //ofc_state

        $model1 = escape_str($parent->_request['model1']); //model
        $variant1 = escape_str($parent->_request['variant1']); //variant
        $color1 = escape_str($parent->_request['color1']); //colour
        $communicate = escape_str($parent->_request['communicate']); //mod_of_com

        $modeofcontact = $newvechicletactionplan;

        $custtype = escape_str($parent->_request['custtype']); //cust_type
        $buyer_type = escape_str($parent->_request['buyer_type']); //buyer_type
        //$lik_pur_days=escape_str($parent->_request['lik_pur_days']); //lik_pur_days
        $lik_pur_days = '0';
        $source = escape_str($parent->_request['source']); //enq_soruce
        $model_cd = '';
        $variant_cd = '';
        $newvechicledate_str = escape_str($parent->_request['newvechicledate']);
        $newvechicletime = escape_str($parent->_request['newvechicletime']);

        $date_arr = @explode('-', $newvechicledate_str);
        $date_str = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];
        $newvechicledatatime = $date_str . " " . $newvechicletime;

        $p_pmc = '2';
        $title = escape_str($parent->_request['title']); //p_title
        $company = escape_str($parent->_request['company']); //p_work_place_id
        $work_place_name = escape_str($parent->_request['work_place_name']); //p_work_place_name
        $enquiry_stage = escape_str($parent->_request['newvechicletpurpose']); //p_stage

        $oldvechicledate = '';
        $oldvechicletime = '';
        $oldvechicletactionplan = '';
        $oldvechicletpurpose = '';
//        $oldvechicledate=escape_str($parent->_request['oldvechicledate']);
        //        $oldvechicletime=escape_str($parent->_request['oldvechicletime']);
        //        $oldvechicletactionplan=escape_str($parent->_request['oldvechicletactionplan']);
        //        $oldvechicletpurpose=escape_str($parent->_request['oldvechicletpurpose']);
        $model2 = escape_str($parent->_request['model2']);
        $variant2 = escape_str($parent->_request['variant2']);
        $color2 = escape_str($parent->_request['color2']);

        $oldvechiclemaker = escape_str($parent->_request['oldvechiclemaker']);
        $oldvechiclemodel = escape_str($parent->_request['oldvechiclemodel']);
        $custage = escape_str($parent->_request['custage']); //p_cust_age_group

        $p_eval_code = escape_str($parent->_request['p_eval_code']);
        $p_old_car_make = escape_str($parent->_request['p_old_car_make']);
        $p_old_car_model = escape_str($parent->_request['p_old_car_model']);
        $p_old_car_submodel = escape_str($parent->_request['p_old_car_submodel']);
        $p_ad_cd = escape_str($parent->_request['p_ad_cd']);
        $p_event_cd = escape_str($parent->_request['p_event_cd']);
        $p_enq_ref_mode = escape_str($parent->_request['p_enq_ref_mode']);
        $p_referred_by = escape_str($parent->_request['p_referred_by']);

        $is_testride = '0';
        $license = escape_str($parent->_request['license']);
        $license_expiry = escape_str($parent->_request['license_expiry']);
        if ($license_expiry != '' || $license != '') {

            $REQUEST_KEYS = array('license' => 'string', 'license_expiry' => 'date|d-m-Y');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $is_testride = '1';

            $ldate_arr = @explode('-', $license_expiry);
            $ldate_str = $ldate_arr[2] . "-" . $ldate_arr[1] . "-" . $ldate_arr[0];
            $license_expiry = $ldate_str;
        }

        $status = "H"; //p_statusid

        $date1 = new DateTime(CUR_DATE);
        $date2 = $date1->diff(new DateTime($date_str));
        $diff_days = $date2->days;

        if ($diff_days <= 7) {
            $status = "H"; //HOT
        } elseif ($diff_days > 7 && $diff_days <= 21) {
            $status = "W"; //WARM
        } elseif ($diff_days > 21) {
            $status = "P"; //COLD
        }

        $p_km_drive_month = escape_str($parent->_request['p_km_drive_month']);
        $p_mode_of_purchase = escape_str($parent->_request['p_mode_of_purchase']);
        $p_any_other_car = escape_str($parent->_request['p_any_other_car']);
        $p_ref_type = escape_str($parent->_request['p_ref_type']);
        $p_ref_no = escape_str($parent->_request['p_ref_no']);
        $p_ref_phone_no = escape_str($parent->_request['p_ref_phone_no']);

        $leadid = 'starenq' . uniqid(); //p_transaction_id

        //FOR SAVE
        if ($is_edit == 1) {
            if ($is_submit == 0) {
                $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET  newvechicledate='" . $date_str . "',newvechicletime='" . $newvechicletime . "',newvechicledatatime='" . $newvechicledatatime . "',newvechicletactionplan='" . $newvechicletactionplan . "',modeofcontact='" . $modeofcontact . "',enquiry_stage='" . $enquiry_stage . "',save_level='" . $save_level . "',license='" . $license . "',license_expiry='" . $license_expiry . "',is_testride='" . $is_testride . "'  WHERE  id='" . $id . "'");

                $data_arr = $this->getEnquirydata($parent, $id);

                //LOG
                $logstr = 'ENQUIRY SAVE LEVEL 4';
                globalfunc::insertUserLog($parent, $logstr);
                $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
            } else {
                $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "*", "id='" . $id . "' AND smpin='" . $smpin . "' AND is_dms=0 AND is_deleted=0", "1");
                if ($check_arr['nr'] != 1) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
                }

                $first_name = $check_arr['result'][0]->first_name;
                $middle_name = $check_arr['result'][0]->middle_name;
                $last_name = $check_arr['result'][0]->last_name;
                $gender = $check_arr['result'][0]->ind_sex;
                $profession = $check_arr['result'][0]->profession;
                $p_email = $check_arr['result'][0]->email;
                $mobile = $check_arr['result'][0]->mobile;

                $address1 = $check_arr['result'][0]->address1;
                $address2 = $check_arr['result'][0]->address2;
                $address3 = $check_arr['result'][0]->address3;

                $ofc_address1 = $check_arr['result'][0]->ofc_address1;
                $ofc_address2 = $check_arr['result'][0]->ofc_address2;
                $ofc_address3 = $check_arr['result'][0]->ofc_address3;
                $ofc_city = $check_arr['result'][0]->ofc_city;
                $ofc_state = $check_arr['result'][0]->ofc_state;

                $model1 = $check_arr['result'][0]->model1;
                $variant1 = $check_arr['result'][0]->variant1;
                $color1 = $check_arr['result'][0]->color1;

                $communicate = $check_arr['result'][0]->communicate;
                //$modeofcontact=$check_arr['result'][0]->modeofcontact;

                $custtype = $check_arr['result'][0]->custtype;
                $buyer_type = $check_arr['result'][0]->buyer_type;
                $source = $check_arr['result'][0]->source;

                $company = $check_arr['result'][0]->company;
                $work_place_name = $check_arr['result'][0]->work_place_name;
                $title = $check_arr['result'][0]->title;
                $custage = $check_arr['result'][0]->custage;
            }
        }

        //CALL DMS ORACLE
        $url = SUZ_DMS_URL;
        $enq_soruce = $source;
        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_enq(:p_mspin, :p_enq, :p_action, :p_stage, :fname, :mid_name, :l_name, :mobile_no, :gender, :occupation, :p_email, :address1, :address2, :address3, :city, :state, :ofc_address1, :ofc_address2, :ofc_address3, :ofc_city, :ofc_state, :model, :variant, :colour, :mod_of_com, :cust_type, :buyer_type, :lik_pur_days, :enq_soruce, :model_cd, :variant_cd, :next_follwowup_date, :p_pmc, :p_work_place_id, :p_work_place_name, :p_transaction_id, :p_eval_code, :p_old_car_make, :p_old_car_model, :p_old_car_submodel, :p_ad_cd, :p_event_cd, :p_enq_ref_mode, :p_referred_by, :p_statusid, :p_km_drive_month, :p_mode_of_purchase, :p_any_other_car, :p_ref_type, :p_ref_no, :p_ref_phone_no, :p_title, :p_village, :p_tehsil, :p_district, :p_pin, :p_ofc_village, :p_ofc_tehsil, :p_ofc_district, :p_ofc_pin, :p_cust_age_group, :enq_number, :p_err_msg, :p_error); END;", "params" => '[{"title":"p_mspin","value":"' . $smpin . '","type":""},{"title":"p_enq","value":"' . $p_enq . '","type":""},{"title":"p_action","value":"' . $newvechicletactionplan . '","type":""},{"title":"p_stage","value":"' . $enquiry_stage . '","type":""},{"title":"fname","value":"' . $first_name . '","type":""},{"title":"mid_name","value":"' . $middle_name . '","type":""},{"title":"l_name","value":"' . $last_name . '","type":""},{"title":"mobile_no","value":"' . $mobile . '","type":""},{"title":"gender","value":"' . $gender . '","type":""},{"title":"occupation","value":"' . $profession . '","type":""},{"title":"p_email","value":"' . $email . '","type":""},{"title":"address1","value":"' . $address1 . '"},{"title":"address2","value":"' . $address2 . '","type":""},{"title":"address3","value":"' . $address3 . '","type":""},{"title":"city","value":"' . $city . '","type":""},{"title":"state","value":"' . $state . '","type":""},{"title":"ofc_address1","value":"' . $ofc_address1 . '","type":""},{"title":"ofc_address2","value":"' . $ofc_address2 . '","type":""},{"title":"ofc_address3","value":"' . $ofc_address3 . '","type":""},{"title":"ofc_city","value":"' . $ofc_city . '","type":""},{"title":"ofc_state","value":"' . $ofc_state . '","type":""},{"title":"model","value":"' . $model1 . '","type":""},{"title":"variant","value":"' . $variant1 . '","type":""},{"title":"colour","value":"' . $color1 . '","type":""},{"title":"mod_of_com","value":"' . $communicate . '","type":""},{"title":"cust_type","value":"' . $custtype . '","type":""},{"title":"buyer_type","value":"' . $buyer_type . '","type":""},{"title":"lik_pur_days","value":"' . $lik_pur_days . '","type":""},{"title":"enq_soruce","value":"' . $enq_soruce . '","type":""},{"title":"model_cd","value":"' . $model_cd . '","type":""},{"title":"variant_cd","value":"' . $variant_cd . '","type":""},{"title":"next_follwowup_date","value":"' . date('d-M-Y', strtotime($newvechicledatatime)) . '","type":""},{"title":"p_pmc","value":2,"type":""},{"title":"p_work_place_id","value":"' . $company . '","type":""},{"title":"p_work_place_name","value":"' . $work_place_name . '","type":""},{"title":"p_transaction_id","value":"' . $leadid . '","type":""},{"title":"p_eval_code","value":"' . $p_eval_code . '","type":""},{"title":"p_old_car_make","value":"' . $p_old_car_make . '","type":""},{"title":"p_old_car_model","value":"' . $p_old_car_model . '","type":""},{"title":"p_old_car_submodel","value":"' . $p_old_car_submodel . '","type":""},{"title":"p_ad_cd","value":"' . $p_ad_cd . '","type":""},{"title":"p_event_cd","value":"' . $p_event_cd . '","type":""},{"title":"p_enq_ref_mode","value":"' . $p_enq_ref_mode . '","type":""},{"title":"p_referred_by","value":"' . $p_referred_by . '","type":""},{"title":"p_statusid","value":"' . $status . '","type":""},{"title":"p_km_drive_month","value":"' . $p_km_drive_month . '","type":""},{"title":"p_mode_of_purchase","value":"' . $p_mode_of_purchase . '","type":""},{"title":"p_any_other_car","value":"' . $p_any_other_car . '","type":""},{"title":"p_ref_type","value":"' . $p_ref_type . '","type":""},{"title":"p_ref_no","value":"' . $p_ref_no . '","type":""},{"title":"p_ref_phone_no","value":"' . $p_ref_phone_no . '","type":""},{"title":"p_title","value":"' . $title . '","type":""},{"title":"p_village","value":"' . $p_village . '","type":""},{"title":"p_tehsil","value":"' . $p_tehsil . '","type":""},{"title":"p_district","value":"' . $p_district . '","type":""},{"title":"p_pin","value":"' . $p_pin . '","type":""},{"title":"p_ofc_village","value":"' . $p_ofc_village . '","type":""},{"title":"p_ofc_tehsil","value":"' . $p_ofc_tehsil . '","type":""},{"title":"p_ofc_district","value":"' . $p_ofc_district . '","type":""},{"title":"p_ofc_pin","value":"' . $p_ofc_pin . '","type":""},{"title":"p_cust_age_group","value":"' . $custage . '","type":""},{"title":"enq_number","value":"","type":"string","length":200},{"title":"p_err_msg","value":"","type":"string","length":1000},{"title":"p_error","value":"","type":"string","length":200}]');

        //print_r($post);exit();

        //LOG
        $obj = new stdClass();
        $obj->type = 'enqsubmit';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        $header = array('Authorization:Bearer ' . SUZ_TOKEN);
        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;
        $emsg = '';

        //REPSONSE SAVE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

        if ($httpcode == '200' && $response != '') {
            $json = json_decode($response);
            if (isset($json->response) && $json->response == 'success' && isset($json->data) && isset($json->data->enq_number) && $json->data->enq_number != '') {
                $error = 0;
                if ($is_edit == 0) {
                    $parent->executeQuery("INSERT INTO `" . DMS_ENQUIRY_MASTER . "` ( transaction_id,  `enq_salesman_cd`, `smpin`, dealer_code, `mobile`, `email`, `buyer_type`, `title`, `first_name`, `middle_name`, `last_name`, `ind_sex`, `address1`, `address2`, `address3`, `city`, `state`, `ofc_address1`, `ofc_address2`, `ofc_address3`, `ofc_city`, `ofc_state`,  `company`, `work_place_name`, `communicate`, `newvechicledate`, `newvechicletime`, `newvechicledatatime`, `newvechicletactionplan`,`model1`, `variant1`, `color1`,  `profession`, `source`, `custtype`, `custage`, `modeofcontact`, `enquiry_stage`, `lik_pur_days`,license,license_expiry,is_testride , `status`,save_level, is_dms, is_starapp, `created_on`, `modified_on`) VALUES ('" . $leadid . "','" . $enq_salesman_cd . "','" . $smpin . "','" . $dealer_code . "', '" . $mobile . "','" . $email . "','" . $buyer_type . "','" . $title . "','" . $first_name . "','" . $middle_name . "','" . $last_name . "','" . $gender . "','" . $address1 . "','" . $address2 . "','" . $address3 . "','" . $city . "', '" . $state . "','" . $ofc_address1 . "','" . $ofc_address2 . "', '" . $ofc_address3 . "',  '" . $ofc_city . "',  '" . $ofc_state . "','" . $company . "','" . $work_place_name . "','" . $communicate . "','" . $date_str . "','" . $newvechicletime . "','" . $newvechicledatatime . "','" . $newvechicletactionplan . "', '" . $model1 . "','" . $variant1 . "','" . $color1 . "','" . $profession . "','" . $source . "','" . $custtype . "','" . $custage . "','" . $modeofcontact . "','" . $enquiry_stage . "','" . $lik_pur_days . "','" . $license . "','" . $license_expiry . "','" . $is_testride . "','" . $status . "',4 ,1 ,1,'" . NOW . "', '" . NOW . "')");
                    $id = $parent->lastInsertId();
                } else {
                    //'id'=>'number','newvechicledate'=>'string','newvechicletime'=>'string','newvechicletactionplan'=>'string','newvechicletpurpose'=>'string'
                    $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET dealer_code='" . $dealer_code . "',transaction_id='" . $leadid . "',`city`='" . $city . "', `state`='" . $state . "',newvechicledate='" . $date_str . "',newvechicletime='" . $newvechicletime . "',newvechicledatatime='" . $newvechicledatatime . "',modeofcontact='" . $modeofcontact . "',newvechicletactionplan='" . $newvechicletactionplan . "',enquiry_stage='" . $enquiry_stage . "',lik_pur_days='" . $lik_pur_days . "',license='" . $license . "',license_expiry='" . $license_expiry . "',is_testride='" . $is_testride . "', `status`='" . $status . "',save_level='" . $save_level . "',is_dms='1' WHERE  id='" . $id . "'");
                }

                $parent->executeQuery("UPDATE " . DMS_ENQUIRY_MASTER . " SET enq_num='" . $json->data->enq_number . "' WHERE id='" . $id . "'");
                //$data_arr=$parent->selectQuery(DMS_ENQUIRY_MASTER ,"*","id='".$id."'","1");
                $data_arr = $this->getEnquirydata($parent, $id);

                //LOG UPDATE
                $obj = new stdClass();
                $obj->id = $log_id;
                $obj->insert_count = 1;
                $obj->status = 1;
                //$obj->apiresponse=$response;
                projectfunc::updateCronLog($parent, $obj);

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

            }
            if ($json->response == 'success' && $json->data->p_err_msg != '') {
                $emsg = $json->data->p_err_msg;
            }
        }

        if ($error == 1) {
            $emsg = ($emsg != '') ? $emsg : "Error to connect DMS. Please try after sometime";
            $parent->response(array('response' => 'failed', 'message' => $emsg), 406);
        }

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DASHBOARD //////////////////////////////////////////////// */
    private function dashboard($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;

        //TODAY ENQUIRY MASTER
        //VISIT
        $today_visit_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . CUR_DATE . "' AND modeofcontact IN ('S','V') AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        //TESTRIDE
        $today_testride_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . CUR_DATE . "' AND enquiry_stage='T'  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        //CALL
        $today_call_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . CUR_DATE . "'  AND modeofcontact IN ('E','F','O','T')  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");

        $today_visit = $today_visit_arr['result'][0]->data_count;
        $today_testride = $today_testride_arr['result'][0]->data_count;
        $today_call = $today_call_arr['result'][0]->data_count;

        //pending task last 10 days only
        $last_ten_date = date('Y-m-d', strtotime('-10 day', strtotime(NOW)));
        //PENDING ENQUIRY MASTER
        $pending_visit_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND newvechicledatatime<'" . CUR_DATE . " 00:00:00' AND newvechicledatatime>'" . $last_ten_date . " 00:00:00' AND modeofcontact  IN ('S','V')   AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        $pending_testride_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND newvechicledatatime<'" . CUR_DATE . " 00:00:00' AND newvechicledatatime>'" . $last_ten_date . " 00:00:00' AND enquiry_stage='T' AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        $pending_call_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND newvechicledatatime<'" . CUR_DATE . " 00:00:00' AND newvechicledatatime>'" . $last_ten_date . " 00:00:00' AND modeofcontact IN ('E','F','O','T')  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");

        $pending_visit = $pending_visit_arr['result'][0]->data_count;
        $pending_testride = $pending_testride_arr['result'][0]->data_count;
        $pending_call = $pending_call_arr['result'][0]->data_count;

        //TOMORROW ENQUIRY MASTER
        $tomorrow_date = date('Y-m-d', strtotime('+1 day', strtotime(NOW)));
        //VISIT
        $tomorrow_visit_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . $tomorrow_date . "' AND modeofcontact  IN ('S','V') AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        //TESTRIDE
        $tomorrow_testride_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . $tomorrow_date . "' AND enquiry_stage='T'  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        //CALL
        $tomorrow_call_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND  DATE(newvechicledatatime)= '" . $tomorrow_date . "'  AND modeofcontact IN ('E','F','O','T')  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");

        $tomorrow_visit = $tomorrow_visit_arr['result'][0]->data_count;
        $tomorrow_testride = $tomorrow_testride_arr['result'][0]->data_count;
        $tomorrow_call = $tomorrow_call_arr['result'][0]->data_count;

        $today = array('visit' => $today_visit, 'testride' => $today_testride, 'call' => $today_call);
        $pending = array('visit' => $pending_visit, 'testride' => $pending_testride, 'call' => $pending_call);
        $tomorrow = array('visit' => $tomorrow_visit, 'testride' => $tomorrow_testride, 'call' => $tomorrow_call);

        $data = array('today' => $today, 'pending' => $pending, 'tomorrow' => $tomorrow);

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

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DASHBOARD SALES //////////////////////////////////////////////// */
    private function enquirysales($parent)
    {

        //sales/2018/2
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 3);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $year_data = escape_str($parent->params[1]);
        $last_data = escape_str($parent->params[2]);
        $last_data_arr = explode('?', $last_data);
        $month_data = escape_str(trim($last_data_arr[0]));
        $smpin = $parent->current_user_data->smpin;

        //*****************SALES****************

        //TARGET
        $user_target = projectfunc::userSalesTarget($parent, $parent->current_user_id, '', $year_data, $month_data);
        //ACHIEVED
        $user_achieved = projectfunc::userSalesAchieved($parent, $parent->current_user_id, '', $year_data, $month_data);
        $sales = array('target' => $user_target, 'achieved' => $user_achieved, 'month' => date('M', strtotime('2018-' . $month_data . "-01")), 'year' => $year_data);

        //****************ENQUIRY****************
        $achieved_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%'  AND is_dms=1 AND is_deleted=0", "1");

        switch ($parent->current_user_data->segment) {
            case '1': //TARGET
                $enquiry_target = (string) ($user_target * 5); //SALES TARGET multiple by 5
                break;
            case '2': //TARGET
                $enquiry_target = (string) ($user_target * 3); //SALES TARGET multiple by 3
                break;
            default:
                $enquiry_target = (string) ($user_target * 3); //SALES TARGET multiple by 3
                break;
        }

        //ACHIEVED
        $enquiry_achieved = $achieved_arr['result'][0]->data_count;
        $enquiry = array('target' => $enquiry_target, 'achieved' => $enquiry_achieved, 'month' => date('M', strtotime('2018-' . $month_data . "-01")), 'year' => $year_data);

        //*****************STATUS
        $hot_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND status='H'  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        $warm_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND status='W'  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");
        $cold_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND status='P'  AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')", "1");

        $hot = $hot_arr['result'][0]->data_count;
        $warm = $warm_arr['result'][0]->data_count;
        $cold = $cold_arr['result'][0]->data_count;
        $status_arr = array("hot" => $hot, "warm" => $warm, "cold" => $cold);

        //*****************STAGE
        $testride_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND enquiry_stage='T' AND is_dms=1 AND is_deleted=0 ", "1");
        $booked_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND enquiry_stage='O' AND is_dms=1 AND is_deleted=0 ", "1");
        $invoiced_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND enquiry_stage IN('Z','P') AND is_dms=1 AND is_deleted=0 ", "1");
        $lost_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND status='L' AND is_dms=1 AND is_deleted=0 ", "1");
        $postponed_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND status='E' AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V') ", "1");
        $delivered_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "COUNT(id) data_count", " smpin='" . $smpin . "' AND created_on LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%' AND enquiry_stage IN ('O','V') AND is_dms=1 AND is_deleted=0 ", "1");

        $testride = $testride_arr['result'][0]->data_count;
        $booked = $booked_arr['result'][0]->data_count;
        $invoiced = $invoiced_arr['result'][0]->data_count;
        $lost = $lost_arr['result'][0]->data_count;
        $postponed = $postponed_arr['result'][0]->data_count;
        $delivered = $delivered_arr['result'][0]->data_count;

        $stage_arr = array("testride" => $testride, 'booked' => $booked, 'invoiced' => $invoiced, 'lost' => $lost, 'postponed' => $postponed, 'delivered' => $delivered);

        $data = array('enquiry' => $enquiry, 'sales' => $sales, 'status' => $status_arr, 'stage' => $stage_arr);
        //LOG
        $logstr = 'SALES DASHBOARD';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// LIST DATA //////////////////////////////////////////////// */
    private function listdata($parent)
    {

        //sales/2018/2
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;
        try {
            //PAGINATION SETTINGS
            $limit_cond = '';
            $data_arr = array();
            $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
            $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

            $REQUEST_KEYS = array('listtype' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $listtype = escape_str($parent->_request['listtype']);

            $cond = '';
            switch ($listtype) {
                case 'today':
                    $todaytype = escape_str($parent->_request['todaytype']);

                    if (strtolower($todaytype) == 'visit') {
                        $cond = " AND e.modeofcontact  IN ('S','V') ";
                    } else if (strtolower($todaytype) == 'test drive') {
                        $cond = " AND e.enquiry_stage='T'";
                    } else if (strtolower($todaytype) == 'call') {
                        $cond = " AND e.modeofcontact IN ('E','F','O','T')";
                    }
                    $cond .= " AND enquiry_stage NOT IN ('Z','O','P','V') AND DATE(e.newvechicledatatime)= '" . CUR_DATE . "'";
                    break;
                case 'tomorrow':
                    $todaytype = escape_str($parent->_request['todaytype']);

                    if (strtolower($todaytype) == 'visit') {
                        $cond = " AND e.modeofcontact  IN ('S','V') ";
                    } else if (strtolower($todaytype) == 'test drive') {
                        $cond = " AND e.enquiry_stage='T'";
                    } else if (strtolower($todaytype) == 'call') {
                        $cond = " AND e.modeofcontact IN ('E','F','O','T')";
                    }

                    $tomorrow_date = date('Y-m-d', strtotime('+1 day', strtotime(NOW)));
                    $cond .= " AND enquiry_stage NOT IN ('Z','O','P','V') AND DATE(e.newvechicledatatime)= '" . $tomorrow_date . "'";
                    break;
                case 'date':
                    $REQUEST_KEYS = array('date' => 'date|Y-m-d');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $date = escape_str($parent->_request['date']);

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

                    if (strtolower($todaytype) == 'visit') {
                        $cond = " AND e.modeofcontact  IN ('S','V') ";
                    } else if (strtolower($todaytype) == 'test drive') {
                        $cond = " AND e.enquiry_stage='T'";
                    } else if (strtolower($todaytype) == 'call') {
                        $cond = " AND e.modeofcontact IN ('E','F','O','T')";
                    }
                    $cond .= " AND enquiry_stage NOT IN ('Z','O','P','V') AND DATE(newvechicledatatime)= '" . $date . "'";
                    break;
                case 'pending':
                    $REQUEST_KEYS = array('pendingtype' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $pendingtype = escape_str($parent->_request['pendingtype']);

                    if (strtolower($pendingtype) == 'visit') {
                        $cond = " AND e.modeofcontact  IN ('S','V') ";
                    } else if (strtolower($pendingtype) == 'test drive') {
                        $cond = "AND e.enquiry_stage='T'";
                    } else if (strtolower($pendingtype) == 'call') {
                        $cond = " AND e.modeofcontact IN ('E','F','O','T')";
                    }
                    $last_ten_date = date('Y-m-d', strtotime('-10 day', strtotime(NOW)));
                    $cond .= " AND enquiry_stage NOT IN ('Z','O','P','V') AND e.newvechicledatatime<'" . CUR_DATE . " 00:00:00' AND newvechicledatatime>'" . $last_ten_date . " 00:00:00'";
                    //$cond.=(in_array(strtolower($pendingtype),array("visit","test drive","call")))?" AND enquiry_stage='".$pendingtype."'":$parent->response(array('response'=>'failed', 'message' => $this->page_data['error5']), 406);
                    //$cond.= " AND enquiry_stage='".$pendingtype."'";
                    //$cond.= " AND enquiry_stage='".$pendingtype."'";
                    break;
                case 'hot':
                case 'warm':
                case 'cold':

                case 'testride':
                case 'booked':
                case 'invoiced':
                case 'lost':
                case 'postponed':

                    $REQUEST_KEYS = array('month' => 'string', 'year' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $month_data = escape_str($parent->_request['month']);
                    $year_data = escape_str($parent->_request['year']);

                    if (in_array($listtype, array("hot", "warm", "cold", 'lost', 'postponed'))) {
                        switch ($listtype) {
                            case 'hot':$listtype_str = 'H';
                                break;
                            case 'warm':$listtype_str = 'W';
                                break;
                            case 'cold':$listtype_str = 'P';
                                break;
                            case 'lost':$listtype_str = 'L';
                                break;
                            case 'postponed':$listtype_str = 'E';
                                break;
                        }
                        if ($listtype != 'lost') {
                            $cond .= " AND enquiry_stage NOT IN ('Z','O','P','V')";
                        }
                        $cond .= " AND e.status='" . $listtype_str . "'";
                    } else {
                        // $str=($listtype=='testride')?"T":$listtype;
                        switch ($listtype) {
                            case 'testride':$str = 'T';
                                break;
                            case 'booked':$str = 'O';
                                break;
                            case 'invoiced':$str = 'Z';
                                break;

                        }
                        $cond = " AND e.enquiry_stage='" . $str . "'";
                    }

                    $cond .= "AND e.created_on  LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%'";
                    break;

                case 'model':
                    $REQUEST_KEYS = array('month' => 'string', 'year' => 'number', 'model' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $month_data = escape_str($parent->_request['month']);
                    $year_data = escape_str($parent->_request['year']);
                    $model = escape_str($parent->_request['model']);

                    switch ($model) {
                        case 'INTRUDER':$cond .= " AND e.model1='GL'";
                            break;
                        case 'BURGMAN':$cond .= " AND e.model1='UB125'";
                            break;
                        case 'ACCESS 125':$cond .= " AND e.model1 IN ('AC','ACZ')";
                            break;
                        case 'GIXXER 250':$cond .= " AND e.model1 IN ('GSX','GSXSF') AND e.variant1 IN (SELECT variant_code  FROM " . DMS_ENQUIRY_MODEL . " WHERE title_code IN ('GSX','GSXSF') AND variant LIKE '%250%')";
                            break;
                        case 'GIXXER':$cond .= " AND e.model1 IN ('GSX','GSXSF') AND e.variant1 IN (SELECT variant_code  FROM " . DMS_ENQUIRY_MODEL . " WHERE title_code IN ('GSX','GSXSF') AND variant NOT LIKE '%250%')";
                            break;
                        case 'OTHERS':$cond .= " AND e.model1 NOT IN ('GSX','GSXSF','GL','UB125','AC','ACZ')";
                            break;
                        default:$parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
                    }
                    $cond .= " AND e.created_on  LIKE '" . date('Y-m', strtotime($year_data . '-' . $month_data . "-01")) . "-%'";
                    break;
                default:$parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
                    break;
            }
            //SEARCH
            $model_cond = '';
            $search = escape_str($parent->_request['search']);
            if ($search != '') {
                $model = $parent->getQueryValue("SELECT title_code  FROM " . DMS_ENQUIRY_MODEL . " WHERE title LIKE '%" . $search . "%'");
                if (count($model) > 0) {
                    $model_arr = array_column($model, 'title_code');
                    $model_quotes = array_map("quotes_array", $model_arr);

                    $model_cond = (count($model_quotes) > 0) ? " OR e.model1 IN (" . @implode(',', $model_quotes) . ")" : '';
                }

                $cond = " AND (e.enq_num LIKE '%" . $search . "%' OR e.first_name LIKE '%" . $search . "%'  OR e.mobile LIKE '%" . $search . "%' " . $model_cond . ") ";
            }
            //$pending_testride_arr=$parent->selectQuery(DMS_ENQUIRY_MASTER,"COUNT(id) data_count"," smpin='".$smpin."' AND newvechicledatatime<'".CUR_DATE." 00:00:00' AND enquiry_stage='T' AND is_dms=1 AND is_deleted=0 AND enquiry_stage NOT IN ('Z','O','P','V')","1");

            //echo  "smpin='".$smpin."' ".$cond."  ORDER BY newvechicledatatime ASC, id DESC ".$limit_cond; exit;
            $data_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER . " e ", "SQL_CALC_FOUND_ROWS e.*", "e.smpin='" . $smpin . "' AND e.is_dms=1 AND e.is_deleted=0 " . $cond . " ORDER BY e.newvechicledatatime ASC, id DESC " . $limit_cond, "");

            $total_arr = $parent->getQueryValue("SELECT FOUND_ROWS() as total_record");
            $total = (count($total_arr) > 0) ? $total_arr[0]->total_record : 0;

            //DATE TO STRING
            if ($data_arr['nr'] > 0) {
                foreach ($data_arr['result'] as $key => $res) {
                    //LEFT JOIN ".DMS_ENQUIRY_MODEL." m ON  m.title_code=e.model1
                    //,m.title as model_name_str
                    $model_arr = $parent->selectQuery(DMS_ENQUIRY_MODEL, "title as model_name,variant as variant_name,color as color_name", "title_code='" . $res->model1 . "' AND variant_code='" . $res->variant1 . "' AND color_code='" . $res->color1 . "'", "");

                    $data_arr['result'][$key]->model_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->model_name : $res->model1;
                    $data_arr['result'][$key]->variant_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->variant_name : $res->variant1;
                    $data_arr['result'][$key]->color_name = ($model_arr['nr'] > 0) ? $model_arr['result'][0]->color_name : $res->color1;
                    $data_arr['result'][$key]->enq_through = ($res->is_starapp == 1) ? "HYPER-M App" : "DMS";
                    $data_arr['result'][$key]->newvechicledatatime_str = projectfunc::enqdatediff($parent, NOW, $res->newvechicledatatime);

                    $checkdate = date('Y-m-d', strtotime($res->newvechicledatatime));
                    //0-overdue,1-current day,2-future
                    switch (true) {
                        case (strtotime($checkdate) < strtotime(CUR_DATE)): $data_arr['result'][$key]->enq_date_type = 0;
                            break;
                        case (strtotime($checkdate) == strtotime(CUR_DATE)): $data_arr['result'][$key]->enq_date_type = 1;
                            break;
                        case (strtotime($checkdate) > strtotime(CUR_DATE)): $data_arr['result'][$key]->enq_date_type = 2;
                            break;
                    }
                    ///PENDING ENQUIRY MASTER
                    if (strtoupper($res->enquiry_stage) == 'T') {
                        $data_arr['result'][$key]->icon_type = 1;
                    } else if (strtoupper($res->modeofcontact) == 'S' || strtoupper($res->modeofcontact) == 'V') {
                        $data_arr['result'][$key]->icon_type = 2;
                    } else if (in_array(strtoupper($res->modeofcontact), array('E', 'F', 'O', 'T'))) {
                        $data_arr['result'][$key]->icon_type = 3;
                    } else {
                        $data_arr['result'][$key]->icon_type = 0;
                    }
                    //visit,call,testdrive
                }
            }

            //LOG
            $logstr = 'ENQUIRY LIST';
            globalfunc::insertUserLog($parent, $logstr);

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

        } catch (PDOException $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 500);

        } catch (Exception $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 500);
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// FOLLOWUP //////////////////////////////////////////////// */
    private function followup($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;

        $REQUEST_KEYS = array('id' => 'number', 'status' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $status = strtoupper(escape_str($parent->_request['status']));

        $reason = '';
        $subreason = '';
        $lostdealer = '';
        $lostmodel = '';
        //'newvechicledate'=>'date|d-m-Y','newvechicletime'=>'string', 'modeofcontact'=>'string','nextfollowup'=>'string',
        switch ($status) {
            case 'L': //Lost
                $REQUEST_KEYS = array('reason' => 'string', 'subreason' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

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

                $lostdealer = escape_str($parent->_request['lostdealer']);
                $lostmodel = escape_str($parent->_request['lostmodel']);
                break;
            case 'E': //Postponed
                $REQUEST_KEYS = array('reason' => 'string', 'newvechicledate' => 'date|d-m-Y', 'newvechicletime' => 'string', 'modeofcontact' => 'string', 'nextfollowup' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                $reason = escape_str($parent->_request['reason']);
                break;
            case 'P': //Cold
            case 'H': //Hot
            case 'W': //Warm
                $REQUEST_KEYS = array('newvechicledate' => 'date|d-m-Y', 'newvechicletime' => 'string', 'modeofcontact' => 'string', 'nextfollowup' => 'string');
                globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                break;
        }

        $id = escape_str($parent->_request['id']);
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,enq_num,newvechicledatatime,enquiry_stage,newvechicletactionplan", " smpin='" . $smpin . "' AND id='" . $id . "'  AND is_dms=1 AND is_deleted=0  ", "1");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

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

        $date_arr = @explode("-", $newvechicledate);
        $date_str = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];
        $newvechicledatatime = $date_str . " " . $newvechicletime;

        $followup_remark = escape_str($parent->_request['followup_remark']);
        $followup_remark = str_replace(array("\n", "\r"), ' ', $followup_remark);
        $modeofcontact = escape_str($parent->_request['modeofcontact']);
        $nextfollowup = escape_str($parent->_request['nextfollowup']);

        $p_act_follow_date = date('m/d/Y', strtotime($check_arr['result'][0]->newvechicledatatime));
        if ($status == 'L') {
            $p_next_stage_date = date('m/d/Y', strtotime(CUR_DATE));
        } else {
            $p_next_stage_date = date('m/d/Y', strtotime($date_str));
        }

        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_followup_update(:p_mspin, :p_enq_num,  :p_act_follow_date, :p_enq_actual_stage, :p_status, :p_enq_actual_action, :p_enq_reas_cd, :p_enq_sub_reas_cd, :p_enq_lost_dlr, :p_enq_lost_mod, :p_at_remarks, :p_next_stage_date, :p_enq_next_action, :p_enq_next_stage, :p_financer_code, :p_competition_manufacture, :p_competition_model, :p_error, :p_err_msg ); END;", "params" => '[{"title":"p_mspin","value":"' . $smpin . '","type":""},{"title":"p_enq_num","value":"' . $check_arr['result'][0]->enq_num . '","type":""}, {"title":"p_act_follow_date","value":"' . $p_act_follow_date . '","type":""}, {"title":"p_enq_actual_stage","value":"' . $check_arr['result'][0]->enquiry_stage . '","type":""},{"title":"p_status","value":"' . $status . '","type":""},{"title":"p_enq_actual_action","value":"' . $check_arr['result'][0]->newvechicletactionplan . '","type":""},{"title":"p_enq_reas_cd","value":"' . $reason . '","type":""},{"title":"p_enq_sub_reas_cd","value":"' . $subreason . '","type":""},{"title":"p_enq_lost_dlr","value":"' . $lostdealer . '","type":""},{"title":"p_enq_lost_mod","value":"' . $lostmodel . '","type":""},{"title":"p_at_remarks","value":"' . $followup_remark . '","type":""},{"title":"p_next_stage_date","value":"' . $p_next_stage_date . '","type":""},{"title":"p_enq_next_action","value":"' . $modeofcontact . '","type":""},{"title":"p_enq_next_stage","value":"' . $nextfollowup . '","type":""},{"title":"p_financer_code","value":"","type":""},{"title":"p_competition_manufacture","value":"","type":""},{"title":"p_competition_model","value":"","type":""},{"title":"p_error","value":"2","type":"string","length":200},{"title":"p_err_msg","value":"","type":"string","length":1000}]');
        $url = SUZ_DMS_URL;
        $header = array('Authorization:Bearer ' . SUZ_TOKEN);

        //LOG
        $obj = new stdClass();
        $obj->type = 'followupdate';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;

        //LOG UPDATE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

        if ($httpcode == '200' && $response != '') {
            $json = json_decode($response);

            //LOG UPDATE
            $obj = new stdClass();
            $obj->id = $log_id;
            $obj->insert_count = 0;
            $obj->status = 1;
            //$obj->apiresponse=$response;
            projectfunc::updateCronLog($parent, $obj);

            if (isset($json->response) && $json->response == 'success' && isset($json->data)) {
                if ($json->data->p_err_msg == '' || $json->data->p_err_msg == null) {
                    $error = 0;
                }
            }
            $emsg = $json->data->p_err_msg;
        }

        //LOG
        $logstr = 'ENQUIRY FOLLOWUP SUBMIT';
        globalfunc::insertUserLog($parent, $logstr, $check_arr['result'][0]->id);

        if ($error == 0) {
            if ($status != 'L') {
                //UPDATE FOLLOW UP
                $update_str = "UPDATE  " . DMS_ENQUIRY_MASTER . " SET newvechicledate='" . $date_str . "', newvechicletime='" . $newvechicletime . "',	newvechicledatatime='" . $newvechicledatatime . "'  WHERE id='" . $check_arr['result'][0]->id . "'";
                $parent->executeQuery($update_str);
            }
            //DIRECT STATUS UPDATE
            $parent->executeQuery("UPDATE  " . DMS_ENQUIRY_MASTER . " SET status='" . $status . "' WHERE id='" . $check_arr['result'][0]->id . "'");

            $parent->response(array('response' => 'success', 'message' => $this->page_data['success2']), 200);
        } else {
            $emsg = ($emsg != '') ? $emsg : "Error to connect DMS. Please try after sometime";
            $parent->response(array('response' => 'failed', 'message' => $emsg), 406);
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// STOCK AVAILABILITY //////////////////////////////////////////////// */
    private function stockavailability($parent)
    {

        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $model = escape_str($parent->_request['model']);
        $variant = escape_str($parent->_request['variant']);
        $color = escape_str($parent->_request['color']);

        $smpin = $parent->current_user_data->smpin;

        $url = SUZ_DMS_URL;
        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_available_stock(:p_mspin, :p_pmc, :p_model_cd, :p_variant_cd, :p_color_cd, :p_list_cursor, :p_err_cd, :p_err_msg); END;", "params" => '[{"title":"p_mspin","value":"' . $smpin . '","type":""},{"title":"p_pmc","value":"2","type":""},{"title":"p_model_cd","value":"' . $model . '","type":""},{"title":"p_variant_cd","value":"' . $variant . '","type":""},{"title":"p_color_cd","value":"' . $color . '","type":""},{"title":"p_list_cursor","value":"","type":"cursor"},{"title":"p_err_cd","value":"","type":"string","length":200},{"title":"p_err_msg","value":"","type":"string","length":1000}]');
        $header = array('Authorization:Bearer ' . SUZ_TOKEN);

        //LOG
        $obj = new stdClass();
        $obj->type = 'callmodelstock';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;

        //LOG UPDATE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

        //LOG
        $logstr = 'ENQUIRY STOCK';
        globalfunc::insertUserLog($parent, $logstr);

        if ($httpcode == '200' && $response != '') {
            $json = json_decode($response);
            if (isset($json->response) && $json->response == 'success' && isset($json->data) && count($json->data) > 0) {
                $data = $json->data;
                $count = count($json->data);

                //0-Data not Found,1-Available,2-Since Transfer,3-Not Available
                $status = array('title' => 'Not Available', 'status' => 0);
                if ($count > 0) {
                    if ($data[0]->AVAILABLE_STOCK > 0) {
                        $status = array('title' => 'Available', 'status' => 1);
                    }

                    if ($data[0]->AVAILABLE_STOCK == 0 && $data[0]->INTRANSIT_STOCK > 0) {
                        $status = array('title' => 'In Transit', 'status' => 2);
                    }

                }

                //LOG UPDATE
                $obj = new stdClass();
                $obj->id = $log_id;
                $obj->insert_count = 1;
                $obj->status = 1;
                //$obj->apiresponse=$response;
                projectfunc::updateCronLog($parent, $obj);

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

        $status = array('title' => 'Not Available', 'status' => 0);
        $parent->response(array('response' => 'success', 'data' => $status, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DETAILS //////////////////////////////////////////////// */
    private function details($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;
        $id = escape_str($parent->params[1]);

        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", " smpin='" . $smpin . "' AND is_deleted=0 AND id='" . $id . "'", "1");
        if ($check_arr['nr'] != '1') {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

        //GET DATA
        $data_arr = $this->getEnquirydata($parent, $id);

        //BROCHURE
        $brochure_arr = array();
        $brochure_url = SITE_URL . "explore_assets/model/";
        $expmodel_data = $parent->selectQuery(TABLE_COMPARE_MODEL, "model_id,CASE WHEN model_brochure!='' THEN CONCAT('" . $brochure_url . "',model_brochure) ELSE '' END AS 'model_brochure' ", "is_deleted=0 AND is_other=0  AND `model_type` = '0'", "");
        if ($expmodel_data['nr'] > 0) {
            $arr_id = array_column($expmodel_data['result'], 'model_id');
            $arr_name = array_column($expmodel_data['result'], 'model_brochure');
            $brochure_arr = array_combine($arr_id, $arr_name);
        }

        // `model1`, `variant1`, `color1`
        switch ($data_arr->model1) {
            case 'GSX': //GIXXER
                $id = (strpos($data_arr->variant1, 'GSX250') !== false || strpos($data_arr->variant_name, 'GIXXER 250') !== false) ? GIXXER_250_ID : GIXXER_ID;

                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'GSXSF': //GIXXER SF
                $id = (strpos($data_arr->variant1, 'GSXF250') !== false || strpos($data_arr->variant_name, 'GIXXER SF 250') !== false) ? GIXXER_SF_250_ID : GIXXER_SF_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'GL': //INTRUDER
                $id = INTRUDER_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'UB125': //BURGMAN
                $id = BURGMAN_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'AC':
            case 'ACZ':
                $id = ACCESS_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            default:
                $brochure_url = '';
                break;

        }
        $data_arr->brochure = $brochure_url;

        //CALL HISTORY
        $data_arr->history = array();

        $url = SUZ_DMS_URL;
        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_followup_history(:p_mspin, :p_enq_num, :p_pmc, :p_cust_name, :p_mobile, :p_email, :p_model_cd, :p_model, :p_variant_cd, :p_variant, :p_status_cd, :p_status, :p_color_cd, :p_color, :p_make, :p_makemodel_cd, :p_makemodel, :p_evaluatorid, :p_evaluator_name, :p_expectedprice, :p_evaluatedprice, :p_buying_price, :p_buyertype, :p_enquiry_source, :p_enquiry_date, :list_cursor, :p_error, :p_err_msg, :p_remarks, :p_km_drive_month, :p_mode_of_purchase, :p_financer_code, :p_financer_name, :p_tl_remarks, :p_comp_manuf_cd, :p_comp_manuf_name, :p_comp_model_cd, :p_comp_model_name, :p_corporate_code, :p_rm_evaluator_remark, :p_evaluator_remark); END;", "params" => '[{"title":"p_mspin","value":"' . $smpin . '","type":""},{"title":"p_enq_num","value":"' . $data_arr->enq_num . '","type":""},{"title":"p_pmc","value":2,"type":""},{"title":"p_cust_name","value":"","type":"string","length":200},{"title":"p_mobile","value":"","type":"string","length":200},{"title":"p_email","value":"","type":"string","length":200},{"title":"p_model_cd","value":"","type":"string","length":200},{"title":"p_model","value":"","type":"string","length":200},{"title":"p_variant_cd","value":"","type":"string","length":200},{"title":"p_variant","value":"","type":"string","length":200},{"title":"p_status_cd","value":"","type":"string","length":200},{"title":"p_status","value":"","type":"string","length":200},{"title":"p_color_cd","value":"","type":"string","length":200},{"title":"p_color","value":"","type":"string","length":200},{"title":"p_make","value":"","type":"string","length":200},{"title":"p_makemodel_cd","value":"","type":"string","length":200},{"title":"p_makemodel","value":"","type":"string","length":200},{"title":"p_evaluatorid","value":"","type":"string","length":200},{"title":"p_evaluator_name","value":"","type":"string","length":200},{"title":"p_expectedprice","value":"","type":"string","length":200},{"title":"p_evaluatedprice","value":"","type":"string","length":200},{"title":"p_buying_price","value":"","type":"string","length":200},{"title":"p_buyertype","value":"","type":"string","length":200},{"title":"p_enquiry_source","value":"","type":"string","length":200},{"title":"p_enquiry_date","value":"","type":"string","length":200},{"title":"list_cursor","value":"","type":"cursor"},{"title":"p_error","value":"","type":"string","length":20 },{"title":"p_err_msg","value":"","type":"string","length":1000},{"title":"p_remarks","value":"","type":"string","length":1000},{"title":"p_km_drive_month","value":"","type":"string","length":200},{"title":"p_mode_of_purchase","value":"","type":"string","length":200},{"title":"p_financer_code","value":"","type":"string","length":200},{"title":"p_financer_name","value":"","type":"string","length":200},{"title":"p_tl_remarks","value":"","type":"string","length":200},{"title":"p_comp_manuf_cd","value":"","type":"string","length":200},{"title":"p_comp_manuf_name","value":"","type":"string","length":200},{"title":"p_comp_model_cd","value":"","type":"string","length":200},{"title":"p_comp_model_name","value":"","type":"string","length":200},{"title":"p_corporate_code","value":"","type":"string","length":200},{"title":"p_rm_evaluator_remark","value":"","type":"string","length":200},{"title":"p_evaluator_remark","value":"","type":"string","length":200}]');

        $header = array('Authorization:Bearer ' . SUZ_TOKEN);

        //LOG
        $obj = new stdClass();
        $obj->type = 'followhistory';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;

        //LOG UPDATE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

//        $hobj=new stdClass();
        //        $hobj->title='Enquiry Created';
        //        $hobj->remarks=trim($parent->current_user_data->fname." ".$parent->current_user_data->lname);
        //        $hobj->created_on=date('Y-m-d',strtotime($data_arr->created_on));
        //        $hobj->created_on_str=date('d-M-Y',strtotime($data_arr->created_on));
        //        $hobj->image='';
        //        $hobj->type='';//testride
        //        $hobj->colorcode='#FFFF00';// Hexcode
        //        $hobj->type=$data_arr->action_str;   //Testride
        //        $hobj->stage=$data_arr->enquiry_str;
        //        $hobj->status=$data_arr->status_str;
        //        $hobj->order=1;
        //        $data_arr->history[]=$hobj;

        if ($httpcode == '200' && $response != '') {

            //LOG UPDATE
            $obj = new stdClass();
            $obj->id = $log_id;
            $obj->insert_count = count($json->data);
            $obj->status = 1;
            //$obj->apiresponse=$response;
            projectfunc::updateCronLog($parent, $obj);

            $json = json_decode($response);
            if (isset($json->response) && $json->response == 'success' && isset($json->data) && count($json->data) > 0) {
                $error = 0;
                if (count($json->data)) {
                    foreach ($json->data as $res) {
                        $hobj = new stdClass();
                        $hobj->title = $res->ACTION_PLAN;
                        $hobj->remarks = ($res->REMARKS) ? $res->REMARKS : '';
                        $hobj->created_on = date('Y-m-d', strtotime($res->FOLLOW_PLAN_DATE));
                        $hobj->created_on_str = date('d-M-Y', strtotime($res->FOLLOW_PLAN_DATE));
                        $hobj->order = strtotime($res->FOLLOW_PLAN_DATE);
                        $hobj->image = '';
                        $hobj->type = ($res->ACTION_PLAN) ? $res->ACTION_PLAN : '';
                        $hobj->stage = ($res->STAGE_PLAN) ? $res->STAGE_PLAN : $res->STAGE_ACTUAL;
                        $hobj->status = ($res->FOLLOWSTATUS) ? $res->FOLLOWSTATUS : '';
                        // Hexcode
                        switch (trim($hobj->stage)) {
                            case 'Invoiced':
                            case 'Order Booking':
                            case 'Vehicle Delivered':
                            case 'Proforma Invoice':
                                $hobj->colorcode = '#008000'; //green
                                break;
                            case 'Lost':
                                $hobj->colorcode = '#FF0000'; //RED
                                break;
                            default:
                                $hobj->colorcode = '#FF8C00'; //orange
                                break;
                        }

                        $data_arr->history[] = $hobj;
                    }
                }

            }
        }

        //SORT
        // if (count($data_arr->history) > 0) {
        //     usort($data_arr->history, 'comparator');
        // }

        //LOG
        $logstr = 'ENQUIRY DETAILS';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// Share //////////////////////////////////////////////// */
    private function sharebrochure($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $email = escape_str($parent->_request['email']);
        $REQUEST_KEYS = array('name' => 'string', 'email' => 'string', 'model' => 'string', 'variant' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        if (!globalfunc::isValidEmail($email)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error12']), 406);
        }

        $smpin = $parent->current_user_data->smpin;

        $name = escape_str($parent->_request['name']);
        $model = escape_str($parent->_request['model']);
        $variant = escape_str($parent->_request['variant']);

        $checkmodel_data = $parent->selectQuery(DMS_ENQUIRY_MODEL, "id,title,variant", " status='1' AND enq_yn='Y' AND title_code='" . $model . "' AND variant_code='" . $variant . "'", "1");
        if ($checkmodel_data['nr'] == 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error13']), 406);
        }

        $brochure_arr = array();
        $brochure_url = SITE_URL . "explore_assets/model/";
        $expmodel_data = $parent->selectQuery(TABLE_COMPARE_MODEL, "model_id,CASE WHEN model_brochure!='' THEN CONCAT('" . $brochure_url . "',model_brochure) ELSE '' END AS 'model_brochure' ", "is_deleted=0 AND is_other=0  AND `model_type` = '0'", "");
        if ($expmodel_data['nr'] > 0) {
            $arr_id = array_column($expmodel_data['result'], 'model_id');
            $arr_name = array_column($expmodel_data['result'], 'model_brochure');
            $brochure_arr = array_combine($arr_id, $arr_name);
        }

        $brochure_url = '';
        switch (strtoupper($model)) {
            case 'GSX': //GIXXER
                $id = (strpos($variant, 'GSX250') !== false || strpos($checkmodel_data['result'][0]->title, 'GIXXER 250') !== false) ? GIXXER_250_ID : GIXXER_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'GSXSF': //GIXXER SF
                $id = (strpos($variant, 'GSXF250') !== false || strpos($checkmodel_data['result'][0]->title, 'GIXXER SF 250') !== false) ? GIXXER_SF_250_ID : GIXXER_SF_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'GL': //INTRUDER
                $id = INTRUDER_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'UB125': //BURGMAN
                $id = BURGMAN_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            case 'AC':
            case 'ACZ':
                $id = ACCESS_ID;
                $brochure_url = isset($brochure_arr[$id]) ? $brochure_arr[$id] : '';
                break;
            default:
                $brochure_url = '';
                break;

        }
        if ($brochure_url == '') {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error14']), 406);
        }

//        $id=escape_str($parent->params[1]);
        //        $check_arr=$parent->selectQuery(DMS_ENQUIRY_MASTER ,"id,email,share_token"," smpin='".$smpin."' AND is_deleted=0 AND id='".$id."'","1");
        //        if($check_arr['nr']!='1') $parent->response(array('response'=>'failed',  'message'=>$this->page_data['error6']),406);
        //
        //        $email=$check_arr['result'][0]->email;
        //        if($email!='') $parent->response(array('response'=>'failed',  'message'=>$this->page_data['error11']),406);
        //
        //        if($check_arr['result'][0]->share_token!='')
        //        {
        //            //SHARE TOKEN UPDATE
        //            $access_token=globalfunc::generateToken($parent,'enquiry',128);
        //            $update_str = "UPDATE  ".DMS_ENQUIRY_MASTER." SET share_token='".$access_token."' WHERE id='".$id."'";
        //            $parent->executeQuery($update_str);
        //        }

        $obj = array();
        $obj['from'] = SUPPORT_EMAIL;
        $obj['FromName'] = 'HYPER-M';
        $obj['to'] = $email;
        $obj['subject'] = 'HYPER-M - Brochure for ' . $checkmodel_data['result'][0]->title . ' ' . $checkmodel_data['result'][0]->variant;

        $explore_url = $brochure_url;

        $cond_mail_str1 = "Thank you for showing your interest in HYPER-M.";
        $cond_mail_str2 = "We hope you had a great experience in exploring our range of Students";
        $email_link = '<a href="' . $explore_url . '" style="font-weight:bold " >Click Here</a> to download the product e-brochure of ' . $checkmodel_data['result'][0]->title . ' ' . $checkmodel_data['result'][0]->variant . '<br>';

        $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;">
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['message'] = $message;
        // globalfunc::sendMai($parent, $obj);

        $parent->executeQuery("INSERT INTO `" . TABLE_ENQBROCHURESHARE . "` (`smpin`, `name`,email, `model`, `variant`, `created_on`) VALUES ('" . $smpin . "','" . $name . "','" . $email . "','" . $model . "','" . $variant . "' ,  '" . NOW . "')");

        //LOG
        $logstr = 'ENQUIRY SHARE BROCHURE';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success7']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// QUOTATION //////////////////////////////////////////////// */
    private function quotation($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;

        $model = escape_str($parent->_request['model']);
        $variant = escape_str($parent->_request['variant']);
        $REQUEST_KEYS = array('model' => 'string', 'variant' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        //DMS_ENQUIRY_MODEL
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MODEL, "title,title_code,variant,variant_code", " title_code='" . $model . "' AND variant_code='" . $variant . "' AND enq_yn='Y' AND status=1 ", "1");

        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error15']), 406);
        }

        //echo $parent->current_user_data->dealer_code;
        //DEALER
        $check_arr = $parent->selectQuery(DMS_DEALER, "dealer_code,for_cd", "dealer_code='" . $parent->current_user_data->dealer_code . "' AND for_cd!='' AND is_deleted=0 ", "1");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error16']), 406);
        }

        $for_cd = $check_arr['result'][0]->for_cd;

        //CALL DMS
        $url = SUZ_DMS_URL;
        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_vehicle_model_price(:p_model, :p_for, :p_pmc, :list_cursor, :p_err_cd, :p_err_msg); END;", "params" => '[{"title":"p_model","value":"' . $model . '","type":""},{"title":"p_for","value":"' . $for_cd . '","type":""},{"title":"p_pmc","value":"2","type":""},{"title":"list_cursor","value":"","type":"cursor"},{"title":"p_err_cd","value":"","type":""},{"title":"p_err_msg","value":"","type":""}]');
        $header = array('Authorization:Bearer ' . SUZ_TOKEN);

        //LOG
        $obj = new stdClass();
        $obj->type = 'modelprice';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;

        //LOG UPDATE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

        if ($httpcode == '200' && $response != '') {
            $json = json_decode($response);
            if (isset($json->response) && $json->response == 'success' && isset($json->data) && count($json->data) > 0) {
                //LOG UPDATE
                $obj = new stdClass();
                $obj->id = $log_id;
                $obj->insert_count = count($json->data);
                $obj->status = 1;
                //$obj->apiresponse=$response;
                projectfunc::updateCronLog($parent, $obj);

                foreach ($json->data as $res) {
                    if (strtolower($variant) == strtolower($res->VARIANT_CD)) {
                        $error = 0;

                        $data = array('exsh_price' => $res->EXSH_PRICE);
                        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);
                        break;
                    }
                }
                $parent->response(array('response' => 'failed', 'message' => $this->page_data['error17']), 406);
            }

            if ($json->response == 'success' && $json->data->p_err_msg != '') {
                $emsg = $json->data->p_err_msg;
            }
        }

        //LOG
        $logstr = 'ENQUIRY QUOTATION';
        globalfunc::insertUserLog($parent, $logstr, $id);
        if ($error == 1) {
            $emsg = ($emsg != '') ? $emsg : "Error to connect DMS. Please try after sometime";
            $parent->response(array('response' => 'failed', 'message' => $emsg), 406);
        } else {
            $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
        }
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SHARE QUOTATION //////////////////////////////////////////////// */
    private function sharequotation($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

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

        //,'validity_date'=>''
        $REQUEST_KEYS = array('name' => 'string', 'email' => 'string', 'mobile' => 'string', 'email' => 'string', 'model' => 'string', 'variant' => 'string', 'exsh_price' => 'number', 'total_price' => 'number');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

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

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

        //DMS_ENQUIRY_MODEL
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MODEL, "title,title_code,variant,variant_code", " title_code='" . $model . "' AND variant_code='" . $variant . "' AND enq_yn='Y' AND status=1 ", "1");

        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error17']), 406);
        }

        $exsh_price = escape_str($parent->_request['exsh_price']);
        $exsh_remark = escape_str($parent->_request['exsh_remark']);
        $rto_price = escape_str($parent->_request['rto_price']);
        $rto_remark = escape_str($parent->_request['rto_remark']);
        $insurance_price = escape_str($parent->_request['insurance_price']);
        $insurance_remark = escape_str($parent->_request['insurance_remark']);
        $access_price = escape_str($parent->_request['access_price']);
        $access_remark = escape_str($parent->_request['access_remark']);
        $exwarr_price = escape_str($parent->_request['exwarr_price']);
        $exwarr_remark = escape_str($parent->_request['exwarr_remark']);
        $other_price = escape_str($parent->_request['other_price']);
        $other_remark = escape_str($parent->_request['other_remark']);
        $total_price = escape_str($parent->_request['total_price']);
        $total_remark = escape_str($parent->_request['total_remark']);
        $validity_date = escape_str($parent->_request['valid_date']);

        $discount = escape_str($parent->_request['offer_price']);
        $final_price = escape_str($parent->_request['after_discound']);

        if (!$validity_date != '') {
            $valid_day = 10;
            $validity_date = date('Y-m-d', strtotime('+ ' . $valid_day . ' day', strtotime(CUR_DATE)));
        }

        $sharetoken = TIMETOKEN . globalfunc::generateToken($parent, '', 32);

        $parent->executeQuery("INSERT INTO `" . TABLE_QUOTATIONSHARE . "` ( `smpin`, dealer_code, `sharetoken`, `name`, `mobile`, `email`, `model`, `variant`, `exsh_price`, `exsh_remark`, `rto_price`, `rto_remark`, `insurance_price`, `insurance_remark`, `access_price`, `access_remark`, `exwarr_price`, `exwarr_remark`, `other_price`, `other_remark`, `total_price`, `total_remark`,discount,final_price, `validity_date`, `created_on`, `modified_on`) VALUES ('" . $smpin . "','" . $dealer_code . "','" . $sharetoken . "', '" . $name . "', '" . $mobile . "', '" . $email . "', '" . $model . "', '" . $variant . "', '" . $exsh_price . "', '" . $exsh_remark . "', '" . $rto_price . "', '" . $rto_remark . "', '" . $insurance_price . "', '" . $insurance_remark . "', '" . $access_price . "', '" . $access_remark . "', '" . $exwarr_price . "', '" . $exwarr_remark . "', '" . $other_price . "', '" . $other_remark . "', '" . $total_price . "', '" . $total_remark . "','" . $discount . "','" . $final_price . "','" . $validity_date . "' ,'" . NOW . "', '" . NOW . "')");

        //LOG
        $logstr = 'SHARE QUOTATION';
        globalfunc::insertUserLog($parent, $logstr);

        $url = SITE_URL . "quotation/" . $sharetoken;

        //GET DEALER DETAILS
        $dealer_arr = $parent->selectQuery(DMS_DEALER, "*", "dealer_code='" . $dealer_code . "' AND is_deleted=0 ", "1");
        $dealer_email = ($dealer_arr['nr'] > 0) ? $dealer_arr['result'][0]->email : '';

        $obj = array();
        $obj['from'] = SUPPORT_EMAIL;
        $obj['FromName'] = 'HYPER-M';
        $obj['to'] = $email;
        if ($dealer_email != '') {
            $obj['cc'] = $dealer_email;
        }

        $obj['subject'] = 'HYPER-M - Quotation for ' . $check_arr['result'][0]->title . ' ' . $check_arr['result'][0]->variant;

        $explore_url = $url;
        $cond_mail_str1 = "Thank you for showing your interest in HYPER-M.";
        $cond_mail_str2 = "We hope you had a great experience in exploring our range of products";
        $email_link = '<a href="' . $explore_url . '" style="font-weight:bold " >Click Here</a> to view the Quotation for ' . $check_arr['result'][0]->title . ' ' . $check_arr['result'][0]->variant . '<br>';
        $dealer_details = '';
        if ($dealer_arr['nr'] > 0) {
            $dealer_details = $dealer_arr['result'][0]->dealer_name;
            $dealer_details .= ($dealer_arr['result'][0]->address != '') ? '<br>' . $dealer_arr['result'][0]->address : '';
            $dealer_details .= ($dealer_arr['result'][0]->phone != '') ? '<br>Mob : ' . $dealer_arr['result'][0]->phone : '';
            $dealer_details .= ($dealer_arr['result'][0]->email != '') ? '<br>Email : ' . $dealer_arr['result'][0]->email : '';

        }

        $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.
<br><br>Regards,<br>' . $dealer_details . '
                        </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;">
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['message'] = $message;
        // globalfunc::sendMai($parent, $obj);

        $parent->response(array('response' => 'success', 'data' => $url, 'message' => $this->page_data['success6']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SHARE QUOTATION //////////////////////////////////////////////// */
//    private function getquotation($parent)
    //    {
    //        globalfunc::checkParamCount($parent,2);
    //        globalfunc::checkMethodType($parent,array('GET'));
    //        globalfunc::checkAuthrozation($parent,array('type'=>'user'));
    //        projectfunc::authorizedRole($parent,array('8','9','10','11','12','13'));
    //
    //        $token=escape_str($parent->params[1]);
    //
    //        //DMS_ENQUIRY_MODEL
    //        $check_arr=$parent->selectQuery(TABLE_QUOTATIONSHARE ,"*","sharetoken='".$token."'","1");
    //        if(!$check_arr['nr']>0)
    //        {
    //            $client_ip=globalfunc::getIp($parent);
    //            $sec=LOCK_ACCESS_MINUTES*60;
    //            $expiry_time=date('Y-m-d H:i:s',strtotime('-'.$sec.' seconds',strtotime(NOW)));
    //            $lock_qry_str="SELECT SUM(lock_count) lock_count FROM ".TABLE_LOCK_ACCESS." WHERE is_deleted='0' AND modified_on>='".$expiry_time."' AND ip='".$client_ip."' GROUP BY ip LIMIT 1";
    //            $lock_value=$parent->getQueryValue($lock_qry_str);
    //            if(count($lock_value)>0 && $lock_value[0]->lock_count>=3)
    //            {
    //                $parent->response(array('response'=>'failed', 'message'=>'Sorry Invalid Access. Access Blocked For 10 min.'), 401);
    //            }
    //            globalfunc::insertLockLog($parent,$token);
    //            $parent->response(array('response'=>'failed','message'=>$this->page_data['error6']),406);
    //        }
    //        $id=$check_arr['result'][0]->id;
    //        $model_arr=$parent->selectQuery(DMS_ENQUIRY_MODEL ,"title,title_code,variant,variant_code"," title_code='".$check_arr['result'][0]->model."' AND variant_code='".$check_arr['result'][0]->variant."'  ","1");
    //        $check_arr['result'][0]->model_str=($check_arr['nr']>0)?$model_arr['result'][0]->title:'';
    //        $check_arr['result'][0]->variant_str=($check_arr['nr']>0)?$model_arr['result'][0]->variant:'';
    //
    //        $data_arr=$check_arr['result'][0];
    //
    //        //LOG
    //        $logstr='GET QUOTATION';
    //        globalfunc::insertUserLog($parent,$logstr,$id);
    //
    //
    //        $parent->response(array('response'=>'success','data'=>$data_arr, 'message'=>$this->page_data['success1']),200);
    //    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PRICELIST //////////////////////////////////////////////// */
    private function pricelist($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;
        $model = escape_str($parent->_request['model']);
        $REQUEST_KEYS = array('model' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        //DMS_ENQUIRY_MODEL
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MODEL, "variant,variant_code", " title_code='" . $model . "' AND enq_yn='Y' AND status=1  GROUP BY variant_code ", "");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error15']), 406);
        }

        $model_arr = $check_arr['result'];

        //DEALER
        $check_arr = $parent->selectQuery(DMS_DEALER, "dealer_code,for_cd", "dealer_code='" . $parent->current_user_data->dealer_code . "' AND for_cd!='' AND is_deleted=0 ", "1");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error16']), 406);
        }

        $for_cd = $check_arr['result'][0]->for_cd;

        //CALL DMS
        $url = SUZ_DMS_URL;
        $post = array("query" => "BEGIN pkg_smipl_star_app.sp_vehicle_model_price(:p_model, :p_for, :p_pmc, :list_cursor, :p_err_cd, :p_err_msg); END;", "params" => '[{"title":"p_model","value":"' . $model . '","type":""},{"title":"p_for","value":"' . $for_cd . '","type":""},{"title":"p_pmc","value":"2","type":""},{"title":"list_cursor","value":"","type":"cursor"},{"title":"p_err_cd","value":"","type":""},{"title":"p_err_msg","value":"","type":""}]');
        $header = array('Authorization:Bearer ' . SUZ_TOKEN);

        //LOG
        $obj = new stdClass();
        $obj->type = 'modelprice';
        $obj->apirequest = $post['params'];
        $log_id = projectfunc::cronLog($parent, $obj);

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //Post Fields
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // $response = curl_exec($ch);
        // $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);
            $httpcode = '200';
            $response="";
        $error = 1;
        $count = 0;
        $vari_arr = array();

        //LOG UPDATE
        $obj = new stdClass();
        $obj->id = $log_id;
        $obj->apiresponse = $response;
        projectfunc::updateCronLog($parent, $obj);

        if ($httpcode == '200' && $response != '') {
            $json = json_decode($response);
            if (isset($json->response) && $json->response == 'success' && isset($json->data) && count($json->data) > 0) {
                //LOG UPDATE
                $obj = new stdClass();
                $obj->id = $log_id;
                $obj->insert_count = count($json->data);
                $obj->status = 1;
                //$obj->apiresponse=$response;
                projectfunc::updateCronLog($parent, $obj);

                foreach ($json->data as $res) {
                    $code = strtolower($res->VARIANT_CD);
                    $vari_arr[$code] = $res->EXSH_PRICE;
                }

                foreach ($model_arr as $mkey => $val) {
                    $error = 0;
                    $variant_code = strtolower($model_arr[$mkey]->variant_code);
                    $model_arr[$mkey]->exsh_price = (isset($vari_arr[$variant_code])) ? $vari_arr[$variant_code] : '';

                    $obj = new stdClass();
                    $obj->model = $model;
                    $obj->variant = $variant_code;
                    $obj->variantname = $model_arr[0]->variant;
                    //print_r($obj);
                    $model_arr[$mkey]->model_image = projectfunc::modelimage($parent, $obj);

                }

            }

            if ($json->response == 'success' && $json->data->p_err_msg != '') {
                $emsg = $json->data->p_err_msg;
            }
        }

        //LOG
        $logstr = 'ENQUIRY PRICE LIST';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $model_arr, 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TEST RIDE //////////////////////////////////////////////// */
    private function testride($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13'));

        $smpin = $parent->current_user_data->smpin;
        $id = escape_str($parent->params[1]);
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id", " smpin='" . $smpin . "' AND is_deleted=0 AND is_dms=1 AND id='" . $id . "'", "1");
        if ($check_arr['nr'] != '1') {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

        //CALL DMS

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

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER LIST //////////////////////////////////////////////// */
    private function getplannerdetails($parent, $id)
    {
        $list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*,DATE_FORMAT(plan_date, '%d-%m-%Y')plandate,DATE_FORMAT(plan_fromtime, '%H:%i') fromtime,DATE_FORMAT(plan_totime, '%H:%i') totime", "id='" . $id . "' AND is_deleted=0", "1");
        return ($list_arr['nr']) ? $list_arr['result'][0] : new stdClass();
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER LIST //////////////////////////////////////////////// */
    private function plannerlist($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13', '14'));

        $userid = $parent->current_user_id;
        $type = escape_str($parent->_request['type']);

        $monthdata = array();
        $todaydata = array();
        $date_arr = array();

        $REQUEST_KEYS = array('type' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        if ($type == 'month') {
            $REQUEST_KEYS = array('month' => 'number', 'year' => 'number');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $month = escape_str($parent->_request['month']);
            $year = escape_str($parent->_request['year']);
            if (!globalfunc::isValidDateTimeString($year . '-' . $month . '-01', 'Y-m-d', 'Asia/Kolkata')) {
                $parent->response(array('response' => 'failed', 'message' => $this->page_data['error21']), 406);
            }

            $start_date = date('Y-m-d', strtotime($year . '-' . $month . '-01'));
            $end_date = date('Y-m-t', strtotime($year . '-' . $month . '-01'));

            $temp = $start_date;
            while (strtotime($temp) <= strtotime($end_date)) {
                $date_str = @explode('-', $temp);
                $value = $date_str[2];
                $monthdata[$value] = array('date' => $temp, 'data' => array());
                $temp = date('Y-m-d', strtotime('+ 1 day', strtotime($temp)));
            }

            $get_list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*,DATE_FORMAT(plan_date, '%d-%m-%Y')plandate,DATE_FORMAT(plan_fromtime, '%H:%i') fromtime,DATE_FORMAT(plan_totime, '%H:%i') totime", " is_deleted='0' AND userid='" . $userid . "' AND plan_date>='" . $start_date . "' AND plan_date<='" . $end_date . "' ORDER BY plan_fromtime ASC", "");

            if ($get_list_arr['nr'] > 0) {
                foreach ($get_list_arr['result'] as $res) {
                    $value = date('d', strtotime($res->plan_date));
                    $monthdata[$value]['data'][] = $res;
                }
            }
        } else if ($type == 'today') {
            $start_date = CUR_DATE;
            $end_date = CUR_DATE;

            $get_list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*,DATE_FORMAT(plan_date, '%d-%m-%Y')plandate,DATE_FORMAT(plan_fromtime, '%H:%i') fromtime,DATE_FORMAT(plan_totime, '%H:%i') totime", " is_deleted='0' AND userid='" . $userid . "'  AND plan_date>='" . $start_date . "' AND plan_date<='" . $end_date . "' ORDER BY plan_fromtime ASC", "");
            $todaydata = ($get_list_arr['nr'] > 0) ? $get_list_arr['result'] : array();
            $monthdata = new stdClass();
        } else if ($type == 'date') {
            $REQUEST_KEYS = array('date' => 'date|Y-m-d');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            $date = escape_str($parent->_request['date']);
            $start_date = $date;
            $end_date = $date;

            $get_list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*,DATE_FORMAT(plan_date, '%d-%m-%Y')plandate,DATE_FORMAT(plan_fromtime, '%H:%i') fromtime,DATE_FORMAT(plan_totime, '%H:%i') totime", " is_deleted='0' AND userid='" . $userid . "'  AND plan_date>='" . $start_date . "' AND plan_date<='" . $end_date . "' ORDER BY plan_fromtime ASC", "");
            $date_arr = ($get_list_arr['nr'] > 0) ? $get_list_arr['result'] : array();

        } else {
            $parent->response(array('response' => 'failed', 'message' => "Invalid type format"), 406);
        }

        $data = array('month' => $monthdata, 'today' => $todaydata, 'date' => $date_arr);

        //LOG
        $logstr = 'PLANNER LIST';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER INSERT //////////////////////////////////////////////// */
    private function plannersave($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13', '14'));

        $userid = $parent->current_user_id;

        $REQUEST_KEYS = array('title' => 'string', 'description' => 'string', 'plandate' => 'string', 'fromtime' => 'string', 'totime' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $title = escape_str($parent->_request['title']);
        $description = escape_str($parent->_request['description']);
        $date = escape_str($parent->_request['plandate']);
        $date_arr = @explode('-', $date);
        $date_str = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];

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

        if (!globalfunc::isValidDateTimeString($date_str, 'Y-m-d', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error18']), 406);
        }

        if (!globalfunc::isValidDateTimeString($date_str . " " . $fromtime . ":00", 'Y-m-d H:i:s', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error19']), 406);
        }

        if (!globalfunc::isValidDateTimeString($date_str . " " . $totime . ":00", 'Y-m-d H:i:s', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error19']), 406);
        }

        $fromdatetime = $date_str . " " . $fromtime;
        $todatetime = $date_str . " " . $totime;

        //CHECK SLOT ALREADY EXIST
        $list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*", "  is_deleted='0' AND userid='" . $userid . "' AND ((plan_fromtime BETWEEN '" . $fromdatetime . "' AND '" . $todatetime . "') OR (plan_totime BETWEEN '" . $fromdatetime . "' AND '" . $todatetime . "') ) ", "1");
        if ($list_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error20']), 406);
        }

        $parent->executeQuery("INSERT INTO `" . TABLE_ENQUIRYPLANNER . "` (`userid`, `plan_date`, `plan_title`, plan_description, `plan_fromtime`, `plan_totime`, `created_on`, `modified_on`) VALUES ('" . $userid . "','" . $date_str . "','" . $title . "','" . $description . "', '" . $fromdatetime . "','" . $todatetime . "','" . NOW . "', '" . NOW . "')");
        $id = $parent->lastInsertId();

        $data = $this->getplannerdetails($parent, $id);

        //LOG
        $logstr = 'PLANNER INSERT';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success3']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER UPDATE //////////////////////////////////////////////// */
    private function plannerupdate($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13', '14'));

        $userid = $parent->current_user_id;
        $id = escape_str($parent->params[1]);

        $list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*", "id='" . $id . "' AND   is_deleted='0' AND userid='" . $userid . "'", "1");
        if (!$list_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

        $REQUEST_KEYS = array('title' => 'string', 'description' => 'string', 'plandate' => 'string', 'fromtime' => 'string', 'totime' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $title = escape_str($parent->_request['title']);
        $description = escape_str($parent->_request['description']);
        $date = escape_str($parent->_request['plandate']);
        $date_arr = @explode('-', $date);
        $date_str = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];

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

        if (!globalfunc::isValidDateTimeString($date_str, 'Y-m-d', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error18']), 406);
        }

        if (!globalfunc::isValidDateTimeString($date_str . " " . $fromtime . ":00", 'Y-m-d H:i:s', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error19']), 406);
        }

        if (!globalfunc::isValidDateTimeString($date_str . " " . $totime . ":00", 'Y-m-d H:i:s', 'Asia/Kolkata')) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error19']), 406);
        }

        $fromdatetime = $date_str . " " . $fromtime;
        $todatetime = $date_str . " " . $totime;

        //CHECK SLOT ALREADY EXIST
        $list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*", "  is_deleted='0' AND id!='" . $id . "' AND userid='" . $userid . "' AND ((plan_fromtime BETWEEN '" . $fromdatetime . "' AND '" . $todatetime . "') OR (plan_totime BETWEEN '" . $fromdatetime . "' AND '" . $todatetime . "') ) ", "1");
        if ($list_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error20']), 406);
        }

        $parent->executeQuery("UPDATE " . TABLE_ENQUIRYPLANNER . " SET `plan_date`='" . $date_str . "', `plan_title`='" . $title . "', plan_description='" . $description . "', `plan_fromtime`='" . $fromdatetime . "', `plan_totime`='" . $todatetime . "',  `modified_on`='" . NOW . "' WHERE id='" . $id . "'");

        $data = $this->getplannerdetails($parent, $id);

        //LOG
        $logstr = 'PLANNER UPDATE';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success4']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER DELETE //////////////////////////////////////////////// */
    private function plannerdelete($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('DELETE'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('8', '9', '10', '11', '12', '13', '14'));

        $userid = $parent->current_user_id;
        $id = escape_str($parent->params[1]);

        $list_arr = $parent->selectQuery(TABLE_ENQUIRYPLANNER, "*", "id='" . $id . "' AND   is_deleted='0' AND userid='" . $userid . "'", "1");
        if (!$list_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }

        $parent->executeQuery("UPDATE  " . TABLE_ENQUIRYPLANNER . " SET is_deleted=1, `modified_on`='" . NOW . "' WHERE id='" . $id . "'");

        //LOG
        $logstr = 'PLANNER DELETE';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success5']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PLANNER TIMER //////////////////////////////////////////////// */
    private function plannertimer($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('GET'));

        $t_arr = array("00", "30");
        for ($i = 6; $i < 23; $i++) {
            $m = ($i < 10) ? "0" . $i : $i;
            foreach ($t_arr as $tstr) {
                //$t=($tstr<10)?"0".$tstr:$tstr;
                $tvalue = $m . ":" . $tstr;
                $time_arr[] = array('title' => $tvalue, 'title_code' => $tvalue);
            }
        }
        $data = $time_arr;

        //LOG
        $logstr = 'PLANNER TIMER';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SMPIN DEALER //////////////////////////////////////////////// */
    private function smpindealer($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('GET'));

        $smpin = escape_str($parent->params[1]);
        $dse_details = $this->getdsedetails($parent, $smpin);

        $dealer_arr = $parent->selectQuery(DMS_DEALER, "dealer_code,dealer_name,phone,email,address,state,city", " dealer_code='" . $dse_details->dealer_code . "'  ", "1");
        $data = ($dealer_arr['nr'] > 0) ? $dealer_arr['result'] : array();
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DEALER //////////////////////////////////////////////// */
    private function dealer($parent)
    {
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkMethodType($parent, array('GET'));

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

        $dealer_arr = $parent->selectQuery(DMS_DEALER, "dealer_code,dealer_name,phone,email,address,state,city", " dealer_code='" . $dealer_code . "'  ", "1");
        $data = ($dealer_arr['nr'] > 0) ? $dealer_arr['result'] : array();

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

    /* /////////////////////////////// PLANNER TIMER //////////////////////////////////////////////// */
    private function getdsedetails($parent, $smpin)
    {
        $data = $parent->selectQuery(DMS_EMPLOYEE, "*", "smpin='" . $smpin . "' AND status=1", "1");
        if (!$data['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error1']), 406);
        }

        return $data['result'][0];
    }

    /* /////////////////////////////// COMMON //////////////////////////////////////////////// */
    private function followupcommon($parent)
    {

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

        $purpose_data = $parent->selectQuery(DMS_ENQUIRY_PURPOSE, "id,title,title_code", " status='1'", "");
        $modeofcontact_data = $parent->selectQuery(DMS_ENQUIRY_MODE, "title,title_code", " status='1' ", "");

        $purpose_arr = ($purpose_data['nr'] > 0) ? $purpose_data['result'] : array();
        $modeofcontact_arr = ($modeofcontact_data['nr'] > 0) ? $modeofcontact_data['result'] : array();

        $t_arr = array("00", "30");
        for ($i = 9; $i < 19; $i++) {
            $m = ($i < 10) ? "0" . $i : $i;
            foreach ($t_arr as $tstr) {
                //$t=($tstr<10)?"0".$tstr:$tstr;
                $tvalue = $m . ":" . $tstr;
                $time_arr[] = array('title' => $tvalue, 'title_code' => $tvalue);
            }
        }

        //LOST REASON
        $lostreason = array();
        $reason_data = $parent->selectQuery(DMS_ENQUIRY_REASON, "list_desc title,list_code title_code", " list_flag='L' AND status=1", "");
        if ($reason_data['nr'] > 0) {
            foreach ($reason_data['result'] as $rkey => $res) {
                $subreason_data = $parent->selectQuery(DMS_ENQUIRY_SUBREASON, "list_desc title,list_code title_code", " reason_code='" . $res->title_code . "' AND status=1", "");
                $reason_data['result'][$rkey]->subreason = ($subreason_data['nr'] > 0) ? $subreason_data['result'] : array();
            }
            $lostreason = $reason_data['result'];
        }
        //POSTPONED REASON
        $reason_data = $parent->selectQuery(DMS_ENQUIRY_REASON, "list_desc title,list_code title_code", "  list_flag='E' AND status=1", "");
        $postponedreason = ($reason_data['nr'] > 0) ? $reason_data['result'] : array();

        //LOST MODEL
        $lost_data = $parent->selectQuery(DMS_ENQUIRY_LOSTMODEL, "cmodel_desc  title,cmodel_cd title_code", " status=1", "");
        $lost_model = ($lost_data['nr'] > 0) ? $lost_data['result'] : array();

        $data = array('purpose' => $purpose_arr, 'time' => $time_arr, 'modeofcontact' => $modeofcontact_arr, 'lostreason' => $lostreason, 'postponedreason' => $postponedreason, 'lost_model' => $lost_model);
        //LOG
        $logstr = 'ENQUIRY FOLLOWUP COMMON';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $data, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* ///////////////////////// TESTRIDE UPDATE //////////////////// */
    private function testrideupdate($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $REQUEST_KEYS = array('id' => 'number', 'license' => 'string', 'license_expiry' => 'date|d-m-Y');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $id = escape_str($parent->_request['id']);
        $license = escape_str($parent->_request['license']);
        $license_expiry_str = escape_str($parent->_request['license_expiry']);
        $date_arr = @explode("-", $license_expiry_str);
        $license_expiry = $date_arr[2] . "-" . $date_arr[1] . "-" . $date_arr[0];

        //CHECK SLOT ALREADY EXIST
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,mobile ", "   id='" . $id . "'  AND is_dms=1 AND is_deleted=0 ", "1");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }
        $otp = globalfunc::generateOTP();

        $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET license='" . $license . "',license_expiry='" . $license_expiry . "',otp='" . $otp . "' WHERE id='" . $id . "' ");
        $mobile = $check_arr['result'][0]->mobile;
        $sms_message = "Your one time password is " . $otp;
        // globalfunc::sendSMS($parent, $mobile, $sms_message);

        //LOG
        $logstr = 'TESTRIDE UPDATE';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* ///////////////////////// TESTRIDE OTP //////////////////// */
    private function testrideotp($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $REQUEST_KEYS = array('id' => 'number', 'otp' => 'number');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

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

        //CHECK SLOT ALREADY EXIST
        $check_arr = $parent->selectQuery(DMS_ENQUIRY_MASTER, "id,otp ", "   id='" . $id . "'    AND is_dms=1 AND is_deleted=0 ", "1");
        if (!$check_arr['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error6']), 406);
        }
        if ($otp != $check_arr['result'][0]->otp) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error3']), 406);
        }

        $parent->executeQuery("UPDATE `" . DMS_ENQUIRY_MASTER . "` SET  is_testride=1 WHERE id='" . $id . "' ");

        //LOG
        $logstr = 'TESTRIDE OTP';
        globalfunc::insertUserLog($parent, $logstr, $id);
        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);

    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

}
