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

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

define('MIN_ASSESSMENT_PERCENT', "60");

class manager
{

    //FUNCTION LISTS
    public function __construct($parent)
    {
        //GET PAGE MESSAGE
        $this->page_data = globalfunc::getMessage($parent, $parent->lang, 'manager');
        if (count($parent->params) == 0) {
            // $this->dashboardfunc($parent);
        } else {
            $qry_params = explode("?", $parent->params[0]);
            $parameter_val = strtolower($qry_params[0]);

            switch ($parameter_val) {
                case "zone":
                case "region":
                case "area":
                case "dealer":
                case "salesreport": //
                case "certifieddsereport": //
                case "assessmentlist":
                case "assessmentreport": //
                case "salesleaderboardreport": //
                case "assessmentleaderboardreport": //
                case "assessmentleaderboardreportnew":
                case "registrationreport": //    OLD ONE REPLACED WITH newregistrationreport
                case "coursereport": //
                case "usercoursereport":
                case "usertopicreport":
                case "salestarget": //
                case "salestargetupdate":

                case "newsalestargetupdate":
                case "surveylist":
                case "surveyreport":
                case "surveyuserreport":
                case "uploadtargetsale":

                case "newregistrationreport":
                case "newcoursereport":
                case "newsurveyreport":
                case "newsalesreport":
                case "newcertifieddsereport":
                case "newassessmentreport":
                case "newsalestarget":
                case "newsalesleaderboardreport":
                case "newassessmentleaderboardreport":

                case "asmassessmentreport":
                case "rmassessmentreport":
                case "zmassessmentreport":
                case "trainerassessmentreport":

                case "newsalestargetreport":
                case "managersalestargetreport":
                case "userlist":
                case "dealerlist":
                //case "saletargetapprovallist":
                case "userstatusupdate":

                case "zmcoursereport":
                case "trainercoursereport":
                case "rmcoursereport":
                case "amcoursereport":
                case "dealercoursereport":
                    $this->$parameter_val($parent);
                    break;
                default:
                    break;
            }

        }

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

    private function getmanagerconditon_arr($parent)
    {
        projectfunc::authorizedRole($parent, array('3', '4', '5', '6', '7', '14'));
        $zmemail = escape_str($parent->_request["zmemail"]);
        $rmemail = escape_str($parent->_request["rmemail"]);
        $amemail = escape_str($parent->_request["amemail"]);
        $dealer_cond = array();

        if ($parent->current_user_role == '3') {
            $REQUEST_KEYS = array('zmemail' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            if ($zmemail != 'all' && $zmemail != '') {
                $dealer_cond[] = "zm_email='" . $zmemail . "'";
            }

            if ($rmemail != 'all' && $rmemail != '') {
                $dealer_cond[] = "rm_email='" . $rmemail . "'";
            }

            if ($amemail != 'all' && $amemail != '') {
                $dealer_cond[] = "am_email='" . $amemail . "'";
            }

        } else if ($parent->current_user_role == '4') {
            $REQUEST_KEYS = array('rmemail' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            $dealer_cond[] = "zm_email='" . $parent->current_user_data->emailid . "'";
            if ($rmemail != 'all' && $rmemail != '') {
                $dealer_cond[] = "rm_email='" . $rmemail . "'";
            }

            if ($amemail != 'all' && $amemail != '') {
                $dealer_cond[] = "am_email='" . $amemail . "'";
            }

        } else if ($parent->current_user_role == '5') {
            $REQUEST_KEYS = array('rmemail' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

            $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
            $trainer_arr = $parent->getQueryValue($get_trainer_str);
            $dealer_cond[] = (count($trainer_arr) > 0) ? "zone='" . $trainer_arr[0]->zone . "'" : "zone='0'";
            if ($rmemail != 'all' && $rmemail != '') {
                $dealer_cond[] = "rm_email='" . $rmemail . "'";
            }

            if ($amemail != 'all' && $amemail != '') {
                $dealer_cond[] = "am_email='" . $amemail . "'";
            }

        } else if ($parent->current_user_role == '6') {
            $REQUEST_KEYS = array('amemail' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $dealer_cond[] = "rm_email='" . $parent->current_user_data->emailid . "'";
            if ($amemail != 'all' && $amemail != '') {
                $dealer_cond[] = "am_email='" . $amemail . "'";
            }

        } else if ($parent->current_user_role == '7') {
            $dealer_cond[] = "am_email='" . $parent->current_user_data->emailid . "'";
        } else if ($parent->current_user_role == '14') {
            $dealer_cond[] = "dealer_code='" . $parent->current_user_data->dealer_code . "'";
        }

        return $dealer_cond;
    }

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

        $rmmanager = isset($parent->_request["rmemail"]) ? escape_str($parent->_request["rmemail"]) : '';
        if ($rmmanager) {
            $query_cond .= " AND rm_email='" . $rmmanager . "'";
        }

        //GET DATA
        $query_str = "SELECT zm_name as name,zm_email as email,zone FROM " . DMS_DEALER . " WHERE zm_name!='' AND status='1' AND is_deleted='0' " . $query_cond . "  GROUP BY zm_email ORDER BY zm_name ASC";
        $query_arr = $parent->getQueryValue($query_str);

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

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

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

        $query_cond = '';
        if ($parent->current_user_role == '5') {
            $zonename = isset($parent->_request["zonename"]) ? escape_str($parent->_request["zonename"]) : '';
            $query_cond .= " AND zone='" . $zonename . "'";
        } else {
            $zonemanager = isset($parent->_request["zone"]) ? escape_str($parent->_request["zone"]) : '';
            if ($zonemanager) {
                $query_cond .= " AND zm_email='" . $zonemanager . "'";
            }

            $ammanager = isset($parent->_request["amemail"]) ? escape_str($parent->_request["amemail"]) : '';
            if ($ammanager) {
                $query_cond .= " AND am_email='" . $ammanager . "'";
            }

        }

        //GET DATA
        $query_str = "SELECT rm_name as name,rm_email as email FROM " . DMS_DEALER . " WHERE rm_name!=''  AND status='1' AND is_deleted='0' " . $query_cond . "  GROUP BY rm_email ORDER BY rm_name ASC";
        $query_arr = $parent->getQueryValue($query_str);

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

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

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

        $query_cond = '';
        $zonemanager = isset($parent->_request["zone"]) ? escape_str($parent->_request["zone"]) : '';
        if ($zonemanager) {
            $query_cond .= " AND zm_email='" . $zonemanager . "'";
        }

        $regionmanager = isset($parent->_request["region"]) ? escape_str($parent->_request["region"]) : '';
        if ($regionmanager) {
            $query_cond .= " AND rm_email='" . $regionmanager . "'";
        }

        $dealer_code = isset($parent->_request["dealer_code"]) ? escape_str($parent->_request["dealer_code"]) : '';
        if ($dealer_code) {
            $query_cond .= " AND dealer_code='" . $dealer_code . "'";
        }

        //GET DATA
        $query_str = "SELECT am_name as name,am_email as email FROM " . DMS_DEALER . " WHERE am_name!=''  AND status='1' AND is_deleted='0' " . $query_cond . "  GROUP BY am_email ORDER BY am_name ASC";
        $query_arr = $parent->getQueryValue($query_str);

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

    /* /////////////////////////////// ZONE MANAGER //////////////////////////////////////////////// */
    private function dealer($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        //GET DATA
        $query_str = "SELECT dealer_code,dealer_name,CONCAT(dealer_name,' - ',dealer_code) as title FROM " . DMS_DEALER . " WHERE am_email='" . $parent->current_user_data->emailid . "' AND status=1 AND is_deleted='0'";
        $query_arr = $parent->getQueryValue($query_str);
        $query_ar = (count($query_arr) > 0) ? $query_arr : array();

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

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

    /* /////////////////////////////// SALES REPORT //////////////////////////////////////////////// */
    private function salesreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 3);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[2]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        //AREA MANAGER SELF
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;
        }
        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= " AND d.status='1' AND d.is_deleted='0'";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0' )";
                break;

//            case '9': break;
            //            case '10': break;
            //            case '11': break;
            //            case '12': break;
            //            case '13': break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);
        $query_modelarr = $parent->selectQuery(TABLE_MODEL, " model_name,model_image ", "model_is_target=1 AND user_type=0 ORDER BY model_id", "");
        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                //TARGET
                $user_target = projectfunc::userSalesTarget($parent, $res_user->userid, '', $year_data, $month_data);
                //ACHIEVED
                $user_achieved = projectfunc::userSalesAchieved($parent, $res_user->userid, '', $year_data, $month_data);
                $sales = array('target' => $user_target, 'achieved' => $user_achieved);

                $user_arr[$mkey]->sales = $sales;
                $model_data_arr = array();
                //GET MODEL

                if ($query_modelarr['nr']) {
                    foreach ($query_modelarr['result'] as $key => $res) {

                        $res->model_image_url = ($res->model_image != '') ? SITE_URL . "hypermupload/model/" . $res->model_image : NOIMAGE_URL;
                        $user_target = projectfunc::userSalesTarget($parent, $res_user->userid, $res->model_name, $year_data, $month_data);

                        if ($user_target > 0) {
                            $res->target = $user_target;
                            $res->achieved = projectfunc::userSalesAchieved($parent, $res_user->userid, $res->model_name, $year_data, $month_data);
                            $model_data_arr[] = (array) $res;
                        }
                    }
                }

                $user_arr[$mkey]->model_data = $model_data_arr;

            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . " LIMIT 1 ";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'MANAGER SALES REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $user_arr, 'month' => date('M', strtotime('2018-' . $month_data . "-01")), 'year' => $year_data, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CERTIFIED DSE REPORT //////////////////////////////////////////////// */
    private function certifieddsereport($parent)
    {

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

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

        //AREA MANAGER SELF
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;
        }

        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= " AND d.status='1' AND d.is_deleted='0'";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }
        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR  d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $user_arr[$mkey]->learning = projectfunc::userLearningLevel($parent, $res_user->userid);
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid) as ucount FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'MANAGER CERTIFIED DSE REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $user_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// ASSESSMENT LIST //////////////////////////////////////////////// */
    private function assessmentlist($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        $query_cond = "";

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

        if (isset($filter_arr) && isset($filter_arr['role'])) {
            $user_type = $filter_arr['role'];
        }
        if (isset($filter_arr) && isset($filter_arr['atype'])) {

            switch ($filter_arr['atype']) {
                case '0':$user_cond = " AND atype='" . $filter_arr['atype'] . "'";
                    break;
                case '1':$user_cond = " AND atype='" . $filter_arr['atype'] . "'";
                    break;
                default:break;
            }
        }

        switch ($user_type) {
            case 'DSE':
                $user_cond .= ' AND user_type=0 ';
                break;
            case 'IDSE':
                $user_cond .= ' AND user_type=1 ';
                break;
            case 'HO':
                $user_cond .= ' AND user_type=2 ';
                break;
            case 'ZM':
                $user_cond .= ' AND user_type=3 ';
                break;
            case 'TR':
                $user_cond .= ' AND user_type=4 ';
                break;
            case 'RM':
                $user_cond .= ' AND user_type=5 ';
                break;
            case 'AM':
                $user_cond .= ' AND user_type=6 ';
                break;
            case 'DR':
                $user_cond .= ' AND user_type=7 ';
                break;
            case 'CE':
                $user_cond .= ' AND user_type=8 ';
                break;
            default:
                $user_cond .= ' AND user_type=0 ';
                break;
        }

        switch ($role) {

            case '3': //HO Manager
                $query_cond .= "";
                break;
            case '4': //Zonal Manager
                $get_zone_str = "SELECT zone FROM " . DMS_DEALER . "  WHERE zm_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY zone ";
                $zone_arr = $parent->getQueryValue($get_zone_str);
                if (count($zone_arr) > 0) {
                    foreach ($zone_arr as $res_zone) {
                        $zone_cond_arr[] = " filter_zone LIKE '%" . $res_zone->zone . "%'";
                    }
                    $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                } else {
                    $query_cond .= " AND (filter_zone='') ";
                }
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $res_user->userid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $query_cond = " AND (filter_zone='' OR filter_zone LIKE '%" . $trainer_arr[0]->zone . "%') ";
                break;
            case '6': //Regional Manager
                $get_city_str = "SELECT city,zone FROM " . DMS_DEALER . "  WHERE rm_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY city ";
                $city_arr = $parent->getQueryValue($get_city_str);
                if (count($city_arr) > 0) {
                    $zone_arr = array();
                    foreach ($city_arr as $res_city) {
                        if (!in_array($res_city->zone, $zone_arr)) {
                            $zone_arr[] = $res_city->zone;
                        }

                        $city_cond_arr[] = " filter_region LIKE '%" . $res_city->city . "%'";
                    }
                    $query_cond .= " AND ( filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }
                } else {
                    $query_cond .= " AND (filter_region='' AND  filter_zone='') ";
                }

                break;
            case '7': //Area Manager
                $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE am_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
                $dealer_arr = $parent->getQueryValue($get_dealer_str);
                if (count($dealer_arr) > 0) {
                    $zone_arr = array();
                    $city_arr = array();
                    foreach ($dealer_arr as $res_dealer) {
                        if (!in_array($res_dealer->zone, $zone_arr)) {
                            $zone_arr[] = $res_dealer->zone;
                        }

                        if (!in_array($res_dealer->city, $city_arr)) {
                            $city_arr[] = $res_dealer->city;
                        }

                        $dealer_cond_arr[] = " filter_dealer LIKE '%" . $res_dealer->dealer_code . "%'";
                    }
                    $query_cond .= " AND ( filter_dealer='' OR " . @implode(" OR ", $dealer_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }

                    if (count($city_arr) > 0) {
                        foreach ($city_arr as $city) {
                            $city_cond_arr[] = " filter_region LIKE '%" . $city . "%'";
                        }
                        $query_cond .= " AND (filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_region='') ";
                    }

                } else {
                    $query_cond .= " AND (filter_dealer='' AND filter_region=''   AND  filter_zone='') ";
                }
                break;

            case '14': //Dealer
                $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE dealer_code='" . $userdata->dealer_code . "' AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
                $dealer_arr = $parent->getQueryValue($get_dealer_str);
                if (count($dealer_arr) > 0) {
                    $zone_arr = array();
                    $city_arr = array();
                    foreach ($dealer_arr as $res_dealer) {
                        if (!in_array($res_dealer->zone, $zone_arr)) {
                            $zone_arr[] = $res_dealer->zone;
                        }

                        if (!in_array($res_dealer->city, $city_arr)) {
                            $city_arr[] = $res_dealer->city;
                        }

                        $dealer_cond_arr[] = " filter_dealer LIKE '%" . $res_dealer->dealer_code . "%'";
                    }
                    $query_cond .= " AND ( filter_dealer='' OR " . @implode(" OR ", $dealer_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }

                    if (count($city_arr) > 0) {
                        foreach ($city_arr as $city) {
                            $city_cond_arr[] = " filter_region LIKE '%" . $city . "%'";
                        }
                        $query_cond .= " AND (filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_region='') ";
                    }

                } else {
                    $query_cond .= " AND (filter_dealer='' AND filter_region=''   AND  filter_zone='') ";
                }
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $data_arr = array();

        //GET COUNT
        $assessment_str = "SELECT assessmentid,assessmentname,atype,pass_score FROM " . TABLE_ASSESSMENT . " WHERE status='1'  AND  assettypeid='1'  AND  publisheddate<='" . NOW . "' " . $user_cond . $query_cond . " ORDER BY assessmentid ASC";
        $get_assessment_arr = $parent->getQueryValue($assessment_str);
        if (count($get_assessment_arr) > 0) {
            $data_arr = $get_assessment_arr;
        }

        //LOG
        $logstr = 'ASSESSMENT REPORT LIST';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);

    }

    /* //////////////////////////////////////////////////////////////////////////////////////////// */

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

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

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $user_cond = "";
        $dealer_code_cond = '';
        //AREA MANAGER SELF
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;
            if ($parent->current_user_role == '14') {
                $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
            }
        }
        $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    /* /////////////////////////////// SALES LEADERBOARD REPORT //////////////////////////////////////////////// */
    private function salesleaderboardreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 3);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[2]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('email' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $email = escape_str($parent->_request["email"]);

        $user_cond = "";
        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[2]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Rank

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = " ORDER BY d.dealer_name,f.rank ASC ";
                    break;
                case '2':$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
                default:$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        if ($parent->current_user_role == '14') {
            $user_cond .= " AND u.dealer_code='" . $dealer_code . "'";
        }
        //GET ALL 20 USER RANK
        $start_date = date('Y-m-d', strtotime($year_data . "-" . $month_data . "-01"));
        $end_date = date('Y-m-t', strtotime($year_data . "-" . $month_data . "-01"));

        $parent->executeQuery("SET @rownum := 0");
        $get_user_str = "SELECT f.*,u.userid,u.fname,u.lname,d.* FROM (SELECT @rownum := @rownum + 1 AS rank, salecount,targetcount,smpin,userid,last_sale,first_sale,sale_per FROM (SELECT c.*, CASE WHEN targetcount=0 THEN 0 ELSE (salecount/targetcount)*100 END as 'sale_per' FROM ( SELECT a.userid,a.smpin,a.salecount,b.targetcount,a.last_sale,a.first_sale FROM (SELECT COALESCE(COUNT(s.id),'0') as scount, COALESCE(SUM(s.sales_count),'0') as salecount, u.smpin,u.userid,MAX(s.sale_date) last_sale,MIN(s.sale_date) first_sale FROM " . TABLE_USER . " as u  JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code LEFT JOIN (SELECT id,smpin,sale_date,sales_count FROM " . DMS_EMPLOYEE_SALES . " WHERE sale_date>='" . $start_date . "' AND sale_date<='" . $end_date . "') as s ON s.smpin=u.smpin WHERE u.is_deleted=0 AND u.status=1 AND u.role>7 AND u.role<14  AND d.am_email='" . $email . "' GROUP BY u.smpin ) as a JOIN  (SELECT  COALESCE(SUM(t.target),'0') as targetcount,u.smpin,u.userid FROM " . TABLE_USER . " as u JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  LEFT JOIN (SELECT id,smpin,target FROM " . TABLE_USER_SALETARGET . " WHERE sale_month>='" . $start_date . "' AND sale_month<='" . $end_date . "')as t ON t.smpin=u.smpin WHERE u.is_deleted=0 AND u.status=1 AND u.role>7  AND u.role<14  AND d.am_email='" . $email . "'  GROUP BY u.smpin ) as b ON a.userid=b.userid )c ORDER BY cast(sale_per as SIGNED) DESC,cast(salecount as SIGNED) DESC,cast(targetcount as SIGNED) DESC,last_sale ASC,first_sale ASC,userid ASC)as a )as f  JOIN " . TABLE_USER . " as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1 " . $user_cond . $order_by_cond . " " . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        //GET COUNT
        $get_user_count_str = "SELECT COUNT(u.userid)as user_count FROM (SELECT  salecount,targetcount,smpin,userid,last_sale,first_sale,sale_per FROM (SELECT c.*, CASE WHEN targetcount=0 THEN 0 ELSE (salecount/targetcount)*100 END as 'sale_per' FROM ( SELECT a.userid,a.smpin,a.salecount,b.targetcount,a.last_sale,a.first_sale FROM (SELECT COALESCE(COUNT(s.id),'0') as scount, COALESCE(SUM(s.sales_count),'0') as salecount, u.smpin,u.userid,MAX(s.sale_date) last_sale,MIN(s.sale_date) first_sale FROM " . TABLE_USER . " as u  JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  LEFT JOIN (SELECT id,smpin,sale_date,sales_count FROM " . DMS_EMPLOYEE_SALES . " WHERE sale_date>='" . $start_date . "' AND sale_date<='" . $end_date . "') as s ON s.smpin=u.smpin WHERE u.is_deleted=0 AND u.status=1 AND u.role>7  AND u.role<14 AND d.am_email='" . $email . "' GROUP BY u.smpin ) as a JOIN  (SELECT  COALESCE(SUM(t.target),'0') as targetcount,u.smpin,u.userid FROM " . TABLE_USER . " as u  JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code LEFT JOIN (SELECT id,smpin,target FROM " . TABLE_USER_SALETARGET . " WHERE sale_month>='" . $start_date . "' AND sale_month<='" . $end_date . "')as t ON t.smpin=u.smpin WHERE u.is_deleted=0 AND u.status=1 AND u.role>7  AND u.role<14 AND d.am_email='" . $email . "' GROUP BY u.smpin ) as b ON a.userid=b.userid )c ORDER BY cast(sale_per as SIGNED) DESC,cast(salecount as SIGNED) DESC,cast(targetcount as SIGNED) DESC,last_sale ASC,first_sale ASC,userid ASC)as a )as f  JOIN " . TABLE_USER . " as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1 " . $user_cond . " LIMIT 1";
        $outof = 0;
        if (count($user_arr) > 0) {
            $user_count_arr = $parent->getQueryValue($get_user_count_str);
            $outof = (count($user_count_arr) > 0) ? $user_count_arr[0]->user_count : '0';
            foreach ($user_arr as $mkey => $res_user) {
                $user_arr[$mkey]->outof = $outof;
            }
        } else {
            $user_arr = array();
        }
        //GET COUNT
        $total = $outof;

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

    /* /////////////////////////////// ASSESSMENT LEADERBOARD REPORT //////////////////////////////////////////////// */
    private function assessmentleaderboardreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

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

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('email' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $email = escape_str($parent->_request["email"]);

        $user_cond = "";
        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = " ORDER BY d.dealer_name,f.rank ASC ";
                    break;
                case '2':$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
                default:$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE am_email='" . $email . "'  AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
        $dealer_arr = $parent->getQueryValue($get_dealer_str);
        if (count($dealer_arr) > 0) {
            $zone_arr = array();
            $city_arr = array();
            foreach ($dealer_arr as $res_dealer) {
                if (!in_array($res_dealer->zone, $zone_arr)) {
                    $zone_arr[] = $res_dealer->zone;
                }

                if (!in_array($res_dealer->city, $city_arr)) {
                    $city_arr[] = $res_dealer->city;
                }

                $dealer_cond_arr[] = " filter_dealer LIKE '%" . $res_dealer->dealer_code . "%'";
            }
            $query_cond .= " AND ( filter_dealer='' OR " . @implode(" OR ", $dealer_cond_arr) . " ) ";

            if (count($zone_arr) > 0) {
                foreach ($zone_arr as $zone) {
                    $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                }
                $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
            } else {
                $query_cond .= " AND (filter_zone='') ";
            }

            if (count($city_arr) > 0) {
                foreach ($city_arr as $city) {
                    $city_cond_arr[] = " filter_region LIKE '%" . $city . "%'";
                }
                $query_cond .= " AND (filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";
            } else {
                $query_cond .= " AND (filter_region='') ";
            }

        } else {
            $query_cond .= " AND (filter_dealer='' AND filter_region='' AND filter_zone=''  ) ";
        }
        $outof = 0;
        $query_cond .= '  a.user_type=0 ';

        //GET ALL ASSESSMENT LIST WHICH PUBLISHED
        $assessment_str = "SELECT a.* FROM `" . TABLE_ASSESSMENT . "` as a  WHERE a.atype='0' AND a.assettypeid='1'   AND a.publisheddate<='" . NOW . "' " . $query_cond;
        $assessment_arr = $parent->getQueryValue($assessment_str);
        $data_arr = array();
        if (count($assessment_arr) > 0) {
            foreach ($assessment_arr as $res_assess) {
                $assessmentid_arr[] = $res_assess->assessmentid;
            }

            $parent->executeQuery("SET @rownum := 0");
            $get_user_rank_str = "SELECT f.*,u.userid,u.fname,u.lname,d.* FROM ( SELECT @rownum := @rownum + 1 AS rank,COALESCE(user_score,'0')as user_score,CASE WHEN user_score IS NULL THEN 0 ELSE (user_score/" . count($assessment_arr) . ") END as percentage_score,userid,total_time,last_modified FROM (SELECT SUM(highscore)as user_score,u.userid,COALESCE(ar.total_time,'0')as total_time,MAX(au.modified_on) as last_modified  FROM " . TABLE_USER . " as u JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code JOIN (SELECT * FROM  " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND highscorearid!=0 ) as au ON u.userid=au.userid  LEFT JOIN (SELECT SUM(time_taken)as total_time,assessmentid,userid FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") GROUP BY userid )as ar ON u.userid=ar.userid  WHERE u.role>7 AND u.role<14 AND  u.is_deleted=0 AND u.status=1  AND d.am_email='" . $email . "'  GROUP BY u.userid ORDER BY user_score DESC,ar.total_time ASC,last_modified ASC,u.userid ASC )as a )as f   JOIN " . TABLE_USER . " as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1  " . $user_cond . $order_by_cond . " " . $limit_cond;
            $get_user_rank_arr = $parent->getQueryValue($get_user_rank_str);

            //GET COUNT
            $get_user_count_str = "SELECT COUNT(u.userid)as user_count FROM ( SELECT  COALESCE(user_score,'0')as user_score,CASE WHEN user_score IS NULL THEN 0 ELSE (user_score/" . count($assessment_arr) . ") END as percentage_score,userid,total_time,last_modified FROM (SELECT SUM(highscore)as user_score,u.userid,COALESCE(ar.total_time,'0')as total_time,MAX(au.modified_on) as last_modified  FROM " . TABLE_USER . " as u JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code JOIN (SELECT * FROM  " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND highscorearid!=0 ) as au ON u.userid=au.userid  LEFT JOIN (SELECT SUM(time_taken)as total_time,assessmentid,userid FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") GROUP BY userid )as ar ON u.userid=ar.userid  WHERE u.role>7 AND u.role<14 AND u.is_deleted=0 AND u.status=1 AND d.am_email='" . $email . "' GROUP BY u.userid ORDER BY user_score DESC,ar.total_time ASC,last_modified ASC,u.userid ASC )as a )as f   JOIN " . TABLE_USER . " as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1 AND d.am_email='" . $email . "'  " . $user_cond . " LIMIT 1";

            if (count($get_user_rank_arr) > 0) {
                $user_count_arr = $parent->getQueryValue($get_user_count_str);
                $outof = (count($user_count_arr) > 0) ? $user_count_arr[0]->user_count : '0';
                foreach ($get_user_rank_arr as $mkey => $res_user) {
                    $get_user_rank_arr[$mkey]->outof = $outof;
                }
            } else {
                $get_user_rank_arr = array();
            }
        }
        $total = $outof;

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

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

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;

        }

        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= "";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,l.created_on as register_date FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code LEFT JOIN (SELECT * FROM " . TABLE_USER_LOG . " WHERE module='REGISTER' )as l ON u.userid=l.userid  WHERE e.status='1' AND e.smpin!='' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (!count($user_arr) > 0) {
            $user_arr = array();
        } else {
            foreach ($user_arr as $mkey => $res_val) {
                $user_arr[$mkey]->is_active = ($res_val->userid) ? "1" : "1";
            }
        }

        //GET COUNT
        $get_count_str = "SELECT  COUNT(e.`smpin`) as ucount  FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code LEFT JOIN (SELECT * FROM " . TABLE_USER_LOG . " WHERE module='REGISTER' )as l ON u.userid=l.userid  WHERE e.status='1' AND e.smpin!=''  " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

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

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

        $dealer_code_cond = '';
        //AREA MANAGER SELF
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;
        }
        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= "";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::userCourseCompleteStatus($parent, $res->userid);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    /* /////////////////////////////// USER COURSE REPORT //////////////////////////////////////////////// */
    private function usercoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $userid = escape_str($parent->params[1]);
        $check_user_str = "SELECT  userid,segment,role FROM " . TABLE_USER . "  WHERE  status='1' AND is_deleted='0' AND userid='" . $userid . "' LIMIT 1";
        $check_user_arr = $parent->getQueryValue($check_user_str);
        if (!count($check_user_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        if ($check_user_arr[0]->role > 7 && $check_user_arr[0]->role < 14) {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role', 'zone', 'city', 'dealer_code'), $userid);
        } else {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role'), $userid);
        }
        $user_cond = str_replace("filter_", "c.filter_", $user_filter_str);

        $cat_str = "SELECT cateid,catename FROM " . TABLE_CATEGORY . " ORDER BY cateid ASC";
        $cat_arr = $parent->getQueryValue($cat_str);

        if ($check_user_arr[0]->role > 7 && $check_user_arr[0]->role < 14) {
            switch ($check_user_arr[0]->segment) {
                case "1":$user_cond .= " AND t.segment IN (0,1)  AND c.segment IN (0,1)";
                    break;
                case "2":$user_cond .= " AND t.segment IN (0,2)  AND c.segment IN (0,2)";
                    break;
                default:$user_cond .= " AND t.segment IN (0)  AND c.segment IN (0)";
                    break;
            }
        }

        $data_arr = array();
        if (count($cat_arr) > 0) {
            foreach ($cat_arr as $ckey => $res_cat) {

                //GET USER ALL CONTENT COUNT
                $get_course_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $res_cat->cateid . "'  " . $user_cond;
                $get_course_arr = $parent->getQueryValue($get_course_str);
                $total_content = (count($get_course_arr) > 0) ? $get_course_arr[0]->totcontent : '0';

                //GET USER COMPLETED CONTENT COUNT
                $get_user_completed_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid JOIN (SELECT * FROM " . TABLE_USER_COMPLETE_CONTENT . " WHERE userid='" . $userid . "' AND status='2') as a ON a.contentid=c.contentid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $res_cat->cateid . "'  " . $user_cond;
                $get_user_completed_arr = $parent->getQueryValue($get_user_completed_str);
                $user_content = (count($get_user_completed_arr) > 0) ? $get_user_completed_arr[0]->totcontent : '0';

                $cat_arr[$ckey]->completed = ($user_content > 0) ? $user_content : '0';
                $cat_arr[$ckey]->total = ($total_content > 0) ? $total_content : '0';
                $cat_arr[$ckey]->percentage = ($total_content > 0) ? round(($user_content / $total_content) * 100) : '0';

                //TOPICS
                $get_asset_topic_str = "SELECT t.assettopicid,t.topicname FROM " . TABLE_ASSET_TOPIC . " as t JOIN " . TABLE_ASSET_CONTENT . " as c ON t.assettopicid=c.assettopicid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $res_cat->cateid . "' " . $user_cond . " GROUP BY t.assettopicid ORDER BY t.assettopicid ASC";
                $get_asset_topic_arr = $parent->getQueryValue($get_asset_topic_str);

                if (count($get_asset_topic_arr) > 0) {

                    foreach ($get_asset_topic_arr as $tkey => $res_topic) {
                        //GET USER ALL CONTENT COUNT
                        $get_course_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $res_cat->cateid . "' AND  t.assettopicid='" . $res_topic->assettopicid . "'  " . $user_cond;
                        $get_course_arr = $parent->getQueryValue($get_course_str);
                        $total_content = (count($get_course_arr) > 0) ? $get_course_arr[0]->totcontent : '0';

                        //GET USER COMPLETED CONTENT COUNT
                        $get_user_completed_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid JOIN (SELECT * FROM " . TABLE_USER_COMPLETE_CONTENT . " WHERE userid='" . $userid . "' AND status='2') as a ON a.contentid=c.contentid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $res_cat->cateid . "' AND t.assettopicid='" . $res_topic->assettopicid . "' " . $user_cond;
                        $get_user_completed_arr = $parent->getQueryValue($get_user_completed_str);
                        $user_content = (count($get_user_completed_arr) > 0) ? $get_user_completed_arr[0]->totcontent : '0';

                        $get_asset_topic_arr[$tkey]->total = ($user_content > 0) ? $user_content : '0';
                        $get_asset_topic_arr[$tkey]->completed = ($total_content > 0) ? $total_content : '0';
                        $get_asset_topic_arr[$tkey]->percentage = ($total_content > 0) ? round(($user_content / $total_content) * 100) : '0';

                    }
                    $cat_arr[$ckey]->topic = (count($get_asset_topic_arr) > 0) ? $get_asset_topic_arr : array();
                }

            }
            $data_arr = $cat_arr;
        }

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

    /* /////////////////////////////// USER TOPIC REPORT //////////////////////////////////////////////// */
    private function usertopicreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 3);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $userid = escape_str($parent->params[1]);
        $assettopicid = escape_str($parent->params[2]);

        $check_user_str = "SELECT  userid,role,segment FROM " . TABLE_USER . "  WHERE  status='1' AND is_deleted='0' AND role>3 AND userid='" . $userid . "' LIMIT 1";
        $check_user_arr = $parent->getQueryValue($check_user_str);
        if (!count($check_user_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        //NEW USER BASED CONDITION
        if ($check_user_arr[0]->role > 7 && $check_user_arr[0]->role < 14) {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role', 'zone', 'city', 'dealer_code'), $userid);
            $user_cond = str_replace("filter_", "c.filter_", $user_filter_str);
            $user_cond .= " AND (c.segment='0' OR c.segment='" . $check_user_arr[0]->segment . "')";
        } else {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role'), $userid);
            $user_cond = str_replace("filter_", "c.filter_", $user_filter_str);
        }

        $get_content_str = "SELECT c.title,c.`contentid`, c.`assettopicid`  FROM " . TABLE_ASSET_CONTENT . " as c  JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' " . $user_cond . " AND t.assettopicid='" . $assettopicid . "'";
        $get_content_arr = $parent->getQueryValue($get_content_str);

        if (count($get_content_arr) > 0) {
            foreach ($get_content_arr as $ckey => $res_content) {
                //GET FILE TYPE
                $get_content_file_str = "SELECT filetypeid,filetype FROM " . TABLE_ASSET_FILE . "   WHERE contentid='" . $res_content->contentid . "' LIMIT 1 ";
                $get_content_file_arr = $parent->getQueryValue($get_content_file_str);

                //USER CONTENT STATUS
                $get_content_status_str = "SELECT status FROM " . TABLE_USER_COMPLETE_CONTENT . "   WHERE userid='" . $userid . "' AND contentid='" . $res_content->contentid . "'  LIMIT 1 ";
                $get_content_status_arr = $parent->getQueryValue($get_content_status_str);

                $get_content_arr[$ckey]->status = (count($get_content_status_arr) > 0) ? $get_content_status_arr[0]->status : '0';
                $get_content_arr[$ckey]->is_completed = (count($get_content_status_arr) > 0 && $get_content_status_arr[0]->status == '2') ? '1' : '0';

                $get_content_arr[$ckey]->filetypeid = (count($get_content_file_arr) > 0) ? $get_content_file_arr[0]->filetypeid : '';
                $get_content_arr[$ckey]->filetype = (count($get_content_file_arr) > 0) ? $get_content_file_arr[0]->filetype : '';

            }
            $data_arr = $get_content_arr;
        } else {
            $data_arr = array();
        }

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

    /* /////////////////////////////// SALES TARGET REPORT //////////////////////////////////////////////// */
    private function salestarget($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        globalfunc::checkParamCount($parent, 3);

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[2]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $dealer_code_cond = '';
        //AREA MANAGER SELF
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;

        }
        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= "";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "'" . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }
        //GET MODEL
        $query_modelarr = $parent->selectQuery(TABLE_MODEL, "model_id, model_name,model_image ", "model_is_target=1 AND user_type=0 ORDER BY model_id", "");

        $get_user_str = "SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name  FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, '', $year_data, $month_data);
                $user_arr[$ukey]->salestarget = $user_target;
                $user_arr[$ukey]->model = array();
                $user_arr[$ukey]->is_edit = (strtotime(CUR_DATE) > strtotime(date('Y-m-d', strtotime($year_data . "-" . $month_data . "-" . TRAINER_BUFFER_DATE)))) ? "0" : "1";

                if ($query_modelarr['nr']) {

                    foreach ($query_modelarr['result'] as $res_model) {

                        $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);
                        if ($user_target > 0) {
                            $mobj = new stdClass();
                            $mobj->model_id = $res_model->model_id;
                            $mobj->model_name = $res_model->model_name;
                            $mobj->target = $user_target;
                            $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);

                            $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                            $user_arr[$ukey]->model[] = $mobj;
                        } else {

                            $mobj = new stdClass();
                            $mobj->model_id = $res_model->model_id;
                            $mobj->model_name = $res_model->model_name;
                            $mobj->target = '0';
                            $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);

                            $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                            $user_arr[$ukey]->model[] = $mobj;

                        }
                    }
                }

            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        $get_count_str = "SELECT  COUNT(e.`smpin`)as ucount FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'SALES TARGET REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

        $is_edit = 0;
        if (date('Y-m', strtotime(CUR_DATE)) == date('Y-m', strtotime($year_data . "-" . $month_data . "-01"))) {
            if (strtotime(CUR_DATE) <= strtotime(date('Y-m-d', strtotime($year_data . "-" . $month_data . "-" . TRAINER_BUFFER_DATE)))) {
                $is_edit = 1;
            }
        }

        $parent->response(array('response' => 'success', 'data' => $user_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1'], 'is_edit' => $is_edit), 200);

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

    /* /////////////////////////////// SALES TARGET UPDATE  //////////////////////////////////////////////// */
    private function salestargetupdate($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('4', '5', '6', '7', '14'));

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('year' => 'integer', 'month' => 'integer', 'smpin' => 'string', 'model_arr' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $model_json_arr = json_decode($parent->_request["model_arr"]);

        if (!count($model_json_arr) > 0 || !$model_json_arr) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error3"]), 406);
        }
        $year = escape_str($parent->_request["year"]);
        $month = escape_str($parent->_request["month"]);
        $smpin = escape_str($parent->_request["smpin"]);

        $dealer_code_cond = '';
        if ($parent->current_user_role == '14') {
            $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
        }

        //VALIDATE SMPIN
        $employee_str = "SELECT * FROM " . DMS_EMPLOYEE . " WHERE smpin='" . $smpin . "' AND status='1' " . $dealer_code_cond . "  LIMIT 1";
        $employee_arr = $parent->getQueryValue($employee_str);
        if (count($employee_arr) != 1) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error4"]), 406);
        }

        if (strtotime(CUR_DATE) > strtotime(date('Y-m-d', strtotime($year . "-" . $month . "-" . TRAINER_BUFFER_DATE)))) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error6"]), 406);
        }

        $model_str = "SELECT * FROM " . TABLE_MODEL . " WHERE model_is_target='1'";
        $model_arr = $parent->getQueryValue($model_str);
        $model_data_arr = array();
        if (count($model_arr) > 0) {
            foreach ($model_arr as $res) {
                $model_data_arr[$res->model_id] = $res->model_name;
            }
        }

        //VALIDATE MODEL EXIST
        if (count($model_json_arr) > 0) {
            foreach ($model_json_arr as $res_model) {
                if (!isset($model_data_arr[$res_model->model_id])) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error5"]), 406);
                }

            }
        }
        //echo "calling";
        //INSERT OR UPDATE
        if (count($model_json_arr) > 0) {
            foreach ($model_json_arr as $res_model) {
                $model_name = $model_data_arr[$res_model->model_id];
                $month_cond = " AND sale_month>='" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "' AND sale_month<='" . date('Y-m-t', strtotime($year . "-" . $month . "-01")) . "'";
                $check_str = "SELECT * FROM " . TABLE_USER_SALETARGET . " WHERE smpin='" . $smpin . "' " . $month_cond . " AND model='" . $model_name . "' LIMIT 1";
                $check_arr = $parent->getQueryValue($check_str);

                if (count($check_arr) > 0) { //UPDATE
                    $parent->executeQuery("UPDATE " . TABLE_USER_SALETARGET . " SET `target`='" . $res_model->target . "', `modified_on`='" . NOW . "' WHERE id='" . $check_arr[0]->id . "' ");
                } else { //INSERT
                    $parent->executeQuery("INSERT INTO " . TABLE_USER_SALETARGET . " (`smpin`, `model`, `am_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('" . $smpin . "','" . $model_name . "','" . $parent->current_user_id . "','" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "','" . $res_model->target . "','" . NOW . "','" . NOW . "')");
                }

                //LOG INSERT
                $parent->executeQuery("INSERT INTO " . TABLE_USER_SALESTARGET_LOG . " (`smpin`, `model`, `roleid`, `userid`, `sale_month`, `target`, `created_on`)VALUES('" . $smpin . "','" . $model_name . "','" . $parent->current_user_role . "','" . $parent->current_user_id . "','" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "','" . $res_model->target . "','" . NOW . "','" . NOW . "')");

//                if($parent->current_user_role=='14') //FOR DEALER
                //                {
                //                    $month_cond=" AND sale_month>='".date('Y-m-d',strtotime($year."-".$month."-01"))."' AND sale_month<='".date('Y-m-t',strtotime($year."-".$month."-01"))."'";
                //                    $check_str = "SELECT * FROM ".TABLE_USER_SALESTARGET_APPROVE." WHERE smpin='".$smpin."' ".$month_cond." AND model='".$model_name."' AND is_deleted=0 LIMIT 1";
                //                    $check_arr=$parent->getQueryValue($check_str);
                //
                //                    if(count($check_arr)>0)
                //                    {                            //UPDATE
                //                        $parent->executeQuery("UPDATE ".TABLE_USER_SALESTARGET_APPROVE." SET `target`='".$res_model->target."', `modified_on`='".NOW."' WHERE id='".$check_arr[0]->id."' ");
                //                    }else
                //                    {    //INSERT
                //                        $parent->executeQuery("INSERT INTO ".TABLE_USER_SALESTARGET_APPROVE." (`smpin`, `model`, `user_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('".$smpin."','".$model_name."','".$parent->current_user_id."','".date('Y-m-d',strtotime($year."-".$month."-01"))."','".$res_model->target."','".NOW."','".NOW."')");
                //                    }
                //                }else
                //                {
                //                    $month_cond=" AND sale_month>='".date('Y-m-d',strtotime($year."-".$month."-01"))."' AND sale_month<='".date('Y-m-t',strtotime($year."-".$month."-01"))."'";
                //                    $check_str = "SELECT * FROM ".TABLE_USER_SALETARGET." WHERE smpin='".$smpin."' ".$month_cond." AND model='".$model_name."' LIMIT 1";
                //                    $check_arr=$parent->getQueryValue($check_str);
                //
                //                    if(count($check_arr)>0)
                //                    {                            //UPDATE
                //                        $parent->executeQuery("UPDATE ".TABLE_USER_SALETARGET." SET `target`='".$res_model->target."', `modified_on`='".NOW."' WHERE id='".$check_arr[0]->id."' ");
                //                    }else
                //                    {    //INSERT
                //                        $parent->executeQuery("INSERT INTO ".TABLE_USER_SALETARGET." (`smpin`, `model`, `am_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('".$smpin."','".$model_name."','".$parent->current_user_id."','".date('Y-m-d',strtotime($year."-".$month."-01"))."','".$res_model->target."','".NOW."','".NOW."')");
                //                    }
                //
                //                }
            }

//            if($parent->current_user_role!='14')
            //            {
            //                $parent->executeQuery("UPDATE ".TABLE_USER_SALESTARGET_APPROVE." SET am_id='".$parent->current_user_id."',is_deleted=1, `modified_on`='".NOW."' WHERE smpin='".$smpin."' AND is_deleted=0 ");
            //            }
        }

        //LOG
        $logstr = 'SALES TARGET UPDATE';
        globalfunc::insertUserLog($parent, $logstr);

        $user_cond = " and u.smpin='" . $smpin . "'";
        $get_user_str = "SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name  FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' " . $user_cond . " LIMIT 1";
        $user_arr = $parent->getQueryValue($get_user_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, '', $year, $month);
                $user_arr[$ukey]->salestarget = $user_target;
                $user_arr[$ukey]->model = array();

                //GET MODEL
                $query_modelarr = $parent->selectQuery(TABLE_MODEL, "model_id, model_name,model_image ", "model_is_target=1 ORDER BY model_id", "");
                if ($query_modelarr['nr']) {

                    foreach ($query_modelarr['result'] as $res_model) {

                        $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, $res_model->model_name, $year, $month);
                        if ($user_target > 0) {
                            $mobj = new stdClass();
                            $mobj->model_id = $res_model->model_id;
                            $mobj->model_name = $res_model->model_name;
                            $mobj->target = $user_target;
                            $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year, $month);

                            $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                            $user_arr[$ukey]->model[] = $mobj;
                        } else {

                            $mobj = new stdClass();
                            $mobj->model_id = $res_model->model_id;
                            $mobj->model_name = $res_model->model_name;
                            $mobj->target = '0';
                            $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year, $month);

                            $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                            $user_arr[$ukey]->model[] = $mobj;

                        }
                    }
                }

            }
        } else {
            $user_arr = array();
        }

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

    /* /////////////////////////////// NEW SALES TARGET UPDATE  //////////////////////////////////////////////// */
    private function newsalestargetupdate($parent)
    {
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('4', '5', '6', '7', '14'));

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('year' => 'integer', 'month' => 'integer', 'model_arr' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $model_json_arr = json_decode($parent->_request["model_arr"]);

        if (!count($model_json_arr) > 0 || !$model_json_arr) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error3"]), 406);
        }
        $year = escape_str($parent->_request["year"]);
        $month = escape_str($parent->_request["month"]);
        //$smpin = escape_str($parent->_request["smpin"]);

        $dealer_code_cond = '';
        if ($parent->current_user_role == '14') {
            $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
        }

        //if(strtotime(CUR_DATE)>strtotime(date('Y-m-d',strtotime($year."-".$month."-".TRAINER_BUFFER_DATE)))) $parent->response(array('response'=>'failed','message'=>$this->page_data["error6"]),406);
        //$tokenid=TIMETOKEN.globalfunc::generateToken($parent,'',5);

        $model_str = "SELECT * FROM " . TABLE_MODEL . " WHERE model_is_target='1'";
        $model_arr = $parent->getQueryValue($model_str);
        $model_data_arr = array();
        if (count($model_arr) > 0) {
            foreach ($model_arr as $res) {
                $model_data_arr[$res->model_id] = $res->model_name;
            }
        }

        $all_smpin_arr = array();
        //VALIDATE MODEL EXIST
        if (count($model_json_arr) > 0) {
            foreach ($model_json_arr as $res_model) {
                if (!isset($model_data_arr[$res_model->model_id])) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error5"]), 406);
                }

                $smpin = $res_model->smpin;
                //VALIDATE SMPIN
                $employee_str = "SELECT * FROM " . DMS_EMPLOYEE . " WHERE smpin='" . $smpin . "' AND status='1' " . $dealer_code_cond . "  LIMIT 1";
                $employee_arr = $parent->getQueryValue($employee_str);
                if (count($employee_arr) != 1) {
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error4"]), 406);
                }

                if (!in_array($smpin, $all_smpin_arr)) {
                    $all_smpin_arr[] = $smpin;
                    $is_edit = projectfunc::setSaleEditpermisson($parent, $smpin, date('Y-m-d', strtotime($year . "-" . $month . "-01")));
                    if ($is_edit != 1) {
                        $manager_error = ($parent->manager_error) ? $parent->manager_error : $this->page_data["error6"];
                        $parent->response(array('response' => 'failed', 'message' => $manager_error), 406);
                    }
                }
            }
        }

        if (count($model_json_arr) > 0) {
            $smpin_tot_arr = array();
            //REMOVE FOR MANAGERS
            $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
            if ($parent->current_user_role != '14') {
                $month_cond = " AND sale_month>='" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "' AND sale_month<='" . date('Y-m-t', strtotime($year . "-" . $month . "-01")) . "'";
                $check_sum_str = "SELECT SUM(target) as tottarget,smpin  FROM " . TABLE_USER_SALETARGET . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") " . $month_cond . "  GROUP BY smpin ";
                $check_sum_arr = $parent->getQueryValue($check_sum_str);
                if (count($check_sum_arr) > 0) {
                    foreach ($check_sum_arr as $res) {
                        $smpin_tot_arr[$res->smpin] = $res->tottarget;
                    }
                }
            }
//            $delete_str=($parent->current_user_role!='14')?"UPDATE ".TABLE_USER_SALESTARGET_APPROVE." SET am_id='".$parent->current_user_id."',is_deleted=1, `modified_on`='".NOW."' WHERE smpin IN (".@implode(',',$smpin_quotes).") AND is_deleted=0 AND sale_month BETWEEN '".date('Y-m-d',strtotime($year."-".$month."-01"))."' AND '".date('Y-m-t',strtotime($year."-".$month."-01"))."'" : "UPDATE ".TABLE_USER_SALESTARGET_APPROVE." SET am_id='0',is_deleted=1, `modified_on`='".NOW."' WHERE smpin IN (".@implode(',',$smpin_quotes).") AND is_deleted=0 AND sale_month BETWEEN '".date('Y-m-d',strtotime($year."-".$month."-01"))."' AND '".date('Y-m-t',strtotime($year."-".$month."-01"))."'";
            //            $parent->executeQuery($delete_str);

            foreach ($model_json_arr as $res_model) {
                $model_name = $model_data_arr[$res_model->model_id];
                $smpin = $res_model->smpin;

//                //DELETE FOR MANAGERS
                //                if($parent->current_user_role=='14') //FOR DEALER TO MANAGER APPROVAL
                //                {
                //                    $parent->executeQuery("INSERT INTO ".TABLE_USER_SALESTARGET_APPROVE." (`tokenid`, `smpin`, `model`, `am_id`, `user_id`, `sale_month`, `target`, `is_approved`, `is_deleted`, `created_on`, `modified_on`)VALUES('".strtoupper($tokenid)."','".$smpin."','".$model_name."','".$parent->current_user_id."','".$parent->current_user_id."','".date('Y-m-d',strtotime($year."-".$month."-01"))."','".$res_model->target."','1','1','".NOW."','".NOW."')");
                //                }else
                //                {
                //                    $month_cond=" AND sale_month>='".date('Y-m-d',strtotime($year."-".$month."-01"))."' AND sale_month<='".date('Y-m-t',strtotime($year."-".$month."-01"))."'";
                //                    $check_str = "SELECT * FROM ".TABLE_USER_SALETARGET." WHERE smpin='".$smpin."' ".$month_cond." AND model='".$model_name."' LIMIT 1";
                //                    $check_arr=$parent->getQueryValue($check_str);
                //
                //                    //AM OWN APPROVAL
                //                    $parent->executeQuery("INSERT INTO ".TABLE_USER_SALESTARGET_APPROVE." (`tokenid`, `smpin`, `model`, `user_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('".strtoupper($tokenid)."','".$smpin."','".$model_name."','".$parent->current_user_id."','".date('Y-m-d',strtotime($year."-".$month."-01"))."','".$res_model->target."','".NOW."','".NOW."')");
                //
                //                    if(count($check_arr)>0)
                //                    {
                //                        //UPDATE
                //                        $parent->executeQuery("UPDATE ".TABLE_USER_SALETARGET." SET `target`='".$res_model->target."', `modified_on`='".NOW."' WHERE id='".$check_arr[0]->id."' ");
                //                    }else
                //                    {    //INSERT
                //                        $parent->executeQuery("INSERT INTO ".TABLE_USER_SALETARGET." (`smpin`, `model`, `am_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('".$smpin."','".$model_name."','".$parent->current_user_id."','".date('Y-m-d',strtotime($year."-".$month."-01"))."','".$res_model->target."','".NOW."','".NOW."')");
                //                    }
                //
                //                }

                $month_cond = " AND sale_month>='" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "' AND sale_month<='" . date('Y-m-t', strtotime($year . "-" . $month . "-01")) . "'";
                $check_str = "SELECT * FROM " . TABLE_USER_SALETARGET . " WHERE smpin='" . $smpin . "' " . $month_cond . " AND model='" . $model_name . "' LIMIT 1";
                $check_arr = $parent->getQueryValue($check_str);

                if (count($check_arr) > 0) {
                    //UPDATE
                    $parent->executeQuery("UPDATE " . TABLE_USER_SALETARGET . " SET `target`='" . $res_model->target . "', `modified_on`='" . NOW . "' WHERE id='" . $check_arr[0]->id . "' ");
                } else { //INSERT
                    $parent->executeQuery("INSERT INTO " . TABLE_USER_SALETARGET . " (`smpin`, `model`, `am_id`, `sale_month`, `target`, `created_on`, `modified_on`)VALUES('" . $smpin . "','" . $model_name . "','" . $parent->current_user_id . "','" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "','" . $res_model->target . "','" . NOW . "','" . NOW . "')");
                }

                //LOG INSERT
                $parent->executeQuery("INSERT INTO " . TABLE_USER_SALESTARGET_LOG . " (`smpin`, `model`, `roleid`, `userid`, `sale_month`, `target`, `created_on`)VALUES('" . $smpin . "','" . $model_name . "','" . $parent->current_user_role . "','" . $parent->current_user_id . "','" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "','" . $res_model->target . "','" . NOW . "')");

            }

            if (count($all_smpin_arr) > 0) {
                $dealer_notification_type = 0;
                foreach ($all_smpin_arr as $smpin) {
                    if ($parent->current_user_role == '14') {
                        $status_str = '1';
                    } else {
                        $month_cond = " AND sale_month>='" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "' AND sale_month<='" . date('Y-m-t', strtotime($year . "-" . $month . "-01")) . "'";
                        $check_sum_str = "SELECT SUM(target) as tottarget,smpin  FROM " . TABLE_USER_SALETARGET . " WHERE smpin ='" . $smpin . "' " . $month_cond . "  GROUP BY smpin LIMIT 1 ";
                        $check_sum_arr = $parent->getQueryValue($check_sum_str);

                        if (count($check_sum_arr) > 0) {
                            $status_str = (isset($smpin_tot_arr[$smpin]) && $smpin_tot_arr[$smpin] != $check_sum_arr[0]->tottarget) ? '3' : '2';
                            if ($status_str == '3') {
                                $dealer_notification_type = "1";
                            }
                        } else {
                            $status_str = '2';
                        }
                    }

                    $parent->executeQuery("INSERT INTO " . TABLE_USER_SALESTARGET_STATUS . " (`smpin`, `roleid`, `userid`, `status`, `sale_month`, `created_on`) VALUES ('" . $smpin . "','" . $parent->current_user_role . "','" . $parent->current_user_id . "','" . $status_str . "','" . date('Y-m-d', strtotime($year . "-" . $month . "-01")) . "','" . NOW . "')");
                }

                //DSE  TRIGGER NOTIFICATION
                $notificationtitle = 'Sales target has been updated';
                $notificationtext = 'Sales target has been updated';
                $notificationtype = '5';
                $obj = new stdClass();
                $notificationdata = json_encode($obj);

                $parent->executeQuery("INSERT INTO `" . TABLE_NOTIFICATION . "` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('" . $notificationtitle . "','" . escape_str($notificationtext) . "','" . $notificationdata . "','" . $notificationtype . "' ,'1','" . NOW . "','" . NOW . "','" . NOW . "')");
                $notificationid = $parent->lastInsertId();
                $data = array('notification_id' => $notificationid, 'title' => $notificationtitle, 'message' => $notificationtext, 'notificationtype' => $notificationtype, 'notificationdata' => $notificationdata, 'created_date' => NOW);

                //TO SMPIN
                $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
                $check_str = "SELECT userid  FROM " . TABLE_USER . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") AND role>7 AND role<14 AND is_deleted=0 AND status=1";
                $check_user_arr = $parent->getQueryValue($check_str);

                if (count($check_user_arr)) {
                    $ins_arr = array();
                    foreach ($check_user_arr as $res_user) {
                        $ins_arr[] = " ('" . $notificationid . "', '" . $res_user->userid . "', '0', '" . NOW . "')";
                    }

                    $insert_chunk = array_chunk($ins_arr, 1000);
                    foreach ($insert_chunk as $chunk_ins) {
                        $parent->executeQuery("INSERT INTO " . TABLE_NOTIFICATION_USER . "(`notificationid`, `userid`, `status`,  `created_on`) VALUES " . @implode(',', $chunk_ins) . "  ON DUPLICATE KEY UPDATE `status` =0");
                    }

                    $usertokenarr = array('ios' => array(), 'android' => array());
                    $user_device_str = "SELECT ud.devicetype,ud.token FROM `" . TABLE_USER_DEVICES . "` as ud JOIN (SELECT userid FROM " . TABLE_NOTIFICATION_USER . " WHERE notificationid='" . $notificationid . "')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                    $user_device_arr = $parent->getQueryValue($user_device_str);
                    if (count($user_device_arr) > 0) {
                        if (strtolower($user_device_arr[0]->devicetype) == 'ios') {
                            $usertokenarr['ios'][] = $user_device_arr[0]->token;
                        } else if (strtolower($user_device_arr[0]->devicetype) == 'android') {
                            $usertokenarr['android'][] = $user_device_arr[0]->token;
                        }
                        // globalfunc::sendUserNotification($data, $usertokenarr);
                    }
                }

                //TO DEALER
                if ($parent->current_user_role != '14') {
                    $notificationtitle = ($dealer_notification_type == '1') ? 'Sales target has been modified by AM' : 'Sales target has been approved by AM';
                    $notificationtext = ($dealer_notification_type == '1') ? 'Sales target has been modified by AM' : 'Sales target has been approved by AM';
                    $notificationtype = '5';
                    $obj = new stdClass();
                    $notificationdata = json_encode($obj);

                    $parent->executeQuery("INSERT INTO `" . TABLE_NOTIFICATION . "` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('" . $notificationtitle . "','" . escape_str($notificationtext) . "','" . $notificationdata . "','" . $notificationtype . "' ,'1','" . NOW . "','" . NOW . "','" . NOW . "')");
                    $notificationid = $parent->lastInsertId();
                    $data = array('notification_id' => $notificationid, 'title' => $notificationtitle, 'message' => $notificationtext, 'notificationtype' => $notificationtype, 'notificationdata' => $notificationdata, 'created_date' => NOW);

                    $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
                    $check_str = "SELECT * FROM " . TABLE_USER . " u JOIN (SELECT dealer_code FROM " . DMS_EMPLOYEE . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") GROUP BY dealer_code) as e ON e.dealer_code=u.dealer_code WHERE u.role=14";
                    $check_user_arr = $parent->getQueryValue($check_str);

                    if (count($check_user_arr)) {
                        $ins_arr = array();
                        foreach ($check_user_arr as $res_user) {
                            $ins_arr[] = " ('" . $notificationid . "', '" . $res_user->userid . "', '0', '" . NOW . "')";
                        }

                        $insert_chunk = array_chunk($ins_arr, 1000);
                        foreach ($insert_chunk as $chunk_ins) {
                            $parent->executeQuery("INSERT INTO " . TABLE_NOTIFICATION_USER . "(`notificationid`, `userid`, `status`,  `created_on`) VALUES " . @implode(',', $chunk_ins) . "  ON DUPLICATE KEY UPDATE `status` =0");
                        }

                        $usertokenarr = array('ios' => array(), 'android' => array());
                        $user_device_str = "SELECT ud.devicetype,ud.token FROM `" . TABLE_USER_DEVICES . "` as ud JOIN (SELECT userid FROM " . TABLE_NOTIFICATION_USER . " WHERE notificationid='" . $notificationid . "')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                        $user_device_arr = $parent->getQueryValue($user_device_str);
                        if (count($user_device_arr) > 0) {
                            if (strtolower($user_device_arr[0]->devicetype) == 'ios') {
                                $usertokenarr['ios'][] = $user_device_arr[0]->token;
                            } else if (strtolower($user_device_arr[0]->devicetype) == 'android') {
                                $usertokenarr['android'][] = $user_device_arr[0]->token;
                            }
                            // globalfunc::sendUserNotification($data, $usertokenarr);
                        }
                    }

                    $dealermail_str = "SELECT d.email FROM (SELECT dealer_code  FROM " . DMS_EMPLOYEE . " WHERE  smpin IN (" . @implode(',', $smpin_quotes) . ") AND status=1) u JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE d.email!='' GROUP BY d.email";
                    $dealer_email_arr = $parent->getQueryValue($dealermail_str);

                    if (count($dealer_email_arr) > 0) {
                        foreach ($dealer_email_arr as $res_dealer) {
                            $subject = 'HYPER-M App - Set Sales Target Update Reminder - ' . date('d-M-Y', strtotime(CUR_DATE));
                            $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">' . $subject . '</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 Dealer Partner,</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;">Area Manager has Approved / Modified the DSE sales target. Please review and communicate the same to respective DSEs.</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:30px; text-align:center; border-bottom:2px solid black"><div class="footer-con">  <p>Thanks &amp; Regards, <strong style="color:#070000;">HYPER-M Support Team</strong></p>
                     </div></td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>';
                            $obj = array();
                            $obj['from'] = SUPPORT_EMAIL;
                            $obj['to'] = $res_dealer->email;
                            $obj['subject'] = $subject;
                            $obj['message'] = $message;
                            // globalfunc::sendMai($parent, $obj);
                        }
                    }

                } else {
                    //TRIGGER NOTIFICATION TO ASM
                    //TO SMPIN
                    $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
                    $check_str = "SELECT a.userid,a.emp_code,a.emailid,d.dealer_name,d.dealer_code FROM (SELECT dealer_code  FROM " . TABLE_USER . " WHERE  smpin IN (" . @implode(',', $smpin_quotes) . ") AND role>7 AND role<14 AND is_deleted=0 AND status=1) u JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code JOIN (SELECT  userid, emp_code, emailid FROM " . TABLE_USER . " WHERE role=7  AND is_deleted=0 AND status=1 ) a ON a.emailid=d.am_email GROUP BY a.userid";
                    $check_user_arr = $parent->getQueryValue($check_str);

                    if (count($check_user_arr) > 0) {
                        $notificationtitle = 'Sales target has been submitted by Dealer';
                        $notificationtext = 'Sales target has been submitted by Dealer';
                        $notificationtype = '5';
                        $obj = new stdClass();
                        $notificationdata = json_encode($obj);

                        $parent->executeQuery("INSERT INTO `" . TABLE_NOTIFICATION . "` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('" . $notificationtitle . "','" . escape_str($notificationtext) . "','" . $notificationdata . "','" . $notificationtype . "' ,'1','" . NOW . "','" . NOW . "','" . NOW . "')");
                        $notificationid = $parent->lastInsertId();
                        $data = array('notification_id' => $notificationid, 'title' => $notificationtitle, 'message' => $notificationtext, 'notificationtype' => $notificationtype, 'notificationdata' => $notificationdata, 'created_date' => NOW);

                        $ins_arr = array();
                        foreach ($check_user_arr as $res_user) {
                            $ins_arr[] = " ('" . $notificationid . "', '" . $res_user->userid . "', '0', '" . NOW . "')";
                        }

                        $insert_chunk = array_chunk($ins_arr, 1000);
                        foreach ($insert_chunk as $chunk_ins) {
                            $parent->executeQuery("INSERT INTO " . TABLE_NOTIFICATION_USER . "(`notificationid`, `userid`, `status`,  `created_on`) VALUES " . @implode(',', $chunk_ins) . "  ON DUPLICATE KEY UPDATE `status` =0");
                        }

                        $usertokenarr = array('ios' => array(), 'android' => array());
                        $user_device_str = "SELECT ud.devicetype,ud.token FROM `" . TABLE_USER_DEVICES . "` as ud JOIN (SELECT userid FROM " . TABLE_NOTIFICATION_USER . " WHERE notificationid='" . $notificationid . "')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                        $user_device_arr = $parent->getQueryValue($user_device_str);
                        if (count($user_device_arr) > 0) {
                            if (strtolower($user_device_arr[0]->devicetype) == 'ios') {
                                $usertokenarr['ios'][] = $user_device_arr[0]->token;
                            } else if (strtolower($user_device_arr[0]->devicetype) == 'android') {
                                $usertokenarr['android'][] = $user_device_arr[0]->token;
                            }
                            // globalfunc::sendUserNotification($data, $usertokenarr);
                        }

                        $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
                        $check_userstr = "SELECT * FROM " . TABLE_USER . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") AND role>7 AND role<14 AND is_deleted=0 AND status=1";
                        $user_data_arr = $parent->getQueryValue($check_userstr);

                        $userdata = (count($user_data_arr) > 0) ? $user_data_arr[0]->fname . " " . $user_data_arr[0]->lname . " smpin: " . $user_data_arr[0]->smpin : '';

                        foreach ($check_user_arr as $res_user) {

                            $subject = 'Sales target has been submitted by Dealer';
                            $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
                              <tr>
                                <td><table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
                                    <tr>
                                      <td bgcolor="#4d90fe" height="36" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#070000;	text-align:left;	font-weight:bold; padding-left:14px; color:#fff">' . $mail_obj->subject . '</td>
                                    </tr>
                                    <tr>
                                      <td bgcolor="#333333" style="line-height:3px;">&nbsp;</td>
                                    </tr>

                                     <tr><td   style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;color:#3f3f3f;text-align:left; padding-left:20px;padding-right:20px;padding-bottom:20px; line-height:1.5"><br>SET SALES TARGET UPDATED BY DEALER (' . $res_user->dealer_name . ' ' . $res_user->dealer_code . ') FOR USER - (' . $userdata . ')</td></tr>

                                    <tr>
                                      <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center;"><div class="footer-con">
                                        <p>Thanks &amp; Regards, <strong style="color:#070000;">HYPER-M Support Team</strong></p>
                                        </div></td>
                                    </tr>
                                    <tr>
                                      <td bgcolor="#4d90fe" style="line-height:1px;">&nbsp;</td>
                                    </tr>
                                  </table></td>
                              </tr>
                            </table>';

                            $obj = array();
                            $obj['from'] = SUPPORT_EMAIL;
                            $obj['to'] = $res_user->emailid;
                            $obj['subject'] = $subject;
                            $obj['message'] = $message;
                            // globalfunc::sendMai($parent, $obj);
                        }
                    }
                }
            }
        }

        //LOG
        $logstr = 'SALES TARGET UPDATE';
        globalfunc::insertUserLog($parent, $logstr);

        $user_arr = array();
//        $user_cond=" and u.smpin='".$smpin."'";
        //        $get_user_str="SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name  FROM ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' ".$user_cond." LIMIT 1";
        //        $user_arr=$parent->getQueryValue($get_user_str);
        //        if(count($user_arr)>0)
        //        {
        //            foreach($user_arr as $ukey=>$res)
        //            {
        //                $user_target= projectfunc::userSmpinSalesTarget($parent,$res->smpin,'',$year,$month);
        //                $user_arr[$ukey]->salestarget= $user_target;
        //                $user_arr[$ukey]->model=array();
        //
        //                //GET MODEL
        //                $query_modelarr=$parent->selectQuery(TABLE_MODEL,"model_id, model_name,model_image ","model_is_target=1 ORDER BY model_id","");
        //                if($query_modelarr['nr'])
        //                {
        //
        //                    foreach($query_modelarr['result'] as $res_model)
        //                    {
        //
        //                        $user_target= projectfunc::userSmpinSalesTarget($parent,$res->smpin,$res_model->model_name,$year,$month);
        //                        if($user_target>0)
        //                        {
        //                            $mobj = new stdClass();
        //                            $mobj->model_id=$res_model->model_id;
        //                            $mobj->model_name=$res_model->model_name;
        //                            $mobj->target=$user_target;
        //                            $mobj->achieved= projectfunc::userSmpinSalesAchieved($parent,$res->smpin,$res_model->model_name,$year,$month);
        //
        //                            $mobj->model_image_url=($res_model->model_image!='')?SITE_URL."hypermupload/model/".$res_model->model_image:NOIMAGE_URL;
        //                            $user_arr[$ukey]->model[]=$mobj;
        //                        }else{
        //
        //                            $mobj = new stdClass();
        //                            $mobj->model_id=$res_model->model_id;
        //                            $mobj->model_name=$res_model->model_name;
        //                            $mobj->target='0';
        //                            $mobj->achieved= projectfunc::userSmpinSalesAchieved($parent,$res->smpin,$res_model->model_name,$year,$month);
        //
        //                            $mobj->model_image_url=($res_model->model_image!='')?SITE_URL."hypermupload/model/".$res_model->model_image:NOIMAGE_URL;
        //                            $user_arr[$ukey]->model[]=$mobj;
        //
        //                        }
        //                    }
        //                }
        //
        //            }
        //        }else
        //        {
        //            $user_arr=array();
        //        }

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

    /* /////////////////////////////// SURVEY REPORT LIST //////////////////////////////////////////////// */
    private function surveylist($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        $query_cond = "";

        switch ($role) {

            case '3': //HO Manager
                $query_cond .= "";
                break;
            case '4': //Zonal Manager
                $get_zone_str = "SELECT zone FROM " . DMS_DEALER . "  WHERE zm_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY zone ";
                $zone_arr = $parent->getQueryValue($get_zone_str);
                if (count($zone_arr) > 0) {
                    foreach ($zone_arr as $res_zone) {
                        $zone_cond_arr[] = " filter_zone LIKE '%" . $res_zone->zone . "%'";
                    }
                    $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                } else {
                    $query_cond .= " AND (filter_zone='') ";
                }
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $res_user->userid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $query_cond = " AND (filter_zone='' OR filter_zone LIKE '%" . $trainer_arr[0]->zone . "%') ";
                break;
            case '6': //Regional Manager
                $get_city_str = "SELECT city,zone FROM " . DMS_DEALER . "  WHERE rm_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY city ";
                $city_arr = $parent->getQueryValue($get_city_str);
                if (count($city_arr) > 0) {
                    $zone_arr = array();
                    foreach ($city_arr as $res_city) {
                        if (!in_array($res_city->zone, $zone_arr)) {
                            $zone_arr[] = $res_city->zone;
                        }

                        $city_cond_arr[] = " filter_region LIKE '%" . $res_city->city . "%'";
                    }
                    $query_cond .= " AND ( filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }
                } else {
                    $query_cond .= " AND (filter_region='' AND  filter_zone='') ";
                }

                break;
            case '7': //Area Manager
                $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE am_email='" . $userdata->emailid . "'  AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
                $dealer_arr = $parent->getQueryValue($get_dealer_str);
                if (count($dealer_arr) > 0) {
                    $zone_arr = array();
                    $city_arr = array();
                    foreach ($dealer_arr as $res_dealer) {
                        if (!in_array($res_dealer->zone, $zone_arr)) {
                            $zone_arr[] = $res_dealer->zone;
                        }

                        if (!in_array($res_dealer->city, $city_arr)) {
                            $city_arr[] = $res_dealer->city;
                        }

                        $dealer_cond_arr[] = " filter_dealer LIKE '%" . $res_dealer->dealer_code . "%'";
                    }
                    $query_cond .= " AND ( filter_dealer='' OR " . @implode(" OR ", $dealer_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }

                    if (count($city_arr) > 0) {
                        foreach ($city_arr as $city) {
                            $city_cond_arr[] = " filter_region LIKE '%" . $city . "%'";
                        }
                        $query_cond .= " AND (filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_region='') ";
                    }

                } else {
                    $query_cond .= " AND (filter_dealer='' AND filter_region=''   AND  filter_zone='') ";
                }
                break;
            case '14': //Dealer
                $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE dealer_code='" . $userdata->dealer_code . "' GROUP BY dealer_code LIMIT 1 ";
                $dealer_arr = $parent->getQueryValue($get_dealer_str);
                if (count($dealer_arr) > 0) {
                    $zone_arr = array();
                    $city_arr = array();
                    foreach ($dealer_arr as $res_dealer) {
                        if (!in_array($res_dealer->zone, $zone_arr)) {
                            $zone_arr[] = $res_dealer->zone;
                        }

                        if (!in_array($res_dealer->city, $city_arr)) {
                            $city_arr[] = $res_dealer->city;
                        }

                        $dealer_cond_arr[] = " filter_dealer LIKE '%" . $res_dealer->dealer_code . "%'";
                    }
                    $query_cond .= " AND ( filter_dealer='' OR " . @implode(" OR ", $dealer_cond_arr) . " ) ";

                    if (count($zone_arr) > 0) {
                        foreach ($zone_arr as $zone) {
                            $zone_cond_arr[] = " filter_zone LIKE '%" . $zone . "%'";
                        }
                        $query_cond .= " AND (filter_zone='' OR " . @implode(" OR ", $zone_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_zone='') ";
                    }
                    if (count($city_arr) > 0) {
                        foreach ($city_arr as $city) {
                            $city_cond_arr[] = " filter_region LIKE '%" . $city . "%'";
                        }
                        $query_cond .= " AND (filter_region='' OR " . @implode(" OR ", $city_cond_arr) . " ) ";
                    } else {
                        $query_cond .= " AND (filter_region='') ";
                    }
                } else {
                    $query_cond .= " AND (filter_dealer='' AND filter_region=''   AND  filter_zone='') ";
                }
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $data_arr = array();
        //GET COUNT
        $assessment_str = "SELECT assessmentid,assessmentname  FROM " . TABLE_ASSESSMENT . " WHERE status='1'  AND  assettypeid='2'  AND  publisheddate<='" . NOW . "' " . $user_cond . $query_cond . " ORDER BY assessmentid ASC";
        $get_assessment_arr = $parent->getQueryValue($assessment_str);
        if (count($get_assessment_arr) > 0) {
            $data_arr = $get_assessment_arr;
        }

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

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

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';
        if ($parent->current_user_role == '7') {
            $role = $parent->current_user_role;
            $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);
            $emailid = $userdata->emailid;
        } else {
            //AREA MANAGER LEVEL REPORT
            $role = '7';
            //FIELDS VALIDATION
            $REQUEST_KEYS = array('area' => 'string');
            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
            $area_manager = escape_str($parent->_request["area"]);
            $emailid = $area_manager;

        }

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $user_cond = "";
        switch ($role) {

            case '3': //HO Manager
                $user_cond .= "";
                break;
            case '4': //Zonal Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '5': //Trainer
                $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.emailid='" . $emailid . "' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                break;
            case '6': //Regional Manager
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                break;
            case '7': //Area Manager
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " AND dealer_code='" . $parent->current_user_data->dealer_code . "'";
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE am_email='" . $emailid . "' " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,au.modified_on as assessment_date FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "'  AND au.highscorearid!='0' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            /*
        foreach($user_arr as $mkey=>$res_user)
        {
        //$exam_highscore_str = "SELECT  * FROM ".TABLE_ASSESSMENT_USER."  WHERE assessmentid='".$assessmentid."' AND userid='".$res_user->userid."' LIMIT 1";
        //$exam_highscore_arr=$parent->getQueryValue($exam_highscore_str);
        //$user_arr[$mkey]->highscore=(count($exam_highscore_arr)>0)?$exam_highscore_arr[0]->highscore:'0';
        }
         */
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.status='1' AND u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "'  AND au.highscorearid!='0' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    /* /////////////////////////////// SURVEY USER REPORT //////////////////////////////////////////////// */
    private function surveyuserreport($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 3);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $assessmentid = escape_str($parent->params[1]);
        $userid = escape_str($parent->params[2]);

        $query_str = "SELECT assessmentid,assessmentname  FROM " . TABLE_ASSESSMENT . " WHERE status='1'  AND  assettypeid='2' AND  assessmentid='" . $assessmentid . "' AND  publisheddate<='" . NOW . "' LIMIT 1";
        $query_arr = $parent->getQueryValue($query_str);
        if (!count($query_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error9"]), 406);
        }

        //GET USER ATTENTED
        $query_assess_str = "SELECT *  FROM " . TABLE_ASSESSMENT_USER . " WHERE userid='" . $userid . "' AND assessmentid='" . $assessmentid . "' AND highscorearid!='0' LIMIT 1";
        $query_assess_arr = $parent->getQueryValue($query_assess_str);
        if (!count($query_assess_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error10"]), 406);
        }

        //GET USER RESULT
        $query_res_str = "SELECT au.*  FROM " . TABLE_ASSESSMENT_USERRESULT . " as au JOIN " . TABLE_ASSESSMENTRESULT . " as ar ON au.arid=ar.arid WHERE au.userid='" . $userid . "' AND au.assessmentid='" . $assessmentid . "' AND au.arid='" . $query_assess_arr[0]->highscorearid . "'   ";
        $query_assess_res_arr = $parent->getQueryValue($query_res_str);
        if (!count($query_assess_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error10"]), 406);
        }

        if (count($query_assess_res_arr) > 0) {
            //CONNECT S3
            $s3 = awsfileserver::connectS3();
            //RATING
            $survey_str = "SELECT * FROM " . TABLE_SURVEY_RATING . " ORDER BY id ASC";
            $survey_arr = $parent->getQueryValue($survey_str);

            if (count($survey_arr) > 0) {
                foreach ($survey_arr as $skey => $res_survey) {
                    $rating_arr[$res_survey->id] = $res_survey->rating_text;
                }
            }

            foreach ($query_assess_res_arr as $res) {
                $ques_str = "SELECT q.id as qid, q.`questiontypeid`, q.`questiontext`, q.`qimage`, q.`qvideo`  FROM " . TABLE_QUESTION . " as q WHERE id='" . $res->qid . "' LIMIT 1";
                $ques_arr = $parent->getQueryValue($ques_str);

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

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

                    //GET USER ANSWERED OPTIONS
                    $user_answer_str = "SELECT * FROM " . TABLE_ASSESSMENT_USERRESULT . "  WHERE userid='" . $userid . "' AND arid='" . $res->arid . "' AND aqid='" . $res->aqid . "'";
                    $user_answer_arr = $parent->getQueryValue($user_answer_str);

                    //GET RATING
                    //$ques_arr[0]->rating_options=array();
                    $ques_arr[0]->survey_text = '';
                    //$ques_arr[0]->options=array();
                    //print_r($ques_arr);
                    $ques_arr[0]->answer = '';

                    if ($ques_arr[0]->questiontypeid == '3') {

                        $rating = $user_answer_arr[0]->survey_rating;
                        $ques_arr[0]->answer = $rating_arr[$rating];

                    } elseif ($ques_arr[0]->questiontypeid == '5' || $ques_arr[0]->questiontypeid == '6') {
                        //GET ALL QUESTION OPTIONS
                        if ($user_answer_arr[0]->choiseid) {
                            $ques_option_str = "SELECT op.optid,op.opttext,'0' as selected  FROM " . TABLE_QUESTIONOPTION . " as op WHERE op.qid='" . $res->qid . "' AND optid='" . $user_answer_arr[0]->choiseid . "' LIMIT 1";
                            $ques_option_arr = $parent->getQueryValue($ques_option_str);

                            if (count($ques_option_arr) > 0) {
                                $ques_arr[0]->answer = $ques_option_arr[0]->opttext;
                            }
                        }
                    } else {
                        $ques_arr[0]->answer = (count($user_answer_arr) > 0 && $user_answer_arr[0]->survey_text != '') ? $user_answer_arr[0]->survey_text : '';
                    }
                    $result_arr[] = $ques_arr[0];
                }
            }
        }

        //LOG
        $logstr = 'SURVEY USER REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $parent->response(array('response' => 'success', 'data' => $result_arr, 'message' => $this->page_data['success1']), 200);
    }

    /* /////////////////////////////// ASSESSMENT //////////////////////////////////////// */
    private function assessmentleaderboardreportnew($parent)
    {
        //assessment/sales/{{year}}/{{month}}
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('email' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $email = escape_str($parent->_request["email"]);

        if (count($parent->params) == 1) {
            $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE am_email='" . $email . "'  AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
            $dealer_arr = $parent->getQueryValue($get_dealer_str);

            //AREA LEADERBOARD COND
            //$dealer_code=$parent->current_user_data->dealer_code;
            // $query_allareadealerarr=$parent->selectQuery(DMS_DEALER,"`dealer_code`,am_email ","  dealer_code='".$dealer_code."'  AND status='1' AND is_deleted='0'","1");
            /*
            $dealer_arr=array();
            if($query_allareadealerarr['nr'])
            {
            $join_cond="JOIN ".DMS_DEALER." as d ON d.dealer_code=u.dealer_code ";
            $area_cond=" and d.am_email ='".$query_allareadealerarr['result'][0]->am_email."'";
            }else
            {
            $area_cond=" and u.dealer_code IN ('')";
            }
             */
            $join_cond = 'JOIN ' . DMS_DEALER . ' as d ON d.dealer_code=u.dealer_code ';

            $start_date = date('Y-m', strtotime(CUR_DATE)) . "-01";
            $end_date = date('Y-m-t', strtotime(CUR_DATE));
            $date_cond = " AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59'";

        } else if (count($parent->params) == 2) {
            //FOR PANINDIA,ZONE,REGION WISE LEADER BOARD
            $dealer_code = $parent->current_user_data->dealer_code;
            $type_data = explode('?', strtolower(escape_str($parent->params[1])));
            switch ($type_data[0]) {
                case "panindia":
                    /*$start_date=date('Y', strtotime(CUR_DATE))."-01-01";
                    $end_date=date('Y',strtotime(CUR_DATE))."-12-31";
                     *
                     */
                    $start_date = date('Y-m', strtotime(CUR_DATE)) . "-01";
                    $end_date = date('Y-m-t', strtotime(CUR_DATE));

                    //COND
                    $join_cond = 'JOIN ' . DMS_DEALER . ' as d ON d.dealer_code=u.dealer_code ';
                    $area_cond = '';

                    $date_cond = " AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59'";
                    break;
                case "zone":
                    $cur_month = date('m', strtotime(CUR_DATE));
                    /*
                    if(in_array($cur_month,array('01','02','03','04','05','06')))
                    {
                    $start_date=date('Y', strtotime(CUR_DATE))."-01-01";
                    $end_date=date('Y',strtotime(CUR_DATE))."-06-30";
                    }else if(in_array($cur_month,array('07','08','09','10','11','12')))
                    {
                    $start_date=date('Y', strtotime(CUR_DATE))."-07-01";
                    $end_date=date('Y', strtotime(CUR_DATE))."-12-31";
                    }
                     */
                    $start_date = date('Y-m', strtotime(CUR_DATE)) . "-01";
                    $end_date = date('Y-m-t', strtotime(CUR_DATE));

                    $date_cond = " AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59'";

                    //COND
                    /*
                    $query_allareadealerarr=$parent->selectQuery(DMS_DEALER,"`dealer_code`,zm_email ","  dealer_code='".$dealer_code."'  AND status='1' AND is_deleted='0'","1");

                    $dealer_arr=array();
                    if($query_allareadealerarr['nr'])
                    {
                    $join_cond="JOIN ".DMS_DEALER." as d ON d.dealer_code=u.dealer_code ";
                    $area_cond=" and d.zm_email ='".$query_allareadealerarr['result'][0]->zm_email."'";
                    }else
                    {
                    $area_cond=" and u.dealer_code IN ('')";
                    }
                     */
                    $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE zm_email='" . $email . "' AND status='1' AND is_deleted='0' GROUP BY dealer_code ";
                    $dealer_arr = $parent->getQueryValue($get_dealer_str);
                    if (count($dealer_arr) > 0) {
                        $join_cond = "JOIN " . DMS_DEALER . " as d ON d.dealer_code=u.dealer_code ";
                        $area_cond = " and d.zm_email ='" . $email . "'";
                    } else {
                        $join_cond = "JOIN " . DMS_DEALER . " as d ON d.dealer_code=u.dealer_code ";
                        $area_cond = " and u.dealer_code IN ('')";
                    }

                    break;
                case "region":
                    $cur_month = date('m', strtotime(CUR_DATE));
                    /*
                    if(in_array($cur_month,array('01','02','03')))
                    {
                    $start_date=date('Y', strtotime(CUR_DATE))."-01-01";
                    $end_date=date('Y',strtotime(CUR_DATE))."-03-31";
                    }else if(in_array($cur_month,array('04','05','06')))
                    {
                    $start_date=date('Y', strtotime(CUR_DATE))."-04-01";
                    $end_date=date('Y',strtotime(CUR_DATE))."-06-30";

                    }else if(in_array($cur_month,array('07','08','09')))
                    {

                    $start_date=date('Y', strtotime(CUR_DATE))."-07-01";
                    $end_date=date('Y',strtotime(CUR_DATE))."-09-30";
                    }else if(in_array($cur_month,array('10','11','12')))
                    {
                    $start_date=date('Y', strtotime(CUR_DATE))."-10-01";
                    $end_date=date('Y', strtotime(CUR_DATE))."-12-31";
                    }

                     */
                    $start_date = date('Y-m', strtotime(CUR_DATE)) . "-01";
                    $end_date = date('Y-m-t', strtotime(CUR_DATE));
                    $date_cond = " AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59'";

                    $get_dealer_str = "SELECT dealer_code,city,zone FROM " . DMS_DEALER . "  WHERE rm_email='" . $email . "' AND status='1' AND is_deleted='0'  GROUP BY dealer_code ";
                    $dealer_arr = $parent->getQueryValue($get_dealer_str);
                    if (count($dealer_arr) > 0) {
                        $join_cond = "JOIN " . DMS_DEALER . " as d ON d.dealer_code=u.dealer_code ";
                        $area_cond = " and d.rm_email ='" . $email . "'";
                    } else {
                        $join_cond = "JOIN " . DMS_DEALER . " as d ON d.dealer_code=u.dealer_code ";
                        $area_cond = " and u.dealer_code IN ('')";
                    }

                    //COND
                    /*
                    $query_allareadealerarr=$parent->selectQuery(DMS_DEALER,"`dealer_code`,rm_email ","  dealer_code='".$dealer_code."'  AND status='1' AND is_deleted='0'","1");
                    $dealer_arr=array();
                    if($query_allareadealerarr['nr'])
                    {
                    $join_cond="JOIN ".DMS_DEALER." as d ON d.dealer_code=u.dealer_code ";
                    $area_cond=" and d.rm_email ='".$query_allareadealerarr['result'][0]->rm_email."'";
                    }else
                    {
                    $area_cond=" and u.dealer_code IN ('')";
                    }
                     */
                    break;
                default:
                    $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
                    break;
            }
        } else {
            $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
        }

        if ($parent->current_user_role == '14') {
            $area_cond .= " AND u.dealer_code='" . $dealer_code . "'";
        }
        $new_cond = 'AND a.user_type=0 ';

        //GET ALL ASSESSMENT LIST WHICH PUBLISHED
        $assessment_str = "SELECT a.* FROM `" . TABLE_ASSESSMENT . "` as a  WHERE  a.status='1' AND a.atype='0' AND a.assettypeid='1' " . $date_cond . $new_cond;
        $assessment_arr = $parent->getQueryValue($assessment_str);
        //ASSESSMENT COUNT
        $assessment_count = (count($assessment_arr) > 0) ? count($assessment_arr) : '0';

        $data_arr = array();
        if (count($assessment_arr) > 0) {
            foreach ($assessment_arr as $res_assess) {
                $assessmentid_arr[] = $res_assess->assessmentid;
            }

            //GET ALL 20 USER RANK
            //$parent->executeQuery("SET @rownum := 0");
            $get_user_rank_str = "SELECT SUM(highscore)as user_score,u.userid,COALESCE(ar.total_time,'0')as total_time,MAX(au.modified_on) as last_modified,u.dealer_code,u.role,d.*  FROM " . TABLE_USER . " as u JOIN (SELECT * FROM  " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND highscorearid!=0 ) as au ON u.userid=au.userid  LEFT JOIN (SELECT SUM(time_taken)as total_time,assessmentid,userid FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") GROUP BY userid )as ar ON u.userid=ar.userid " . $join_cond . "  WHERE u.role>'7' AND  u.role<14 AND  u.is_deleted=0 " . $area_cond . " GROUP BY u.userid ORDER BY user_score DESC,ar.total_time ASC,last_modified ASC,u.userid ASC ";
            $get_user_rank_arr = $parent->getQueryValue($get_user_rank_str);
            if ($get_user_rank_arr) {
                foreach ($get_user_rank_arr as $res_user) {
                    $user_data_arr = new stdClass();
                    $get_time_str = "SELECT * FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND userid='" . $res_user->userid . "'";
                    $get_time_arr = $parent->getQueryValue($get_time_str);

                    $user_data_arr->user = projectfunc::getuserdata($parent, $res_user->userid);
                    $user_data_arr->rank = '0';
                    $user_data_arr->tot_user_score = (count($get_time_arr) > 0) ? $res_user->user_score : '-';
                    $user_data_arr->percentage_score = (count($get_time_arr) > 0) ? '0' : '-';

                    $user_data_arr->total_time = $res_user->total_time;
                    $user_data_arr->last_time = (count($get_time_arr) > 0) ? $res_user->last_modified : '-';

                    $user_cond = array();
                    //GET EACH USER COND
                    $getuser_data = projectfunc::getuserdata($parent, $res_user->userid);
                    if ($getuser_data->role) {
                        $user_cond[] = " (a.filter_role LIKE '%" . $getuser_data->role . "%' OR a.filter_role='')";
                    }
                    if ($getuser_data->zone) {
                        $user_cond[] = " (a.filter_zone LIKE '%" . $getuser_data->zone . "%' OR a.filter_zone='')";
                    }
                    if ($getuser_data->city) {
                        $user_cond[] = " (a.filter_region LIKE '%" . $getuser_data->city . "%' OR a.filter_region='')";
                    }
                    if ($getuser_data->dealer_code) {
                        $user_cond[] = " (a.filter_dealer LIKE '%" . $getuser_data->dealer_code . "%'  OR a.filter_dealer='')";
                    }
                    $assess_user_cond = " AND " . @implode(' AND ', $user_cond);

                    $count_assessment_str = "SELECT COUNT(a.assessmentid) as acount FROM `" . TABLE_ASSESSMENT . "` as a  WHERE a.status='1' AND a.atype='0' AND a.assettypeid='1'  AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59' AND a.enddate>='" . $user_data_arr->user->user_created_on . "' AND  assessmentid IN (" . @implode(',', $assessmentid_arr) . ") " . $assess_user_cond . $new_cond . " LIMIT 1";
                    $count_assessment_arr = $parent->getQueryValue($count_assessment_str);
                    $user_data_arr->percentage_score = (count($assessment_arr) > 0) ? round($res_user->user_score / $count_assessment_arr[0]->acount) : '0';
                    $user_data_arr->percentage = $user_data_arr->percentage_score;

                    if ((($assessment_count / $count_assessment_arr[0]->acount) * 100) >= MIN_ASSESSMENT_PERCENT) {
                        $data_arr[] = $user_data_arr;
                    }
                }
            }

            if (count($data_arr) > 0) {
                $outof = count($data_arr);
                array_multisort(array_column($data_arr, 'percentage_score'), SORT_DESC, array_column($rank_arr, 'total_time'), SORT_ASC, $rank_arr);
                $rank = 1;
                foreach ($data_arr as $key => $res) {
                    $data_arr[$key]->rank = $rank;
                    $data_arr[$key]->outof = $outof;
                    $rank++;
                }
            }

        } else {
            /*
            $cur_data_arr=new stdClass();
            $udata=projectfunc::getuserdata($parent,$parent->current_user_id);
            $cur_data_arr->user=$udata;
            foreach($udata as $key=>$res)
            {
            $cur_data_arr->$key=$res;
            }

            $cur_data_arr->rank='-';
            $cur_data_arr->tot_user_score='-';
            $cur_data_arr->percentage_score='-';
            $cur_data_arr->percentage=$cur_data_arr->percentage_score;
            $cur_data_arr->total_time='0';
            $cur_data_arr->last_time='-';
             */
            $get_count_arr = array();
        }

        $total_count = count($data_arr);
        /*if(count($data_arr)>0)
        {
        $temp=array_chunk($data_arr,20);
        $data_arr=$temp[0];
        }
         */

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

    /* /////////////////////////////// UPLOAD TARGET SALE //////////////////////////////////////// */
    private function uploadtargetsale($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        //CHECK FILE
        if (!isset($_FILES['file'])) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error11']), 406);
        }

        switch ($parent->current_user_role) {
            case "14": //Dealer
            case "7": //Area Manager
            case "6": //Regional Manager
            case "5": //Trainer
            case "4": //Zonal Manager
            case "3": //HO Manager

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

        //AREA
        $REQUEST_KEYS = array('area' => 'string');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $area_manager = escape_str($parent->_request["area"]);

        //CONNECT S3
        $s3 = awsfileserver::connectS3();
        //IMAGE UPLOAD
        $obj = new stdClass();
        $obj->filekey = 'file';
        $obj->size = '100'; //IN MB
        $obj->type = array('xlsx');
        globalfunc::validateFile($parent, $obj);

        $obj->path = "../../" . S3_REPORT_URL;
        $obj->filename = 'import_sales_target_' . date('Ymd') . "_" . uniqid();
        //if(isset($parent->_request['width']))$obj->width=$parent->_request['width'];
        //if(isset($parent->_request['height']))$obj->height=$parent->_request['height'];
        //$obj->cord=(isset($parent->_request['cord']))?$parent->_request['cord']:NULL;
        $fileName = globalfunc::uploadFile($parent, $obj);

        awsfileserver::checkupload($parent, $s3, S3_BUCKET, S3_REPORT_URL . $fileName, dirname(__FILE__) . "/../../../" . S3_REPORT_URL . $fileName);

        //UNLINK

        require dirname(__FILE__) . '/../../excelreader/excel_reader2.php';
        require dirname(__FILE__) . '/../../excelreader/SpreadsheetReader.php';

        $Spreadsheet = @new SpreadsheetReader("../../" . S3_REPORT_URL . $fileName);

        $Spreadsheet->ChangeSheet(0);

        //print_r($Spreadsheet);
        $excelhead = "TARGET SALES";

        $query_user_str = "SELECT * FROM `" . DMS_DEALER . "` WHERE am_email='" . $area_manager . "'  AND status='1' AND is_deleted='0'  LIMIT 1";
        $query_user_arr = $parent->getQueryValue($query_user_str);

        $logstr = 'UPLOAD TARGET SALE';
        globalfunc::insertUserLog($parent, $logstr);

        $insert_row = 0;
        $ins_qryarr = array();
        $smpin_arr = array();
        $model_arr = array();
        $ins_arr = array();
        $delete_arr = array();
        $ins_log_arr = array();
        if (count($query_user_arr) > 0) {
            if (count($Spreadsheet) > 0) {
                foreach ($Spreadsheet as $Key => $Row) {
                    if ($Key <= 1) {
                    } else {
                        $i = 0;
                        if ($Key == '2') {
                            for ($i = 4; $i < count($Row); $i++) {
                                $model_arr[$i] = $Row[$i];
                            }
                            $model_quotes = array_map("quotes_array", $model_arr);

                            $query_model_str = "SELECT * FROM `" . TABLE_MODEL . "` WHERE model_name IN (" . @implode(',', $model_quotes) . ")";
                            $query_model_arr = $parent->getQueryValue($query_model_str);

                            if (count($query_model_arr) != count($model_arr)) {
                                $parent->response(array('response' => 'failed', 'message' => $this->page_data["error12"]), 406);
                            }

                        } else {
                            //print_r($Row);
                            $smpin = $Row[0];
                            $name = $Row[1];
                            $mobile = $Row[2];
                            $dealer_details = $Row[3];

                            $delete_arr[] = "DELETE FROM " . TABLE_USER_SALETARGET . " WHERE smpin='" . $smpin . "' AND sale_month>='" . date("Y-m", strtotime(NOW)) . "-01' AND sale_month<'" . date('Y-m', strtotime('+1 month', strtotime(NOW))) . "-01'";

                            foreach ($model_arr as $mkey => $name) {
                                $ins_arr[] = "('" . $smpin . "', '" . $name . "', '" . $parent->current_user_id . "', '" . date("Y-m", strtotime(NOW)) . "-01', '" . $Row[$mkey] . "','" . NOW . "', '" . NOW . "')";
                                $ins_log_arr[] = "('" . $smpin . "','" . $name . "','" . $parent->current_user_role . "','" . $parent->current_user_id . "','" . date("Y-m", strtotime(NOW)) . "-01','" . $Row[$mkey] . "','" . NOW . "')";
                            }

                            $smpin_arr[] = $smpin;
                            $insert_row++;

                            //EXCEL UPLOAD CHECK
                            $is_edit = projectfunc::setSaleEditpermisson($parent, $smpin, date("Y-m", strtotime(NOW)) . "-01");
                            if ($is_edit != 1) {
                                $manager_error = ($parent->manager_error) ? $parent->manager_error : $this->page_data["error6"];
                                $parent->response(array('response' => 'failed', 'message' => $manager_error), 406);
                            }

                        }

                    }
                }

                if (count($smpin_arr) > 0) {
                    $smpin__quote_arr = array_map("quotes_array", $smpin_arr);
                    $query_emp_str = "SELECT * FROM `" . DMS_EMPLOYEE . "` WHERE smpin IN (" . @implode(',', $smpin__quote_arr) . ")";
                    $query_emp_arr = $parent->getQueryValue($query_emp_str);

                    $unique_ids = array_unique($smpin_arr);
                    if (count($unique_ids) != $insert_row) {
                        $parent->response(array('response' => 'failed', 'message' => $this->page_data["error13"]), 406);
                    }

                    if (count($query_emp_arr) != count($smpin_arr)) {
                        $parent->response(array('response' => 'failed', 'message' => $this->page_data["error14"]), 406);
                    }

                    if (count($ins_arr) > 0) {
                        if (count($delete_arr) > 0) {
                            foreach ($delete_arr as $res_query) {
                                $parent->executeQuery($res_query);
                            }
                            $parent->executeQuery("INSERT INTO " . TABLE_USER_SALETARGET . " (`smpin`, `model`, `am_id`, `sale_month`, `target`, `created_on`, `modified_on`) VALUES " . @implode(',', $ins_arr));
                            $parent->executeQuery("INSERT INTO " . TABLE_USER_SALETARGET . " (`smpin`, `model`, `roleid`, `userid`, `sale_month`, `target`, `created_on`) VALUES " . @implode(',', $ins_log_arr));
                        }
                    }

                    if (count($smpin_arr) > 0) {
                        $dealer_notification_type = 0;
                        foreach ($smpin_arr as $smpin) {
                            $status_str = ($parent->current_user_role == '14') ? '1' : '3';

                            $parent->executeQuery("INSERT INTO " . TABLE_USER_SALESTARGET_STATUS . " (`smpin`, `roleid`, `userid`, `status`, `sale_month`, `created_on`) VALUES ('" . $smpin . "','" . $parent->current_user_role . "','" . $parent->current_user_id . "','" . $status_str . "','" . date("Y-m", strtotime(NOW)) . "-01','" . NOW . "')");
                        }

                        //DSE  TRIGGER NOTIFICATION
                        $notificationtitle = 'Sales target has been updated';
                        $notificationtext = 'Sales target has been updated';
                        $notificationtype = '5';
                        $obj = new stdClass();
                        $notificationdata = json_encode($obj);

                        $parent->executeQuery("INSERT INTO `" . TABLE_NOTIFICATION . "` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('" . $notificationtitle . "','" . escape_str($notificationtext) . "','" . $notificationdata . "','" . $notificationtype . "' ,'1','" . NOW . "','" . NOW . "','" . NOW . "')");
                        $notificationid = $parent->lastInsertId();
                        $data = array('notification_id' => $notificationid, 'title' => $notificationtitle, 'message' => $notificationtext, 'notificationtype' => $notificationtype, 'notificationdata' => $notificationdata, 'created_date' => NOW);

                        //TO SMPIN
                        $smpin_quotes = array_map("quotes_array", $smpin_arr);
                        $check_str = "SELECT userid  FROM " . TABLE_USER . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") AND role>7 AND role<14 AND is_deleted=0 AND status=1";
                        $check_user_arr = $parent->getQueryValue($check_str);

                        if (count($check_user_arr)) {
                            $ins_arr = array();
                            foreach ($check_user_arr as $res_user) {
                                $ins_arr[] = " ('" . $notificationid . "', '" . $res_user->userid . "', '0', '" . NOW . "')";
                            }

                            $insert_chunk = array_chunk($ins_arr, 1000);
                            foreach ($insert_chunk as $chunk_ins) {
                                $parent->executeQuery("INSERT INTO " . TABLE_NOTIFICATION_USER . "(`notificationid`, `userid`, `status`,  `created_on`) VALUES " . @implode(',', $chunk_ins) . "  ON DUPLICATE KEY UPDATE `status` =0");
                            }

                            $usertokenarr = array('ios' => array(), 'android' => array());
                            $user_device_str = "SELECT ud.devicetype,ud.token FROM `" . TABLE_USER_DEVICES . "` as ud JOIN (SELECT userid FROM " . TABLE_NOTIFICATION_USER . " WHERE notificationid='" . $notificationid . "')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                            $user_device_arr = $parent->getQueryValue($user_device_str);
                            if (count($user_device_arr) > 0) {
                                if (strtolower($user_device_arr[0]->devicetype) == 'ios') {
                                    $usertokenarr['ios'][] = $user_device_arr[0]->token;
                                } else if (strtolower($user_device_arr[0]->devicetype) == 'android') {
                                    $usertokenarr['android'][] = $user_device_arr[0]->token;
                                }
                                // globalfunc::sendUserNotification($data, $usertokenarr);
                            }
                        }

                        //DEALER TRIGGER NOTIFICATION
                        if ($parent->current_user_role != '14') {
                            $notificationtitle = 'Sales target has been modified';
                            $notificationtext = 'Sales target has been modified';
                            $notificationtype = '5';
                            $obj = new stdClass();
                            $notificationdata = json_encode($obj);

                            $parent->executeQuery("INSERT INTO `" . TABLE_NOTIFICATION . "` (  `notificationtitle`, `notificationtext`, `notificationdata`, `notificationtype`,  `status`, `publisheddate`, `created_on`, `modified_on`) VALUES ('" . $notificationtitle . "','" . escape_str($notificationtext) . "','" . $notificationdata . "','" . $notificationtype . "' ,'1','" . NOW . "','" . NOW . "','" . NOW . "')");
                            $notificationid = $parent->lastInsertId();
                            $data = array('notification_id' => $notificationid, 'title' => $notificationtitle, 'message' => $notificationtext, 'notificationtype' => $notificationtype, 'notificationdata' => $notificationdata, 'created_date' => NOW);

                            $smpin_quotes = array_map("quotes_array", $all_smpin_arr);
                            $check_str = "SELECT * FROM " . TABLE_USER . " u JOIN (SELECT dealer_code FROM " . DMS_EMPLOYEE . " WHERE smpin IN (" . @implode(',', $smpin_quotes) . ") GROUP BY dealer_code) as e ON e.dealer_code=u.dealer_code WHERE u.role=14";
                            $check_user_arr = $parent->getQueryValue($check_str);

                            if (count($check_user_arr)) {
                                $ins_arr = array();
                                foreach ($check_user_arr as $res_user) {
                                    $ins_arr[] = " ('" . $notificationid . "', '" . $res_user->userid . "', '0', '" . NOW . "')";
                                }

                                $insert_chunk = array_chunk($ins_arr, 1000);
                                foreach ($insert_chunk as $chunk_ins) {
                                    $parent->executeQuery("INSERT INTO " . TABLE_NOTIFICATION_USER . "(`notificationid`, `userid`, `status`,  `created_on`) VALUES " . @implode(',', $chunk_ins) . "  ON DUPLICATE KEY UPDATE `status` =0");
                                }

                                $usertokenarr = array('ios' => array(), 'android' => array());
                                $user_device_str = "SELECT ud.devicetype,ud.token FROM `" . TABLE_USER_DEVICES . "` as ud JOIN (SELECT userid FROM " . TABLE_NOTIFICATION_USER . " WHERE notificationid='" . $notificationid . "')  as u ON ud.userid=u.userid  WHERE ud.is_deleted='0' AND (devicetype='ios' OR devicetype='android')  AND token!=''";
                                $user_device_arr = $parent->getQueryValue($user_device_str);
                                if (count($user_device_arr) > 0) {
                                    if (strtolower($user_device_arr[0]->devicetype) == 'ios') {
                                        $usertokenarr['ios'][] = $user_device_arr[0]->token;
                                    } else if (strtolower($user_device_arr[0]->devicetype) == 'android') {
                                        $usertokenarr['android'][] = $user_device_arr[0]->token;
                                    }
                                    // globalfunc::sendUserNotification($data, $usertokenarr);
                                }
                            }
                        }

                    }

                    @unlink(dirname(__FILE__) . "/../../../" . S3_REPORT_URL . $fileName);
                    $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
                } else {
                    @unlink(dirname(__FILE__) . "/../../../" . S3_REPORT_URL . $fileName);
                    $parent->response(array('response' => 'failed', 'message' => $this->page_data["error14"]), 406);
                }

            }

        } else {
            @unlink(dirname(__FILE__) . "/../../../" . S3_REPORT_URL . $fileName);
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error12"]), 406);
        }

    }

    /* /////////////////////////////// NEW REGISTRATION REPORT //////////////////////////////////////////////// */
    private function newregistrationreport($parent)
    {

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

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";
        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND d.status='1' AND d.is_deleted='0' AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,e.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,e.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,e.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,e.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $user_cond .= " AND e.is_current='1' ";
        //$get_user_str="SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,l.created_on as register_date FROM ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code LEFT JOIN (SELECT userid,created_on FROM ".TABLE_USER_LOG." WHERE module='REGISTER' )as l ON u.userid=l.userid  WHERE e.status='1' AND u.is_deleted=0 AND e.smpin!='' ".$user_cond.$order_by_cond.$limit_cond;
        $get_user_str = "SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,d.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,u.created_on as register_date,u.status FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin  LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' AND u.is_deleted=0 " . $user_cond . $order_by_cond . $limit_cond;
        //$get_user_str="SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,u.userid,d.city,d.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,u.created_on as register_date,u.status FROM ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON u.smpin=e.smpin AND u.is_deleted=0 LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' ".$user_cond.$order_by_cond.$limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (!count($user_arr) > 0) {
            $user_arr = array();
        } else {
            foreach ($user_arr as $mkey => $res_val) {
                if ($res_user->userid > 0) {
                    $status = ($res_user->status == '1') ? 'Active' : 'Inactive';
                } else {
                    $status = "Not registered";
                }
                $user_arr[$mkey]->status_str = $status;
                $user_arr[$mkey]->is_active = ($res_val->status == '1') ? "1" : "0";
            }
        }

        //GET COUNT
        //$get_count_str="SELECT  COUNT(e.`smpin`) as ucount  FROM ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code LEFT JOIN (SELECT * FROM ".TABLE_USER_LOG." WHERE module='REGISTER' )as l ON u.userid=l.userid  WHERE e.status='1' AND e.smpin!=''  ".$user_cond." LIMIT 1";
        $get_count_str = "SELECT  COUNT(e.`smpin`) as ucount  FROM  " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin  LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!=''  AND u.is_deleted=0 " . $user_cond . " LIMIT 1";
        //$get_count_str="SELECT  COUNT(e.`smpin`) as ucount  FROM  ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON u.smpin=e.smpin AND u.is_deleted=0 LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!=''  ".$user_cond." LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    // New Course Report
    private function newcoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND d.status='1' AND d.is_deleted='0' AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $user_cond .= " AND e.is_current='1' ";
        // u.status='1' AND
        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,e.segment FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::userSegmentCourseCompleteStatus($parent, $res->userid, $res->segment);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        // u.status='1' AND
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    /* /////////////////////////////// NEW SURVEY REPORT //////////////////////////////////////////////// */
    private function newsurveyreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';
//        if($parent->current_user_role=='7')
        //        {
        //            $role=$parent->current_user_role;
        //            $userdata=projectfunc::getuserdata($parent,$parent->current_user_id);
        //            $emailid=$userdata->emailid;
        //        }else
        //        {
        //            //AREA MANAGER LEVEL REPORT
        //            $role='7';
        //            //FIELDS VALIDATION
        //            $REQUEST_KEYS=array('area'=>'string');
        //            globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        //            $area_manager = $parent->_request["area"];
        //            $emailid=$area_manager;
        //
        //
        //        }

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);
        $user_cond = "";

        switch ($type) {
            case "zm":
                if ($parent->current_user_role == '3') {
                    $REQUEST_KEYS = array('zmemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["zmemail"]);
                    if ($emailid != 'all') {
                        $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                    } else {
                        $user_cond .= "";
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "rm":
                if ($parent->current_user_role < '7') {
                    if ($parent->current_user_role == '5') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                        if ($emailid == 'all') {
                            $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                        } else {
                            $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' AND " . $zone_cond . "  AND status='1' AND is_deleted='0' )";
                        }
                    } else {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            $REQUEST_KEYS = array('zmemail' => 'string');
                            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                            $emailid = escape_str($parent->_request["zmemail"]);
                            $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                        } else {
                            //ZM EMAIL
                            $zmemail = escape_str($parent->_request["zmemail"]);
                            $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND zm_email='" . $zmemail . "'" : '';
                            $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' " . $zmcond . "  AND status='1' AND is_deleted='0')";
                        }
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "am":
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " dealer_code='" . $parent->current_user_data->dealer_code . "'";
                } else {
                    $REQUEST_KEYS = array('amemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["amemail"]);
                    if ($emailid == 'all') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                        $emailid = escape_str($parent->_request["rmemail"]);
                        $dealer_code_cond = " rm_email='" . $emailid . "'";

                    } else {
                        $dealer_code_cond = "  am_email='" . $emailid . "'";
                    }
                    if ($parent->current_user_role != '5') {
                        //ZM EMAIL
                        $zmemail = escape_str($parent->_request["zmemail"]);
                        $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND zm_email='" . $zmemail . "'" : '';
                        $dealer_code_cond .= $zmcond;
                    }
                    //RM EMAIL
                    $rmemail = escape_str($parent->_request["rmemail"]);
                    $rmcond = ($rmemail != 'all' && $rmemail != '') ? " AND rm_email='" . $rmemail . "'" : '';
                    $dealer_code_cond .= $rmcond;
                    //TRAINER
                    if ($parent->current_user_role == '5') {
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $dealer_code_cond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
                    }
                }
                $user_cond .= " AND u.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE  " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[1]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }
        //u.status='1' AND
        $user_cond .= " AND e.is_current='1' ";
        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name,au.modified_on as assessment_date FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "'  AND au.highscorearid!='0' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            /*
        foreach($user_arr as $mkey=>$res_user)
        {
        //$exam_highscore_str = "SELECT  * FROM ".TABLE_ASSESSMENT_USER."  WHERE assessmentid='".$assessmentid."' AND userid='".$res_user->userid."' LIMIT 1";
        //$exam_highscore_arr=$parent->getQueryValue($exam_highscore_str);
        //$user_arr[$mkey]->highscore=(count($exam_highscore_arr)>0)?$exam_highscore_arr[0]->highscore:'0';
        }
         */
        }

        //GET COUNT
        //u.status='1' AND
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 AND au.assessmentid='" . $assessmentid . "'  AND au.highscorearid!='0' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    /* /////////////////////////////// NEW SALES REPORT //////////////////////////////////////////////// */
    private function newsalesreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 4);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[3]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $qry_params = explode("?", $parent->params[3]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";
        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND d.status='1' AND d.is_deleted='0' AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,e.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,e.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,e.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,e.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,e.fname ASC ";
                    break;

            }
        }
        //GET ROLE
        $role_data = array();
        $role_arr = $parent->getQueryValue("SELECT rolename FROM " . TABLE_ROLE . " WHERE status=1 AND id>7 AND id<14 ");
        if (count($role_arr) > 0) {
            foreach ($role_arr as $res) {
                $role_data[] = "'" . $res->rolename . "'";
            }
        } else {
            $role_data[] = '';
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }
        //u.status='1' AND

        $is_history = (isset($parent->_request["is_history"]) && $parent->_request["is_history"] == 1) ? "1" : "0";
        if ($is_history == 0) {
            $user_cond .= " AND e.is_current='1' AND e.status=1 ";
        } else {
            $user_cond .= " AND e.status=1 ";
        }
        //$get_user_str="SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,u.segment,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM ".TABLE_USER." u LEFT JOIN ".DMS_EMPLOYEE." e ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 ".$user_cond.$order_by_cond.$limit_cond;
        //$get_user_str="SELECT SQL_CALC_FOUND_ROWS u.userid,e.fname,e.lname,e.smpin,e.emp_code,d.city,e.dealer_code,e.segment,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM ".DMS_EMPLOYEE." e LEFT JOIN ".TABLE_USER." u ON e.smpin=u.smpin LEFT JOIN ".DMS_DEALER." d ON e.dealer_code=d.dealer_code  WHERE e.role IN (".@implode(',',$role_data).") ".$user_cond.$order_by_cond.$limit_cond;
        $get_user_str = "SELECT SQL_CALC_FOUND_ROWS e.id,e.fname,e.lname,e.smpin,e.emp_code,d.city,e.dealer_code,e.segment,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . DMS_EMPLOYEE . " e  LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code  WHERE e.role IN (" . @implode(',', $role_data) . ") " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        $total_arr = $parent->getQueryValue("SELECT FOUND_ROWS() as total_record");

        $query_modelarr = $parent->selectQuery(TABLE_MODEL, " model_name,model_image,segment ", "model_is_target=1 AND user_type=0 ORDER BY model_id", "");
        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                //TARGET
                $user_target = projectfunc::userSmpinSalesTarget($parent, $res_user->smpin, '', $year_data, $month_data);
                //ACHIEVED
                $user_achieved = projectfunc::userSmpinSalesAchieved($parent, $res_user->smpin, '', $year_data, $month_data);
                $sales = array('target' => $user_target, 'achieved' => $user_achieved);

                $user_arr[$mkey]->sales = $sales;
                $model_data_arr = array();
                //GET MODEL

                $salemodel_arr = array();
                $query_salesmodelarr = $parent->selectQuery(DMS_EMPLOYEE_SALES, " model ", "smpin='" . $res_user->smpin . "' AND sale_date>='" . date('Y-m-d', strtotime($year_data . "-" . $month_data . "-01")) . "' AND sale_date<='" . date('Y-m-t', strtotime($year_data . "-" . $month_data . "-01")) . "' GROUP BY model ", "");
                if ($query_salesmodelarr['nr']) {
                    foreach ($query_salesmodelarr['result'] as $res) {
                        $salemodel_arr[] = strtolower($res->model);
                    }
                }

                if ($query_modelarr['nr']) {
                    foreach ($query_modelarr['result'] as $key => $res) {
                        if ($res->segment == 0 || ($res->segment == $res_user->segment) || in_array(strtolower($res->model_name), $salemodel_arr)) {
                            $res->model_image_url = ($res->model_image != '') ? SITE_URL . "hypermupload/model/" . $res->model_image : NOIMAGE_URL;
                            $user_target = projectfunc::userSmpinSalesTarget($parent, $res_user->smpin, $res->model_name, $year_data, $month_data);

                            $res->target = $user_target;
                            $res->achieved = projectfunc::userSmpinSalesAchieved($parent, $res_user->smpin, $res->model_name, $year_data, $month_data);
                            $model_data_arr[] = (array) $res;
//                            if($user_target>0)
                            //                            {
                            //                                $res->target=$user_target;
                            //                                $res->achieved= projectfunc::userSalesAchieved($parent,$res_user->userid,$res->model_name,$year_data,$month_data);
                            //                                $model_data_arr[]=(array)$res;
                            //                            }
                        }
                    }
                }

                $user_arr[$mkey]->model_data = $model_data_arr;

            }
        }

        //GET COUNT
        //u.status='1' AND
        //        $get_count_str="SELECT COUNT(u.userid)as ucount FROM ".TABLE_USER." u LEFT JOIN ".DMS_EMPLOYEE." e ON u.smpin=e.smpin LEFT JOIN ".DMS_DEALER." d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 ".$user_cond." LIMIT 1 ";
        //        $get_count_arr=$parent->getQueryValue($get_count_str);
        $total = (count($total_arr) > 0) ? $total_arr[0]->total_record : 0;

        //LOG
        $logstr = 'MANAGER SALES REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $user_arr, 'month' => date('M', strtotime('2018-' . $month_data . "-01")), 'year' => $year_data, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// NEW CERTIFIED DSE REPORT //////////////////////////////////////////////// */
    private function newcertifieddsereport($parent)
    {

        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3', '4', '5', '6', '7', '14'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND d.status='1' AND d.is_deleted='0' AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR  d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }
        //u.status='1' AND
        $user_cond .= " AND e.is_current='1' ";
        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $user_arr[$mkey]->learning = projectfunc::userLearningLevel($parent, $res_user->userid);
            }
        }

        //GET COUNT
        //u.status='1' AND
        $get_count_str = "SELECT COUNT(u.userid) as ucount FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' AND u.role>7 AND u.role<14 " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'MANAGER CERTIFIED DSE REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $user_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// NEW ASSESSMENT REPORT //////////////////////////////////////////////// */
    private function newassessmentreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3', '4', '5', '6', '7', '14'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $assess_str = "SELECT assessmentid,pass_score FROM " . TABLE_ASSESSMENT . "  WHERE assessmentid='" . $assessmentid . "'  LIMIT 1";
        $assess_arr = $parent->getQueryValue($assess_str);
        if (!(count($assess_arr) > 0)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $pass_score = $assess_arr[0]->pass_score;

        $user_cond = "";
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";
        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND d.status='1' AND d.is_deleted='0' AND " . @implode(" AND ", $dealer_cond_arr);
        }

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[1]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY au.highscore DESC,au.modified_on ASC, d.dealer_name,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        $dse_cond = (isset($parent->_request["is_idse"]) && $parent->_request["is_idse"] !== '1') ? " AND u.role='15'" : "AND u.role>7 AND u.role<14";
        $user_cond .= " AND e.is_current='1' ";
        //u.status='1' AND
        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.smpin,u.emp_code,d.city,u.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' " . $dse_cond . " AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
                $user_arr[$mkey]->is_pass = ($user_arr[$mkey]->highscore >= $pass_score) ? '1' : '0';
            }
        }

        //GET COUNT
        //u.status='1' AND
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  WHERE  u.is_deleted='0' " . $dse_cond . " AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'ASSESSMENT REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

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

    /* /////////////////////////////// NEW SALES TARGET REPORT //////////////////////////////////////////////// */
    private function newsalestarget($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        globalfunc::checkParamCount($parent, 4);

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[3]);
        //$limit_cond=($limit_str)?" LIMIT ".$limit_str:'';
        $limit_cond = '';
        $dealer_code_cond = '';
        $qry_params = explode("?", $parent->params[3]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

        switch ($type) {
            case "zm":
                if ($parent->current_user_role == '3') {
                    $REQUEST_KEYS = array('zmemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["zmemail"]);
                    if ($emailid != 'all') {
                        $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                    } else {
                        $user_cond .= "";
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "rm":
                if ($parent->current_user_role < '7') {
                    if ($parent->current_user_role == '5') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $zone_cond .= (count($trainer_arr) > 0) ? " zone='" . $trainer_arr[0]->zone . "'" : " zone='0'";

                        if ($emailid == 'all') {
                            $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE " . $zone_cond . "  AND status='1' AND is_deleted='0')";
                        } else {
                            $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' AND " . $zone_cond . "  AND status='1' AND is_deleted='0' )";
                        }
                    } else {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            $REQUEST_KEYS = array('zmemail' => 'string');
                            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                            $emailid = escape_str($parent->_request["zmemail"]);
                            $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE zm_email='" . $emailid . "'  AND status='1' AND is_deleted='0')";
                        } else {
                            //ZM EMAIL
                            $zmemail = escape_str($parent->_request["zmemail"]);
                            $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND zm_email='" . $zmemail . "'" : '';
                            $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE rm_email='" . $emailid . "' " . $zmcond . "  AND status='1' AND is_deleted='0')";
                        }
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "am":
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " dealer_code='" . $parent->current_user_data->dealer_code . "'";
                } else {
                    $REQUEST_KEYS = array('amemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["amemail"]);
                    if ($emailid == 'all') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                        $emailid = escape_str($parent->_request["rmemail"]);
                        $dealer_code_cond = " rm_email='" . $emailid . "'";

                    } else {
                        $dealer_code_cond = "  am_email='" . $emailid . "'";
                    }
                    if ($parent->current_user_role != '5') {
                        //ZM EMAIL
                        $zmemail = escape_str($parent->_request["zmemail"]);
                        $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND zm_email='" . $zmemail . "'" : '';
                        $dealer_code_cond .= $zmcond;
                    }
                    //RM EMAIL
                    $rmemail = escape_str($parent->_request["rmemail"]);
                    $rmcond = ($rmemail != 'all' && $rmemail != '') ? " AND rm_email='" . $rmemail . "'" : '';
                    $dealer_code_cond .= $rmcond;
                    //TRAINER
                    if ($parent->current_user_role == '5') {
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $dealer_code_cond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
                    }
                }
                $user_cond .= " AND d.dealer_code IN (SELECT dealer_code FROM " . DMS_DEALER . " WHERE  " . $dealer_code_cond . "  AND status='1' AND is_deleted='0')";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

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

        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname,u.userid ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Location
            //3-AM
            //4-RM
            //5-ZM
            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY d.dealer_name,u.fname,u.userid ASC ";
                    break;
                case '2':$order_by_cond = "ORDER BY d.city,u.fname,u.userid ASC ";
                    break;
                case '3':$order_by_cond = "ORDER BY d.am_email,u.fname,u.userid ASC ";
                    break;
                case '4':$order_by_cond = "ORDER BY d.rm_email,u.fname,u.userid ASC ";
                    break;
                case '5':$order_by_cond = "ORDER BY d.zm_email,u.fname,u.userid ASC ";
                    break;
                default:$order_by_cond = "ORDER BY d.dealer_name,u.fname,u.userid ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (e.fname LIKE '%" . $search_txt . "%' OR e.lname LIKE '%" . $search_txt . "%' OR e.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        if (isset($parent->_request["dealer"]) && $parent->_request["dealer"] != '') {
            $user_cond .= " AND d.dealer_code='" . escape_str($parent->_request["dealer"]) . "'";
        }

        $user_cond .= " AND e.is_current='1' ";
        $segment_result = array();

        $query_modelarr = $parent->selectQuery(TABLE_MODEL, "model_id, model_name,model_image,segment,min_target ", "model_is_target=1 AND user_type=0 " . $model_cond . " ORDER BY model_id", "");
        //$user_cond.=" AND u.role>7 AND u.role<14 ";
        $get_user_str = "SELECT  e.`smpin`, e.`emp_code`,e. `fname`,e.`lname`,e.emp_code,e.segment,u.userid,d.city,e.dealer_code,d.dealer_name,d.zm_name,d.rm_name,d.am_name  FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1'  AND e.smpin!='' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, '', $year_data, $month_data);
                $user_arr[$ukey]->salestarget = $user_target;
                $user_arr[$ukey]->model = array();
                //$user_arr[$ukey]->is_edit=(strtotime(CUR_DATE)>strtotime(date('Y-m-d',strtotime($year_data."-".$month_data."-".TRAINER_BUFFER_DATE))))?"0":"1";
                $user_arr[$ukey]->is_edit = projectfunc::setSaleEditpermisson($parent, $res->smpin, date('Y-m-d', strtotime($year_data . "-" . $month_data . "-01")));

                $query_get_statusarr = $parent->selectQuery(TABLE_USER_SALESTARGET_STATUS, "* ", "smpin='" . $res->smpin . "' AND  sale_month='" . date('Y-m-d', strtotime($year_data . "-" . $month_data . "-01")) . "' ORDER BY id DESC", "1");
                if ($query_get_statusarr['nr']) {
                    switch ($query_get_statusarr['result'][0]->status) {
                        case '1':
                            $user_arr[$ukey]->sale_status = '1';
                            $user_arr[$ukey]->sale_status_str = 'Waiting';
                            break;
                        case '2':
                            $user_arr[$ukey]->sale_status = '2';
                            $user_arr[$ukey]->sale_status_str = 'Approval';
                            break;
                        case '3':
                            $user_arr[$ukey]->sale_status = '3';
                            $user_arr[$ukey]->sale_status_str = 'Modification';
                            break;

                    }

                } else {
                    $user_arr[$ukey]->sale_status = '0';
                    $user_arr[$ukey]->sale_status_str = 'No Action';
                }
                switch ($res->segment) {
                    case '1':$user_arr[$ukey]->segment_min_target = SEGMENT_MIN_TARGET_PARENTS;
                        break;
                    case '2':$user_arr[$ukey]->segment_min_target = SEGMENT_MIN_TARGET_INSTRUCTOR;
                        break;
                    default:$user_arr[$ukey]->segment_min_target = SEGMENT_MIN_TARGET_STUDENT_LEANER;
                        break;
                }

                //GET SEGMENT
                //$segment= projectfunc::userSegment($parent,$res->smpin);
                $segment = $res->segment;
                //$model_cond=" AND (segment='".$segment."' OR segment='0' )";

//                if(!isset($segment_result[$segment]))
                //                {
                //                    //GET MODEL
                //                    $query_modelarr=$parent->selectQuery(TABLE_MODEL,"model_id, model_name,model_image ","model_is_target=1 AND user_type=0 ".$model_cond." ORDER BY model_id","");
                //                    $segment_result[$segment]=$query_modelarr;
                //                }else
                //                {
                //                    $query_modelarr=$segment_result[$segment];
                //                }

                if ($query_modelarr['nr']) {

                    foreach ($query_modelarr['result'] as $res_model) {
                        //|| in_array(strtolower($res_model->model_name),$salemodel_arr)
                        if ($res_model->segment == 0 || ($res_model->segment == $segment)) {
                            $user_target = projectfunc::userSmpinSalesTarget($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);
                            if ($user_target > 0) {
                                $mobj = new stdClass();
                                $mobj->model_id = $res_model->model_id;
                                $mobj->model_name = $res_model->model_name;
                                $mobj->target = $user_target;
                                $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);
                                $mobj->min_target = $res_model->min_target;
                                $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                                $user_arr[$ukey]->model[] = $mobj;
                            } else {

                                $mobj = new stdClass();
                                $mobj->model_id = $res_model->model_id;
                                $mobj->model_name = $res_model->model_name;
                                $mobj->target = '0';
                                $mobj->achieved = projectfunc::userSmpinSalesAchieved($parent, $res->smpin, $res_model->model_name, $year_data, $month_data);
                                $mobj->min_target = $res_model->min_target;
                                $mobj->model_image_url = ($res_model->model_image != '') ? SITE_URL . "hypermupload/model/" . $res_model->model_image : NOIMAGE_URL;
                                $user_arr[$ukey]->model[] = $mobj;

                            }
                        }
                    }
                }

            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        $get_count_str = "SELECT  COUNT(e.`smpin`)as ucount FROM " . DMS_EMPLOYEE . " e LEFT JOIN " . TABLE_USER . " u ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON e.dealer_code=d.dealer_code WHERE e.status='1' AND e.smpin!='' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'SALES TARGET REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

        $is_edit = 0;
        if (date('Y-m', strtotime(CUR_DATE)) == date('Y-m', strtotime($year_data . "-" . $month_data . "-01"))) {
            if ($parent->current_user_role == '14') {
                $def_edit_date = date('Y-m', strtotime(CUR_DATE)) . "-" . DEALER_SETSALE_DATE;
            } else {
                $def_edit_date = date('Y-m', strtotime(CUR_DATE)) . "-" . AM_SETSALE_DATE;
            }

            if (strtotime(CUR_DATE) <= strtotime($def_edit_date)) {
                $is_edit = 1;
            }
        }

        $parent->response(array('response' => 'success', 'data' => $user_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1'], 'is_edit' => $is_edit), 200);

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

    /* /////////////////////////////// NEW SALES LEADERBOARD REPORT //////////////////////////////////////////////// */
    private function newsalesleaderboardreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 4);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $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]));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[3]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        /*
        $REQUEST_KEYS=array('email'=>'string');
        globalfunc::mandatoryKey($parent,$REQUEST_KEYS);
        $email = escape_str($parent->_request["email"]);
         */

        $qry_params = explode("?", $parent->params[3]);
        $type = strtolower($qry_params[0]);
        $dealer_cond = "";

        switch ($type) {
            case "zm":
                if ($parent->current_user_role == '3') {
                    $REQUEST_KEYS = array('zmemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["zmemail"]);
                    if ($emailid != 'all') {
                        //$dealer_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE zm_email='". $emailid."')";
                        $dealer_cond .= " AND d.zm_email='" . $emailid . "'";
                    } else {
                        $dealer_cond .= "";
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "rm":
                if ($parent->current_user_role < '7') {
                    if ($parent->current_user_role == '5') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $zone_cond .= (count($trainer_arr) > 0) ? " d.zone='" . $trainer_arr[0]->zone . "'" : " d.zone='0'";

                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            //$user_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE ".$zone_cond.")";
                            $dealer_cond .= " AND " . $zone_cond;
                        } else {
                            //$user_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE rm_email='".$emailid."')";
                            $dealer_cond .= "AND d.rm_email='" . $emailid . "'  AND " . $zone_cond;
                        }
                    } else {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            $REQUEST_KEYS = array('zmemail' => 'string');
                            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                            $emailid = escape_str($parent->_request["zmemail"]);
                            //$user_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE zm_email='". $emailid."')";
                            $dealer_cond .= " AND d.zm_email='" . $emailid . "'";
                        } else {
                            //ZM EMAIL
                            $zmemail = escape_str($parent->_request["zmemail"]);
                            $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND d.zm_email='" . $zmemail . "'" : '';
                            //$user_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE rm_email='".$emailid."')";
                            $dealer_cond .= " AND d.rm_email='" . $emailid . "' " . $zmcond;
                        }
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "am":
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " d.dealer_code='" . $parent->current_user_data->dealer_code . "'";
                } else {
                    $REQUEST_KEYS = array('amemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["amemail"]);
                    if ($emailid == 'all') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                        $emailid = escape_str($parent->_request["rmemail"]);
                        $dealer_code_cond = " d.rm_email='" . $emailid . "'";

                    } else {
                        $dealer_code_cond = "  d.am_email='" . $emailid . "'";
                    }
                    if ($parent->current_user_role != '5') {
                        //ZM EMAIL
                        $zmemail = escape_str($parent->_request["zmemail"]);
                        $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND d.zm_email='" . $zmemail . "'" : '';
                        $dealer_code_cond .= $zmcond;
                    }
                    //RM EMAIL
                    $rmemail = escape_str($parent->_request["rmemail"]);
                    $rmcond = ($rmemail != 'all' && $rmemail != '') ? " AND d.rm_email='" . $rmemail . "'" : '';
                    $dealer_code_cond .= $rmcond;
                    //TRAINER
                    if ($parent->current_user_role == '5') {
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $dealer_code_cond .= (count($trainer_arr) > 0) ? "AND d.zone='" . $trainer_arr[0]->zone . "'" : "AND d.zone='0'";
                    }
                }
                //$user_cond.=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE  ".$dealer_code_cond.")";
                $dealer_cond .= " AND " . $dealer_code_cond;
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $user_cond = "";
        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[3]);
        //SORT
        $order_by_cond = "ORDER BY d.dealer_name,u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Dealer
            //2-Rank

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = " ORDER BY d.dealer_name,f.rank ASC ";
                    break;
                case '2':$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
                default:$order_by_cond = " ORDER BY f.rank,d.dealer_name ASC ";
                    break;
            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.smpin LIKE '%" . $search_txt . "%' OR d.dealer_name LIKE '%" . $search_txt . "%' OR d.zm_name LIKE '%" . $search_txt . "%'  OR d.rm_name LIKE '%" . $search_txt . "%' OR d.am_name LIKE '%" . $search_txt . "%' OR d.city LIKE '%" . $search_txt . "%'  )";
        }

        if ($parent->current_user_role == '14') {
            $user_cond .= " AND u.dealer_code='" . $dealer_code . "'";
        }
        //GET ALL 20 USER RANK
        $start_date = date('Y-m-d', strtotime($year_data . "-" . $month_data . "-01"));
        $end_date = date('Y-m-t', strtotime($year_data . "-" . $month_data . "-01"));

        $parent->executeQuery("SET @rownum := 0");
        $get_user_str = "SELECT f.*,u.userid,u.fname,u.lname,d.* FROM (SELECT @rownum := @rownum + 1 AS rank, salecount,targetcount,smpin,userid,last_sale,first_sale,sale_per FROM (SELECT c.*, CASE WHEN targetcount=0 THEN 0 ELSE (salecount/targetcount)*100 END as 'sale_per' FROM ( SELECT a.userid,a.smpin,a.salecount,b.targetcount,a.last_sale,a.first_sale FROM (SELECT COALESCE(COUNT(s.id),'0') as scount, COALESCE(SUM(s.sales_count),'0') as salecount, u.smpin,u.userid,MAX(s.sale_date) last_sale,MIN(s.sale_date) first_sale FROM " . TABLE_USER . " as u LEFT JOIN " . DMS_EMPLOYEE . " e  ON u.smpin=e.smpin  JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code LEFT JOIN (SELECT id,smpin,sale_date,sales_count FROM " . DMS_EMPLOYEE_SALES . " WHERE sale_date>='" . $start_date . "' AND sale_date<='" . $end_date . "') as s ON s.smpin=u.smpin WHERE u.is_deleted=0 AND u.role>7 AND u.role<14  AND e.is_current='1' " . $dealer_cond . "  GROUP BY u.smpin ) as a JOIN  (SELECT  COALESCE(SUM(t.target),'0') as targetcount,u.smpin,u.userid FROM " . TABLE_USER . " as u LEFT JOIN " . DMS_EMPLOYEE . " e  ON u.smpin=e.smpin JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  LEFT JOIN (SELECT id,smpin,target FROM " . TABLE_USER_SALETARGET . " WHERE sale_month>='" . $start_date . "' AND sale_month<='" . $end_date . "')as t ON t.smpin=u.smpin WHERE u.is_deleted=0 AND u.role>7  AND u.role<14  AND e.is_current='1' " . $dealer_cond . "  GROUP BY u.smpin ) as b ON a.userid=b.userid )c ORDER BY cast(sale_per as SIGNED) DESC,cast(salecount as SIGNED) DESC,cast(targetcount as SIGNED) DESC,last_sale ASC,first_sale ASC,userid ASC)as a )as f  JOIN " . TABLE_USER . "  as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1 " . $user_cond . $order_by_cond . " " . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        //GET COUNT
        $get_user_count_str = "SELECT COUNT(u.userid)as user_count FROM (SELECT  salecount,targetcount,smpin,userid,last_sale,first_sale,sale_per FROM (SELECT c.*, CASE WHEN targetcount=0 THEN 0 ELSE (salecount/targetcount)*100 END as 'sale_per' FROM ( SELECT a.userid,a.smpin,a.salecount,b.targetcount,a.last_sale,a.first_sale FROM (SELECT COALESCE(COUNT(s.id),'0') as scount, COALESCE(SUM(s.sales_count),'0') as salecount, u.smpin,u.userid,MAX(s.sale_date) last_sale,MIN(s.sale_date) first_sale FROM " . TABLE_USER . " as u LEFT JOIN " . DMS_EMPLOYEE . " e  ON u.smpin=e.smpin JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code  LEFT JOIN (SELECT id,smpin,sale_date,sales_count FROM " . DMS_EMPLOYEE_SALES . " WHERE sale_date>='" . $start_date . "' AND sale_date<='" . $end_date . "') as s ON s.smpin=u.smpin WHERE u.is_deleted=0 AND u.role>7  AND u.role<14  AND e.is_current='1' " . $dealer_cond . " GROUP BY u.smpin ) as a JOIN  (SELECT  COALESCE(SUM(t.target),'0') as targetcount,u.smpin,u.userid FROM " . TABLE_USER . " as u LEFT JOIN " . DMS_EMPLOYEE . " e  ON u.smpin=e.smpin JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code LEFT JOIN (SELECT id,smpin,target FROM " . TABLE_USER_SALETARGET . " WHERE sale_month>='" . $start_date . "' AND sale_month<='" . $end_date . "')as t ON t.smpin=u.smpin WHERE u.is_deleted=0 AND u.role>7  AND u.role<14  AND e.is_current='1' " . $dealer_cond . " GROUP BY u.smpin ) as b ON a.userid=b.userid )c ORDER BY cast(sale_per as SIGNED) DESC,cast(salecount as SIGNED) DESC,cast(targetcount as SIGNED) DESC,last_sale ASC,first_sale ASC,userid ASC)as a )as f  JOIN " . TABLE_USER . " as u ON f.userid=u.userid LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE 1=1 " . $user_cond . " LIMIT 1";
        $outof = 0;
        if (count($user_arr) > 0) {
            $user_count_arr = $parent->getQueryValue($get_user_count_str);
            $outof = (count($user_count_arr) > 0) ? $user_count_arr[0]->user_count : '0';
            foreach ($user_arr as $mkey => $res_user) {
                $user_arr[$mkey]->outof = $outof;
            }
        } else {
            $user_arr = array();
        }
        //GET COUNT
        $total = $outof;

        //LOG
        $logstr = 'SALES LEADERBOARD REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $user_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'qry' => $get_user_str, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// ASSESSMENT //////////////////////////////////////// */
    private function newassessmentleaderboardreport($parent)
    {
        //assessment/sales/{{year}}/{{month}}
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        globalfunc::checkParamCount($parent, 2);

        //DATE CONDITION
        //$start_date="2018-".date('m',strtotime(CUR_DATE))."-01";
        $start_date = date('Y-m', strtotime(CUR_DATE)) . "-01";
        $end_date = date('Y-m-t', strtotime(CUR_DATE));
        $date_cond = " AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59'";

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";
        switch ($type) {
            case "zm":
                if ($parent->current_user_role == '3') {
                    $REQUEST_KEYS = array('zmemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["zmemail"]);
                    if ($emailid != 'all') {
                        $user_cond .= " AND d.zm_email='" . $emailid . "'";
                    } else {
                        $user_cond .= "";
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "rm":
                if ($parent->current_user_role < '7') {
                    if ($parent->current_user_role == '5') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                        $get_trainer_str = "SELECT h.* FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $zone_cond .= (count($trainer_arr) > 0) ? " d.zone='" . $trainer_arr[0]->zone . "'" : " d.zone='0'";
                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            $user_cond .= " AND " . $zone_cond;
                        } else {
                            $user_cond .= " AND d.rm_email='" . $emailid . "'  AND " . $zone_cond . "";
                        }
                    } else {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                        $emailid = escape_str($parent->_request["rmemail"]);
                        if ($emailid == 'all') {
                            $REQUEST_KEYS = array('zmemail' => 'string');
                            globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

                            $emailid = escape_str($parent->_request["zmemail"]);
                            $user_cond .= " AND d.zm_email='" . $emailid . "'";
                        } else {
                            //ZM EMAIL
                            $zmemail = escape_str($parent->_request["zmemail"]);
                            $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND d.zm_email='" . $zmemail . "'" : '';
                            $user_cond .= " AND d.rm_email='" . $emailid . "' " . $zmcond;
                        }
                    }
                } else {
                    $parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                }
                break;

            case "am":
                if ($parent->current_user_role == '14') {
                    $dealer_code_cond = " d.dealer_code='" . $parent->current_user_data->dealer_code . "'";
                } else {
                    $REQUEST_KEYS = array('amemail' => 'string');
                    globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                    $emailid = escape_str($parent->_request["amemail"]);
                    if ($emailid == 'all') {
                        $REQUEST_KEYS = array('rmemail' => 'string');
                        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
                        $emailid = escape_str($parent->_request["rmemail"]);
                        $dealer_code_cond = " d.rm_email='" . $emailid . "'";

                    } else {
                        $dealer_code_cond = "  d.am_email='" . $emailid . "'";
                    }
                    if ($parent->current_user_role != '5') {
                        //ZM EMAIL
                        $zmemail = escape_str($parent->_request["zmemail"]);
                        $zmcond = ($zmemail != 'all' && $zmemail != '') ? " AND d.zm_email='" . $zmemail . "'" : '';
                        $dealer_code_cond .= $zmcond;
                    }
                    //RM EMAIL
                    $rmemail = escape_str($parent->_request["rmemail"]);
                    $rmcond = ($rmemail != 'all' && $rmemail != '') ? " AND d.rm_email='" . $rmemail . "'" : '';
                    $dealer_code_cond .= $rmcond;
                    //TRAINER
                    if ($parent->current_user_role == '5') {
                        $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                        $trainer_arr = $parent->getQueryValue($get_trainer_str);
                        $dealer_code_cond .= (count($trainer_arr) > 0) ? "AND d.zone='" . $trainer_arr[0]->zone . "'" : "AND d.zone='0'";
                    }
                }
                $user_cond .= "AND " . $dealer_code_cond . "";
                break;
            default:$parent->response(array('response' => 'failed', 'message' => 'Sorry No access'), 401);
                break;
        }

        $join_cond = 'JOIN ' . DMS_DEALER . ' as d ON d.dealer_code=u.dealer_code ';
        $new_cond = 'AND a.user_type=0 ';

        //GET ALL ASSESSMENT LIST WHICH PUBLISHED
        $assessment_str = "SELECT a.* FROM `" . TABLE_ASSESSMENT . "` as a  WHERE  a.status='1' AND a.atype='0' AND a.assettypeid='1' " . $date_cond . $new_cond;
        $assessment_arr = $parent->getQueryValue($assessment_str);
        //ASSESSMENT COUNT
        $assessment_count = (count($assessment_arr) > 0) ? count($assessment_arr) : '0';

        $data_arr = array();
        if (count($assessment_arr) > 0) {
            foreach ($assessment_arr as $res_assess) {
                $assessmentid_arr[] = $res_assess->assessmentid;
            }

            //GET ALL 20 USER RANK
            //$parent->executeQuery("SET @rownum := 0");
            $get_user_rank_str = "SELECT SUM(highscore)as user_score,u.userid,COALESCE(ar.total_time,'0')as total_time,MAX(au.modified_on) as last_modified,u.dealer_code,u.role,d.*  FROM " . TABLE_USER . " as u LEFT JOIN " . DMS_EMPLOYEE . " e  ON u.smpin=e.smpin JOIN (SELECT * FROM  " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND highscorearid!=0 ) as au ON u.userid=au.userid  LEFT JOIN (SELECT SUM(time_taken)as total_time,assessmentid,userid FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") GROUP BY userid )as ar ON u.userid=ar.userid " . $join_cond . "  WHERE  u.role>'7' AND  u.role<14 AND  u.is_deleted=0 AND e.is_current='1' " . $user_cond . " GROUP BY u.userid ORDER BY user_score DESC,ar.total_time ASC,last_modified ASC,u.userid ASC ";
            $get_user_rank_arr = $parent->getQueryValue($get_user_rank_str);
            if ($get_user_rank_arr) {
                foreach ($get_user_rank_arr as $res_user) {
                    $user_data_arr = new stdClass();
                    $get_time_str = "SELECT * FROM " . TABLE_ASSESSMENTRESULT . " WHERE assessmentid IN (" . @implode(',', $assessmentid_arr) . ") AND userid='" . $res_user->userid . "'";
                    $get_time_arr = $parent->getQueryValue($get_time_str);

                    $user_data_arr->user = projectfunc::getuserdata($parent, $res_user->userid);
                    $user_data_arr->rank = '0';
                    $user_data_arr->tot_user_score = (count($get_time_arr) > 0) ? $res_user->user_score : '-';
                    $user_data_arr->percentage_score = (count($get_time_arr) > 0) ? '0' : '-';

                    $user_data_arr->total_time = $res_user->total_time;
                    $user_data_arr->last_time = (count($get_time_arr) > 0) ? $res_user->last_modified : '-';

                    $user_cond = array();
                    //GET EACH USER COND
                    $getuser_data = projectfunc::getuserdata($parent, $res_user->userid);
//                    if($getuser_data->role)
                    //                    {
                    //                        $user_cond[]=" (a.filter_role LIKE '%".$getuser_data->role."%' OR a.filter_role='')";
                    //                    }
                    if ($getuser_data->zone) {
                        $user_cond[] = " (a.filter_zone LIKE '%" . $getuser_data->zone . "%' OR a.filter_zone='')";
                    }
                    if ($getuser_data->city) {
                        $user_cond[] = " (a.filter_region LIKE '%" . $getuser_data->city . "%' OR a.filter_region='')";
                    }
                    if ($getuser_data->dealer_code) {
                        $user_cond[] = " (a.filter_dealer LIKE '%" . $getuser_data->dealer_code . "%'  OR a.filter_dealer='')";
                    }
                    $assess_user_cond = " AND " . @implode(' AND ', $user_cond);

                    $count_assessment_str = "SELECT COUNT(a.assessmentid) as acount FROM `" . TABLE_ASSESSMENT . "` as a  WHERE a.status='1' AND a.atype='0' AND a.assettypeid='1'  AND a.publisheddate>='" . $start_date . " 00:00:00'  AND a.publisheddate<='" . $end_date . " 23:59:59' AND a.enddate>='" . $user_data_arr->user->user_created_on . "' AND  assessmentid IN (" . @implode(',', $assessmentid_arr) . ") " . $assess_user_cond . $new_cond . " LIMIT 1";
                    $count_assessment_arr = $parent->getQueryValue($count_assessment_str);
                    $user_data_arr->percentage_score = (count($assessment_arr) > 0) ? round($res_user->user_score / $count_assessment_arr[0]->acount) : '0';
                    $user_data_arr->percentage = $user_data_arr->percentage_score;

                    if ((($assessment_count / $count_assessment_arr[0]->acount) * 100) >= MIN_ASSESSMENT_PERCENT) {
                        $data_arr[] = $user_data_arr;
                    }
                }
            }

            if (count($data_arr) > 0) {
                $outof = count($data_arr);
                array_multisort(array_column($data_arr, 'percentage_score'), SORT_DESC, array_column($rank_arr, 'total_time'), SORT_ASC, $rank_arr);
                $rank = 1;
                foreach ($data_arr as $key => $res) {
                    $data_arr[$key]->rank = $rank;
                    $data_arr[$key]->outof = $outof;
                    $rank++;
                }
            }

        } else {
            /*
            $cur_data_arr=new stdClass();
            $udata=projectfunc::getuserdata($parent,$parent->current_user_id);
            $cur_data_arr->user=$udata;
            foreach($udata as $key=>$res)
            {
            $cur_data_arr->$key=$res;
            }

            $cur_data_arr->rank='-';
            $cur_data_arr->tot_user_score='-';
            $cur_data_arr->percentage_score='-';
            $cur_data_arr->percentage=$cur_data_arr->percentage_score;
            $cur_data_arr->total_time='0';
            $cur_data_arr->last_time='-';
             */
            $get_count_arr = array();
        }

        $total_count = count($data_arr);
        /*if(count($data_arr)>0)
        {
        $temp=array_chunk($data_arr,20);
        $data_arr=$temp[0];
        }
         */

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

    /* /////////////////////////////// ASV ASSESSMENT REPORT //////////////////////////////////////////////// */
    private function asmassessmentreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3', '4', '5', '6'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $assess_str = "SELECT assessmentid,pass_score FROM " . TABLE_ASSESSMENT . "  WHERE assessmentid='" . $assessmentid . "'  LIMIT 1";
        $assess_arr = $parent->getQueryValue($assess_str);
        if (!(count($assess_arr) > 0)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $pass_score = $assess_arr[0]->pass_score;

        $user_cond = "";
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $zm_email = escape_str($parent->_request["zmemail"]);
        $rm_email = escape_str($parent->_request["rmemail"]);
        //$am_email = escape_str($parent->_request["amemail"]);

        if (($rm_email != 'all' && $rm_email != '') || ($zm_email != 'all' && $zm_email != '')) {
            $mcond = '';
            //$mcond=($am_email!='all' && $am_email!='')?" AND am_email='".$am_email."'":'';
            $mcond .= ($rm_email != 'all' && $rm_email != '') ? " AND rm_email='" . $rm_email . "'" : '';
            if ($parent->current_user_role != '5') {
                $mcond .= ($zm_email != 'all' && $zm_email != '') ? " AND zm_email='" . $zm_email . "'" : '';
            }
            if ($parent->current_user_role == '5') {
                $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $mcond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
            }

            //MANAGER
            $query_all_amarr = $parent->selectQuery(DMS_DEALER, "`dealer_code`,am_email ", " status='1' AND is_deleted='0' " . $mcond . " GROUP BY am_email", "");
            $emailid_arr = array();
            if ($query_all_amarr['nr'] > 0) {
                foreach ($query_all_amarr['result'] as $res) {
                    $emailid_arr[] = "'" . $res->am_email . "'";
                }
                $user_cond .= " AND u.emailid IN (" . implode(',', $emailid_arr) . ")";
            } else {
                $user_cond .= " AND u.emailid IN ('')";
            }
        } else {
            //PAN
            $user_cond = '';
            if ($parent->current_user_role == '5') {
                $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $mcond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
                //$user_cond=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE is_deleted='0' ".$mcond.")";
                $query_all_amarr = $parent->selectQuery(DMS_DEALER, "`dealer_code`,am_email ", " status='1' AND is_deleted='0' " . $mcond . " GROUP BY am_email", "");
                $emailid_arr = array();
                if ($query_all_amarr['nr'] > 0) {
                    foreach ($query_all_amarr['result'] as $res) {
                        $emailid_arr[] = "'" . $res->am_email . "'";
                    }
                    $user_cond .= " AND u.emailid IN (" . implode(',', $emailid_arr) . ")";
                } else {
                    $user_cond .= " AND u.emailid IN ('')";
                }
            }
        }

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[1]);
        //SORT
        $order_by_cond = "ORDER BY u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //0-Score
            //1-Name

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY au.highscore DESC,au.modified_on ASC,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.emp_code LIKE '%" . $search_txt . "%' OR u.emailid LIKE '%" . $search_txt . "%'  )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=7 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
                $user_arr[$mkey]->is_pass = ($user_arr[$mkey]->highscore >= $pass_score) ? '1' : '0';
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=7 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'AM ASSESSMENT REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

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

    /* /////////////////////////////// RM ASSESSMENT REPORT //////////////////////////////////////////////// */
    private function rmassessmentreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3', '4', '5'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $assess_str = "SELECT assessmentid,pass_score FROM " . TABLE_ASSESSMENT . "  WHERE assessmentid='" . $assessmentid . "'  LIMIT 1";
        $assess_arr = $parent->getQueryValue($assess_str);
        if (!(count($assess_arr) > 0)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $pass_score = $assess_arr[0]->pass_score;

        $user_cond = "";
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[1]);
        $type = strtolower($qry_params[0]);

        $zm_email = escape_str($parent->_request["zmemail"]);
        //$rm_email = escape_str($parent->_request["rmemail"]);
        //$am_email = escape_str($parent->_request["amemail"]);

        if ($zm_email != 'all' && $zm_email != '') {
            $mcond = '';
            //$mcond=($am_email!='all' && $am_email!='')?" AND am_email='".$am_email."'":'';
            //$mcond.=($rm_email!='all' && $rm_email!='')?" AND rm_email='".$rm_email."'":'';
            if ($parent->current_user_role != '5') {
                $mcond .= ($zm_email != 'all' && $zm_email != '') ? " AND zm_email='" . $zm_email . "'" : '';
            }
            if ($parent->current_user_role == '5') {
                $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $mcond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
            }

            //MANAGER
            $query_all_amarr = $parent->selectQuery(DMS_DEALER, "`dealer_code`,rm_email ", " status='1' AND is_deleted='0' " . $mcond . " GROUP BY rm_email", "");
            $emailid_arr = array();
            if ($query_all_amarr['nr'] > 0) {
                foreach ($query_all_amarr['result'] as $res) {
                    $emailid_arr[] = "'" . $res->rm_email . "'";
                }
                $user_cond .= " AND u.emailid IN (" . implode(',', $emailid_arr) . ")";
            } else {
                $user_cond .= " AND u.emailid IN ('')";
            }
        } else {
            //PAN
            $user_cond = '';
            if ($parent->current_user_role == '5') {
                $get_trainer_str = "SELECT h.zone FROM " . DMS_HOUSER . " h JOIN " . TABLE_USER . " u ON u.emp_code=h.emp_code WHERE u.userid='" . $parent->current_user_id . "' AND u.role='5' LIMIT 1";
                $trainer_arr = $parent->getQueryValue($get_trainer_str);
                $mcond .= (count($trainer_arr) > 0) ? "AND zone='" . $trainer_arr[0]->zone . "'" : "AND zone='0'";
                //$user_cond=" AND u.dealer_code IN (SELECT dealer_code FROM ".DMS_DEALER." WHERE is_deleted='0' ".$mcond.")";
                $query_all_amarr = $parent->selectQuery(DMS_DEALER, "`dealer_code`,rm_email ", " status='1' AND is_deleted='0' " . $mcond . " GROUP BY rm_email", "");
                $emailid_arr = array();
                if ($query_all_amarr['nr'] > 0) {
                    foreach ($query_all_amarr['result'] as $res) {
                        $emailid_arr[] = "'" . $res->rm_email . "'";
                    }
                    $user_cond .= " AND u.emailid IN (" . implode(',', $emailid_arr) . ")";
                } else {
                    $user_cond .= " AND u.emailid IN ('')";
                }
            }
        }

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[1]);
        //SORT
        $order_by_cond = "ORDER BY u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Name
            //2-RM
            //3-ZM

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY au.highscore DESC,au.modified_on ASC,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.emp_code LIKE '%" . $search_txt . "%'   )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=6 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
                $user_arr[$mkey]->is_pass = ($user_arr[$mkey]->highscore >= $pass_score) ? '1' : '0';
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=6 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'RM ASSESSMENT REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

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

    /* /////////////////////////////// ZM ASSESSMENT REPORT //////////////////////////////////////////////// */
    private function zmassessmentreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3'));

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

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $assess_str = "SELECT assessmentid,pass_score FROM " . TABLE_ASSESSMENT . "  WHERE assessmentid='" . $assessmentid . "'  LIMIT 1";
        $assess_arr = $parent->getQueryValue($assess_str);
        if (!(count($assess_arr) > 0)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $pass_score = $assess_arr[0]->pass_score;

        $user_cond = "";
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);
        //SORT
        $order_by_cond = "ORDER BY u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Name
            //2-RM
            //3-ZM

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY au.highscore DESC,au.modified_on ASC,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.emp_code LIKE '%" . $search_txt . "%'   )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=4 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
                $user_arr[$mkey]->is_pass = ($user_arr[$mkey]->highscore >= $pass_score) ? '1' : '0';
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=4 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'ZM ASSESSMENT REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

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

    /* /////////////////////////////// TRAINER  ASSESSMENT REPORT //////////////////////////////////////////////// */
    private function trainerassessmentreport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('3'));

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

        $role = $parent->current_user_role;
        $userdata = projectfunc::getuserdata($parent, $parent->current_user_id);

        //FIELDS VALIDATION
        $REQUEST_KEYS = array('assessmentid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);
        $assessmentid = escape_str($parent->_request["assessmentid"]);

        $assess_str = "SELECT assessmentid,pass_score FROM " . TABLE_ASSESSMENT . "  WHERE assessmentid='" . $assessmentid . "'  LIMIT 1";
        $assess_arr = $parent->getQueryValue($assess_str);
        if (!(count($assess_arr) > 0)) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error1"]), 406);
        }

        $pass_score = $assess_arr[0]->pass_score;

        $user_cond = "";
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $filter_arr = globalfunc::getFilterValues($parent, $parent->params[0]);
        //SORT
        $order_by_cond = "ORDER BY u.fname ASC ";
        if (isset($filter_arr) && isset($filter_arr['sort'])) {
            //1-Name
            //2-RM
            //3-ZM

            switch ($filter_arr['sort']) {
                case '1':$order_by_cond = "ORDER BY u.fname ASC ";
                    break;
                default:$order_by_cond = "ORDER BY au.highscore DESC,au.modified_on ASC,u.fname ASC ";
                    break;

            }
        }

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' OR u.emp_code LIKE '%" . $search_txt . "%'   )";
        }

        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=5 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $mkey => $res_user) {
                $exam_highscore_str = "SELECT  * FROM " . TABLE_ASSESSMENT_USER . "  WHERE assessmentid='" . $assessmentid . "' AND userid='" . $res_user->userid . "' LIMIT 1";
                $exam_highscore_arr = $parent->getQueryValue($exam_highscore_str);
                $user_arr[$mkey]->highscore = (count($exam_highscore_arr) > 0) ? $exam_highscore_arr[0]->highscore : '0';
                $user_arr[$mkey]->is_pass = ($user_arr[$mkey]->highscore >= $pass_score) ? '1' : '0';
            }
        }

        //GET COUNT
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u JOIN " . TABLE_ASSESSMENT_USER . " as au ON u.userid=au.userid WHERE u.status='1' AND u.is_deleted='0' AND u.role=4 AND au.assessmentid='" . $assessmentid . "' " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

        //LOG
        $logstr = 'ZM ASSESSMENT REPORT';
        globalfunc::insertUserLog($parent, $logstr);
        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;

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

    /* /////////////////////////////// NEW SALES TAREGT REPORT //////////////////////////////////////////////// */
    private function newsalestargetreport($parent)
    {
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// managersalestargetreport //////////////////////////////////////////////// */
    private function managersalestargetreport($parent)
    {
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// DEALER LIST //////////////////////////////////////////////// */
    private function dealerlist($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7'));
        $am_email = $parent->current_user_data->emailid;

        $query_str = "SELECT dealer_code,dealer_name FROM " . DMS_DEALER . " WHERE status='1' AND is_deleted='0' and am_email='" . $am_email . "'";
        $data_arr = $parent->getQueryValue($query_str);
        $data_arr = (count($data_arr) > 0) ? $data_arr : array();

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

    /* /////////////////////////////// USER LIST //////////////////////////////////////////////// */
    private function userlist($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7', '14'));

        $userid = $parent->current_user_id;
        $role = $parent->current_user_role;
        $usercond = '';
        if ($role == 7) //AM
        {
            $dealer_code = escape_str($parent->_request["dealer_code"]);
            if ($dealer_code != '') {
                $usercond = " and u.dealer_code='" . $dealer_code . "'";
            } else {

                $am_email = $parent->current_user_data->emailid;
                $usercond = " and d.am_email='" . $am_email . "'";
            }
        } else //DEALER
        {
            $dealer_code = $parent->current_user_data->dealer_code;
            $usercond = "and u.dealer_code='" . $dealer_code . "'";
        }
        $query_str = "SELECT u.status,u.userid,u.fname,u.lname,u.smpin,u.dealer_code,d.dealer_name,u.segment,CASE WHEN u.segment=0 THEN 'Student Learner' WHEN u.segment=1 THEN 'Parents/Guardian' WHEN u.segment=2 THEN 'Instructor' END as segment_str,CASE WHEN  u.status=1 THEN '1' ELSE '0' END as is_active FROM " . TABLE_USER . " u LEFT JOIN " . DMS_EMPLOYEE . " e ON u.smpin=e.smpin LEFT JOIN " . DMS_DEALER . " d ON u.dealer_code=d.dealer_code WHERE e.is_current='1' AND u.is_deleted='0' and u.role>7 AND u.role<14 " . $usercond . " ORDER BY  u.dealer_code ASC,u.fname ASC,u.userid ASC";
        $data_arr = $parent->getQueryValue($query_str);
        $data_arr = (count($data_arr) > 0) ? $data_arr : array();

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

    /* /////////////////////////////// USER STATUS UPDATE //////////////////////////////////////////////// */
    private function userstatusupdate($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));
        projectfunc::authorizedRole($parent, array('7', '14'));

        $REQUEST_KEYS = array('userid' => 'number', 'status' => "number");
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $userid = escape_str($parent->_request["userid"]);
        $status = (escape_str($parent->_request["status"]) == 1) ? 1 : 2;
        $remark = escape_str($parent->_request["remark"]);

        $cond_str = ($status == 2) ? ",inactivated_on='" . NOW . "'" : "";
        $update_qry = "UPDATE " . TABLE_USER . " SET status='" . $status . "' " . $cond_str . " , modified_on='" . NOW . "' WHERE userid='" . $userid . "'";
        $parent->executeQuery($update_qry);

        $insert_qry = "INSERT INTO " . TABLE_USER_STATUS_HISTORY . " ( `userid`, `action_user`,status, `remarks`, `created_on`) VALUES ('" . $userid . "', '" . $parent->current_user_id . "','" . $status . "', '" . $remark . "','" . NOW . "')";
        $parent->executeQuery($insert_qry);

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

    // ZM Course Report
    private function zmcoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

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

        //SORT
        $order_by_cond = "ORDER BY u.fname ASC,u.lname ASC,u.userid ASC ";

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' )";
        }

        //$user_cond.=" AND e.is_current='1' ";
        // u.status='1' AND
        $get_user_str = "SELECT SQL_CALC_FOUND_ROWS u.userid,u.fname,u.lname,u.emp_code,u.mobileno,u.emailid FROM " . TABLE_USER . " u JOIN " . DMS_DEALER . " d ON u.emailid=d.zm_email  WHERE u.is_deleted='0' AND u.role=4 " . $user_cond . "  GROUP BY u.userid  " . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        $get_count_str = "SELECT FOUND_ROWS() as ucount";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::managerCourseCompleteStatus($parent, $res->userid, 4);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        // u.status='1' AND

        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    // TRAINER Course Report
    private function trainercoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

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

        //SORT
        $order_by_cond = "ORDER BY u.fname ASC,u.lname ASC,u.userid ASC ";

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' )";
        }

        //$user_cond.=" AND e.is_current='1' ";
        // u.status='1' AND
        $get_user_str = "SELECT u.userid,u.fname,u.lname,u.emp_code,u.mobileno,u.emailid FROM " . TABLE_USER . " u  WHERE u.is_deleted='0' AND u.role=5 " . $user_cond . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);

        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::managerCourseCompleteStatus($parent, $res->userid, 5);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

        //GET COUNT
        // u.status='1' AND
        $get_count_str = "SELECT COUNT(u.userid)as ucount FROM " . TABLE_USER . " u WHERE u.is_deleted='0' AND u.role=5 " . $user_cond . " LIMIT 1";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        $total = (count($get_count_arr) > 0) ? $get_count_arr[0]->ucount : 0;

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

    // RM Course Report
    private function rmcoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY u.fname ASC,u.lname ASC,u.userid ASC ";

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' )";
        }

        //$user_cond.=" AND e.is_current='1' ";
        // u.status='1' AND
        $get_user_str = "SELECT SQL_CALC_FOUND_ROWS u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . DMS_DEALER . " d ON u.emailid=d.rm_email  WHERE u.is_deleted='0' AND u.role=6 " . $user_cond . " GROUP BY u.userid  " . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);
        $get_count_str = "SELECT FOUND_ROWS() as ucount";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::managerCourseCompleteStatus($parent, $res->userid, 6);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

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

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

    // AM Course Report
    private function amcoursereport($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $dealer_code_cond = '';

        $qry_params = explode("?", $parent->params[0]);
        $type = strtolower($qry_params[0]);

        $user_cond = "";

        //MANAGER WISE DEALER CONDITION
        $dealer_cond_arr = $this->getmanagerconditon_arr($parent);

        if (count($dealer_cond_arr) > 0) {
            //APPEND prefix
            array_walk($dealer_cond_arr, function (&$value, $key) {$value = 'd.' . $value;});
            $user_cond .= " AND " . @implode(" AND ", $dealer_cond_arr);
        }

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

        //SORT
        $order_by_cond = "ORDER BY u.fname ASC,u.lname ASC,u.userid ASC ";

        if (isset($parent->_request["search"]) && $parent->_request["search"] != '') {
            $search_txt = escape_str($parent->_request["search"]);
            $user_cond .= " AND (u.fname LIKE '%" . $search_txt . "%' OR u.lname LIKE '%" . $search_txt . "%' )";
        }

        //$user_cond.=" AND e.is_current='1' ";
        // u.status='1' AND
        $get_user_str = "SELECT SQL_CALC_FOUND_ROWS u.userid,u.fname,u.lname,u.emp_code,u.emailid FROM " . TABLE_USER . " u JOIN " . DMS_DEALER . " d ON u.emailid=d.am_email  WHERE u.is_deleted='0' AND u.role=7 " . $user_cond . " GROUP BY u.userid  " . $order_by_cond . $limit_cond;
        $user_arr = $parent->getQueryValue($get_user_str);
        $get_count_str = "SELECT FOUND_ROWS() as ucount";
        $get_count_arr = $parent->getQueryValue($get_count_str);
        if (count($user_arr) > 0) {
            foreach ($user_arr as $ukey => $res) {
                $content_arr = projectfunc::managerCourseCompleteStatus($parent, $res->userid, 7);
                $user_arr[$ukey]->total_content = $content_arr['total'];
                $user_arr[$ukey]->completed_content = $content_arr['completed'];
                $user_arr[$ukey]->percentage = ($content_arr['total'] > 0) ? round(($content_arr['completed'] / $content_arr['total']) * 100) : '0';
            }
        } else {
            $user_arr = array();
        }

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

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