<?php

class MysqlJson {
    /*
     * Cette classe dÃ©finit toutes les propriÃ©tÃ©s et methodes pour l'intÃ©raction des services avec les base de donnÃ©es
     * 
     */

    public $dbHost;
    public $dbUser;
    public $dbPassword;
    public $dbDatabase;
    public $dbTnsnames;
    public $svaLog;

    /*     * ********* Connection au base de donnÃ©es Oracle **************** */

    function __construct($dbHost, $dbUser, $dbPassword, $dbDatabase, $dbTnsnames, $svaLog) {

        $this->dbHost = $dbHost;
        $this->dbUser = $dbUser;
        $this->dbPassword = $dbPassword;
        $this->dbTnsnames = $dbTnsnames;
        $this->dbDatabase = $dbDatabase;
        $this->svaLog = $svaLog;
    }

    private function connectMysqlDatabase() {
        $dbAccess['dbConnection'] = false;
        $dbAccess['errorMessage'] = "";

        if ($this->dbUser == "")
            $dbAccess['errorCode'] = 1000;
        /// elseif($this->dbPassword=="") $dbAccess['errorCode']=1001;
        elseif ($this->dbHost == "")
            $dbAccess['errorCode'] = 1002;
        else
            $dbAccess['errorCode'] = 0;


        //echo $this->dbDatabase.$this->dbHost.$this->dbPassword.$this->dbUser;

        if ($dbAccess['errorCode'] == 0) {
            // echo "$this->dbUser,$this->dbPassword,$this->dbTnsnames";

            $Compt = 0;
            $dbAccess['dbConnection'] = mysql_connect($this->dbHost, $this->dbUser, $this->dbPassword) or die(mysql_error());
            //echo $dbAccess['dbConnection']; 
            //$dbAccess['dbConnection'] =mysql_connect($this->dbHost,$this->dbUser,$this->dbPassword) or die (mysql_error());
            //     echo $dbAccess['dbConnection']; 

            while (!$dbAccess['dbConnection'] && $Compt <= 5) {

                $dbAccess['dbConnection'] = @mysql_connect($this->dbHost, $this->dbUser, $this->dbPassword);
                $Compt++;
            }

            if (!$dbAccess['dbConnection']) {
                $data = oci_error();
                $dbAccess['errorMessage'] = $data['message'];
            } else {

                @mysql_select_db($this->dbDatabase, $dbAccess['dbConnection']);
                mysql_set_charset("utf8");
            }
        }


        return $dbAccess;
    }

    /*     * *********************************************Obtention de la connexion Mysql**************************************************************** */

    public function getMysqlConnection() {

        $dbAccess = $this->connectMysqlDatabase();
        return $dbAccess;
    }

    /*     * ****************** Fermeture de la connexion de la connexion Mysql ********************** */

    public function closeMysqlConnection($dbConnection) {

        if ($dbConnection)
            mysql_close($dbConnection);
    }

    public function getManagerDetails($login) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getManagerDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT *
                FROM master_users_tab 
                WHERE user_name_v ='$login'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }
    
    
    public function getUserDetailById($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserDetailById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT *
                FROM master_users_tab 
                WHERE user_id_n ='$id'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
           // $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }
    

    public function getPlatformsAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getPlatformsAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                    select * from master_platforms_tab

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    private function mysqlRessourceJson($ressource) {
        $work = null;
        $numfield = mysql_num_fields($ressource);
        $numrows = mysql_num_rows($ressource);
        $fieldArray = null;

        for ($i = 0; $i < $numfield; $i++) {
            $fieldArray [$i] = mysql_field_name($ressource, $i);
        }

        $j = 0;
        while ($data = mysql_fetch_array($ressource)) {

            for ($i = 0; $i < $numfield; $i++) {

                $work[$j][$fieldArray[$i]] = $data[$i];
            }

            $j++;
        }


        return $work;
    }

    public function getModulesByPlatformId($platformId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getModulesByPlatformId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                    select b.* 
                    from   master_platforms_tab a
                        , master_modules_tab b 
                    where a.platform_id_n = b.platform_id_n
                    and a.platform_id_n = '$platformId' 

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getMenuByModuleIdAndProfile($moduleId, $profileId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuByModuleIdAndProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select * from  menu_builder_tab where module_id_n='$moduleId' and char_field_1 like '%$profileId%' order by menu_order_n asc

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getMenuDesc($menuId, $lang) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuDesc()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select * from menu_builder_tab where menu_id_n='$menuId' and language_id_n='$lang'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getMenuDetail($menuId, $lang, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "   select distinct             c.topmenu_id_n
                                                            ,c.language_id_n
							   ,c.menu_desc_v 
							   ,c.menu_name_v 
							   ,c.page_link_v 
                                                           ,c.char_field_1
						from  	 role_details_tab  n
							 , menu_details_tab c
						where c.topmenu_id_n = n.object_id_n 
						and  n.role_id_n in (select distinct role_id_n from user_roles_tab us where us.user_id_n=$userId)
						and n.menu_id_n = $menuId
                                               order by 1 asc"
            ;

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadQosParams() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadQosParams()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select * from iad_qos_tab

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function updateQosParams($qosCode, $qosValue) {
        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateQosParams()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE iad_qos_tab
                SET qos_value_v='$qosValue'
                WHERE qos_code_v='$qosCode'
                ";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $status;
    }

    public function getIadHomeNetworkInfo() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadHomeNetworkInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select * from iad_home_network_tab limit 1

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $data;
    }

    public function getIadNDCList() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadNDCList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select * from iad_home_ndcs_tab

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function updateIadHomeNwDtls($nwName, $mcc, $mnc, $cc) {
        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateIadHomeNwDtls()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE iad_home_network_tab
                SET mcc_v='$mcc'
                   ,mnc_v='$mnc'
                   ,cc_v='$cc'
                   ,network_name_v ='$nwName'
                WHERE network_id_n='1'
                ";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $status;
    }

    public function updateIadNdc($id, $ndc) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateIadNdc()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update iad_home_ndcs_tab  set ndc_v='$ndc' where network_id_n='$id'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function deleteNdc($id) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteNdc()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "delete from iad_home_ndcs_tab where  network_id_n='$id'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function addNDC($ndc) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec addNDC()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO iad_home_ndcs_tab  VALUES (NULL,'$ndc','0')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getIadSenderListAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadSenderListAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                    
                  select    sender_id_n
                            , creation_date_d
                            , short_code_v
                            , status_n 
                    FROM iad_senders_tab
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function shortcodeUpdate($rowId, $code) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec shortcodeUpdate()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update iad_senders_tab  set short_code_v='$code' where sender_id_n='$rowId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function deleteShortCode($shortcodeId) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteShortCode()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "delete from iad_senders_tab where  sender_id_n='$shortcodeId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function addShortCode($shortcode) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec addShortCode()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO iad_senders_tab  VALUES (NULL, now(),'$shortcode','0')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getIadWhiteListAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadWhiteListAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                        select detail_id_n, phone_number_v from group_details_tab where group_id_n='1';
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function updatePhoneNumber($rowId, $number) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updatePhoneNumber()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update group_details_tab  set phone_number_v='$number' where detail_id_n='$rowId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function deletePhoneNumber($rowId) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteNdc()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "delete from group_details_tab where  detail_id_n='$rowId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function addPhoneNumber($phoneNumber) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec addPhoneNumber()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO group_details_tab (detail_id_n, group_id_n, creation_date_d,phone_number_v)  VALUES (NULL,'1',now(),'$phoneNumber' )";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getRulesList($option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getRulesList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            $sqlQuery = "
                    
                  select a.*, b.description_v status_desc 
                  from iad_master_rules_tab a, master_status_tab b
                  where a.status_n = b.status_n
                  $limitQuery

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getApplicationListByOwner($ownerId, $profileId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getApplicationListByOwner()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            if ($profileId == 1) {


                $sqlQuery = "
                    
                  select a.*, b.description_v status_desc 
                  from iad_apps_rule_tab a, master_status_tab b
                  where a.status_n = b.status_n
                  $limitQuery

                ";
            } else {

                $sqlQuery = "
                    
                  select a.*, b.description_v status_desc 
                  from iad_apps_rule_tab a, master_status_tab b
                  where a.status_n = b.status_n
                  and a.owner_id_n = '$ownerId'
                  $limitQuery

                ";
            }


            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getApplicationById($appId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getApplicationById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                  select *
                  from iad_apps_rule_tab 
                  where app_id_n='$appId'

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $data;
    }

    public function getRulesById($ruleId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getRulesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                  select a.*, b.description_v status_desc 
                  from iad_master_rules_tab a, master_status_tab b
                  where a.status_n = b.status_n
                  and a.rule_id_n='$ruleId'

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $data;
    }

    public function getRuleVariableMapping($ruleId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getRuleVariableMapping()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                  select variable_name_v, var_type_n from iad_rulervar_mapping_tab where rule_id_n='$ruleId';

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function iadUpdateApplication($appName, $appDesc, $ruleId, $ruleData, $appId) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec iadCreateApplication()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE iad_apps_rule_tab
                             SET  app_name_v='$appName',
                                  app_desc_v='$appDesc',
                                  rule_data_v='$ruleData',
                                  rule_id_n = '$ruleId'
                            where app_id_n ='$appId'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getApplicationCampaignsCount($appId) {

        $dbAccess = $this->getMysqlConnection();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getApplicationCampaignsCount()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select count(1) total from master_campaigns_tab where appid='$appId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            $data = mysql_fetch_array($queryResult);
            $total = $data['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $total;
    }

    public function deleteIadApplication($rowId) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteIadApplication()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "delete from iad_apps_rule_tab where  app_id_n='$rowId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function iadCreateApplication($appName, $appDesc, $ruleId, $ruleData, $ownerId, $statusN) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec iadCreateApplication()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO iad_apps_rule_tab  VALUES (NULL,now(),'$appName','$ruleData','$appDesc','$ownerId','$ruleId','$statusN')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getOfferList($option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getOfferList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            $sqlQuery = "
                    
                   select   offer_id_n
                            , DATE_FORMAT(creation_date_d, '%d/%m/%Y %H:%i:%s') eventDateTime 
                            , offer_name_v
                            , offer_type_n
                            , owner_id_n
                            , offer_desc_v
                            , short_code_v
                            , keyword_v
                            , sms_charged_v
                            , service_price_v
                            , char_field_1
                            , char_field_2
                            , char_field_3
                            , char_field_4
                            , char_field_5
                            , b.description_v status_desc
                    from iad_master_offers_tab a,  master_status_tab b
                    where a.status_n = b.status_n
                    ORDER BY creation_date_d DESC
                    $limitQuery

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getOfferListById($offerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getOfferListById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select   offer_id_n
                            , DATE_FORMAT(creation_date_d, '%d/%m/%Y %H:%i:%s') eventDateTime 
                            , offer_name_v
                            , offer_type_n
                            , owner_id_n
                            , offer_desc_v
                            , short_code_v
                            , keyword_v
                            , sms_charged_v
                            , service_price_v
                            , char_field_1
                            , char_field_2
                            , char_field_3
                            , char_field_4
                            , char_field_5
                            , status_n 
                    from iad_master_offers_tab
                    where offer_id_n ='$offerId'

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $data;
    }

    public function iadUpdateOffer($offerName, $offerDesc, $offerType, $shortCode, $keyword, $price, $offerId) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec iadUpdateOffer()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE iad_master_offers_tab
                             SET  offer_name_v='$offerName',
                                  offer_type_n='$offerType',
                                  offer_desc_v='$offerDesc',
                                  short_code_v = '$shortCode',
                                  keyword_v = '$keyword',
                                  service_price_v = '$price'
                            where offer_id_n ='$offerId'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function iadCreateOffer($offerName, $offerDesc, $offerType, $shortCode, $ownerId, $keyword, $charged, $price, $field, $statusN) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec iadCreateOffer()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO iad_master_offers_tab  VALUES (NULL,now(),'$offerName','$offerType','$offerDesc','$ownerId','$shortCode','$keyword','$charged','$price','$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$statusN')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function deleteOffer($offerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteOffer()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                   delete from   iad_master_offers_tab  where offer_id_n='$offerId'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $sqlResult;
    }

    public function getCampaignList($profileId, $ownerId, $startLimit, $maxElement, $option) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCampaignList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitSql = "";
            $profileSql = "";
            $userSql = "";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement   ";
            if ($profileId == 2)
                $profileSql = "AND b.profile_id_n='$profileId' ";
            if (isset($ownerId) && $profileId == 2)
                $userSql = "AND b.user_id_n='$ownerId' ";



            $sqlQuery = " 
                    
                      select    campaign_id_n
                                , a.creation_date_d
                                , campaign_name_v
                                , date_format(start_date_d,'%d/%m/%Y') start_date_d 
                                , date_format(start_time_d,'%H:%i:%s') start_time_d 
                                , owner_id_n
                                , sender_id_n
                                , appid
                                , c.description_v status_desc
                                , b.user_name_v
                                , c.status_n
                                , a.char_field_2  totalElement
                                , a.char_field_3 totalCalled
                            from master_campaigns_tab a,
                                master_users_tab b,
                                master_status_tab c
                            where a.owner_id_n = b.user_id_n
                            and a.status_n = c.status_n
                            $userSql
                            $profileSql
                            ORDER BY a.creation_date_d DESC
                            $limitSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getApplicationsListAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getApplicationsListAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                    
                  select app_id_n
                        , creation_date_d
                        , app_name_v
                        , rule_data_v
                        , app_desc_v
                        , owner_id_n
                        , rule_id_n
                        , status_n  
                    from iad_apps_rule_tab
                    ORDER BY app_id_n DESC

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function checkCampaignName($name) {
        $dbAccess = $this->getMysqlConnection();
        $totalUser = 2;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkCampaignName()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT count(1) total
                FROM master_campaigns_tab 
                WHERE campaign_name_v ='$name'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $totalUser = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $totalUser;
    }

    public function getDbConnection() {
        $dbAccess = $this->getMysqlConnection();

        return $dbAccess;
    }

    public function closeDbConnection($dbConnection) {

        $this->closeMysqlConnection($dbConnection);
    }

    public function uploadTemporaryData($session, $entity, $dbAccess) {
        // $dbAccess = $this->getMysqlConnection();   
        $id = -1;
        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec uploadTemporaryData()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO temporary_entities_tab
                VALUES (null,
                
                '$session','$entity')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id();
            // $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getGroupDetailByGroupId($groupId, $dbAccess) {

        // $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGroupDetailByGroupId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                    
                  select  detail_id_n
                            , group_id_n
                            , creation_date_d
                            , entity_name_v
                            , additionnal_info_v
                            , phone_number_v
                            , email_v
                            , char_field_1
                            , char_field_2
                            , char_field_3
                            , char_field_4
                            , char_field_5
                            , status_n 
                    from group_details_tab
                    where group_id_n='$groupId'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$this->closeMysqlConnection($dbAccess['dbConnection'])  ;
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function createCampaign($campaignName
            , $internalCode
            , $startDate
            , $startTime
            , $endDate
            , $endTime
            , $ownerId
            , $priority
            , $senderId
            , $message
            , $appId
            , $moduleId
            , $field
            , $status
    ) {

        $dbAccess = $this->getMysqlConnection();
        $id = -1;
        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec createCampaign()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                             INTO master_campaigns_tab 
                             VALUES (NULL,now(),'$campaignName','$internalCode','$startDate','$startTime','$endDate','$endTime','$ownerId','$priority','$senderId','$message','$appId','$moduleId','$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]','$field[9]','$status')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id();
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getTemporaryDataBySession($session) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTemporaryDataBySession()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                  select distinct entity_v from temporary_entities_tab where session_id_v='$session'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function processTemporaryData($session, $campaignId, $statut) {

        $dbAccess = $this->connectMysqlDatabase();
        $total = null;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec processTemporaryData()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                  
      
                INSERT INTO queues_processor_tab (item_id_n, event_datetime_d, campaign_id_n, phone_number_v, entity_v, status_n )  (select distinct null,now(),'$campaignId', entity_v,entity_v,'$statut' from temporary_entities_tab where session_id_v='$session')
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $total = mysql_affected_rows();
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function deleteTemporaryDataBySession($session) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteTemporaryDataBySession()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                  delete from   temporary_entities_tab where session_id_v='$session'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $sqlResult;
    }

    public function getSystemUserByProfile($profileId, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemUserByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($profileId == 1 || $profileId == 3) {
                $sqlQuery = "  
                 select   user_id_n
                        , user_name_v
                        , profile_id_n
                    FROM master_users_tab
                ";
            } elseif ($profileId == 2) {

                $sqlQuery = "  
                  select   user_id_n
                        , user_name_v
                        , profile_id_n
                    FROM master_users_tab
                    where user_id_n='$userId'
                ";
            }
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCampaignByProfile($profileId, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCampaignByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($profileId == 1 || $profileId == 3) {
                $sqlQuery = "  
                 select campaign_id_n, campaign_name_v, owner_id_n 
                 FROM master_campaigns_tab
                 order by campaign_id_n desc
                ";
            } elseif ($profileId == 2) {

                $sqlQuery = "  
                  select campaign_id_n, campaign_name_v, owner_id_n 
                 FROM master_campaigns_tab where owner_id_n='$userId'
                  order by campaign_id_n desc
                ";
            }
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getOfferListAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getOfferListAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                  select offer_id_n, offer_name_v FROM iad_master_offers_tab
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getStatusAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCampaignByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "  
                 select status_n, description_v FROM master_status_tab
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadDetailledStatParam($profileId, $userId, $campaignId, $startLimit, $maxElement, $startDate, $endDate, $statusId, $option) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadDetailledStatParam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";

            if ($profileId == 2)
                $profileSql = "AND d.profile_id_n='$profileId' ";
            if (($userId == -1 && $profileId == 2) || ($profileId != 2 && $userId != -1 ))
                $userSql = "AND d.user_id_n='$userId' ";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement   ";
            if ($campaignId != -1 && $campaignId != "")
                $campaignSql = " AND a.campaign_id_n = '$campaignId' ";
            if ($statusId != -1)
                $statusSql = "AND a.status_n='$statusId' ";

            $sqlQuery = "
                      
                    select  date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') DATE
                                ,a.phone_number_v MSISDN
                                ,a.duration_n DUREE
                                ,date_format(concat(b.start_date_d,\" \",b.end_date_d ),'%d/%m/%Y %H:%i:%s')  DEBUT
                                ,f.short_code_v IDENTIFIANT
                                ,e.description_v STATUT
                                ,c.app_name_v APPLICATION
                                ,b.campaign_name_v CAMPAGNE
                                ,d.user_name_v LOGIN
                        from queues_processor_tab a,
                                    master_campaigns_tab b,
                                    iad_apps_rule_tab c,
                                    master_users_tab d,
                                    master_status_tab e,
                                    iad_senders_tab f
                        where a.campaign_id_n = b.campaign_id_n
                        and b.appid = c.app_id_n
                        and b.owner_id_n = d.user_id_n
                        and e.status_n = a.status_n
                        and a.event_datetime_d>='$startDate'
                        and a.event_datetime_d <='$endDate'
                        and f.sender_id_n = b.sender_id_n
                        $profileSql
                        $userSql
                        $campaignSql
                        $statusSql
                        order by DATE  desc
                        $limitSql
                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadDetailledSubsStatParam($profileId, $userId, $campaignId, $startLimit, $maxElement, $startDate, $endDate, $offerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadDetailledStatParam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $offerSql = "";
            $campaignSql = "";

            if ($profileId == 2)
                $profileSql = "AND d.profile_id_n='$profileId' ";
            if (($userId == -1 && $profileId == 2) || ($profileId != 2 && $userId != -1 ))
                $userSql = "AND d.user_id_n='$userId' ";
            if (isset($startLimit) && isset($maxElement))
                $limitSql = "LIMIT $startLimit, $maxElement   ";
            if ($campaignId != -1 && $campaignId != "")
                $campaignSql = " AND a.campaign_id_n = '$campaignId' ";
            if ($offerId != -1)
                $offerSql = "AND a.offer_id_n='$offerId' ";

            $sqlQuery = "
                      
                    select  date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') DATE
                                ,a.telephone_v MSISDN
                                ,c.short_code_v IDENTIFIANT
                                ,c.offer_name_v OFFRE
                                ,c.keyword_v \"MOT-CLE\"
                                ,b.campaign_name_v CAMPAGNE
                                ,d.user_name_v LOGIN
                        from  subs_offer_details_tab a,
                                    master_campaigns_tab b,
                                    iad_master_offers_tab c ,
                                    master_users_tab d
                        where a.campaign_id_n = b.campaign_id_n
                        and b.owner_id_n = d.user_id_n
                        and c.offer_id_n = a.offer_id_n
                        and a.event_datetime_d>='$startDate'
                        and a.event_datetime_d <='$endDate'
                        $profileSql
                        $userSql
                        $campaignSql
                        $offerSql
                        order by DATE  desc
                        $limitSql
                        

                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadDetailledSharingStatParam($profileId, $userId, $campaignId, $startLimit, $maxElement, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadDetailledStatParam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $campaignSql = "";

            if ($profileId == 2)
                $profileSql = "AND d.profile_id_n='$profileId' ";
            if (($userId == -1 && $profileId == 2) || ($profileId != 2 && $userId != -1 ))
                $userSql = "AND d.user_id_n='$userId' ";
            if (isset($startLimit) && isset($maxElement))
                $limitSql = "LIMIT $startLimit, $maxElement   ";
            if ($campaignId != -1 && $campaignId != "")
                $campaignSql = " AND a.campaign_id_n = '$campaignId' ";

            $sqlQuery = "
                      
                    select  date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') DATE
                                ,a.a_number_v EMETTEUR
                                ,a.b_number_v DESTINATAIRE
                                ,d.user_name_v LOGIN
                                ,b.campaign_name_v CAMPAGNE
                        from  subs_sharing_details_tab a,
                                    master_campaigns_tab b,
                                    master_users_tab d
                        where a.campaign_id_n = b.campaign_id_n
                        and b.owner_id_n = d.user_id_n
                        and a.event_datetime_d>='$startDate'
                        and a.event_datetime_d <='$endDate'
                        $profileSql
                        $userSql
                        $campaignSql
                        order by DATE  desc
                        $limitSql
                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGroupDetailByGroupIdInside($groupId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGroupDetailByGroupId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                    
                  select  detail_id_n
                            , group_id_n
                            , creation_date_d
                            , entity_name_v
                            , additionnal_info_v
                            , phone_number_v
                            , email_v
                            , char_field_1
                            , char_field_2
                            , char_field_3
                            , char_field_4
                            , char_field_5
                            , status_n 
                    from group_details_tab
                    where group_id_n='$groupId'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function upldQueuesProcessor($campaignId, $phone, $entity, $statut) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec upldQueuesProcessor()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO queues_processor_tab (item_id_n, event_datetime_d, campaign_id_n, phone_number_v, entity_v, status_n ) 
                             VALUES (NULL, now(), '$campaignId','$phone','$entity','$statut')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getCurrentCampaignStatus($campaignId) {

        $dbAccess = $this->getMysqlConnection();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCurrentCampaignStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select status_n statut from master_campaigns_tab where campaign_id_n='$campaignId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            $data = mysql_fetch_array($queryResult);
            $total = $data['statut'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $total;
    }

    public function updateQueuedEventsBulk($campaignId, $newStatus, $oldStatus) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateQueuedEventsBulk()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE broadcast_queues_tab
                             SET  status_n ='$newStatus'
                            where campaign_id_n = '$campaignId'
                            and status_n='$oldStatus'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function updateCampaignStatus($campaignId, $newStatus) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateCampaignStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE master_campaigns_tab
                             SET  status_n ='$newStatus'
                            where campaign_id_n = '$campaignId'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function updateQueuedProcessordEventsBulk($campaignId, $newStatus, $oldStatus) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateQueuedProcessordEventsBulk()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE queues_processor_tab
                             SET  status_n ='$newStatus'
                            where campaign_id_n = '$campaignId'
                            and status_n in ($oldStatus)
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function getStdMenuDesc($menuId, $lang) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuDesc()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select * from std_menu_builder_tab where menu_id_n='$menuId' and language_id_n='$lang'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getStdMenuDetail($menuId, $lang) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select * from std_menu_detail_tab  where parent_menu_id='$menuId' and language_id_n='$lang' order by menu_order_n asc";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemUsersAll($option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemUsersAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitSql = "";

            if ($option)
                $limitSql = "LIMIT $startLimit,$maxElement";

            $sqlQuery = "
                    
                   select  a.user_id_n
                        ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
                        ,date_format(a.creation_date_d,'%d/%m/%Y %H:%i:%s') creationDate
                        ,a.mobile_phone_v
                        ,a.email_v
                        ,b.profile_name_v 
                        ,c.description_v status_desc
                        ,a.status_n
                from master_users_tab a,
                    master_profiles_tab b,
                    master_status_tab c
                where a.profile_id_n = b.profile_id_n
                and a.status_n = c.status_n
                $limitSql
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getProfileList() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getProfileList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "  
                   select   profile_id_n
                        , profile_name_v
                        , long_desc_v
                        , status_n 
                    FROM master_profiles_tab
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function updateMainSubsInfo($rowId, $firstName, $lastName, $phoneNumber, $email) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateMainSubsInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update master_users_tab  
                                    set  first_name_v='$firstName'
                                        ,last_name_v = '$lastName'
                                        ,mobile_phone_v = '$phoneNumber'
                                        ,email_v = '$email'
                             where user_id_n='$rowId'";

            //echo $sqlQuery;

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function updateMyAccountPassword($rowId, $newPassword) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateMyAccountPassword()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update master_users_tab  
                                    set  password_v='$newPassword'
                             where user_id_n='$rowId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function addUserShort($username, $password, $firstName, $lastName, $profileId, $mobilePhone, $emailId, $ownerId) {
        $dbAccess = $this->getMysqlConnection();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec addUserShort()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO master_users_tab  (user_id_n,creation_date_d,user_name_v,password_v,profile_id_n,creator_id_n, first_name_v, last_name_v, mobile_phone_v, email_v, status_n)
                VALUES (NULL,now(),'$username','$password','$profileId','$ownerId','$firstName','$lastName','$mobilePhone','$emailId','0')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function userChangeStatus($userId, $newStatus) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec userChangeStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = " UPDATE master_users_tab SET status_n='$newStatus' WHERE user_id_n='$userId'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function getSystemUserById($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemUserById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "  
                 select   user_id_n
                        , user_name_v
                        , profile_id_n
                        , first_name_v
                        , last_name_v
                        , email_v
                        , mobile_phone_v 
                    FROM master_users_tab
                    WHERE user_id_n='$userId'
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $data;
    }

    public function updateMainSubsInfoAdmin($rowId, $firstName, $lastName, $phoneNumber, $email, $profileId) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateMainSubsInfoAdmin()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update master_users_tab  
                                    set  first_name_v='$firstName'
                                        ,last_name_v = '$lastName'
                                        ,mobile_phone_v = '$phoneNumber'
                                        ,email_v = '$email'
                                        ,profile_id_n ='$profileId'
                             where user_id_n='$rowId'";

            //echo $sqlQuery;

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function dropUserById($userId) {

        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec dropUserById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "DELETE FROM   master_users_tab
                WHERE user_id_n='$userId'";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $status;
    }

    public function createGroupe($goupName, $groupDesc, $moduleId, $groupOwner, $groupType, $groupEnabled, $otherEnabled, $charfield, $statut) {
        $dbAccess = $this->getMysqlConnection();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec createGroupe()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO master_groups_tab  
                VALUES (NULL,now(),'$goupName','$groupDesc','$moduleId','$groupOwner','$groupType','$groupEnabled','$otherEnabled','$charfield[0]','$charfield[1]','$charfield[2]','$charfield[3]','$charfield[4]','$statut')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function upldGroupDetail($groupId, $entityName, $additionalInfo, $contact, $email, $charfield, $statut) {

        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec upldGroupDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO group_details_tab   
                VALUES (null,'$groupId',now(),'$entityName','$additionalInfo','$contact','$email','$charfield[0]','$charfield[1]','$charfield[2]','$charfield[3]','$charfield[4]','$statut')";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getGroupDtlsByOwner($ownerId, $groupType, $groupId, $startLimit) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGroupDtlsByOwner()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                    select * 
                    from   master_group_tab a
                          ,group_details_tab b
                    where a.group_id_n = b.group_id_n
                    and a.owner_id_n='$ownerId' 
                    and a.group_type_n='$groupType'
                    and a.group_id_n = '$groupId'
                    order by b.first_name_v asc


                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGroupByOwnerId($profileId, $ownerId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getProfileList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement ";


            if ($profileId == 1) {

                $sqlQuery = "  
                   select  date_format(a.creation_date_d,'%d/%m/%Y %H:%I:%S') eventDate
                            ,a.group_id_n
                            ,a.group_name_v
                            ,a.group_type_n
                            ,b.user_name_v
                            ,a.short_desc_v
                     from master_groups_tab a,
                          master_users_tab b
                     where a.owner_id_n =  b.user_id_n
                     and a.group_id_n <> '1'
                     ORDER BY a.group_id_n DESC
                     $limitQuery
                     

                ";
            } else {



                $sqlQuery = " 
                    
select  date_format(a.creation_date_d,'%d/%m/%Y %H:%I:%S') eventDate
                            ,a.group_id_n
                            ,a.group_name_v
                            ,a.group_type_n
                            ,b.user_name_v
                            ,a.short_desc_v
                     from master_groups_tab a,
                          master_users_tab b
                     where a.owner_id_n =  b.user_id_n
                     and a.owner_id_n = '$ownerId'
                     and a.group_id_n <> '1'
                          ORDER BY a.group_id_n DESC
                     $limitQuery
                         
                ";
            }






            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGroupDetail($groupId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGroupDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement ";

            $sqlQuery = "  
                  select  date_format(c.creation_date_d,'%d/%m/%Y %H:%I:%S') eventDate
                            ,a.group_id_n
                            ,a.group_name_v
                            ,a.group_type_n
                            ,b.user_name_v
                            ,a.short_desc_v
                            ,c.phone_number_v
                     from master_groups_tab a,
                          master_users_tab b,
                          group_details_tab c
                     where a.owner_id_n =  b.user_id_n
                     and c.group_id_n = a.group_id_n
                     and c.group_id_n = '$groupId'
                     ORDER BY a.group_id_n DESC
                     $limitQuery
                     

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function deleteGroupAndDataById($groupId) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec deleteIadApplication()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "delete from master_groups_tab where  group_id_n='$groupId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $sqlQuery = "delete from group_details_tab where  group_id_n='$groupId'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function uploadNotificationPhone($campaignId, $entityId, $statut) {
        $dbAccess = $this->getMysqlConnection();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec createGroupe()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO campaign_notification_tab  
                VALUES (NULL,'$campaignId','$entityId','$statut')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function updateMasterCampaignMetaData($campaignId, $current, $total) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateQueuedEventsBulk()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE master_campaigns_tab
                             SET  char_field_2 =char_field_2 + $total
                                 , char_field_3 =char_field_3 + $current
                            where campaign_id_n = '$campaignId'
                          ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryResult;
    }

    public function getActiveCampaignByProfile($profileId, $userId, $campaignId, $option, $startLimit, $maxElement, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCampaignByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitSql = "";
            $campaignSql = "";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement";
            if ($campaignId != -1)
                $campaignSql = "AND campaign_id_n = '$campaignId'";

            if ($profileId == 1 || $profileId == 3) {
                $sqlQuery = "  
                 select    campaign_id_n
                        , campaign_name_v
                        , owner_id_n 
                        , concat(start_date_d,' ',start_time_d) start_datetime_d
                        , concat(end_date_d,' ',end_time_d) end_datetime_d  
                        ,creation_date_d
                        ,char_field_2
                 FROM master_campaigns_tab
                 where status_n not in ('3','5')
                 and creation_date_d>='$startDate'
                 and creation_date_d<='$endDate'
                 $campaignSql
                 order by campaign_id_n desc
                 $limitSql
                ";
            } elseif ($profileId == 2) {

                $sqlQuery = "  
                    select    campaign_id_n
                        , campaign_name_v
                        , owner_id_n 
                        , concat(start_date_d,' ',start_time_d) start_datetime_d
                        , concat(end_date_d,' ',end_time_d) end_datetime_d  
                        ,creation_date_d
                        ,char_field_2
                 FROM master_campaigns_tab
                 where status_n not in ('3','5')
                 and creation_date_d>='$startDate'
                 and creation_date_d<='$endDate'
                 and owner_id_n='$userId'
                 $campaignSql
                 order by campaign_id_n desc
                 $limitSql

                ";
            }
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadCallStatus($campaignId, $option) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadCallStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            switch ($option) {

                case 0 : $statusSql = " status_n in ('3','8') ";
                    break; // Picked up
                case 1 : $statusSql = " status_n in ('7') ";
                    break;  // Non-Picked up
                case 2 : $statusSql = " status_n not in ('7','3','8') ";
                    break;  // Non-Processed up   
            }

            $sqlQuery = "  
                 select count(1) total from queues_processor_tab where campaign_id_n='$campaignId' and  $statusSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);

            $total = $data['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function getIadTransfertCalls($campaignId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadTransfertCalls()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                 select count(1) total from subs_sharing_details_tab where campaign_id_n='$campaignId' 
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);

            $total = $data['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function getIadSubscriptionCalls($campaignId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadSubscriptionCalls()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                 select count(1) total from subs_offer_details_tab where campaign_id_n='$campaignId' 
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $data = mysql_fetch_array($sqlResult);

            $total = $data['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function getIadStatistic($profileId, $userId, $campaignId, $option, $startLimit, $maxElement, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCampaignByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitSql = "";
            $campaignSql = "";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement";
            if ($campaignId != -1)
                $campaignSql = "AND b.campaign_id_n = '$campaignId'";

            if ($profileId == 1 || $profileId == 3) {
                $sqlQuery = "  
                 select b.campaign_id_n
                        ,b.campaign_name_v
                        ,b.owner_id_n 
                        , concat(b.start_date_d,' ',b.start_time_d) start_datetime_d
                        , concat(b.end_date_d,' ',b.end_time_d) end_datetime_d  
                        ,b.creation_date_d
                        ,b.char_field_2
                        ,a.total_picked_v
                        ,a.total_unpicked_v
                        ,a.total_forwarded_v
                        ,a.total_subscription_v
                        ,round( 100*(a.total_picked_v/a.total_count_v),2) avgSucess
                        ,c.user_name_v
                  from iad_statistics_tab a
                       ,  master_campaigns_tab b
                       ,  master_users_tab c
                  where a.campaign_id_n = b.campaign_id_n
                  and c.user_id_n = b.owner_id_n
                  and b.creation_date_d>='$startDate'
                  and b.creation_date_d<='$endDate'
                      $campaignSql
                  order by a.campaign_id_n asc
                  $limitSql
                ";
            } elseif ($profileId == 2) {



                $sqlQuery = "  
                 select b.campaign_id_n
                        ,b.campaign_name_v
                        ,b.owner_id_n 
                        , concat(b.start_date_d,' ',b.start_time_d) start_datetime_d
                        , concat(b.end_date_d,' ',b.end_time_d) end_datetime_d  
                        ,b.creation_date_d
                        ,b.char_field_2
                        ,a.total_picked_v
                        ,a.total_unpicked_v
                        ,a.total_forwarded_v
                        ,a.total_subscription_v
                        ,round(100 * (a.total_picked_v/a.total_count_v),2) avgSucess
                        ,c.user_name_v
                  from iad_statistics_tab a
                       ,  master_campaigns_tab b
                       ,  master_users_tab c
                  where a.campaign_id_n = b.campaign_id_n
                  and c.user_id_n = b.owner_id_n
                  and b.creation_date_d>='$startDate'
                  and b.creation_date_d<='$endDate'
                  and b.owner_id_n='$userId'
                      $campaignSql
                  order by a.campaign_id_n asc
                  $limitSql
                ";
            }
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getIadStatisticDetailled($profileId, $userId, $campaignId, $option, $startLimit, $maxElement, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIadStatisticDetailled()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitSql = "";
            $campaignSql = "";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement";
            if ($campaignId != -1)
                $campaignSql = "AND b.campaign_id_n = '$campaignId'";

            if ($profileId == 1 || $profileId == 3) {
                $sqlQuery = " 
                    select b.campaign_id_n
                            ,b.campaign_name_v
                            ,b.owner_id_n 
                            , concat(b.start_date_d,' ',b.start_time_d) start_datetime_d
                            , concat(b.end_date_d,' ',b.end_time_d) end_datetime_d  
                            ,b.creation_date_d
                            ,b.char_field_2
                            ,a.entity_v
                            ,a.has_forwarded_n
                            ,a.has_subscribe_n
                            ,c.user_name_v
                             , case a.status_n
                            when 3 then 'DECROCHE'
                            when 7 then 'NON-DECROCHE'
                           end status_desc
                      from sva_upld_events_tab a
                           ,  master_campaigns_tab b
                           ,  master_users_tab c
                      where a.campaign_id_n = b.campaign_id_n
                      and c.user_id_n = b.owner_id_n
                      and b.creation_date_d>='$startDate'
                      and b.creation_date_d<='$endDate'
                          $campaignSql
                      order by a.campaign_id_n asc
                      $limitSql

                 
                ";
            } elseif ($profileId == 2) {



                $sqlQuery = "  
                     select b.campaign_id_n
                            ,b.campaign_name_v
                            ,b.owner_id_n 
                            , concat(b.start_date_d,' ',b.start_time_d) start_datetime_d
                            , concat(b.end_date_d,' ',b.end_time_d) end_datetime_d  
                            ,b.creation_date_d
                            ,b.char_field_2
                            ,a.entity_v
                            ,a.has_forwarded_n
                            ,a.has_subscribe_n
                            ,c.user_name_v
                             , case a.status_n
                                when 3 then 'DECROCHE'
                                when 7 then 'NON-DECROCHE'
                               end status_desc
                      from sva_upld_events_tab a
                           ,  master_campaigns_tab b
                           ,  master_users_tab c
                      where a.campaign_id_n = b.campaign_id_n
                      and c.user_id_n = b.owner_id_n
                      and b.creation_date_d>='$startDate'
                      and b.creation_date_d<='$endDate'
                      and b.owner_id_n='$userId'
                          $campaignSql
                      order by a.campaign_id_n asc
                      $limitSql


            
                ";
            }
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getActiveCampaign($dbAccess) {

        //$dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getActiveCampaign()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "  
                   select  campaign_id_n
                            ,start_date_d
                            ,start_time_d
                            ,end_date_d
                            ,end_time_d
                            ,char_field_2 total
                            ,char_field_3 processed
                     from master_campaigns_tab 
                     where status_n not in ('3','9')
                    
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$this->closeMysqlConnection($dbAccess['dbConnection'])  ;
        }


        return $this->mysqlRessourceJson($sqlResult);
    }

    public function updateCampaignByIdBulk($campaignId, $statut, $dbAccess) {
        //$dbAccess = $this->getMysqlConnection();  
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateCampaignByIdBulk()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update master_campaigns_tab 
                             set status_n='$statut'   
                             where campaign_id_n= '$campaignId'  

                ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $this->closeMysqlConnection($dbAccess['dbConnection']);
            $status = true;
        }

        return $queryResult;
    }

    public function updateCampaignDetailById($campaignId, $currentStatus, $newStatus, $dbAccess) {
        //$dbAccess = $this->getMysqlConnection();  
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateCampaignDetailById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update queues_processor_tab 
                             set status_n='$newStatus'   
                             where campaign_id_n= '$campaignId' 
                             and status_n = '$currentStatus'

                ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // $this->closeMysqlConnection($dbAccess['dbConnection']);
            $status = true;
        }

        return $queryResult;
    }

    public function updateProcessStats($issueDate, $itemId, $campaignId, $phone, $statusId, $dbAccess) {
        // $dbAccess = $this->getMysqlConnection();  
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateProcessStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "update queues_processor_tab 
                             set issued_date_d='$issueDate' 
                                 ,status_n='$statusId'
                             where item_id_n='$itemId'
                             and campaign_id_n= '$campaignId' 
                             and phone_number_v= '$phone'

                ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            $status = true;
        }

        return $status;
    }

    public function iadRunEodStats() {
        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec iadRunDetailledStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = " call SCM_EOD_HISTORY_GEN()            ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $sqlQuery = " call IAD_EOD_STATS_AGGRAGATE()            ";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // $this->closeMysqlConnection($dbAccess['dbConnection']);
            $status = true;
        }

        return $queryResult;
    }

    public function getIpLocation($ip2number) {

        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getIpLocation()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT * FROM ip_locator_tab  where $ip2number between `ip_from_n` and `ip_to_n` 


				";

            echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            $status = true;
        }

        return $queryData;
    }

    public function upldCampaignResultData($campaignId, $queueId, $adresseIP, $country, $city, $regionName, $platform, $status) {

        $dbAccess = $this->getMysqlConnection();
        $result = NULL;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec upldCampaignResultData()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO `smm_upld_report_tab`  VALUES (NULL, now(), '$campaignId', '$queueId', '$adresseIP', '$country', '$city','$regionName','$platform','$status')";
            //echo  $sqlQuery;
            $result = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $result;
    }

    public function getViewMailReportByCampaignId($campaignId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getViewMailReportByCampaignId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            $sqlQuery = "
                    
                   SELECT b.campaign_id_n
             ,DATE_FORMAT(a.event_datetime_d, '%d/%m/%Y %H:%i:%s') eventDateTime  
             ,b.campaign_name_v
             ,c.entity_v
             , a.country_name_v
             , a.city_name_v
             , a.platform_name_v
FROM smm_upld_report_tab a
         , master_campaigns_tab b
         , queues_processor_tab c
where a.campain_id_n = b.campaign_id_n
and c.item_id_n = a.queue_id_n
and a.campain_id_n = '$campaignId'
                    $limitQuery

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function upldGroupDetailBulk($dbAccess, $groupId, $entityName, $additionalInfo, $contact, $email, $charfield, $statut) {

        // $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec upldGroupDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO group_details_tab   
                VALUES (null,'$groupId',now(),'$entityName','$additionalInfo','$contact','$email','$charfield[0]','$charfield[1]','$charfield[2]','$charfield[3]','$charfield[4]','$statut')";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            //$this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function sccGetCustomerList($ownerId, $profileId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetCustomerList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            if ($profileId == 1) {


                $sqlQuery = "
                    
                  select   customer_id_n
                            , date_format(creation_date_d,'%d/%m/%Y %H:%i:%S') creation_date_d
                            , customer_name_v
                            , description_v
                            , cc_line_v
                            , location_v
                            , status_n
                     FROM scc_customers_tab 
                     $limitQuery

                ";
            } else {

                $sqlQuery = "
                    
                  select   customer_id_n
                            , date_format(creation_date_d,'%d/%m/%Y %H:%i:%S') creation_date_d
                            , customer_name_v
                            , description_v
                            , cc_line_v
                            , location_v
                            , status_n
                     FROM scc_customers_tab 
                     $limitQuery

                ";
            }


            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function sccCreateCustomer($customerName, $desc, $infoLine, $location, $field, $statusN) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccCreateCustomer()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO scc_customers_tab  VALUES (NULL,now(),'$customerName','$desc','$infoLine','$location','$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$statusN')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function sccGetAgentsList($ownerId, $profileId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetAgentsList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";

            if ($profileId == 1) {


                $sqlQuery = "
                    
                    select a.user_id_n
                            ,b.first_name_v
                            ,b.last_name_v
                            ,a.caller_id_v
                            ,b.user_name_v
                            ,date_format(a.creation_date_d,'%d/%m/%Y %H:%i:%S') creation_date_d
                      from scc_agents_tab a,  master_users_tab b
                      where a.user_id_n = b.user_id_n 
                     $limitQuery

                ";
            } else {

                $sqlQuery = "
                    
                   select a.user_id_n
                            ,b.first_name_v
                            ,b.last_name_v
                            ,a.caller_id_v
                            ,b.user_name_v
                            ,date_format(a.creation_date_d,'%d/%m/%Y %H:%i:%S') creation_date_d
                      from scc_agents_tab a,  master_users_tab b
                      where a.user_id_n = b.user_id_n 
                     $limitQuery

                ";
            }


            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function sccGetSystemUsersAll($option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetSystemUsersAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitSql = "";

            if ($option)
                $limitSql = "LIMIT $startLimit,$maxElement";

            $sqlQuery = "
                    
                   select  a.user_id_n
                        ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
                        ,date_format(a.creation_date_d,'%d/%m/%Y %H:%i:%s') creationDate
                        ,a.mobile_phone_v
                        ,a.email_v
                        ,b.profile_name_v 
                        ,c.description_v status_desc
                        ,a.status_n
                from master_users_tab a,
                    master_profiles_tab b,
                    master_status_tab c    
                where a.profile_id_n = b.profile_id_n
                and a.status_n = c.status_n
                and a.user_id_n not in (select e.user_id_n  from scc_agents_tab e)
                $limitSql
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function sccCreateAgent($userId, $callerId, $statusN) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccCreateAgent()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO scc_agents_tab  VALUES (NULL,now(),'$userId','$callerId','$statusN')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function sccGetIncomingCalls($option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetIncomingCalls()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitSql = "";

            if ($option)
                $limitSql = "LIMIT $startLimit,$maxElement";

            $sqlQuery = "
                    
                   select  a.call_id_n
                        , date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
                        ,a.from_callerid_v
                        ,a.to_number_v
                        ,b.customer_name_v
                        , case a.online_status_n
                           when 0 then 'En ligne'
                           when 1 then 'Raccroché'
                          end online_status_n
                 from  scc_call_history_tab a
                      ,scc_customers_tab b
                 where a.to_number_v = b.cc_line_v
                 and a.status_n = 0
                $limitSql
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function sccGetIncomingCallById($callId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetIncomingCallById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                SELECT  a.call_id_n
                        , date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
                        , a.event_datetime_d issue_datetime_d
                        ,a.from_callerid_v
                        ,a.to_number_v
                        ,b.customer_name_v
                FROM scc_call_history_tab a
                    ,scc_customers_tab b
                WHERE call_id_n ='$callId'   "
                    . " and a.to_number_v = b.cc_line_v ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function sccUpldCallEventDetails($callId, $userId, $callerId, $title, $reason, $contact, $location, $creationDate, $statusN) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccUpldCallEventDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO scc_call_reason_tab  VALUES (NULL,now(),'$callId','$userId','$callerId','$title','$reason','$contact','$location','$creationDate','$statusN')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function sccGetStats($profileId, $userId, $startLimit, $maxElement, $startDate, $endDate, $option) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";

            if ($profileId == 2)
                $profileSql = "AND d.profile_id_n='$profileId' ";
            if (($userId == -1 && $profileId == 2) || ($profileId != 2 && $userId != -1 ))
                $userSql = "AND d.user_id_n='$userId' ";
            if ($option)
                $limitSql = "LIMIT $startLimit, $maxElement   ";


            $sqlQuery = "
                      
                    select   a.item_id_n
                            ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
                            ,date_format(a.creation_date_d,'%d/%m/%Y %H:%i:%s') issued_datetime_d
                            ,c.customer_name_v
                            ,a.call_title_v
                            ,d.user_name_v
                            ,a.contact_v
                            ,a.caller_name_v
                    from  scc_call_reason_tab a
                         ,scc_call_history_tab b
                         ,scc_customers_tab c
                         ,master_users_tab d
                    where  a.call_id_n = b.call_id_n
                    and c.cc_line_v = b.to_number_v
                    and a.user_id_n = d.user_id_n
                    and a.event_datetime_d>='$startDate'
                    and a.event_datetime_d <='$endDate'
                    $profileSql
                    $userSql
                    $campaignSql
                    order by a.event_datetime_d  desc
                    $limitSql
                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllModules() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getPlatformsAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                    
                   select  m.module_id_n
				  ,m.creation_date_d
				  ,m.module_name_v
				  ,m.version_v
				  ,m.description_v
				  ,m.status_n
			from master_modules_tab m

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getModuleMenusById($moduleId, $lang, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getModuleMenusById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
               
                     select distinct                       n.module_id_n 
							  ,n.header_menu_id_n 
                                                          , c.menu_id_n
							   ,c.creation_date_d
                                                            ,c.language_id_n
							   ,c.menu_desc_v 
							   ,c.menu_name_v 
							   ,c.page_link_v 
						from  	 role_details_tab  n
							 , menu_builder_tab c
						where c.menu_id_n = n.menu_id_n 
						and  n.role_id_n in (select distinct role_id_n from user_roles_tab us where us.user_id_n=$userId)
						and n.module_id_n = $moduleId
                                               order by n.menu_id_n asc

                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getProfileListByRight($profile) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getProfileListByRight()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($profile == 2) {

                $userSql = "where profile_id_n=$profile";
            }

            $sqlQuery = "  
                   select   profile_id_n
                        , profile_name_v
                        , long_desc_v
                        , status_n 
                    FROM master_profiles_tab
                    $userSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function crmNewTicket($ticketNumber, $userId, $firstName, $lastName, $emailId, $mobilePhone1, $mobilePhone2, $reasonCategoryId, $reasonId, $location, $gender, $reasonDesc, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmNewTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO crm_tickets_tab VALUES (null, now(),'$ticketNumber','$userId','$firstName','$lastName','$emailId','$reasonDesc','$mobilePhone1','$location','$mobilePhone2','$gender','$reasonCategoryId','$reasonId','','','','','','$status')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSequenceNumber($appName) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSequenceNumber()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $curSeq = 0;
            $sqlQuery = "SELECT seqno +1 as seqno
						FROM `accountGeneration`
						WHERE application_id = '$appName'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $curSeq = $queryData['seqno'];

            $sqlQuery = " UPDATE accountGeneration SET seqno='$curSeq'  WHERE  application_id = '$appName'";
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $curSeq;
    }

    public function crmGetTicketReasonList($item) {
        $dbAccess = $this->connectMysqlDatabase();
        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmGetTicketReasonList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $sqlQuery = "
                               select * from  master_motifs_tab where id_categorie_n=$item order by motif_name_v asc
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function crmGetTicketByProfile($profile, $userId, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmGetTicketByProfile()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";
            $statusSql = "";

            if ($status != -1) {

                $statusSql = " AND a.status_n = $status ";
            }

            if ($profile == 2) {

                $userSql = "AND user_id_n=$userId";
            }

            $sqlQuery = "  
                   SELECT   event_datetime_d
				          , ticket_number_v
						  , user_name_v 
						  , a.first_name_v
						  , a.last_name_v
						  , email_id_v
						  , ticket_reason_desc_v
						  , mobile1_phone_v
						  , location_v
						  , mobile2_phone_v
						  , gender_v
						  , reason_n
						  , case a.status_n
						    when 0 then 'Initialis&eacute;'
							when 1 then 'Ouvert' 
							when 2 then 'Clos' end statut
						  , motif_name_v
						 
                   FROM `crm_tickets_tab` a
				         , master_users_tab b
						 , master_motifs_tab c
				   WHERE a.user_id_n = b.user_id_n
				   AND a.reason_n = c.motif_id_n
                    $userSql
					$statusSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getProfileListByRight1($profile) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getProfileListByRight()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($profile == 2) {

                $userSql = "where profile_id_n=$profile";
            }

            $sqlQuery = "  
                   select   profile_id_n
                        , profile_name_v
                        , long_desc_v
                        , status_n 
                    FROM master_profiles_tab
                    $userSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function crmNewAgent($profileId, $login, $firstName, $lastName, $password, $mobilePhone, $userId, $emailId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmNewAgent()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO master_users_tab (user_id_n, creation_date_d, user_name_v, password_v, profile_id_n, creator_id_n, first_name_v, last_name_v, mobile_phone_v, email_v, status_n) VALUES (null, now(),'$login','$password','$profileId','$userId','$firstName','$lastName','$mobilePhone','$emailId','0')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getUserDetailByRight($profile, $userId, $id, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getProfileListByRight()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";
            $usql = "";

            if ($profile == 2) {


                $userSql = " and (a.user_id_n='$userId' OR a.creator_id_n='$userId') ";
            }

            if ($id > 0) {

                $usql = " AND a.user_id_n = '$userId'";
            }



            $sqlQuery = "
                    select a.user_id_n
                        ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
						,a.profile_id_n
                        ,a.creation_date_d
                        ,a.mobile_phone_v
                        ,a.email_v
                        ,b.profile_name_v 
                        ,c.description_v status_desc
                        ,a.status_n
						,(select  agency_name_v  from master_agencies_tab where agency_id_n = a.primary_address_v limit 1 )  primary_address_v
                 from master_users_tab a,
                    master_profiles_tab b,
                    master_status_tab c
                where a.profile_id_n = b.profile_id_n
                and a.status_n = c.status_n
                $userSql
				 $usql

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCRMTicketCountByUser($profile, $login) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTicketCountByUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $curDate = date("Y-m-d") . "%";

            if ($profile == 2) {

                $userSql = " AND  b.user_name_v ='$login' ";
            }


            $sqlQuery = "SELECT count(1) total
                FROM  crm_tickets_tab a
				     ,master_users_tab b
			     WHERE a.user_id_n = b.user_id_n
                             and a.event_datetime_d like '$curDate'
				$userSql
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getCRMTicketStatusCountByUser($profile, $login, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTicketCountByUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $curDate = date("Y-m-d") . "%";

            if ($profile == 2) {

                $userSql = " AND b.user_name_v ='$login' ";
            }


            $sqlQuery = "SELECT count(1) total
                FROM   crm_tickets_tab a
				      , master_users_tab b
                WHERE a.user_id_n = b.user_id_n 
                 and a.event_datetime_d like '$curDate'
				AND a.status_n = '$status' 
				$userSql
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getCRMWeeklyStats($profile, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMWeeklyStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $userSql = "";
            if ($profile == 2) {
                $userSql = " AND  user_id_n ='$userId' ";
            }
            $sqlQuery = "
			          select  STR_TO_DATE(EventDate, '%d/%m/%Y') EventDate
                           ,sum(Initiated)  Initiated
						   ,sum(Opened) Opened
						   ,sum(Closed) Closed
					  from (   select date_format(c.event_datetime_d, '%d/%m/%Y') EventDate
								,case c.status_n
								   when -1 then 1 else 0
								  end Initiated
								,case c.status_n
								   when 2 then 1 else 0
								  end Opened
								,case c.status_n
								   when 3 then 1 else 0
								  end Closed
						  from crm_tickets_tab c
						  where c.event_datetime_d>= curdate() - INTERVAL DAYOFWEEK(curdate())+30 DAY
						  and c.event_datetime_d <= now()
						  $userSql
						  order by c.event_datetime_d asc
						  ) t
					   group by EventDate
					   order by  EventDate asc 
								
               

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCRMMonthlyStats($profile, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMMonthlyStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $userSql = "";

            if ($profile == 2) {

                $userSql = " WHERE  user_id_n ='$userId' ";
            }

            $sqlQuery = "
                   SELECT date_format(event_datetime_d,'%m-%Y') eventdatetime
						  ,count(1) total
					FROM `crm_tickets_tab`
					 $userSql
					group by date_format(event_datetime_d,'%m-%Y') 
					order by event_datetime_d  asc
               

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCRMTopTicketreasonList($profile, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTicketCountByUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";

            if ($profile == 2) {

                $userSql = " AND user_id_n ='$userId' ";
            }


            $sqlQuery = "SELECT  b.motif_name_v
							   ,count(1) total
						FROM `crm_tickets_tab`  a
							 ,master_motifs_tab b
						WHERE a.reason_n = b.motif_id_n
						$userSql
						group by b.motif_name_v
						order by 2 desc
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            // $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCRMTotalTicketDaily($profile, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTotalTicketDaily()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";

            if ($profile == 2) {

                $userSql = " WHERE user_id_n ='$userId' ";
            }


            $sqlQuery = "SELECT  date_format(a.event_datetime_d,'%d/%m/%Y') datetime
							   ,count(1) total
						FROM `crm_tickets_tab`  a
						$userSql
						group by date_format(a.event_datetime_d,'%d/%m/%Y')
						order by 1 desc
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            // $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCQosDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCQosDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";

            if ($id > 0) {

                $idSql = " AND qos_id_n='$id'";
            }

            $sqlQuery = "
                   SELECT  qos_id_n
					   ,creation_date_d
					   ,qos_name_v
					   ,qos_value_v
					   ,qos_desc_v
					   ,qos_code_v
				FROM `scc_system_params_tab`
				WHERE status_n =0
				$idSql

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCQueueDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCQueueDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";

            if ($id > 0) {
                $idSql = "WHERE queue_id_n='$id'";
            }

            $sqlQuery = "
                  SELECT   queue_id_n
							,name
							,event_datetime_d
							,musiconhold
							,wrapuptime
							,strategy
					FROM `master_queue_table` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddCRMQueue($id, $queueId, $queueName, $musicOnHoldClass, $strategy, $wrapTime) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCRMQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT INTO master_queue_table (queue_id_n, event_datetime_d, name, musiconhold, context, wrapuptime, strategy) VALUES (null, now(),'$queueName','$musicOnHoldClass','qoutscc','$wrapTime','$strategy')";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE master_queue_table 
				                 SET name = '$queueName'
								 ,wrapuptime ='$wrapTime'
								 ,strategy = '$strategy'
						     WHERE queue_id_n = '$queueId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM master_queue_table WHERE queue_id_n in ($queueId)     ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCCustomerDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCustomerDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";

            if ($id > 0) {

                $idSql = "WHERE customer_id_n='$id'";
            }

            $sqlQuery = "
                  SELECT   customer_id_n
							,creation_date_d
							,first_name_v
							,last_name_v
							,cc_line_v
							,location_v
							,email_id_v
							,char_field_1
					FROM `scc_customers_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCCallReasonDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCallReasonDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND motif_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.motif_id_n
							,a.motif_name_v
							,a.motif_desc_v
                                                        ,b.group_name_v
                                                        ,b.group_id_n
					FROM `master_motifs_tab` a,
                                              master_groups_tab b
                                        WHERE a.id_categorie_n = b.group_id_n
					$idSql
                                        ORDER BY a.motif_name_v ASC
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSIPTrunkConfiguration($id, $sipType) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSIPTrunkConfiguration()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            $typeSql = "";
            if ($id > 0) {
                $idSql = "AND id = '$id'";
            }

            if ($sipType != -1) {
                $typeSql = "AND sip_type_n='$sipType'";
            }

            $sqlQuery = "
                  SELECT   id
							,creation_date_d
							,name
							,host
							,type
							,allow
							,port
							,presence
							,username
							,status_n
							,sip_type_n
					FROM `master_sip_tab` 
					WHERE status_n = 0
					 $typeSql
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddCallReason($opId, $id, $motifName, $description, $groupId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCallReason()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_motifs_tab  (motif_id_n, motif_name_v, motif_desc_v, id_categorie_n) VALUES (null, '$motifName','$description','$groupId')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_motifs_tab
				                  SET motif_name_v='$motifName'
								     ,motif_desc_v='$description'
                                                                         ,id_categorie_n='$groupId'
							    WHERE motif_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  master_motifs_tab WHERE motif_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddSIPTrunk($opId, $id, $trunkName, $hostName, $port, $type, $username, $secret, $sipType, $userId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSIPTrunk()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_sip_tab  (id,creation_date_d,  name, host, type, username, secret, sip_type_n, user_id_n, status_n) VALUES (null, now(),'$trunkName','$hostName','$type','$username','$secret','$sipType','$userId','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  master_sip_tab 
			                 SET  name ='$trunkName'
							     ,host ='$hostName'
								 ,secret='$secret'
								 ,sip_type_n='$sipType'
								 ,status_n='$status'
								 ,type = '$type'
								 ,port = '$port'
								 ,username= '$username'
						   WHERE id = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  master_sip_tab WHERE id in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCIncomingCallDetails_backp($status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCIncomingCallDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $statusSql = "";

            if ($status != -1) {

                $statusSql = " WHERE status_n='$status'";
            }


            $sqlQuery = "
                  SELECT   call_id_n
							,event_datetime_d
							,from_callerid_v
							,to_number_v
							,online_status_n
							,caller_ticket_id
							,uniq_id_v
							,case status_n
							  when 0 then 'Initi&eacute;' 
							  when 1 then 'Pris en charge'
							  when 2 then 'Trait&eacute;'
							 end status_n
					FROM `scc_call_history_tab` 
					$statusSql
					order by 1 desc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketDetails($ticketId, $userId, $profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            /*
              if ($userId == -1 && $profileId == 2){
              $profileSql = "AND c.profile_id_n='$profileId' ";
              }
              elseif($userId != -1 && $profileId == 2){
              $userSql = "AND a.user_id_n='$userId' ";
              } */

            if ($status != -1) {
                $statusSql = "and a.status_n='$status'";
            }

            if ($startDate != NULL) {
                $date1Sql = "and a.event_datetime_d>='$startDate'";
            }

            if ($endDate != NULL) {
                $date2Sql = "and a.event_datetime_d <='$endDate'";
            }

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,d.motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_motifs_tab d
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.reason_n = d.motif_id_n
					and a.status_n = b.status_n
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketDetailById($callId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketDetailById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
			
			 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v caller_ticket_id
						   ,mobile1_phone_v from_callerid_v
					           ,e.user_name_v  to_number_v
						  ,d.description_v
						  ,c.reason_n
                                                  ,c.reason_category_n
						  ,ticket_reason_desc_v
						  ,c.char_field_2 
						  ,c.char_field_5
                                                  ,c.first_name_v
                                                  ,c.last_name_v
                                                  ,c.location_v location_v
                                                  ,c.mobile1_phone_v contact_v
                                                  ,c.mobile2_phone_v
                                                  ,c.gender_v
						  ,c.company_name_v
                                                  ,c.char_field_6 
                                                  ,c.email_id_v
                                                  ,c.status_n
                                                  ,c.char_field_3
                                                  ,c.char_field_4
                                                  ,c.char_field_10
                                                  ,c.user_id_n
                                                 
                                                  
                                                  
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
			 AND c.item_id_n = '$callId'
	         order by 1 desc
			  ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getSCCTicketDetailByTicketId($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketDetailByTicketId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
			
			 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v caller_ticket_id
						   ,mobile1_phone_v from_callerid_v
					           ,e.user_name_v  to_number_v
						  ,d.description_v
						  ,c.reason_n
                                                  ,c.reason_category_n
						  ,ticket_reason_desc_v
						  ,c.char_field_2
						  ,c.char_field_5
                                                  ,c.first_name_v
                                                  ,c.last_name_v
                                                  ,(select concat(aa.company_name_v, '[', aa.company_id_n, ']') from master_companies_tab aa where aa.company_id_n=c.location_v) location_v
                                                  ,c.mobile1_phone_v contact_v
                                                  ,c.mobile2_phone_v
                                                  ,c.gender_v
						  ,c.company_name_v
                                                  ,c.char_field_6 
                                                  ,c.email_id_v
                                                  ,c.status_n
                                                  ,c.char_field_3
                                                  ,c.char_field_4
                                                 
                                                  
                                                  
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
			 AND c.ticket_number_v = '$ticketId'
	         order by 1 desc
			  ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getSCCTicketDetailById_backup($callId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketDetailById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
			
			 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v caller_ticket_id
								  ,mobile1_phone_v from_callerid_v
								  ,e.user_name_v  to_number_v
						  ,d.description_v
						  ,reason_n
						  ,ticket_reason_desc_v
                                                  ,c.char_field_4
						  ,c.char_field_2
						  ,c.char_field_5
						   ,(select first_name_v from scc_customers_tab b where ( b.cc_line_v= c.mobile2_phone_v OR  b.cc_line_v= c.mobile1_phone_v ) ) first_name_v
						   ,(select last_name_v from scc_customers_tab b where ( b.cc_line_v= c.mobile2_phone_v OR  b.cc_line_v= c.mobile1_phone_v )) last_name_v
						   ,(select location_v from scc_customers_tab b where ( b.cc_line_v= c.mobile2_phone_v OR  b.cc_line_v= c.mobile1_phone_v )) location_v
						   ,(select cc_line_v from scc_customers_tab b where ( b.cc_line_v= c.mobile2_phone_v OR  b.cc_line_v= c.mobile1_phone_v )) contact_v
						   ,(select email_id_v from scc_customers_tab b where ( b.cc_line_v= c.mobile2_phone_v OR  b.cc_line_v= c.mobile1_phone_v )) email_id_v
						   ,f.type_id_n
						   ,f.type_v
						   ,c.company_name_v
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
						 ,customer_type_tab f
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
			 AND f.type_id_n = c.char_field_6
			 AND c.item_id_n = '$callId'
	         order by 1 desc
			  ";

            // echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getSCC() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCIncomingCallDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                  SELECT   call_id_n
							,event_datetime_d
							,from_callerid_v
							,to_number_v
							,online_status_n
							,caller_ticket_id
							,uniq_id_v
							,status_n
					FROM `scc_call_history_tab` 
					order by 1 desc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddTicketExt($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $callType, $status, $customerType) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
					   ,mobile2_phone_v='$mobileNumber'
					   ,gender_v=''
					   ,reason_category_n ='$callReasonType'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_6='$customerType'
					   $ackSql
					   $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,char_field_5,aknowledge_date_d, closure_date_d, status_n,company_name_v, char_field_6 )
              VALUES (NULL, now(), '$csrId', '$userId', '$callId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callReasonType','$callReasonType',0,'','$callType','$ack','$cls','$status','$company','$customerType') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddTicket($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $callType, $status, $customerType) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
					   ,mobile2_phone_v='$mobileNumber'
					   ,gender_v=''
					   ,reason_category_n ='$callReasonType'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_6='$customerType'
					   $ackSql
					   $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,char_field_5,aknowledge_date_d, closure_date_d, status_n,company_name_v, char_field_6 )
              VALUES (NULL, now(), '$csrId', '$userId', '$callId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callReasonType','$callReasonType',0,'','$callType','$ack','$cls','$status','$company','$customerType') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddTicket__backup($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $mobileNumber, $emailId, $callReasonType, $csrDetails) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO scc_call_reason_tab (item_id_n, event_datetime_d, call_id_n, user_id_n, call_title_n, call_desc_v, contact_v, 	location_v, s_contact_v, email_id_v, first_name_v, last_name_v) VALUES (null, now(),'$callId','$userId','$callReasonType','$csrDetails','$callerId','$address','$mobileNumber','$emailId','$firstName','$lastName')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddSCCCustomer($opId, $id, $firstName, $lastName, $mobileNumber, $desc, $location, $emailId, $field) {
        $dbAccess = $this->getMysqlConnection();
        //  $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSCCCustomer()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {


                $sqlQuery = "INSERT 
                INTO scc_customers_tab  VALUES (NULL,now(),'$firstName','$lastName','$desc','$mobileNumber','$location','$emailId','$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','0')";
            } elseif ($opId == 1) {

                $sqlQuery = " UPDATE  scc_customers_tab
			               SET  first_name_v='$firstName'
						       ,last_name_v='$lastName'
						       ,description_v='$desc'
							   ,location_v='$location'
							   ,email_id_v='$emailId'
							   ,cc_line_v ='$mobileNumber' 
							 WHERE customer_id_n='$id'";
            } else {

                $sqlQuery = " DELETE FROM   scc_customers_tab where  customer_id_n in ($id)";
            }



            // echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function UpdateAddComment($id, $userId, $ticketNumber, $comment, $type, $customerName, $status) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddComment()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT 
                INTO scc_ticket_comments_tab  VALUES (NULL,now(),'$userId','$ticketNumber','$comment','$type','$status','$customerName')";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $sqlQuery = " UPDATE  scc_ticket_comments_tab
			               SET  comment_v='$comment' 
							 WHERE comment_id_n='$id'";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function UpdateCallHistory($callId, $status) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateCallHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {




            $sqlQuery = " UPDATE  scc_call_history_tab
			               SET  status_n='$status' 
							 WHERE call_id_n='$callId'";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getGlobalStats($userId, $profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($userId != -1 && $profileId == 2) {
                $userSql = "AND a.user_id_n='$userId' ";
            } elseif ($userId != -1) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            $sqlQuery = "
                      
                 SELECT     eventDateTime
						   ,sum(INITIALISE) INITIALISE
						   ,sum(OUVERT) OUVERT
						   ,sum(CLOS)  CLOS
                                                   ,sum(UNPICKED)  UNPICKED
					   FROM (
						SELECT  date_format(event_datetime_d,'%Y-%m-%d' ) eventDateTime
							   ,case a.status_n
							  when -1  then 1 else 0
							 end INITIALISE
							   ,case a.status_n
							  when 2  then 1 else 0
							 end OUVERT
							   ,case a.status_n
							  when 3  then 1 else 0
							 end CLOS
                                                          ,case a.status_n
							  when 7  then 1 else 0
							 end UNPICKED
						FROM `crm_tickets_tab` a
							 , master_status_tab b
						where a.status_n = b.status_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$userSql

						order  by 1 desc
						   ) t
					group by eventDateTime
					order by eventDateTime desc
					 

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCIncomingCallDetails($status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCIncomingCallDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $statusSql = "";

            if ($status == -1) {

                $statusSql = " AND c.status_n='$status'";
            }


            $sqlQuery = "
                 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v
						  ,mobile1_phone_v
						  ,e.user_name_v
						  ,d.description_v
						  ,e.first_name_v
						  ,e.last_name_v
						  ,(select concat(g.first_name_v,' ',g.last_name_v) from scc_customers_tab g where g.cc_line_v=c.mobile1_phone_v) customerName
						  , c.aknowledge_date_d
						  , c.closure_date_d
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
             $statusSql
	         order by 1 desc
                ";
            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTicketComments($ticketId, $userId, $profileId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTicketComments()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($userId == -1 && $profileId == 2) {
                $profileSql = "AND d.profile_id_n='$profileId' ";
            } elseif ($userId != -1 && $profileId == 2) {
                $userSql = "AND d.user_id_n='$userId' ";
            }


            $sqlQuery = "
                      
                  select date_format(c.event_datetime_d ,'%d/%m/%Y %H:%I:%S') eventDate
							  ,d.user_name_v
							  ,c.comment_type_n
							  ,c.customer_name_v
							  ,c.comment_v
						from  scc_ticket_comments_tab c
							 ,master_users_tab d
							 ,crm_tickets_tab e
						where e.ticket_number_v = c.ticket_number_v
						and c.user_id_n = d.user_id_n
						and  c.ticket_number_v = '$ticketId'
						$profileSql
						$userSql
						order by c.event_datetime_d  asc

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function crmGetAgentList_back($profile, $userId, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmGetAgentList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";
            $statusSql = "";

            if ($status != -1) {

                $statusSql = " AND a.status_n = $status ";
            }

            if ($profile == 2) {

                $userSql = "AND user_id_n=$userId";
            }

            $sqlQuery = "  
                  select  m.user_id_n
						   ,date_format(m.creation_date_d,'%d/%m/%Y %H:%I:%S') creationDate
						   ,m.user_name_v
						   ,m.first_name_v
						   ,m.last_name_v
						   ,m.mobile_phone_v
						   ,m.email_v
					FROM  master_users_tab m
					where ( m.profile_id_n = 2 OR m.profile_id_n = 3)
                    $userSql
					
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddSCCSystemParam($opId, $id, $qosName, $qosValue, $qosDesc, $qosCode) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSCCSystemParam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_system_params_tab (qos_id_n, creation_date_d, qos_name_v, qos_value_v, qos_desc_v, qos_code_v, status_n) VALUES (null, now(),'$qosName','$qosValue','$qosDesc','$qosCode','0')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_system_params_tab
			                  SET   qos_name_v ='$qosName'
								  , qos_value_v ='$qosValue'
								  , qos_desc_v ='$qosDesc'
								  , qos_code_v ='$qosCode'
								  , status_n ='0'
							WHERE qos_id_n ='$id'
							  
							  ";
            } else {
                $sqlQuery = "DELETE from scc_system_params_tab WHERE qos_id_n in ($id)  ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddSCCUser($opId, $id, $profileId, $login, $firstName, $lastName, $password, $mobilePhone, $userId, $emailId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmNewAgent()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($opId == 0) {


                $sqlQuery = "INSERT INTO master_users_tab (user_id_n, creation_date_d, user_name_v, password_v, profile_id_n, creator_id_n, first_name_v, last_name_v, mobile_phone_v, email_v, status_n) VALUES (null, now(),'$login','$password','$profileId','$userId','$firstName','$lastName','$mobilePhone','$emailId','0')";

                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_users_tab 
				                  SET   user_name_v = '$login'
								       ,profile_id_n = '$profileId'
									   ,first_name_v = '$firstName'
									   ,last_name_v = '$lastName'
									   ,mobile_phone_v= '$mobilePhone'
									   ,email_v = '$emailId'
							   WHERE user_id_n ='$id' ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE from master_sip_tab  WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $sqlQuery = "DELETE from master_users_tab WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }



            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $totalUser;
    }

    public function getSIPDetailConfiguration($type, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSIPDetailConfiguration()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $typeSql = "";

            if ($type != -1) {

                $typeSql = " and sip_type_n = '$type' ";
            }


            $sqlQuery = "  
                     SELECT   id
							,creation_date_d
							,name
							,host
							,type
							,allow
							,port
							,presence
							,status_n
							,sip_type_n
							,secret
							,username
					FROM `master_sip_tab`
					where status_n='$status'
					$typeSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSIPAccountIdbyUsername($username) {
        $dbAccess = $this->getMysqlConnection();
        $totalUser = 2;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSIPAccountIdbyUsername()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT id 
                FROM master_sip_tab 
                WHERE username ='$username'";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $totalUser = $queryData['id'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $totalUser;
    }

    public function getSCCDetailStats($userId, $profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCDetailStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($userId == -1 && $profileId == 2) {
                $$userSql = "AND c.profile_id_n='$profileId' ";
            } elseif ($userId != -1) {
                $userSql = "AND a.user_id_n='$userId' ";
            }
            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            if ($startDate != NULL) {
                $date1Sql = "and a.event_datetime_d>='$startDate'";
            }

            if ($endDate != NULL) {
                $date2Sql = "and a.event_datetime_d <='$endDate'";
            }

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,c.first_name_v
						   ,c.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.char_field_5
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,(select concat(g.first_name_v,' ',g.last_name_v) from scc_customers_tab g where g.cc_line_v=a.mobile2_phone_v) customerName
						   ,a.ticket_reason_desc_v
						   ,a.email_id_v
						   ,d.type_v
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
						  ,customer_type_tab d
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
					and d.type_id_n = a.char_field_6
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAgentStats($userId, $profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAgentStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($userId != -1 && $profileId == 2) {
                $userSql = "AND a.user_id_n='$userId' ";
            } elseif ($userId != -1) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            $sqlQuery = "

						SELECT  date_format(event_datetime_d,'%Y-%m-%d' ) eventDateTime
							   ,concat(c.first_name_v,' ',c.last_name_v) name
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_status_tab b
							 , master_users_tab c
						where a.status_n = b.status_n
						and  a.user_id_n = c.user_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$userSql
						$statusSql
						group by date_format(event_datetime_d,'%Y-%m-%d' ), concat(c.first_name_v,' ',c.last_name_v)
						order  by event_datetime_d desc
						
					
					 

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallReasonStats($profileId, $callreasonId, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $callreasonSql = "";

            if ($callreasonId != -1) {

                $callreasonSql = " AND b.motif_id_n = '$callreasonId' ";
            }



            $sqlQuery = "

						SELECT  date_format(event_datetime_d,'%Y-%m-%d' ) eventDateTime
							   ,b.motif_name_v name
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_motifs_tab b
						where a.reason_n = b.motif_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$callreasonSql
						group by date_format(event_datetime_d,'%Y-%m-%d' ), b.motif_name_v
						order  by event_datetime_d desc     

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTopCallStats($profileId, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTopCallStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            $sqlQuery = "

						SELECT  date_format(event_datetime_d,'%Y-%m-%d' ) eventDateTime
							   ,concat(a.mobile1_phone_v,'/',b.first_name_v,' ',b.last_name_v)  name
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , scc_customers_tab b
						where a.mobile1_phone_v = b.cc_line_v
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						group by date_format(event_datetime_d,'%Y-%m-%d' ), concat(a.mobile1_phone_v,'/',b.first_name_v,' ',b.last_name_v)
						order  by total desc     

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCMailDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCMailDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND campaign_id_n = '$id'";
            }

            $sqlQuery = "
                  select  m.campaign_id_n
						   ,date_format(m.creation_date_d,'%d/%m/%Y %H:%I:%S') creation_date_d
						   ,m.campaign_name_v
						   ,m.char_field_6 subject
						   ,m.char_field_7
						   ,m.message_v
						   ,m.status_n
						   ,n.first_name_v
						   ,n.last_name_v
						   ,n.user_name_v
						   ,p.description_v
					FROM   master_campaigns_tab m
						  ,master_users_tab n
						  ,master_status_tab p
					WHERE m.owner_id_n = n.user_id_n
					AND p.status_n = m.status_n
					$idSql
					order by m.creation_date_d desc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddMailCampaign($opId, $id, $campaignName, $ownerId, $message, $subject, $count, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddMailCampaign()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_campaigns_tab  (campaign_id_n, creation_date_d, campaign_name_v, owner_id_n, message_v, char_field_6, char_field_7, status_n) VALUES (null, now(), '$campaignName','$ownerId','$message','$subject','$count','$status')";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_campaigns_tab
				                  SET message_v='$message'
								     ,char_field_6='$subject'
									 ,char_field_7='$count'
									 ,status_n ='$status'
							    WHERE campaign_id_n = '$id' ";

                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE FROM  master_campaigns_tab  WHERE campaign_id_n in ($id)";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }


            // echo $sqlQuery;
            // 
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $totalUser;
    }

    public function getTicketCommentsByTicketId($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTicketCommentsByTicketId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            $sqlQuery = "
                      
                  select date_format(c.event_datetime_d ,'%d/%m/%Y %H:%I:%S') eventDate
							  ,c.comment_type_n
							  ,c.customer_name_v
							  ,c.comment_v
						from  scc_ticket_comments_tab c
						where ticket_number_v = '$ticketId'
						and comment_type_n = 1
						order by c.event_datetime_d  desc
						limit 1

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCSRID($label) {
        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCSRID()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select getAccountNumber('$label') as ticketId";    
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $totalUser = $queryData['ticketId'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $totalUser;
    }

    public function getQueueConfiguration($type, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getQueueConfiguration()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $typeSql = "";

            if ($type != -1) {

                $typeSql = " and sip_type_n = '$type' ";
            }


            $sqlQuery = "  
                     SELECT   id
							,creation_date_d
							,name
							,host
							,type
							,allow
							,port
							,presence
							,status_n
							,sip_type_n
							,secret
							,username
					FROM `master_sip_tab`
					where status_n='$status'
					$typeSql
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCCDRStats($userId, $profileId, $callDirection, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCDRStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $directionSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($userId == -1 && $profileId == 2) {
                $$userSql = "AND c.profile_id_n='$profileId' ";
            } elseif ($userId != -1) {
                $userSql = "AND a.user_id_n='$userId' ";
            }
            if ($callDirection != -1) {
                $directionSql = "and a.call_direction_n='$callDirection'";
            }

            if ($startDate != NULL) {
                $date1Sql = "and a.event_datetime_d>='$startDate'";
            }

            if ($endDate != NULL) {
                $date2Sql = "and a.event_datetime_d <='$endDate'";
            }

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,c.first_name_v
						   ,c.last_name_v
						   ,c.user_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.char_field_5
						   ,a.ticket_number_v
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,b.src
						   ,b.dst
						   ,b.duration
						   ,b.calldate
						   ,a.status_n
						   ,(select motif_name_v from master_motifs_tab where motif_id_n= a.reason_n) motif_name_v
						   ,case a.call_direction_n
						     when 0 then 'Entrant'
							 when 1 then 'Sortant'
							end call_direction
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_cdr_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.char_field_2 = b.uniqueid
					$date1Sql
					$date2Sql
					$directionSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCLiveCallDetails($status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCLiveCallDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $statusSql = "";

            if ($status == -1) {

                $statusSql = " AND c.status_n='$status'";
            }


            $sqlQuery = "
                 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v
						  ,mobile1_phone_v
						  ,e.user_name_v
						  ,d.description_v
						  ,e.first_name_v
						  ,e.last_name_v
						  ,(select concat(g.first_name_v,' ',g.last_name_v) from scc_customers_tab g where ( g.cc_line_v=c.mobile1_phone_v ) ) customerName
						  , c.aknowledge_date_d
						  , c.closure_date_d
						  ,case c.call_direction_n
						     when 0 then 'Entrant'
							 when 1 then 'Sortant'
							end call_direction
						  , (select m.agency_name_v from master_agencies_tab m where agency_id_n = e.primary_address_v ) agency_name_v
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
             $statusSql
	         order by 1 desc
                ";
            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCCustomerType($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCustomerType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE type_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   type_id_n
							,type_v
							,status_n
					FROM `customer_type_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCCCompanyList($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCCompanyList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE company_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   company_id_n
							,company_name_v
							,company_desc_v
					FROM `master_companies_tab` 
					$idSql
					order by 2 asc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddCompany($opId, $id, $name, $description) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCompany()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_companies_tab  (company_id_n, company_name_v, company_desc_v) VALUES (null, '$name','$description')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_companies_tab
				                  SET company_name_v='$motifName'
								     ,company_desc_v='$description'
							    WHERE company_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  master_companies_tab WHERE company_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //  echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getCompanyStats($profileId, $companyId, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCompanyStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $companySql = "";

            if ($companyId != -1) {

                $companySql = " AND b.company_id_n = '$companyId' ";
            }



            $sqlQuery = "

						SELECT  date_format(event_datetime_d,'%Y-%m-%d' ) eventDateTime
							   ,b.company_name_v name
							   ,c.motif_name_v 
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_companies_tab b
							 , master_motifs_tab c
						where a.company_name_v = b.company_id_n
						and c.motif_id_n = a.reason_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$companySql
						group by date_format(event_datetime_d,'%Y-%m-%d' ), b.company_name_v, c.motif_name_v
						order  by event_datetime_d desc     

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getUserDetailByRightExtend($profile, $userId, $id, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserDetailByRightExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";
            $usql = "";

            if ($profile == 2) {


                $userSql = " and (a.user_id_n='$userId' OR a.creator_id_n='$userId') ";
            }

            if ($id > 0) {

                $usql = " AND a.user_id_n = '$userId'";
            }



            $sqlQuery = "
                    select a.user_id_n
                        ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
						,a.profile_id_n
                        ,a.creation_date_d
                        ,a.mobile_phone_v
                        ,a.email_v
                        ,b.profile_name_v 
                        ,c.description_v status_desc
                        ,a.status_n
                 from master_users_tab a,
                    master_profiles_tab b,
                    master_status_tab c
                where a.profile_id_n = b.profile_id_n
                and a.status_n = c.status_n
                $userSql
				 $usql

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddUser($opId, $id, $profileId, $login, $firstName, $lastName, $password, $mobilePhone, $userId, $emailId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($opId == 0) {


                $sqlQuery = "INSERT INTO master_users_tab (user_id_n, creation_date_d, user_name_v, password_v, profile_id_n, creator_id_n, first_name_v, last_name_v, mobile_phone_v, email_v, status_n) VALUES (null, now(),'$login','$password','$profileId','$userId','$firstName','$lastName','$mobilePhone','$emailId','0')";

                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_users_tab 
				                  SET   user_name_v = '$login'
								       ,profile_id_n = '$profileId'
									   ,first_name_v = '$firstName'
									   ,last_name_v = '$lastName'
									   ,mobile_phone_v= '$mobilePhone'
									   ,email_v = '$emailId'
							   WHERE user_id_n ='$id' ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE from master_sip_tab  WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $sqlQuery = "DELETE from master_users_tab WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }



            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $totalUser;
    }

    public function getSCCAgencies($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCAgencies()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE agency_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   agency_id_n
							,agency_name_v
							,agency_desc_v
					FROM `master_agencies_tab` 
					$idSql
					order by 2 asc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddAgency($opId, $id, $name, $description) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddAgency()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_agencies_tab  (agency_id_n, creation_datetime_d,  agency_name_v, agency_desc_v) VALUES (null,now(), '$name','$description')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_agencies_tab
				                  SET agency_name_v='$name'
								     ,agency_desc_v='$description'
							    WHERE agency_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  master_agencies_tab WHERE agency_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddSCCUserExtend($opId, $id, $profileId, $login, $firstName, $lastName, $password, $mobilePhone, $userId, $emailId, $primaryAdress) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSCCUserExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($opId == 0) {


                $sqlQuery = "INSERT INTO master_users_tab (user_id_n, creation_date_d, user_name_v, password_v, profile_id_n, creator_id_n, first_name_v, last_name_v, mobile_phone_v, email_v, primary_address_v, status_n) VALUES (null, now(),'$login','$password','$profileId','$userId','$firstName','$lastName','$mobilePhone','$emailId','$primaryAdress','0')";

                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_users_tab 
				                  SET   user_name_v = '$login'
								       ,profile_id_n = '$profileId'
									   ,first_name_v = '$firstName'
									   ,last_name_v = '$lastName'
									   ,mobile_phone_v= '$mobilePhone'
									   ,email_v = '$emailId'
									   ,primary_address_v = '$primaryAdress'
							   WHERE user_id_n ='$id' ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE from master_sip_tab  WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

                $sqlQuery = "DELETE from master_users_tab WHERE user_id_n in ($id)  ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }



            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $totalUser;
    }

    public function UpdateAddTicketExtend($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $callType, $status, $customerType, $agencyName, $callModule, $submodule, $callprority) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicketExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
					   ,mobile2_phone_v='$mobileNumber'
					   ,gender_v=''
					   ,reason_category_n ='$callModule'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_6='$customerType'
					   ,char_field_7='$agencyName'
                                           ,char_field_3='$submodule'
                                           ,char_field_4='$callprority'
                                           ,mobile1_phone_v='$callerId'
                                           $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,char_field_5,aknowledge_date_d, closure_date_d, status_n,company_name_v, char_field_6,char_field_7,char_field_3,char_field_4 )
              VALUES (NULL, now(), '$csrId', '$userId', '$callerId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callModule','$callReasonType',0,'','$callType','$ack','$cls','$status','$company','$customerType','$agencyName','$submodule','$callprority') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            echo $sqlQuery; 
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddTicketExtend_back($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $callType, $status, $customerType, $agencyName) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicketExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
					   ,mobile2_phone_v='$mobileNumber'
					   ,gender_v=''
					   ,reason_category_n ='$callReasonType'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_6='$customerType'
					   ,char_field_7='$agencyName'
					   $ackSql
					   $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,char_field_5,aknowledge_date_d, closure_date_d, status_n,company_name_v, char_field_6,char_field_7 )
              VALUES (NULL, now(), '$csrId', '$userId', '$callId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callReasonType','$callReasonType',0,'','$callType','$ack','$cls','$status','$company','$customerType','$agencyName') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCAgencyByUserId($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCAgencyByUserId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {




            $sqlQuery = "
                  SELECT   agency_id_n
							,agency_name_v
							,agency_desc_v
					FROM `master_agencies_tab` a,
					      master_users_tab b 
					WHERE a.agency_id_n = b.primary_address_v
					AND  user_id_n = '$userId'
                                            limit 1
					
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryData;
    }

    public function getBasicCallReasonStats($profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getBasicCallReasonStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $callreasonSql = "";

            if ($status != -2) {

                $statusSql = " AND a.status_n = '$status' ";
            }



            $sqlQuery = "

						SELECT  b.motif_id_n
						       ,b.motif_name_v name
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_motifs_tab b
						where a.reason_n = b.motif_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$callreasonSql
						$statusSql
						group by  b.motif_id_n, b.motif_name_v
						order  by total desc     

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
        ;
    }

    public function getBasicCallReasonStatsCount($profileId, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getBasicCallReasonStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $callreasonSql = "";

            if ($status != -2) {

                $statusSql = " AND a.status_n = '$status' ";
            }



            $sqlQuery = "

						SELECT count(1) total
						FROM `crm_tickets_tab` a
							 , master_motifs_tab b
						where a.reason_n = b.motif_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$callreasonSql  
						$statusSql 

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function getActivityReport($profileId, $startDate, $endDate, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getActivityReport()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $callreasonSql = "";

            if ($status != -1) {

                $statusSql = " AND a.status_n = '$status' ";
            }



            $sqlQuery = "

                       
					   SELECT concat(a.first_name_v,' ',a.last_name_v)  customer_name
						  ,(select company_name_v from master_companies_tab where company_id_n = a.company_name_v) company_name_v
						  ,a.char_field_5  call_type_v
						  ,a.call_direction_n
						  ,(select motif_name_v from master_motifs_tab where motif_id_n= a.reason_n) motif_name_v
						  ,a.ticket_reason_desc_v customer_query
						  ,( select comment_v from scc_ticket_comments_tab where a.ticket_number_v = ticket_number_v and comment_type_n=1 order by comment_id_n desc limit 1) agent_response
						  ,a.email_id_v
						  ,concat(a.mobile1_phone_v,'/',a.mobile2_phone_v) contact
						  ,date_format(a.event_datetime_d,'%Y-%m-%d %H:%i:%s') call_date
						  ,(select concat(first_name_v,' ',last_name_v)  from master_users_tab  where user_id_n = a.user_id_n) agent_name
						  ,(select  type_v  from customer_type_tab  where type_id_n = a.char_field_6) type_v
					FROM  `crm_tickets_tab` a
					WHERE  a.event_datetime_d >='$startDate'
					and   a.event_datetime_d <='$endDate'
					$statusSql
					order by    a.event_datetime_d asc

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
        ;
    }

    public function getExcludeCallReasonStats($excludedIds) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getExcludeCallReasonStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $callreasonSql = "";

            $sqlQuery = "

						SELECT motif_name_v name
					FROM `master_motifs_tab`
					WHERE motif_id_n not in ($excludedIds)    

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAutocompleteCompany($search) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAutocompleteCompany()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $search = strtoupper($search);

            $sqlQuery = "

						SELECT company_name_v, company_id_n
					FROM `master_companies_tab`
					WHERE upper(company_name_v) like '%$search%' 
					

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function checkAdminUser($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkAdminUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                 select count(1) total 
					from role_details_tab r
						, user_roles_tab u
					where r.ROLE_ID_N = u.ROLE_ID_N
					and  r.MODULE_ID_N = -1
					and  r.MENU_ID_N = -1
					and r.OBJECT_ID_N = -1
					and r.OBJECT_RIGHT_N = -1
					and u.user_id_n = '$userId'
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $total;
    }

    public function getModulesByUserRole($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getModulesByUserRole()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                 select m.module_id_n
									  ,m.creation_date_d
									  ,m.module_name_v
									  ,m.version_v
									  ,m.description_v
									  ,m.status_n
					from role_details_tab r
						, user_roles_tab u
						, master_modules_tab m
					where r.ROLE_ID_N = u.ROLE_ID_N
					and u.user_id_n = '$userId'
					and  (  r.MODULE_ID_N = -1  OR r.MODULE_ID_N = m.MODULE_ID_N )
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function BuildHeaderMenu($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec BuildHeaderMenu()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                SELECT distinct  a.level_id_n
                        , a.creation_datetime_d
                        , a.menu_name_v
                        , a.menu_desc_v 
                        , a.status_n
                        , (select count(1) total from menu_builder_tab m where m.level_n = level_id_n) totalMenu 
                  FROM `menu_headers_tab` a
                       ,  role_details_tab r
		       , user_roles_tab u
		 WHERE r.ROLE_ID_N = u.ROLE_ID_N
		 and u.user_id_n = '$userId'
		 and r.header_menu_id_n = a.level_id_n 			
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getMenuBuilderItemByLevel($levelId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenuBuilderItemByLevel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT *
                FROM menu_builder_tab 
                WHERE level_n ='$levelId'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $queryData;
    }

    public function getModulesByHeaderId($levelId, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getModulesByHeaderId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";

            $sqlQuery = "  
                       
                       select distinct m.module_id_n
									  ,m.creation_date_d
									  ,m.module_name_v
									  ,m.version_v
									  ,m.description_v
									  ,m.status_n
					from  master_modules_tab m
                                            , user_roles_tab a
                                            , role_details_tab b
					where a.role_id_n = b.role_id_n
                                        and  m.module_id_n = b.module_id_n 
                                        and m.header_menu_id_n = $levelId
                                        and a.user_id_n = $userId
                                  
                                      


                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemUsersById($userId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemUsersById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";

            $limitQuery = "";
            if ($option)
                $limitQuery = "LIMIT $startLimit, $maxElement";


            if ($userId != "") {

                $userSql = " AND a.user_id_n = '$userId'";
            }



            $sqlQuery = "
                    select a.user_id_n
                         ,DATE_FORMAT(a.creation_date_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    " ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
			,a.profile_id_n
                        ,a.mobile_phone_v
                        ,a.email_v
                        ,c.description_v status_desc
                        ,a.status_n	
                 from master_users_tab a,
                    master_status_tab c
                where a.status_n = c.status_n
                
                $userSql
                $limitQuery

                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getUserRolesById($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserRolesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {




            $sqlQuery = "SELECT b.role_name_v
                FROM user_roles_tab a
				     , master_roles_tab b
                WHERE a.role_id_n = b.role_id_n
				AND a.user_id_n  ='$userId'"
            ;
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemRoles($userId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserRolesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $limitQuery = "";
            $userSql = "";

            if ($userId != -1) {


                $userSql = " and n.user_id_n ='$userId' ";
            }



            if ($option)
                $limitQuery = " limit $startLimit , $maxElement + $startLimit ";

            $sqlQuery = "
                    select role_id_n
							  ,DATE_FORMAT(m.creation_datetime_d,'%d/%m/%Y') creation_datetime_d
							  ,m.role_name_v
							  ,m.role_desc_v
							  ,m.status_n
							  ,n.user_name_v
						from  master_roles_tab m
							 ,master_users_tab n
						where m.user_id_n = n.user_id_n
						order by 1 asc
					        $limitQuery 
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemModules($moduleId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserRolesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $moduleSql = "";

            if ($moduleId != -1) {

                $moduleSql = "where m.MODULE_ID_N='$moduleId' ";
            }

            $sqlQuery = "  
                   select m.MODULE_ID_N
						  ,m.PLATFORM_ID_N
						  ,m.MODULE_NAME_V
						  ,m.VERSION_V
						  ,m.DESCRIPTION_V
						  ,m.SHORT_DESC_V
						  ,m.STATUS_N
						  ,to_char(m.CREATION_DATE_D,'DD/MM/YYYY') CREATION_DATE_D
					from master_modules_tab m
                    $moduleSql
                ";

            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAccessLevel($levelId, $option) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAccessLevel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $optionSql = "";

            if ($option) {

                $optionSql = "where md.access_n='$levelId' ";
            }

            $sqlQuery = "  
                   select  md.level_id_n
						   ,md.access_n
						   ,md.access_desc_v
					from master_access_level_tab md
                    $optionSql
                ";

            //  echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemRolesById($roleId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserRolesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
                    select  m.role_id_n
							  ,DATE_FORMAT(m.creation_datetime_d,'%d/%m/%Y')  creation_datetime_d
							  ,m.role_name_v
							  ,m.role_desc_v
						from  master_roles_tab m
						where m.role_id_n = '$roleId'
						order by 1 asc
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getRoleDetailsById($roleId) {



        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserRolesById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";

            $sqlQuery = "
                    select  m.role_id_n
							  ,DATE_FORMAT(m.creation_datetime_d,'%d/%m/%Y')  creation_datetime_d
							  ,m.role_name_v
							  ,m.role_desc_v
							  ,n.module_id_n 
							  ,n.menu_id_n
							  ,n.object_id_n
							  ,n.object_right_n
                                                          ,n.header_menu_id_n 
                                                          , (select menu_name_v from menu_headers_tab ma where ma.level_id_n = n.header_menu_id_n ) headerName
							  ,( select  module_name_v from master_modules_tab p where p.module_id_n = n.module_id_n ) module
							  , ( select menu_name_v from menu_builder_tab c where c.menu_id_n = n.menu_id_n ) menu
							  , ( select menu_name_v from menu_details_tab a where a.topmenu_id_n = n.object_id_n ) submenu
							  , ( select access_desc_v from master_access_level_tab b where b.access_n = n.object_right_n ) uright
						from  master_roles_tab m
							 ,role_details_tab  n
						where m.role_id_n = n.role_id_n
						and  m.role_id_n = '$roleId'
						order by 1 asc
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemHeader($headerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemHeader()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $headerSQL = "";

            if ($headerId != -1) {

                $headerSQL = "where m.level_id_n='$headerId' ";
            }

            $sqlQuery = "  
                   select m.level_id_n
						  ,m.creation_datetime_d
						  ,m.menu_name_v
						  ,m.menu_desc_v
						  ,m.status_n

					from menu_headers_tab m
                    $headerSQL
                ";

            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getApplicationMenusDetails($headerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getApplicationMenusDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $menuSql = "";

            if ($headerId != -1) {

                $menuSql = "where md.header_menu_id_n='$headerId' ";
            }

            $sqlQuery = "  
                   select  md.module_id_n
						   ,md.module_name_v
						   ,md.version_v
						   ,md.description_v
					from master_modules_tab md
                    $menuSql
                ";

            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getMenusDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getMenusDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $menuSql = "";

            if ($headerId != -1) {

                $menuSql = "where md.module_id_n='$id' ";
            }

            $sqlQuery = "  
                   select  md.menu_id_n
						   ,md.menu_name_v
						   ,md.menu_desc_v
						   ,md.page_link_v
					from menu_builder_tab md
                    $menuSql
                ";

            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSubMenusDetails($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSubMenusDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $menuSql = "";

            if ($headerId != -1) {

                $menuSql = "where md.parent_menu_id='$id' ";
            }

            $sqlQuery = "  
                   select  md.topmenu_id_n
						   ,md.menu_name_v
						   ,md.menu_desc_v
						   ,md.page_link_v
					from menu_details_tab md
                    $menuSql
                ";

            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelRolesDetails($opId, $roleIds, $headerId, $moduleId, $menuId, $submenuName, $submenuId, $submenuPath, $right, $char1, $char2, $char3, $char4, $char5, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelRolesDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            switch ($opId) {

                case 1 : // Insert Query
                    $sqlQuery = "  INSERT INTO role_details_tab  (
											   item_id_n, creation_datetime_d, role_id_n, header_menu_id_n, module_id_n 
											   ,menu_id_n, object_name_v, object_id_n, object_path_v, object_right_n, 
											   char_field_1, char_field_2, char_field_3, char_field_4, char_field_5, status_n) 
											VALUES ( null , now() ,'$roleIds','$headerId' ,'$moduleId'
												,'$menuId' ,'$submenuName' ,'$submenuId' 
												, '$submenuPath', '$right' ,'$char1'
												,'$char2' ,'$char3' ,'$char4'
												,'$char4' , '$status' )  
	
	           ";
                    break;
                case 2 : // Update Query
                    $sqlQuery = "UPDATE  role_details_tab
						              SET module_id_n ='$moduleId'
									     ,menu_id_n='$menuId'
										 ,object_name_v='$submenuName'
										 ,object_id_n='$submenuId'
										 ,object_path_v='$submenuPath'
										 ,object_right_n='$right'
										 ,char_field_1='$char1'
										 ,char_field_2='$char2'
										 ,char_field_3='$char3'
										 ,char_field_4='$char4'
										 ,char_field_5='$char5'
										 ,status_n='$status'
								     WHERE item_id_n='$roleIds'
						";

                    break;
                case 3 : // Delete Query
                    $sqlQuery = "DELETE FROM   role_details_tab  WHERE role_id_n IN ($roleIds)		     
						";
                    break;
            }

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $sqlResult;
    }

    public function UpdateAddDelRoles($opId, $roleIds, $roleName, $roleDesc, $userId, $status) {

        $dbAccess = $this->connectMysqlDatabase();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelRoles()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            switch ($opId) {

                case 1 : // Insert Query
                    $sqlQuery = "  INSERT INTO master_roles_tab (role_id_n, creation_datetime_d, user_id_n, role_name_v, role_desc_v, status_n) VALUES (null, now(), '$userId', '$roleName', '$roleDesc', '$status') ";
                    break;
                case 2 : // Update Query
                    $sqlQuery = "UPDATE  master_roles_tab
						              SET role_name_v='$roleName'
									     ,role_desc_v='$roleDesc'
								     WHERE role_id_n='$roleIds'
						";

                    break;
                case 3 : // Delete Query
                    $sqlQuery = "DELETE FROM   master_roles_tab WHERE role_id_n IN ($roleIds)		     
						";
                    break;
            }



            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function checkRoleInUse($roleId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkRoleInUse()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "SELECT count(1) total 
                FROM user_roles_tab  
                WHERE role_id_n  ='$roleId'"
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $id = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getUserRoleExtend($userId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkRoleInUse()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $queryData = "";
            $total = 0;

            $sqlQuery = "SELECT  b.role_name_v
			                    ,b.role_id_n
								,b.role_desc_v
								,(select count(1)  from user_roles_tab u where u.role_id_n = b.role_id_n and  u.user_id_n = '$userId' ) is_enabled_n
                FROM  master_roles_tab b
                  "
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelUsers($opId, $userId, $username, $pwd, $userType, $profileId, $onwerId, $lang, $citizen, $firstName, $lastName, $primaryPhone, $secondaryPhone, $homePhone, $mobilePhone, $email, $primAddress, $secondAddress, $profession, $char1, $char2, $char3, $char4, $char5, $char6, $char7, $char8, $char9, $char10, $status) {

        $dbAccess = $this->connectMysqlDatabase();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelRoles()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            switch ($opId) {

                case 1 : // Insert Query
                    $sqlQuery = "  INSERT INTO master_users_tab (
									   User_id_n, creation_date_d, user_name_v, 
									   Password_v, user_type_n, profile_id_n, 
									   Creator_id_n, default_lang_v, citizen_v, 
									   First_name_v, last_name_v, primary_phone_v, 
									   Secondary_phone_v, home_phone_v, mobile_phone_v, 
									   Email_v, primary_address_v, secondary_address_v, 
									   Profession_v, char_field_1, char_field_2, 
									   Char_field_3, char_field_4, char_field_5, 
									   Char_field_6, char_field_7, char_field_8, 
									   Char_field_9, char_field_10, status_n) 
									VALUES ( null , now() ,'$username' ,'$pwd'
										,'$userType' ,'$profileId' ,'$onwerId'
										,'$lang' ,'$citizen' ,'$firstName'
										,'$lastName' ,'$primaryPhone' ,'$secondaryPhone'
										,'$homePhone' ,'$mobilePhone' ,'$email'
										,'$primAddress' ,'$secondAddress' ,'$profession'
										,'$char1' ,'$char2' ,'$char3'
										,'$char4' ,'$char5' ,'$char6'
										,'$char7' ,'$char8' ,'$char9'
										,'$char10' ,'$status' ) ";
                    break;
                case 2 : // Update Query
                    $sqlQuery = "UPDATE  master_users_tab
										SET  user_type_n            = '$userType',
										     profile_id_n           = '$profileId',
										     creator_id_n           = '$onwerId',
									             default_lang_v         = '$lang',
										     citizen_v              = '$citizen',
										     first_name_v           = '$firstName',
										     last_name_v            = '$lastName',
										     primary_phone_v        = '$primaryPhone',
										     secondary_phone_v      = '$secondaryPhone',
										     home_phone_v           = '$homePhone',
										     mobile_phone_v         = '$mobilePhone',
										     email_v                = '$email',
										     primary_address_v      = '$primAddress',
										     secondary_address_v    = '$secondAddress',
										     profession_v           = '$profession',
										     char_field_1           = '$char1',
											   char_field_2        = '$char2',
											   char_field_3        = '$char3',
											   char_field_4        = '$char4',
											   char_field_5        = '$char5',
											   char_field_6        = '$char6',
											   char_field_7        = '$char7',
											   char_field_8        = '$char8',
											   char_field_9        = '$char9',
											   char_field_10       = '$char10',
											   status_n            = '$status'
										WHERE  user_id_n           = $userId

						";

                    break;
                case 3 : // Delete Query
                    $sqlQuery = "DELETE FROM   master_users_tab  WHERE user_id_n IN ($userId)		     
						";
                    break;
            }




            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function UpdateAddDelUserRoles($opId, $userId, $roleId, $status) {

        $dbAccess = $this->connectMysqlDatabase();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelUserRoles()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            switch ($opId) {

                case 1 : // Insert Query
                    $sqlQuery = " INSERT INTO user_roles_tab (
										   item_id_n, creation_datetime_d, user_id_n, 
										   role_id_n, status_n) 
										VALUES ( null,now() , '$userId','$roleId'
											,'$status' ) 
											
	           ";
                    break;
                case 2 : // Update Query
                    $sqlQuery = " UPDATE user_roles_tab
										SET   
											   user_id_n           = '$userId',
											   role_id_n           = '$roleId'
											   status_n            = '$status'
										WHERE  user_id_n           = '$userId'

						";

                    break;
                case 3 : // Delete Query
                    $sqlQuery = "DELETE FROM   user_roles_tab  WHERE user_id_n IN ($userId)		     
						";
                    break;
            }




            //echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getSystemUsers($userId, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemUsers()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $queryData = "";
            $total = 0;

            $limitQuery = "";
            $userSql = "";

            if ($option) {


                $userSql = " and m.user_id_n ='$userId' ";
            }


            /*
              if ($option)
              $limitQuery = " LIMIT  $startLimit ,  $startLimit "; */

            $sqlQuery = "
                      select     
					           m.user_id_n
							   ,DATE_FORMAT(m.creation_date_d,'%d/%m/%Y') creation_date_d
							   ,m.user_name_v
							   ,m.first_name_v
							   ,m.last_name_v
							   ,m.email_v
							   ,m.mobile_phone_v
                                                           ,m.password_v
                                                           ,n.description_v status
						from master_users_tab m
						, master_status_tab n
						where m.status_n = n.status_n 
                                                $userSql
                                                ORDER BY m.creation_date_d desc
                                                $limitQuery

                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getLeftMenuByRoles($moduleId, $lang, $userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getLeftMenuByRoles()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                select  m.menu_id_n
							   ,m.creation_date_d
							   ,m.language_id_n
							   ,m.menu_desc_v 
							   ,m.menu_name_v 
							   ,m.page_link_v 
							   ,m.status_n
						from menu_builder_tab m
						where m.module_id_n = $moduleId
						and m.language_id_n='$lang'
						and m.char_field_1 like '%$right%'
						order by m.menu_order_n asc

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllMenuHeader() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllMenuHeader()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                       select level_id_n 
                       from menu_headers_tab 
                       
                       
                  
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllApplicationMenuByHeader($headerId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllApplicationMenu()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                       
                      select module_id_n, header_menu_id_n
                       from master_modules_tab where header_menu_id_n = $headerId
                  
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllMenuBuilderByAppId($appId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllMenuBuilder()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                       
                      select menu_id_n, level_n
                       from menu_builder_tab where module_id_n = $appId
                  
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllSubMenuByMenuId($menuId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllSubMenuByMenuId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                       
                      select topmenu_id_n, parent_menu_id
                       from menu_details_tab where parent_menu_id= $menuId
                  
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function BatchInsertFromHeader($opId, $roleIds, $right) {

        $nRes = false;

        $hres = $this->getAllMenuHeader();

        for ($hresId = 0; $hresId < count($hres); $hresId++) {
            //  echo "Header-> ".$hres[$hresId]['level_id_n'];
            $this->BatchInsertFromApplication($opId, $roleIds, $right, $hres[$hresId]['level_id_n']);
        }

        return $nRes;
    }

    public function BatchInsertFromApplication($opId, $roleIds, $right, $headerId) {

        $nRes = false;

        $apRes = $this->getAllApplicationMenuByHeader($headerId);

        $char1 = $char2 = $char3 = $char4 = $char5 = "";
        if (count($apRes) > 0) {

            for ($apResId = 0; $apResId < count($apRes); $apResId++) {

                $this->BatchInsertFromMenu($opId, $roleIds, $right, $headerId, $apRes[$apResId]['module_id_n']);
            }
        } else {

            $res = $this->UpdateAddDelRolesDetails($opId, $roleIds, $headerId, -1, -1, "None", -1, "None", $right, $char1, $char2, $char3, $char4, $char5, 0);
        }


        return $nRes;
    }

    public function BatchInsertFromMenu($opId, $roleIds, $right, $headerId, $applicationId) {

        $nRes = false;

        $menuRes = $this->getAllMenuBuilderByAppId($applicationId);

        if (count($menuRes)) {


            for ($menuResId = 0; $menuResId < count($menuRes); $menuResId++) {


                $this->BatchInsertFromSubMenu($opId, $roleIds, $right, $headerId, $applicationId, $menuRes[$menuResId]['menu_id_n']);
            }
        } else {

            $res = $this->UpdateAddDelRolesDetails($opId, $roleIds, $headerId, $applicationId, -1, "None", -1, "None", $right, $char1, $char2, $char3, $char4, $char5, 0);
        }





        return $nRes;
    }

    public function BatchInsertFromSubMenu($opId, $roleIds, $right, $headerId, $applicationId, $menuId) {

        $nRes = false;
        $char1 = $char2 = $char3 = $char4 = $char5 = "";

        $subMenuRes = $this->getAllSubMenuByMenuId($menuId);

        if (count($subMenuRes)) {

            for ($subMenuResId = 0; $subMenuResId < count($subMenuRes); $subMenuResId++) {


                $res = $this->UpdateAddDelRolesDetails($opId, $roleIds, $headerId, $applicationId, $menuId, "None", $subMenuRes[$subMenuResId]['topmenu_id_n'], "None", $right, $char1, $char2, $char3, $char4, $char5, 0);
            }
        } else {

            $res = $this->UpdateAddDelRolesDetails($opId, $roleIds, $headerId, $applicationId, $menuId, "None", -1, "None", $right, $char1, $char2, $char3, $char4, $char5, 0);
        }





        return $nRes;
    }

    public function SCCGetAgentList($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetAgentList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($userId != "") {

                $usql = " AND a.user_id_n = '$userId'";
            }



            $sqlQuery = "
                 SELECT   a.agent_id_n
                        , DATE_FORMAT(a.creation_date_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    "  , a.user_id_n
                        , a.caller_id_v
                        , c.description_v
                        ,b.user_name_v
                        ,b.first_name_v
                        ,b.last_name_v
                  FROM `scc_agents_tab` a
                      , master_users_tab b
                      , master_status_tab c
                  where a.user_id_n = b.user_id_n
                  and a.status_n = c.status_n                



                    
                
                $userSql


                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableAgents($roleId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableAgents()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                   select  md.user_id_n
						   ,md.first_name_v
						   ,md.last_name_v
						   ,md.status_n
					from master_users_tab md
                                        , user_roles_tab a
                    where a.user_id_n = md.user_id_n
                    and a.role_id_n=$roleId
                    and a.user_id_n not in (select p.user_id_n from scc_agents_tab p) 
                ";

            //   echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    function UpdateAddSCCAgent($id, $itemId, $userId, $callerId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCRMQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT 
                INTO scc_agents_tab  VALUES (NULL,now(),'$userId','$callerId','$status')";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE scc_agents_tab 
				                 SET user_id_n = '$userId'
								 , 	caller_id_v ='$callerId'
								 ,status_n = '$status'
						     WHERE agent_id_n = '$itemId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM scc_agents_tab WHERE user_id_n in ($itemId)     ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getChannelById($channelId, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $channelSql = "";

            if ($channelId > 0) {

                $channelSql = " AND a.channel_type_n = '$channelId'";
            }



            $sqlQuery = "
                     
                    SELECT a.item_id_n
                          ,a.channel_type_n
                          ,a.channel_desc_v
                          ,a.page_link_v
                          ,a.link_img_v
                          ,a.status_n
                    FROM `master_channels_tab` a
                    WHERE a.status_n ='$status'
                    $channelSql

                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddSCCChannel($opId, $id, $channelType, $userId, $channelName, $desc, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSCCChannel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_channels_tab   VALUES (null,now(), '$userId','$channelName','$desc', '$channelType', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_channels_tab
				                  SET channel_name_v='$channelName'
						 ,channel_desc_v='$desc'
                                                 ,status_n = '$status'
						 WHERE channel_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_channels_tab WHERE channel_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //  echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetServiceChannelById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetServiceChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceChannelSql = "";

            if ($itemId > 0) {

                $serviceChannelSql = " AND a.channel_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                  select  a.channel_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n
                    , a.channel_name_v
                    , a.channel_desc_v desc_v
                    , a.channel_type_n
                    , b.channel_desc_v
                    , b.page_link_v
                    , case a.status_n
                       when 0 then 'ACTIF'
                       when 1 then 'INACTIF'
                      end status_n
              from scc_channels_tab a
                  , master_channels_tab b
              where a.channel_type_n = b.channel_type_n
              $serviceChannelSql
              ORDER BY 1 DESC

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddSIPChannel($opId, $id, $name, $hostName, $port, $type, $username, $secret, $sipType, $itemId, $codecs, $callLimit, $callerId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSIPChannel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO sip_channels_tab  (id, name, host, type, username, secret, sip_type_n,call_limit,allow, port, channel_id_n, callerid, status_n) VALUES (null,'$name','$hostName','$type','$username','$secret','$sipType','$callLimit','$codecs','$port','$itemId','$callerId','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  sip_channels_tab 
			                 SET  name ='$name'
							     ,host ='$hostName'
								 ,secret='$secret'
								 ,sip_type_n='$sipType'
								 ,status_n='$status'
								 ,type = '$type'
								 ,port = '$port'
								 ,username= '$username'
                                                                 ,allow = '$codecs'
                                                                 ,call_limit = '$callLimit'
                                                                 ,callerid = '$callerId'
						   WHERE channel_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  sip_channels_tab WHERE channel_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //  echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetSipVoiceChannelById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetSipVoiceChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $serviceChannelSql = "";

            if ($itemId > 0) {
                $serviceChannelSql = " AND a.channel_id_n = '$itemId'";
            }
            $sqlQuery = "
                
                  select  a.channel_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n, a.channel_name_v, a.channel_desc_v desc_v, a.channel_id_n, b.channel_desc_v
                    , b.page_link_v
                    , case a.status_n
                       when 0 then 'ACTIF'
                       when 1 then 'INACTIF'
                      end  status_n
                    ,c.name,c.host,c.call_limit,c.callerid,c.secret,c.allow,c.port,c.username,c.sip_type_n,c.channel_id_n
              from scc_channels_tab a
                  , master_channels_tab b, sip_channels_tab c
              where a.channel_type_n = b.channel_type_n
              and  c.channel_id_n = a.channel_id_n
              $serviceChannelSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelMailChannel($opId, $id, $accountName, $mailAccount, $accountPassword, $smtpHostName, $smtpHostPort, $smtpSecurityType, $smtpAuth, $inHostname, $inPort, $inSecurityType, $inServerType, $channelId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelMailChannel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `mail_channels_tab` (`item_id_n`, `account_name_v`, `account_email_v`, `account_password_v`, `smtp_hostname_v`, `smtp_port_n`, `smtp_security_type_n`, `use_smtp_auth_n`, `in_hostname_v`, `in_port_n`, `in_security_type_n`, `in_server_type_n`, `channel_id_n`, `status_n`) VALUES (null, '$accountName', '$mailAccount', '$accountPassword', '$smtpHostName', '$smtpHostPort', '$smtpSecurityType', '$smtpAuth', '$inHostname', '$inPort', '$inSecurityType', '$inServerType', '$channelId', '$status')
                ";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  mail_channels_tab 
			                 SET  account_name_v ='$accountName'
							     ,account_email_v ='$mailAccount'
								 ,account_password_v='$accountPassword'
								 ,smtp_hostname_v='$smtpHostName'
								 ,smtp_port_n='$smtpHostPort'
								 ,smtp_security_type_n = '$smtpSecurityType'
								 ,use_smtp_auth_n = '$smtpAuth'
								 ,in_hostname_v= '$inHostname'
                                                                 ,in_port_n = '$inPort'
                                                                 ,in_security_type_n = '$inSecurityType'
                                                                 ,in_server_type_n = '$inServerType'
                                                                 ,status_n = '$status'
                                                                     
						   WHERE channel_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  mail_channels_tab WHERE channel_id_n in ($id)";
            }


            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetMailChannelById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetMailChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceChannelSql = "";

            if ($itemId > 0) {

                $serviceChannelSql = " AND a.channel_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                  select  a.channel_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n
                    , a.channel_name_v
                    , a.channel_desc_v desc_v
                    , a.channel_id_n
                    , b.channel_desc_v
                    , b.page_link_v
                    , a.status_n
                    ,c.account_name_v
                    ,c.account_email_v
                    ,c.account_password_v
                    ,c.smtp_hostname_v
                    ,c.smtp_port_n
                    ,c.smtp_security_type_n
                    ,c.use_smtp_auth_n
                    ,c.in_hostname_v
                    ,c.in_port_n
                    ,c.in_security_type_n
                     ,c.in_server_type_n
                    ,c.channel_id_n
              from scc_channels_tab a
                  , master_channels_tab b
                  , mail_channels_tab c
              where a.channel_type_n = b.channel_type_n
              and  c.channel_id_n = a.channel_id_n
              $serviceChannelSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelSMPPChannel($opId, $id, $host, $port, $port, $systemId, $systemPassword, $mode, $systemType, $srcTon, $srcNpi, $dstTon, $dstNpi, $serviceType, $enquiryDelay, $reconnectDelay, $msgIdType, $outThruput, $inThruput, $charset, $channelId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelSMPPChannel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `smpp_channels_tab` (`item_id_n`, `host_name_v`, `receive_port_n`, `send_port_n`, `system_id_v`, `system_password_v`, `bind_type_n`, `system_type_v`, `src_ton_n`, `src_npi_n`, `dst_ton_n`, `dst_npi_n`, `service_type_v`, `use_ssl_n`, `ssl_client_file_v`, `interface_version_n`, `address_range_v`, `enquire_link_int_n`, `max_pending_submit_n`, `reconnect_delay_n`, `msgid_type_n`, `dlvrd_thrput_n`, `rcvd_thrput_n`, `alt_charset_n`, `channel_id_n`, `status_n`) VALUES (null, '$host', '$port', '$port', '$systemId', '$systemPassword', '$mode', '$systemType', '$srcTon', '$srcNpi', '$dstTon', '$dstNpi', '$serviceType', '0', '0', '34', '0', '$enquiryDelay',0, '$reconnectDelay', '$msgIdType' , '$outThruput', '$inThruput', '$charset','$channelId', '$status')
";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  smpp_channels_tab 
			                 SET  host_name_v ='$host'
							     ,receive_port_n ='$port'
								 ,send_port_n='$port'
								 ,system_id_v='$systemId'
								 ,system_password_v='$systemPassword'
								 ,bind_type_n = '$mode'
								 ,system_type_v = '$systemType'
								 ,src_ton_n= '$srcTon'
                                                                 ,src_npi_n = '$srcNpi'
                                                                 ,dst_ton_n = '$dstTon'
                                                                 ,dst_npi_n = '$dstNpi'
                                                                 ,service_type_v = '$serviceType'
                                                                 ,enquire_link_int_n = '$enquiryDelay'  
                                                                 ,reconnect_delay_n = '$reconnectDelay'
                                                                 ,msgid_type_n = '$msgIdType'
                                                                 ,dlvrd_thrput_n = '$outThruput'
                                                                 ,alt_charset_n = '$charset'
                                                                 ,status_n = '$status'
                                                                     
						   WHERE channel_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  smpp_channels_tab WHERE channel_id_n in ($id)";
            }


            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetSMPPChannelById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetSMPPChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceChannelSql = "";

            if ($itemId > 0) {

                $serviceChannelSql = " AND a.channel_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                  select  a.channel_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n
                    , a.channel_name_v
                    , a.channel_desc_v desc_v
                    , a.channel_id_n
                    , b.channel_desc_v
                    , b.page_link_v
                    , a.status_n
                    ,c.host_name_v
                    ,c.receive_port_n
                    ,c.send_port_n
                    ,c.system_id_v
                    ,c.system_password_v
                    ,c.bind_type_n
                    ,c.system_type_v
                    ,c.src_ton_n
                    ,c.src_npi_n
                    ,c.dst_ton_n
                    ,c.dst_npi_n
                    ,c.service_type_v
                    ,c.enquire_link_int_n
                    ,c.reconnect_delay_n
                    ,c.msgid_type_n
                    ,c.dlvrd_thrput_n
                    ,c.rcvd_thrput_n
                    ,c.alt_charset_n
                    ,c.channel_id_n
              from scc_channels_tab a
                  , master_channels_tab b
                  , smpp_channels_tab c
              where a.channel_type_n = b.channel_type_n
              and  c.channel_id_n = a.channel_id_n
              $serviceChannelSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelHTTPChannel($opId, $id, $url, $timeout, $channelId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelHTTPChannel()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `http_channels_tab` (`item_id_n`, `outgoing_link_v`, `default_timeout_n`, `channel_id_n`, `status_n`) VALUES (NULL, '$url', '$timeout', '$channelId', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  http_channels_tab 
			                 SET  outgoing_link_v ='$name'
							     ,default_timeout_n ='$hostName'
	
						   WHERE channel_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  http_channels_tab WHERE channel_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetHTTPSmsChannelById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetHTTPSmsChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceChannelSql = "";

            if ($itemId > 0) {

                $serviceChannelSql = " AND a.channel_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                  select  a.channel_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n
                    , a.channel_name_v
                    , a.channel_desc_v desc_v
                    , a.channel_id_n
                    , b.channel_desc_v
                    , b.page_link_v
                    , a.status_n
                    ,c.outgoing_link_v
                    ,c.default_timeout_n
              from scc_channels_tab a
                  , master_channels_tab b
                  , http_channels_tab c
              where a.channel_type_n = b.channel_type_n
              and  c.channel_id_n = a.channel_id_n
              $serviceChannelSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetServiceQueueById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetServiceQueueById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceQueueSql = "";

            if ($itemId > 0) {

                $serviceQueueSql = " AND a.queue_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                  select  a.queue_id_n
                     , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  , a.user_id_n
                    , a.queue_name_v
                    , a.queue_desc_v desc_v
                    , a.channel_type_n
                    , b.channel_desc_v
                    , b.page_link_v
                    , a.status_n
                    , c.mode_name_v
              from scc_queues_tab a
                  , master_channels_tab b
                  , master_modes_tab c
              where a.channel_type_n = b.channel_type_n
              and a.queue_mode_n = c.mode_id_n
              $serviceQueueSql
              ORDER BY 1 DESC

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getQueueMemberById($queueId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getQueueMemberById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";
            $usql = "";

            $sqlQuery = "
                    select  a.user_id_n
					       ,b.mobile_phone_v
						   ,b.user_name_v 
                 from queue_members_tab a,
				      master_users_tab b
                where a.queue_id_n = '$queueId'
				and a.user_id_n = b.user_id_n

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelQueueMember($id, $queueId, $userId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelQueueMember()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT INTO queue_members_tab (item_id_n, queue_id_n, user_id_n, status_n)  VALUES (null,$queueId, $userId, $status)";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE queue_members_tab 
				                 SET queue_id_n = '$queueId'
								 ,user_id_n ='$userId'
								 ,status_n = '$status'
						     WHERE item_id_n = '$queueId'
                             ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_affected_rows($dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE FROM queue_members_tab WHERE queue_id_n in ($queueId)     ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_affected_rows($dbAccess['dbConnection']);
            }



            //  echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $totalUser;
    }

    public function UpdateAddDelQueue($opId, $id, $userId, $queueName, $queueDesc, $mode, $channelType, $groupId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `scc_queues_tab` (`queue_id_n`, `creation_datetime_d`, `user_id_n`, `queue_name_v`, `queue_desc_v`, `queue_mode_n`, `channel_type_n`,`reason_group_id_n`, `status_n`) VALUES (NULL, now(), '$userId', '$queueName', '$queueDesc', '$mode', '$channelType','$groupId', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  scc_queues_tab 
			                 SET  queue_name_v ='$queueName'
					     ,queue_desc_v ='$queueDesc'
                                             ,queue_mode_n ='$mode'
                                             ,channel_type_n ='$channelType'
                                             ,reason_group_id_n='$groupId'
                                             ,status_n ='$status'
                            WHERE queue_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_queues_tab WHERE queue_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getUserExtend($queueId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getUserExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $queryData = "";
            $total = 0;

            $sqlQuery = "SELECT  b.user_id_n
			                    ,b.user_name_v
								,b.first_name_v
                                                                ,b.last_name_v
                                                                ,a.profile_id_n
								,(select count(1)  from queue_members_tab  u where u.user_id_n = b.user_id_n and  u.queue_id_n = '$queueId' ) is_enabled_n
                FROM  master_users_tab b
                     , scc_users_tab a
                WHERE a.user_id_n = b.user_id_n
                  "
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetSipVoiceQueueById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetSipVoiceQueueById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceQueueSql = "";

            if ($itemId > 0) {

                $serviceQueueSql = " AND a.queue_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                   select a.queue_id_n
       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    " ,a.queue_name_v
      ,a.queue_desc_v
      ,a.queue_mode_n
      ,a.user_id_n
      ,b.wrapuptime
      ,b.strategy
      ,c.channel_desc_v
      ,d.group_id_n
from scc_queues_tab a
     , voice_queues_tab b
     , master_channels_tab c
     , master_groups_tab d
where a.queue_id_n = b.queue_id_n
and a.channel_type_n = c.channel_type_n
and a.reason_group_id_n = d.group_id_n
$serviceQueueSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelVoiceQueue($opId, $id, $wrappupTime, $strategy, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelVoiceQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";
            $name = "VOICEQ_" . $id;

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `voice_queues_tab` (`item_id_n`, `name`,`wrapuptime`,`strategy`, `queue_id_n`, `status_n`) VALUES (NULL,  '$name', '$wrappupTime', '$strategy', '$id','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  voice_queues_tab 
			                 SET  wrapuptime ='$wrappupTime'
					     ,strategy ='$strategy'
                                             ,status_n ='$status'
                            WHERE queue_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  voice_queues_tab WHERE queue_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetQueueDtlsById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetQueueDtlsById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceQueueSql = "";

            if ($itemId > 0) {

                $serviceQueueSql = " AND a.queue_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                   select a.queue_id_n
       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    " ,a.queue_name_v
      ,a.queue_desc_v
      ,a.queue_mode_n
      ,a.user_id_n
      ,c.channel_desc_v
      ,b.group_id_n
from scc_queues_tab a
     , master_channels_tab c
     , master_groups_tab b
where  a.channel_type_n = c.channel_type_n
and b.group_id_n = a.reason_group_id_n
$serviceQueueSql
              ORDER BY 2 DESC

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetRouteConfigById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetRouteConfigById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $routeSql = "";

            if ($itemId > 0) {

                $routeSql = " AND a.route_id_n = '$itemId'";
            }



            $sqlQuery = "
                

          select a.route_id_n
            , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  ,a.route_name_v
             ,a.route_desc_v
             ,a.channel_type_n
             ,b.channel_desc_v
             ,b.page_link_v
             ,a.status_n
             ,c.form_name_v
             ,a.form_id_n
       from scc_routes_tab a
           , master_channels_tab b
           , scc_forms_tab c
       where a.channel_type_n = b.channel_type_n
       and a.form_id_n = c.form_id_n
       $routeSql
                     ORDER BY 1 DESC


                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableVoiceQueue($channelType) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableVoiceQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                    select  a.queue_id_n chId
                    , a.queue_name_v  chName
              from scc_queues_tab a
                  , master_channels_tab b
              where a.channel_type_n = b.channel_type_n
              and b.channel_type_n = '$channelType'
              ORDER BY 1 DESC
                ";

            //     echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableIvrList() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableIvrList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                    select  a.ivr_id_n chId
                    , a.ivr_name_v  chName
              from scc_ivr_data_tab a
              ORDER BY 1 DESC
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableVoiceExtension($channelType) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableVoiceQueue()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                    select  a.channel_id_n chId
                    , a.channel_name_v  chName
              from scc_channels_tab a
                  , master_channels_tab b
                  , sip_channels_tab c
              where a.channel_type_n = b.channel_type_n
              and a.channel_id_n = c.channel_id_n
              and b.channel_type_n = '$channelType'
              ORDER BY 1 DESC
                ";

            //  echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelRouteConfig($opId, $id, $routeName, $routeDesc, $userId, $channelType, $queueId, $channelId, $formId, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelRouteConfig()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";
            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `scc_routes_tab` (`route_id_n`, `creation_datetime_d`, `route_name_v`, `route_desc_v`,`user_id_n`, `channel_type_n`, `queue_id_n`, `channel_id_n`, `form_id_n`,`status_n`) VALUES (NULL, now(), '$routeName', '$routeDesc','$userId', '$channelType', '$queueId', '$channelId', '$formId', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  scc_routes_tab 
			                 SET  route_name_v ='$routeName'
					     ,route_desc_v ='$routeDesc'
                                             ,queue_id_n ='$queueId'
                                             ,channel_id_n ='$channelId'
                                             ,form_id_n = '$formId'
                                             ,status_n = '$status'
                            WHERE route_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_routes_tab  WHERE route_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function UpAddDelVoiceRtCfg($opId, $id, $routeId, $dstAddress, $dstType, $dstEntity, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpAddDelVoiceRtCfg()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";
            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `voice_routes_tab` (`route_id_n`, `dst_address_v`, `dst_type_n`, `dst_entity_id_n`, `status_n`) VALUES ('$routeId', '$dstAddress', '$dstType', '$dstEntity', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  voice_routes_tab 
			                 SET  dst_address_v ='$dstAddress'
					     ,dst_type_n ='$dstType'
                                             ,dst_entity_id_n ='$dstEntity'
                            WHERE route_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  voice_routes_tab  WHERE route_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetVoiceRouteConfig($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetVoiceRouteConfig()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $routeSql = "";

            if ($itemId > 0) {

                $routeSql = " AND a.route_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                   select a.route_id_n
       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    " ,a.route_name_v
      ,a.route_desc_v
      ,a.queue_id_n
      ,a.channel_id_n
      ,a.channel_type_n
      ,a.form_id_n
      ,a.status_n
      ,b.dst_address_v
      ,b.dst_entity_id_n
from scc_routes_tab a
     , voice_routes_tab b
where a.route_id_n = b.route_id_n
$routeSql
              ORDER BY 1 DESC

                ";
            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableQueueById($channelType) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableQueueById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                    select  a.queue_id_n chId
                    , a.queue_name_v  chName
              from scc_queues_tab a
                  , master_channels_tab b
              where a.channel_type_n = b.channel_type_n
              and b.channel_type_n = '$channelType'
              ORDER BY 1 DESC
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAvailableChannelById($channelType) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAvailableChannelById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "  
                    select  a.channel_id_n chId
                    , a.channel_name_v  chName
              from scc_channels_tab a
                  , master_channels_tab b
              where a.channel_type_n = b.channel_type_n
              and b.channel_type_n = '$channelType'
              ORDER BY 1 DESC
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetRouteConfig($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetRouteConfig()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $routeSql = "";

            if ($itemId > 0) {

                $routeSql = " WHERE a.route_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                   select a.route_id_n
       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    " ,a.route_name_v
      ,a.route_desc_v
      ,a.queue_id_n
      ,a.channel_id_n
      ,a.channel_type_n
      ,a.status_n
      ,a.form_id_n
from scc_routes_tab a
$routeSql
              ORDER BY 1 DESC

                ";
            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpAddDelSmsRtCfg($opId, $id, $routeId, $srcAddress, $status) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpAddDelSmsRtCfg()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";
            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `sms_routes_tab` (`route_id_n`, `src_address_v`, `status_n`) VALUES ('$routeId', '$srcAddress', '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  sms_routes_tab 
			                 SET  src_address_v ='$srcAddress'
                                             ,status_n ='$status'
                            WHERE route_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  sms_routes_tab  WHERE route_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCGetRteCfg($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetRouteConfig()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $routeSql = "";

            if ($itemId > 0) {

                $routeSql = " AND a.route_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                   select a.route_id_n
       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    " ,a.route_name_v
      ,a.route_desc_v
      ,a.queue_id_n
      ,a.channel_id_n
      ,a.channel_type_n
      ,a.status_n
      ,b.src_address_v
      ,a.form_id_n
from scc_routes_tab a
     , sms_routes_tab b
where a.route_id_n = b.route_id_n
$routeSql
              ORDER BY 1 DESC

                ";
            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetCalendars($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetCalendars()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($userId != "") {

                $usql = " AND s.user_id_n = '$userId'";
            }



            $sqlQuery = "
                    select s.calendar_id_n
                      , DATE_FORMAT(s.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " . " 
                        ,s.type_id_n
                        ,s.calendar_name_v
                        ,s.calendar_desc_v
                        , DATE_FORMAT(s.start_date_d, '" . $_SESSION['cfg']['date.format'] . "') start_date_d " . " 
                        , DATE_FORMAT(s.end_date_d, '" . $_SESSION['cfg']['date.format'] . "') end_date_d " . " 
                        ,s.start_time_d
                        ,s.end_time_d
                        ,s.fulltime_indicator_v
                        ,s.days_list_v
                        ,s.months_list_v
                        ,s.status_n
                        ,p.user_name_v
              from scc_calendars_tab s
                  , master_users_tab p
              where s.user_id_n = p.user_id_n
               
                $userSql


                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCLastCallByMsisdn($msisdn) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCLastCallByMsisdn()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                     SELECT   a.event_datetime_d
                            , a.ticket_number_v
                            , a.reason_n
                            , a.status_n 
                            , b.motif_name_v
                            , c.user_name_v
                            , d.description_v
                            , a.ticket_reason_desc_v	
                            , (select comment_v from scc_ticket_comments_tab s  where s.ticket_number_v = a.ticket_number_v and comment_type_n = 1 order by s.event_datetime_d desc limit 1) agent_comment_v
                     FROM `crm_tickets_tab` a
                         , guce_modules_tab b
                         , master_users_tab c
                         , master_status_tab d
                     where b.motif_id_n = a.reason_category_n
                     and a.user_id_n = c.user_id_n
                     and d.status_n = a.status_n
                     and a.mobile1_phone_v like '%$msisdn%'
                     order by 1 desc
                     limit 5
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketHistory($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                     SELECT item_id_n 
                            ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%I:%S') event_date
                            ,b.user_name_v
                            ,(select profile_name_v from master_profiles_tab m where m.profile_id_n = a.profile_id_n) profile_name_v
                            ,a.ticket_number_v
                            ,a.comment_v
                            ,c.description_v
                      FROM `crm_tickets_history_tab` a
                          , master_users_tab b
                          , master_status_tab c
                      where a.user_id_n = b.user_id_n
                      and a.status_n = c.status_n
                      and a.ticket_number_v='$ticketId'
                      order by 1 desc
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCPriorities($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCPriorities()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE priority_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   priority_id_n
							,short_desc_v
							,long_desc_v
                                                        ,status_n
					FROM `master_priorities_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGUCEModules($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGUCEModules()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE motif_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   motif_id_n
							,motif_name_v
							,motif_desc_v
					FROM `guce_modules_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCInprogressTicketDetails($userId, $right, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCInprogressTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            if (!$right) {

                $userSql = "and c.user_id_n='$userId'";
            }



            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
                                                   ,case a.call_direction_n
						     when 0 then 'Entrant'
							 when 1 then 'Sortant'
							end call_direction
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.status_n not in  ('3','7')
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddStdTicket($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $status, $priority) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddStdTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
                                           ,mobile1_phone_v='$callerId'
					   ,mobile2_phone_v='$mobileNumber'
					   ,reason_category_n ='$callReasonType'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_4='$priority'
					   $ackSql
					   $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,aknowledge_date_d, closure_date_d, status_n,company_name_v,char_field_4 )
              VALUES (NULL, now(), '$csrId', '$userId', '$callerId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callReasonType','$callReasonType',0,'','$ack','$cls','$status','$company','$priority') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getAssigneeProfileById($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAssigneeProfileById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND assignee_id_n <> '$id'";
            }

            $sqlQuery = "
                  SELECT   b.profile_id_n
							,b.profile_name_v
							,b.long_desc_v
					FROM `assignee_group_tab` a,
                                             master_profiles_tab b
                                        WHERE b.profile_id_n = a.assignee_id_n
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function checkSaveTicketDetails($ticketId) {
        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkSaveTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT count(1) total
                FROM crm_tickets_tab 
                WHERE ticket_number_v ='$ticketId'"
                    . " AND status_n <> -1";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $totalUser = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $totalUser;
    }

    public function updateTicketTransferMode($ticketId, $trStatus) {
        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateTicketTransferMode()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE crm_tickets_tab
                SET char_field_9='$trStatus'
                    
                WHERE ticket_number_v='$ticketId'
                ";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $status;
    }

    public function UploadTicketHistory($userId, $profileId, $ticketNumber, $type, $csrComment, $status) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UploadTicketHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "INSERT 
                INTO crm_tickets_history_tab  VALUES (NULL,now(),'$userId','$profileId','$ticketNumber','$type','$csrComment','$status')";

            //  echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function ChangeTicketStatus($ticketNumber, $newStatus) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec ChangeTicketStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET  status_n= '$newStatus'
					WHERE ticket_number_v ='$ticketNumber' ";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function updateTicketByStatus($ticketId, $closureDate, $trStatus) {
        $dbAccess = $this->getMysqlConnection();
        $status = false;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec updateTicketByStatus()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "UPDATE crm_tickets_tab
                SET status_n='$trStatus',
                    closure_date_d='$closureDate'
                WHERE ticket_number_v='$ticketId'
                ";
            //echo $sqlQuery;
            $status = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $status;
    }

    public function sccGetCallEventById($userId) {

        $dbAccess = $this->connectMysqlDatabase();
        $ticket = -1;
        $queryData = "";

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec sccGetCallEventById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "  
                  select  m.ticket_number_v, p.page_link_v as formLink , n.item_id_n
					FROM  scc_callevent_listener_tab m
                                             , crm_tickets_tab n
                                             , scc_forms_tab p
					where m.ticket_number_v = n.ticket_number_v
                                        and p.form_id_n = n.char_field_10
                                        and m.user_id_n = $userId
                                            limit 1

					
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $count = mysql_num_rows($sqlResult);

            if ($count > 0) {

                $queryData = mysql_fetch_array($sqlResult);
                $ticket = $queryData['ticket_number_v'];

                $sqlQuery = "delete FROM  scc_callevent_listener_tab  where ticket_number_v = $ticket   ";
                // echo $sqlQuery;
                $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $queryData;
    }

    public function checkSccOnlineUser($userId, $extension) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkSccOnlineUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT  s.item_id_n
                                ,s.user_id_n
                                ,s.extension_n
                                ,s.last_update_d
                                ,s.status_n
                FROM scc_online_users_tab s
                WHERE  s.extension_n ='$extension'"
                    . " LIMIT 1 "


            ;

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelSCCOnlineUser($opId, $id, $userId, $extension, $lastUpdate, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelSCCOnlineUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `scc_online_users_tab` (`item_id_n`, `event_datetime_d`, `user_id_n`, `extension_n`, `last_update_d`, `status_n`) VALUES (NULL, now(), '$userId', '$extension', now(), '$status')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_online_users_tab
				                  SET user_id_n='$userId'
						      ,extension_n='$extension'
                                                      , last_update_d = now()
			     WHERE item_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_online_users_tab WHERE user_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getDefaultPageById($userId) {
        $dbAccess = $this->getMysqlConnection();
        $filename = "dashboard.php";

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getDefaultPageById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "  SELECT distinct file_path_v
                        FROM `scc_users_tab` u,
                              default_pages_tab d
                        WHERE u.profile_id_n = d.role_id_n
                        and u.user_id_n = $userId
                        order by priority_id_n desc
                        limit 1

";
            //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $filename = $queryData['file_path_v'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $filename;
    }

    public function getCallGlobalStats($startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallGlobalStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                
                select t.eventDate  EVENT_DATE
                        , sum(PICKED) TOTAL_PICKED
                        , sum(UNPICKED) TOTAL_UNPICKED
                        , ( sum(PICKED) + sum(UNPICKED) ) TOTAL

                 from (
                 SELECT date_format(m.event_datetime_d,'$granularity') eventDate
                       ,  case m.status_n
                                    when 7 then 0 ELSE 1
                                  end PICKED
                       , case m.status_n
                                    when 7 then 1 ELSE 0
                                  end UNPICKED
                 FROM `crm_tickets_tab` m 
                 WHERE m.event_datetime_d >='$startDate'
                 AND  m.event_datetime_d <='$endDate'

                 ) t
                 group by t.eventDate
                 LIMIT $maxElement


                     
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallDtlsStats($startDate, $endDate, $status, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallDtlsStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $statusSql = "";

            if ($status != -1) {

                $statusSql = "WHERE PICKED=" . $status;
            }


            $sqlQuery = "
                
             SELECT eventDate
                   , src
                   , dst
                   , duration
                   , PICKED
             FROM (
                    SELECT date_format(m.calldate,'%d/%m/%Y %H:%I:%S') eventDate
                           ,  src
                           ,  dst
                           ,  duration
                           ,  (select case status_n
                                        when 7 then 0 ELSE 1
                                      end
                              from crm_tickets_tab c where m.uniqueid = c.char_field_2) PICKED
                     FROM `master_cdr_tab` m 
                     WHERE m.calldate >='$startDate'
                     AND  m.calldate <='$endDate'
                     ORDER BY 1 DESC
                     LIMIT $maxElement
                 ) t
              $statusSql 
                 

                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketGlobalStats($userId, $pageAccessLevel, $status, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketGlobalStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($pageAccessLevel == 0) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($userId != -1) {


                $userSql = "AND a.user_id_n='$userId' ";
            }



            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            $sqlQuery = "
                      
                 SELECT     eventDateTime
						   ,sum(INITIALISE) INITIALISE
						   ,sum(OUVERT) OUVERT
						   ,sum(CLOS)  CLOS
                                                   
					   FROM (
						SELECT  date_format(event_datetime_d,'$granularity' ) eventDateTime
							   ,case a.status_n
							  when -1  then 1 else 0
							 end INITIALISE
							   ,case a.status_n
							  when 2  then 1 else 0
							 end OUVERT
							   ,case a.status_n
							  when 3  then 1 else 0
							 end CLOS
						FROM `crm_tickets_tab` a
							 , master_status_tab b
						where a.status_n = b.status_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$userSql
                                                $statusSql

						order  by 1 desc
						   ) t
					group by eventDateTime
					order by eventDateTime desc
					 

                        

                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketDetailStats($userId, $pageAccessLevel, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCDetailStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($pageAccessLevel == 0) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($userId != -1) {


                $userSql = "AND a.user_id_n='$userId' ";
            }



            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            if ($startDate != NULL) {
                $date1Sql = "and a.event_datetime_d>='$startDate'";
            }

            if ($endDate != NULL) {
                $date2Sql = "and a.event_datetime_d <='$endDate'";
            }

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,c.first_name_v
						   ,c.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.char_field_5
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,concat(a.first_name_v,' ',a.last_name_v) customerName
						   ,a.ticket_reason_desc_v
						   ,a.email_id_v
						   ,(select   d.type_v from customer_type_tab d where d.type_id_n = a.char_field_6 ) type_v
                                                   ,(select   sm.motif_name_v from scc_modules_tab sm where sm.motif_id_n = a.reason_category_n ) module
                                                   ,(select   mm.motif_name_v from master_sub_motifs_tab mm where mm.motif_id_n = a.char_field_3 ) submodule
                                                   , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                    AND a.char_field_10 NOT IN (4, 5)
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc
                    limit 1000

                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCTicketDetailStatsReclamation($userId, $pageAccessLevel, $status, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCDetailStatsReclamation()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($pageAccessLevel == 0) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($userId != -1) {


                $userSql = "AND a.user_id_n='$userId' ";
            }



            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            if ($startDate != NULL) {
                $date1Sql = "and a.event_datetime_d>='$startDate'";
            }

            if ($endDate != NULL) {
                $date2Sql = "and a.event_datetime_d <='$endDate'";
            }

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,c.first_name_v
						   ,c.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.char_field_5
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,concat(a.first_name_v,' ',a.last_name_v) customerName
						   ,a.ticket_reason_desc_v
						   ,a.email_id_v
						   ,(select   d.type_v from customer_type_tab d where d.type_id_n = a.char_field_6 ) type_v
                                                   ,(select   sm.motif_name_v from scc_modules_tab sm where sm.motif_id_n = a.reason_category_n ) module
                                                   ,(select   mm.motif_name_v from master_sub_motifs_tab mm where mm.motif_id_n = a.char_field_3 ) submodule
                                                   , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                    AND a.char_field_10 IN (4, 5)  -- Filtrer uniquement les tickets de réclamation
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc
                    limit 1000

                        

                ";

           // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }


    public function SCCGetGroupsList($groupId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetGroupsList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $groupSql = "";

            if ($groupId != 0) {

                $groupSql = " AND a.group_id_n = '$groupId'";
            }



            $sqlQuery = "
                 
                  
                SELECT a.group_id_n
                       , DATE_FORMAT(a.creation_date_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    "   , a.group_name_v
                         ,b.type_name_v
                       , b.type_desc_v
                 FROM `master_groups_tab` a
                      , group_types_tab b
                 WHERE a.group_type_n = b.type_id_n
                 $groupSql



                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSystemGroupTypes() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemGroupTypes()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                    select type_id_n

							  ,type_name_v
							  ,type_desc_v
						from  group_types_tab 
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $this->mysqlRessourceJson($sqlResult);
    }

    function UpdateAddDelSCCGroup($id, $itemId, $userId, $groupTypeId, $groupName) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelSCCGroup()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT 
                INTO master_groups_tab (group_id_n, creation_date_d, group_name_v, owner_id_n, group_type_n, status_n)  VALUES (NULL,now(),'$groupName','$userId','$groupTypeId','0')";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE master_groups_tab 
				                 SET group_type_n = '$groupTypeId'
								 , group_name_v ='$groupName' 
						     WHERE group_id_n = '$itemId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM master_groups_tab WHERE group_id_n in ($itemId)     ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSystemGroupByType($type) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSystemGroupByType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                                     select group_id_n
					   ,group_name_v
				     from  master_groups_tab  
                                     where group_type_n = $type
                ";

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetTeams($teamId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetTeams()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != 0) {

                $teamSql = " AND a.team_id_n = '$teamId'";
            }



            $sqlQuery = "
                 
                  
                SELECT a.team_id_n
                       , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    "   , a.team_name_v
                         ,a.team_desc_v
                         ,a.creator_id_n
                         ,a.supervisor_id_n
                         ,a.group_id_n
                         ,a.status_n
                       , b.user_name_v
                       , c.group_name_v
                 FROM `scc_teams_tab` a
                      , master_users_tab b
                      , master_groups_tab c
                 WHERE a.supervisor_id_n = b.user_id_n
                 and  a.group_id_n = c.group_id_n
                 $teamSql



                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetGroupsByType($type) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetGroupsByType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $typeSql = "";

            if ($type != 0) {

                $typeSql = " AND a.group_type_n = '$type'";
            }



            $sqlQuery = "
                 
                  
                SELECT a.group_id_n
                       , DATE_FORMAT(a.creation_date_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    "   , a.group_name_v
                         ,b.type_name_v
                       , b.type_desc_v
                 FROM `master_groups_tab` a
                      , group_types_tab b
                 WHERE a.group_type_n = b.type_id_n
                 $typeSql



                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetUsersList($userId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetUsersList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($userId != "") {

                $usql = " AND a.user_id_n = '$userId'";
            }



            $sqlQuery = "
                 SELECT   a.user_id_n
                        , DATE_FORMAT(a.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_date_d " .
                    "  , a.user_id_n
                        , a.caller_id_v
                        , c.description_v
                        ,b.user_name_v
                        ,b.first_name_v
                        ,b.last_name_v
                        ,d.profile_name_v
                  FROM `scc_users_tab` a
                      , master_users_tab b
                      , master_status_tab c
                      , scc_profiles_tab d
                  where a.user_id_n = b.user_id_n
                  and a.status_n = c.status_n  
                  and a.profile_id_n = d.profile_id_n



                    
                
                $userSql


                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCProfileList($profileId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCProfileList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $profileSQL = "";

            if ($profileId > 0) {

                $profileSQL = "WHERE profile_id_n = " . $profileId;
            }

            $sqlQuery = "  
                   select   profile_id_n
                        , profile_name_v
                        , long_desc_v
                        , status_n 
                    FROM scc_profiles_tab
                    $profileSQL
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    function UpdateAddDelSCCUser($id, $userId, $profileId, $callerId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelSCCUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT 
                INTO scc_users_tab (user_id_n, creation_datetime_d, profile_id_n, caller_id_v, status_n) VALUES ($userId,now(),'$profileId','$callerId','$status')";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE scc_users_tab 
				                 SET profile_id_n = '$profileId'
						     ,caller_id_v ='$callerId'
								 ,status_n = '$status'
						     WHERE user_id_n = '$userId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM scc_users_tab WHERE user_id_n in ($userId)     ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    function UpdateAddDelTeam($id, $itemId, $name, $desc, $ownerId, $supervisorId, $groupId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT INTO `scc_teams_tab` (`team_id_n`, `creation_datetime_d`, `team_name_v`, `team_desc_v`, `creator_id_n`, `supervisor_id_n`, `group_id_n`, `status_n`) VALUES (NULL, now(), '$name', '$desc', '$ownerId', '$supervisorId', '$groupId', '$status')";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $id = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE scc_teams_tab 
				                 SET supervisor_id_n = '$supervisorId'
						     , team_desc_v ='$desc'
                                                     , group_id_n = '$groupId'
                                                     , team_name_v = '$name'
						     WHERE team_id_n = '$itemId'
                             ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE FROM scc_teams_tab WHERE team_id_n in ($itemId)     ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            }



            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $id;
    }

    function UpdateAddDelTeamDetail($id, $itemId, $groupId, $agentId, $additionalInfo, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelTeamDetail()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT `group_details_tab` (`detail_id_n`, `group_id_n`, `creation_date_d`, `entity_name_v`,additionnal_info_v, `status_n`) VALUES (NULL, '$groupId', now(), $agentId,'$additionalInfo',  $status)";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE group_details_tab 
				                 SET ,entity_name_v = '$agentId'
						     WHERE group_id_n = '$itemId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM group_details_tab WHERE group_id_n in ('$groupId')  and additionnal_info_v='$additionalInfo'    ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //   echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCTeamQueueById($queueId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTeamById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $queryData = "";
            $total = 0;

            $sqlQuery = "SELECT   b.team_id_n
			         ,b.team_name_v
                                 ,b.team_desc_v
                                 ,(select count(1)  from team_queues_tab  u where u.team_id_n = b.team_id_n and  u.queue_id_n = '$queueId' ) is_enabled_n
                FROM  scc_teams_tab b
        
                  "
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelQueueTeamDetails($id, $queueId, $teamId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelQueueTeamDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT INTO `team_queues_tab` (`item_id_n`, `queue_id_n`, `team_id_n`, `status_n`) VALUES (null,$queueId, $teamId, $status)";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_insert_id($dbAccess['dbConnection']);
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE team_queues_tab 
				                 SET team_id_n ='$userId'
								 ,status_n = '$status'
						     WHERE queue_id_n = '$queueId'
                             ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_affected_rows($dbAccess['dbConnection']);
            } else {

                $sqlQuery = "DELETE FROM team_queues_tab WHERE queue_id_n in ($queueId)     ";
                $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $totalUser = mysql_affected_rows($dbAccess['dbConnection']);
            }



            //  echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $totalUser;
    }

    public function SCCGetTeamsById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetTeamsById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $serviceTeamSql = "";

            if ($itemId > 0) {

                $serviceTeamSql = " WHERE stt.team_id_n = '$itemId'";
            }



            $sqlQuery = "
                
            SELECT  stt.team_id_n 
            , DATE_FORMAT(stt.creation_datetime_d, '" . $_SESSION['cfg']['date.format'] . "') creation_datetime_d " .
                    "  ,stt.team_name_v 
       ,stt.team_desc_v 
       ,stt.creator_id_n 
       ,stt.supervisor_id_n 
       ,stt.group_id_n 
       ,stt.status_n 
from scc_teams_tab stt 
$serviceTeamSql
              ORDER BY 2 DESC


                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCUserTeam($teamId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCUserTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $queryData = "";
            $total = 0;

            $sqlQuery = "SELECT  b.user_id_n
			                    ,b.user_name_v
								,b.first_name_v
                                                                ,b.last_name_v
                                                                ,a.profile_id_n
								,(select count(1)  from group_details_tab  u where u.entity_name_v = b.user_id_n and  u.additionnal_info_v = '$teamId' ) is_enabled_n
                FROM  master_users_tab b
                     , scc_users_tab a
                WHERE a.user_id_n = b.user_id_n
                  "
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetVoiceQueueAll() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetVoiceQueueAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                
                SELECT a.queue_id_n 
                        ,b.name
                        ,b.wrapuptime 
                        ,b.strategy 
                  FROM  scc_queues_tab a
                       , voice_queues_tab b
                  WHERE  a.queue_id_n  = b.queue_id_n 

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetVoiceQueueMembersById($queueId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetVoiceQueueMembersById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                
                select distinct a.user_id_n 
                        , a.caller_id_v 
                  from scc_users_tab a
                      , team_queues_tab b
                      , group_details_tab c
                  WHERE a.user_id_n = c.entity_name_v 
                  AND  b.team_id_n = c.additionnal_info_v 
                  AND b.queue_id_n = $queueId

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    function UpdateAddDelSCCUserNoProfilCheck($id, $userId, $profileId, $callerId, $status) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelSCCUser()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            if ($id == 0) {

                $sqlQuery = "INSERT 
                INTO scc_users_tab (user_id_n, creation_datetime_d, profile_id_n, caller_id_v, status_n) VALUES ($userId,now(),'$profileId','$callerId','$status')";
            } elseif ($id == 1) {

                $sqlQuery = "UPDATE scc_users_tab 
				                 SET      caller_id_v ='$callerId'
								 ,status_n = '$status'
						     WHERE user_id_n = '$userId'
                             ";
            } else {

                $sqlQuery = "DELETE FROM scc_users_tab WHERE user_id_n in ($userId)     ";
            }

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCProfileByUserId($userId) {

        $dbAccess = $this->connectMysqlDatabase();
        $profileId = -1;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCProfileByUserId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT profile_id_n
                FROM scc_users_tab 
                WHERE user_id_n ='$userId'";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $profileId = $queryData['profile_id_n'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $profileId;
    }

    public function crmGetAgentList($profile, $userId, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec crmGetAgentList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";
            $statusSql = "";

            if ($status != -1) {

                $statusSql = " AND m.status_n = $status ";
            }

            if ($profile == 2) {

                $userSql = "AND m.user_id_n=$userId";
            }

            $sqlQuery = "  
                  select  m.user_id_n
						   ,date_format(m.creation_date_d,'%d/%m/%Y %H:%I:%S') creationDate
						   ,m.user_name_v
						   ,m.first_name_v
						   ,m.last_name_v
						   ,n.caller_id_v   mobile_phone_v
						   ,m.email_v
					FROM  master_users_tab m
                                             , scc_users_tab n
					where m.user_id_n = n.user_id_n
                                        and ( n.profile_id_n = 2 OR n.profile_id_n = 3)
                    $userSql
					
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetVoiceQueueAll_backup() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetVoiceQueueAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                
                select name
                from voice_queues_tab

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getOnlineUserAll() {

        $dbAccess = $this->connectMysqlDatabase();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getOnlineUserAll()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT count(1) total
                FROM scc_online_users_tab 
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $total;
    }

    public function getSCCAverageCallTime($date) {

        $dbAccess = $this->connectMysqlDatabase();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCAverageCallTime()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT sum(duration) total
                FROM master_cdr_tab
                where calldate like '$date%'
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $total;
    }

    public function getSCCAvgCallRespRate($date) {

        $dbAccess = $this->connectMysqlDatabase();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCAvgCallRespRate()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "SELECT 
                               round(( (select count(1) from crm_tickets_tab c where c.event_datetime_d like '$date%' ) /  (select count(1) from master_cdr_tab m where m.calldate like '$date%' )*100),2)  total
      
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $total;
    }

    public function getCallReasonGlobalStats($startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonGlobalStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,master_motifs_tab d
                 WHERE c.reason_n = d.motif_id_n
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement

             

                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallReasonAgentStats($startDate, $endDate, $granularity, $userId, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonAgentStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";

            if ($userId != -1) {

                $userSql = " AND m.user_id_n ='$userId'";
            }


            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,m.user_name_v
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,master_motifs_tab d
                      , master_users_tab m
                 WHERE c.reason_n = d.motif_id_n
                 AND m.user_id_n = c.user_id_n
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                 $userSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'),m.user_name_v, d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement

             

                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallDurationAvgStats($startDate, $endDate, $granularity, $userId, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallDurationAvgStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";

            if ($userId != -1) {

                $userSql = " AND m.user_id_n ='$userId'";
            }


            $sqlQuery = "
                
               
                 select date_format(c.event_datetime_d,'$granularity') eventDate
                        ,a.user_name_v
                        ,sum(m.duration) total
                  from crm_tickets_tab c,
                       master_cdr_tab m,
                       master_users_tab a
                  where c.char_field_2 = m.uniqueid
                  AND a.user_id_n = c.user_id_n
                  AND c.event_datetime_d >='$startDate'
                  AND  c.event_datetime_d <='$endDate'
                  $userSql
                  GROUP BY date_format(c.event_datetime_d,'$granularity'),a.user_name_v
                  ORDER BY 1 DESC
                  LIMIT $maxElement

             

                     
                ";

             echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCGetUserById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetUserById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $userSql = "";

            if ($itemId > 0) {

                $userSql = " AND a.user_id_n = '$itemId'";
            }



            $sqlQuery = "
                
                 select a.user_id_n
                        ,b.profile_id_n
                        ,b.caller_id_v
                        ,a.user_name_v
                  from master_users_tab a
                       , scc_users_tab b
                  where a.user_id_n = b.user_id_n
                  $userSql

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCGroupById($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCGroupById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND a.group_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.group_id_n
							,a.group_name_v
                                                        ,b.type_id_n

					FROM `master_groups_tab` a,
                                              group_types_tab b
                                        WHERE a.group_type_n = b.type_id_n
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function checkGroupInUse($groupId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkGroupInUse()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "SELECT count(1) total 
                FROM master_motifs_tab  
                WHERE id_categorie_n  ='$groupId'"
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $id = $queryData['total'];

            if ($id == 0) {


                $sqlQuery = "SELECT count(1) total 
                FROM group_details_tab   
                WHERE group_id_n  ='$groupId'"
                ;

                // echo $sqlQuery;

                $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $queryData = mysql_fetch_array($sqlResult);
                $id = $queryData['total'];
            }


            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getQueueTeamMemberById($queueId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getQueueTeamMemberById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $userSql = "";
            $usql = "";

            $sqlQuery = "
                    select  a.team_id_n
			   ,a.team_name_v
                 from scc_teams_tab a,
	               team_queues_tab b
                where a.team_id_n = b.team_id_n
                and b.queue_id_n = '$queueId'
		 

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function checkChannelInUse($channelId) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkChannelInUse()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "SELECT count(1) total 
                FROM scc_routes_tab  
                WHERE channel_id_n  ='$channelId'"
            ;

            // echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $id = $queryData['total'];

            if ($id == 0) {


                $sqlQuery = "SELECT count(1) total 
                FROM voice_routes_tab   
                WHERE dst_entity_id_n  ='$channelId'"
                ;

                // echo $sqlQuery;

                $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $queryData = mysql_fetch_array($sqlResult);
                $id = $queryData['total'];
            }


            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function checkQueueInUse($id) {

        $dbAccess = $this->connectMysqlDatabase();
        // $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec checkQueueInUse()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "SELECT count(1) total 
                FROM scc_routes_tab  
                WHERE queue_id_n  ='$id'"
            ;

            //    echo $sqlQuery;

            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $id = $queryData['total'];

            if ($id == 0) {


                $sqlQuery = "SELECT count(1) total 
                FROM voice_routes_tab   
                WHERE dst_entity_id_n  ='$id'"
                ;

                // echo $sqlQuery;

                $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
                $queryData = mysql_fetch_array($sqlResult);
                $id = $queryData['total'];
            }


            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getSCCTypeList($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTypeList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE type_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   type_id_n
							,type_v
							,status_n
					FROM `customer_type_tab` 
					$idSql
					order by 2 asc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddType($opId, $id, $typeId, $name) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO customer_type_tab  (type_id_n, type_v,  status_n) VALUES ($typeId, '$name','0')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE customer_type_tab
				                  SET type_v='$name'
							    WHERE type_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  customer_type_tab WHERE type_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getTypeId() {

        $dbAccess = $this->getMysqlConnection();
        $total = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTypeId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select count(1) total from customer_type_tab ";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            $data = mysql_fetch_array($queryResult);
            $total = $data['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }


        return $total;
    }

    public function getSCCSubModules($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCSubModules()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "and a.motif_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.motif_id_n
							,a.motif_name_v
							,a.motif_desc_v
                                                        ,b.motif_name_v module_name_v
                                                        ,a.parent_motif_id_n
					FROM `scc_modules_tab` b,
                                        master_sub_motifs_tab a
                         WHERE a.parent_motif_id_n = b.motif_id_n
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddCallSubModule($opId, $id, $motifName, $description, $moduleId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCallSubModule()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO master_sub_motifs_tab  (motif_id_n, motif_name_v, motif_desc_v, parent_motif_id_n) VALUES (null, '$motifName','$description','$moduleId')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE master_sub_motifs_tab
				                  SET motif_name_v='$motifName'
								     ,motif_desc_v='$description'
                                                                     ,parent_motif_id_n = '$moduleId'
							    WHERE motif_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  master_sub_motifs_tab WHERE motif_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCKnownledgeBase($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCKnownledgeBase()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "and item_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.item_id_n
							,DATE_FORMAT(a.creation_datetime_d, '%d/%m/%Y %H:%I:%S') creation_datetime_d
							,article_title_v
                                                        ,article_body_v
                                                        ,attachment_path_v
                                                        ,DATE_FORMAT(a.last_update_d, '%d/%m/%Y %H:%I:%S') last_update_d
                                                        ,b.user_name_v                                                        
					FROM `crm_knownledge_base_tab` a
                                             ,master_users_tab b
                                        where a.user_id_n = b.user_id_n
					$idSql
					order by 2 asc
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddKnownledgeBase($opId, $id, $title, $body, $path, $userId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddKnownledgeBase()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO crm_knownledge_base_tab  (item_id_n, creation_datetime_d,  article_title_v, article_body_v, attachment_path_v, last_update_d, user_id_n) VALUES (null,now(), '$title','$body','$path', now(), '$userId')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE crm_knownledge_base_tab
				                  SET article_title_v='$title'
						     ,article_body_v='$body'
                                                     ,attachment_path_v = '$path'
                                                     ,last_update_d = now()
					WHERE item_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  crm_knownledge_base_tab WHERE item_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCCustomerDetailsByNumber($msisdn) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCustomerDetailsByNumber()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";

            if ($msisdn > 0) {

                $idSql = "WHERE cc_line_v='$msisdn'";
            }

            $sqlQuery = "
                  SELECT   customer_id_n
							,creation_date_d
							,first_name_v
							,last_name_v
							,cc_line_v
                                                        ,location_v company_id_n
							,(select company_name_v from master_companies_tab m where m.company_id_n = location_v) location_v
							,email_id_v
							,char_field_1
					FROM `scc_customers_tab` 
					$idSql
                                            order by 1 desc
                                            limit 1
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getModuleMenusDetails($menuId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getModuleMenusDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $menuSql = "";

            if ($menuId != -1) {

                $menuSql = "where md.parent_motif_id_n='$menuId' ";
            }

            $sqlQuery = "  
                   select  md.motif_id_n
						   ,md.motif_name_v
						   ,md.motif_desc_v
					from master_sub_motifs_tab md
                    $menuSql
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCBulkCloseTickets($userId, $ticketList) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCBulkCloseTickets()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            $ackSql = ",aknowledge_date_d=now()";
            $closureSql = ",closure_date_d=now()";
            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET status_n='3'
					   $closureSql
					WHERE ticket_number_v in ($ticketList) ";

            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function UpdateAddCallModule($opId, $id, $motifName, $description) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddCallModule()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_modules_tab  (motif_id_n, motif_name_v, motif_desc_v) VALUES (null, '$motifName','$description')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_modules_tab
				                  SET motif_name_v='$motifName'
								     ,motif_desc_v='$description'
							    WHERE motif_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_modules_tab WHERE motif_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getEmailList($profileId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getEmailList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                      
                 SELECT m.email_v
                 FROM `master_users_tab` m
                     , group_details_tab g 
                 WHERE m.user_id_n =g.entity_name_v
                 and g.additionnal_info_v = $profileId

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSubMobuleById($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSubMobuleById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $menuSql = "";

            if ($id != -1) {

                $menuSql = "where md.motif_id_n='$id' ";
            }

            $sqlQuery = "  
                   select  md.motif_id_n
						   ,md.motif_name_v
						   ,md.motif_desc_v
					from master_sub_motifs_tab md
                    $menuSql
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getItemIdByCRSID($crsid) {
        $item = 0;
        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getItemIdByCRSID()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {




            $sqlQuery = "
                  select item_id_n from crm_tickets_tab where ticket_number_v='$crsid' order by item_id_n desc limit 1
					
                ";
            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($sqlResult);
            $item = $queryData['item_id_n'];

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $item;
    }

    public function SCCGetFormNameByCallId($callId) {
        $dbAccess = $this->getMysqlConnection();
        $page = "";

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetFormNameByCallId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select b.page_link_v master_cdr_tab a, scc_forms_tab b where a.dst = b.short_code_v and  a.uniqueid ='" . $callId . "'";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $queryData = mysql_fetch_array($queryResult);
            $page = $queryData['page_link_v'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $page;
    }

    public function UploadEventInformation($userId, $methodId, $eventId) {

        $res = $this->getLastEventInfoByMethodAndId($userId, $methodId);
        switch ($eventId) {

            case 0: // Openning

                if (count($res) > 0) {
                    // Some sessions are opened / Closing Them
                    $this->UpdateAddDelUserEvent(1, $res[0]['item_id_n'], $userId, $methodId);
                    $this->UpdateAddDelUserEvent(0, 0, $userId, $methodId);
                } else {
                    $this->UpdateAddDelUserEvent(0, 0, $userId, $methodId);
                }
                break;

            case 1: // Closing
                if (count($res) > 0) {
                    // Some sessions are opened / Closing Them
                    $this->UpdateAddDelUserEvent(1, $res[0]['item_id_n'], $userId, $methodId);
                }
                break;
        }

        return 0;
    }

    public function getLastEventInfoByMethodAndId($userId, $methodId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getLastEventInfoByMethodAndId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $sqlQuery = "select * from scc_users_cnx_hist_tab where user_id_n = " . $userId . " and method_id_n=" . $methodId . " and status_n = -1 LIMIT 1";
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelUserEvent($opId, $id, $userId, $methodId) {
        $dbAccess = $this->connectMysqlDatabase();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelUserEvent()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $idSql = "";

            if ($opId == 0) {

                $sqlQuery = "INSERT INTO `scc_users_cnx_hist_tab` (`item_id_n`, `event_datetime_d`, `user_id_n`, `method_id_n`, `start_datetime_d`, `end_datetime_d`, `status_n`) VALUES (NULL, now(), '$userId', '$methodId', now(), '', -1)";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE  scc_users_cnx_hist_tab 
			     SET  end_datetime_d =now()
				  ,status_n ='0'
	                      WHERE item_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_users_cnx_hist_tab WHERE item_id_n in ($id)";
            }



            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            // echo $sqlQuery;
            $id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getSCCFormsList($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCFormsList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND a.form_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.form_id_n
							,DATE_FORMAT(a.creation_date_d, '%d/%m/%Y %H:%I:%S') creation_date_d
							,a.form_name_v
                                                        ,a.form_desc_v
                                                        ,a.page_link_v
                                                        ,b.user_name_v
					FROM `scc_forms_tab` a,
                                              master_users_tab b
                                        WHERE a.user_id_n = b.user_id_n
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelForms($opId, $id, $formName, $description, $link, $userId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelForms()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_forms_tab  (form_id_n, creation_date_d,  form_name_v, form_desc_v, page_link_v, user_id_n, status_n) VALUES (null,now(), '$formName','$description', '$link', '$userId', 0)";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_forms_tab
			     SET form_name_v='$formName'
				,form_desc_v='$description'
                                ,page_link_v='$link'
			     WHERE form_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_forms_tab WHERE form_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCIVRList($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCIVRList()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND a.ivr_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.ivr_id_n
							,DATE_FORMAT(a.creation_datetime_d, '%d/%m/%Y %H:%I:%S') creation_datetime_d
							,a.ivr_name_v
                                                        ,a.ivr_desc_v
                                                        ,a.ivr_data_v
                                                        ,b.user_name_v
					FROM `scc_ivr_data_tab` a,
                                              master_users_tab b
                                        WHERE a.user_id_n = b.user_id_n
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelIVR($opId, $id, $ivrName, $description, $ivrData, $userId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelIVR()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_ivr_data_tab  (ivr_id_n, creation_datetime_d,  ivr_name_v, ivr_desc_v, ivr_data_v, user_id_n, status_n) VALUES (null,now(), '$ivrName','$description', '$ivrData', '$userId', 0)";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_ivr_data_tab
			     SET ivr_name_v='$ivrName'
				,ivr_desc_v='$description'
                                ,ivr_data_v='$ivrData'
			     WHERE ivr_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_ivr_data_tab WHERE ivr_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }
    
    

    public function getSCCModules($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCModules()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE motif_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   motif_id_n
							,motif_name_v
							,motif_desc_v
					FROM `scc_modules_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function AddTicketExtend($id, $firstName, $lastName, $callId, $userId, $csrId, $callerId, $address, $company, $mobileNumber, $emailId, $callReasonType, $csrDetails, $callType, $status, $customerType, $agencyName, $callModule, $submodule, $callprority, $formId) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddTicketExtend()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $ackSql = "";
            $closureSql = "";

            $ack = date("Y-m-d H:i:s");
            $cls = date("Y-m-d H:i:s");

            if ($status == 2) {
                $ackSql = ",aknowledge_date_d=now()";
                $ack = date("Y-m-d H:i:s");
            }

            if ($status == 3) {
                $ackSql = ",aknowledge_date_d=now()";
                $closureSql = ",closure_date_d=now()";
                $ack = date("Y-m-d H:i:s");
                $cls = date("Y-m-d H:i:s");
            }

            if ($id == 0) {

                $sqlQuery = "
			
			       UPDATE crm_tickets_tab
					SET first_name_v='$firstName'
					   ,last_name_v ='$lastName'
					   ,email_id_v='$emailId'
					   ,ticket_reason_desc_v ='$csrDetails'
					   ,location_v='$address'
					   ,mobile2_phone_v='$mobileNumber'
					   ,gender_v=''
					   ,reason_category_n ='$callModule'
					   ,reason_n='$callReasonType'
					   ,status_n='$status'
					   ,company_name_v='$company'
					   ,char_field_6='$customerType'
					   ,char_field_7='$agencyName'
                                           ,char_field_3='$submodule'
                                           ,char_field_4='$callprority'
                                           ,mobile1_phone_v='$callerId'
					   $ackSql
					   $closureSql
					WHERE item_id_n ='$callId' ";
            } else {

                $sqlQuery = "INSERT INTO crm_tickets_tab ( item_id_n, event_datetime_d, ticket_number_v, user_id_n, mobile1_phone_v ,first_name_v,last_name_v, email_id_v, ticket_reason_desc_v, location_v, mobile2_phone_v, reason_category_n,reason_n, char_field_1, char_field_2,char_field_5,aknowledge_date_d, closure_date_d, status_n,company_name_v, char_field_6,char_field_7,char_field_3,char_field_4 ,char_field_10)
              VALUES (NULL, now(), '$csrId', '$userId', '$callerId', '$firstName','$lastName','$emailId','$csrDetails','$address','$mobileNumber','$callModule','$callReasonType',0,'','$callType','$ack','','$status','$company','$customerType','$agencyName','$submodule','$callprority','$formId') ";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getCRMTotalDailyTicket() {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTotalDailyTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $curDate = date("Y-m-d") . "%";

            $sqlQuery = "SELECT count(1) total
                FROM  crm_tickets_tab a
		WHERE  a.event_datetime_d like '$curDate'
                ";

            //  echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $total;
    }

    public function getCRMTotalDailyTicketByStatus($status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCRMTotalDailyTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $userSql = "";
            $curDate = date("Y-m-d") . "%";

            $sqlQuery = "SELECT count(1) total
                FROM  crm_tickets_tab a
		WHERE  a.event_datetime_d like '$curDate'
                and a.status_n='$status'
                ";

            //echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
            $queryData = mysql_fetch_array($sqlResult);
            $total = $queryData['total'];
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

        return $total;
    }

    public function getPartnerStats($profileId, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getPartnerStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $calltypesql = "";
            $profileSQL = "";

            $sqlQuery = "

						SELECT  date_format(a.event_datetime_d,'$granularity') eventDate
                                                           ,a.company_name_v name
							   ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_users_tab c 
						where c.user_id_n = a.user_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$profileSQL
						group by date_format(a.event_datetime_d,'$granularity'), a.company_name_v
				    

                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getPartnerTypeStats($profileId, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getPartnerTypeStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";
            $calltypesql = "";
            $profileSQL = "";

            $sqlQuery = "

						SELECT  date_format(a.event_datetime_d,'$granularity') eventDate
                                                           ,b.type_v name
							   ,count(1) total
						FROM `crm_tickets_tab` a
                                                     ,customer_type_tab b
						where b.type_id_n = a.char_field_6
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$profileSQL
						group by date_format(a.event_datetime_d,'$granularity'), b.type_v
				    

                ";

            echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCCallReasonByFormId($formId, $id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCallReasonByFormId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "AND motif_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   a.motif_id_n
							,a.motif_name_v
							,a.motif_desc_v
                                                        ,b.group_name_v
                                                        ,b.group_id_n
					FROM `master_motifs_tab` a,
                                              master_groups_tab b,
                                              scc_callreasons_form_tab c
                                        WHERE a.id_categorie_n = b.group_id_n
                                        and c.group_id_n = b.group_id_n
                                        and c.form_id_n = $formId
					$idSql
                                        ORDER BY a.motif_name_v ASC
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAssigneeTeamById($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAssigneeTeamById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "and b.team_id_n <> '$id'";
            }

            $sqlQuery = "
                  SELECT   b.team_id_n
							,b.team_name_v
					FROM `scc_teams_tab` b
                                        where b.team_id_n not in  ( select additionnal_info_v from group_details_tab where entity_name_v = $id )
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCFwdTicketDetails($userId, $teamId, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCFwdTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if (!$right) {

                $userSql = "and ( c.user_id_n='$userId' OR $userId in (select entity_name_v
from group_details_tab  g
     , scc_teams_tab  s
     ,crm_tickets_history_tab c
where g.additionnal_info_v = s.team_id_n 
and c.profile_id_n = s.team_id_n 
and c.ticket_number_v =a.ticket_number_v
and c.status_n =10
ORDER by c.event_datetime_d  desc )  )";
            }



            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 order by 1 asc limit 1 ) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 order by 1 asc limit 1 ) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
                                                  , (select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdBy
                                                   , (select date_format(l.event_datetime_d ,'%d/%m/%Y %H:%i:%s')  from crm_tickets_history_tab l where  a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1 ) fwdDate
                                                    , (select s.team_name_v from crm_tickets_history_tab l , scc_teams_tab s   where l.profile_id_n  = s.team_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdTo
			                FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.char_field_9 = 10
                                        and a.status_n not in  ('3','7')
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCFwdTicketDetailsSave20230919($userId, $teamId, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCFwdTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if (!$right) {

                $userSql = "and ( c.user_id_n='$userId' OR $userId in (select entity_name_v
from group_details_tab  g
     , scc_teams_tab  s
     ,crm_tickets_history_tab c
where g.additionnal_info_v = s.team_id_n 
and c.profile_id_n = s.team_id_n 
and c.ticket_number_v =a.ticket_number_v
and c.status_n =10
ORDER by c.event_datetime_d  desc )  )";
            }



            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
					          , (select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc) fwdBy
                                                   , (select date_format(l.event_datetime_d ,'%d/%m/%Y %H:%i:%s')  from crm_tickets_history_tab l where  a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc) fwdDate
                                                    , (select s.team_name_v from crm_tickets_history_tab l , scc_teams_tab s   where l.profile_id_n  = s.team_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc) fwdTo
                                                FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.char_field_9 = 10
                                        and a.status_n not in  ('3','7')
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UploadTicketFiles($filename, $filePath, $ticketNumber) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UploadTicketFiles()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "INSERT 
                INTO crm_ticket_files_tab  VALUES (NULL,now(),'$filename','$filePath','$ticketNumber','0')";

            //  echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getSCCTicketFileHistory($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketFileHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
                     SELECT item_id_n 
                            ,file_name_v 
                            ,file_path_v 
                      from crm_ticket_files_tab  
                      WHERE  ticket_number_v ='$ticketId'
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllTeam($teamId, $all) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";
            $teamSql = "";
            $usql = "";

            if ($all) {


                $teamSql = " Where a.team_id_n= $teamId";
            }




            $sqlQuery = "
                    select team_id_n
                          ,team_name_v  
                 from scc_teams_tab
                $teamSql

                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
                    ,s.team_name_v
                    , COUNT(1)  total
            from crm_tickets_tab c
                 ,group_details_tab g
                 ,scc_teams_tab s
            where c.user_id_n = g.entity_name_v 
            and s.team_id_n = g.additionnal_info_v 
            and c.event_datetime_d >='$startDate'
            AND  c.event_datetime_d <='$endDate'
            $teamSql
            group by date_format(c.event_datetime_d,'$granularity'), s.team_name_v
            LIMIT BY $maxElement
           
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getDetailsStatsPerTeam($teamId, $granularity, $status, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getDetailsStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
                    ,s.team_name_v
                    , m.user_name_v
                    , c.ticket_number_v
                    , a.motif_name_v
                    , p.description_v
            from crm_tickets_tab c
                 ,group_details_tab g
                 ,scc_teams_tab s
                 , master_users_tab m
                 , master_status_tab p
                 , master_motifs_tab a
            where c.user_id_n = g.entity_name_v 
            and s.team_id_n = g.additionnal_info_v 
            and c.event_datetime_d >='$startDate'
            AND  c.event_datetime_d <='$endDate'
            and m.user_id_n = c.user_id_n
            and p.status_n = c.status_n
            and c.reason_n = a.motif_id_n
            $teamSql
           
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalStatsPerTeamAvg($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
                    ,s.team_name_v
                    , COUNT(1)  total
            from crm_tickets_tab c
                 ,group_details_tab g
                 ,scc_teams_tab s
            where c.user_id_n = g.entity_name_v 
            and s.team_id_n = g.additionnal_info_v 
            and c.event_datetime_d >='$startDate'
            AND  c.event_datetime_d <='$endDate'
            $teamSql
            group by date_format(c.event_datetime_d,'$granularity'), s.team_name_v
           
                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallReasonGlobalStatsByTeam($teamId, $startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonGlobalStatsByTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = " AND s.team_id_n=$teamId";
            }


            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,s.team_name_v
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,master_motifs_tab d
                      ,group_details_tab g
                      ,scc_teams_tab s
                 WHERE c.reason_n = d.motif_id_n
                 and c.user_id_n = g.entity_name_v 
                 and s.team_id_n = g.additionnal_info_v
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                  $teamSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement

             

                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getCallReasonGlobalAgentStatsByTeam($teamId, $startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonGlobalAgentStatsByTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = " AND s.team_id_n=$teamId";
            }


            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,s.team_name_v
                       ,m.user_name_v
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,master_motifs_tab d
                      ,group_details_tab g
                      ,scc_teams_tab s
                      ,master_users_tab m
                 WHERE c.reason_n = d.motif_id_n
                 and c.user_id_n = g.entity_name_v 
                 and s.team_id_n = g.additionnal_info_v
                 and c.user_id_n = m.user_id_n
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                 $teamSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, m.user_name_v, d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement

             

                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTeamGlobalTicketStats($teamId, $status, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTeamGlobalTicketStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $teamSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($teamId != -1) {

                $teamSql = " and s.team_id_n ='$teamId'";
            }



            if ($status != -2) {

                $statusSql = " and a.status_n ='$status'";
            }




            $sqlQuery = "
                      
                 SELECT     eventDateTime
                           ,user_name_v
						   ,sum(INITIALISE) INITIALISE
						   ,sum(OUVERT) OUVERT
						   ,sum(CLOS)  CLOS
                                                   ,sum(UNPICKED)  UNPICKED
					   FROM (
						SELECT  date_format(event_datetime_d,'$granularity' ) eventDateTime
                                                           ,m.user_name_v
							   ,case a.status_n
							  when -1  then 1 else 0
							 end INITIALISE
							   ,case a.status_n
							  when 2  then 1 else 0
							 end OUVERT
							   ,case a.status_n
							  when 3  then 1 else 0
							 end CLOS
                                                          ,case a.status_n
							  when 7  then 1 else 0
							 end UNPICKED
						FROM `crm_tickets_tab` a
							 , master_status_tab b
                                                         ,group_details_tab g
                                                         ,scc_teams_tab s
                                                         ,master_users_tab m
						where a.status_n = b.status_n
                                                and a.user_id_n = g.entity_name_v 
                                                and s.team_id_n = g.additionnal_info_v
                                                and a.user_id_n = m.user_id_n
                                                and m.user_id_n NOT IN (66, 72)
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$teamSql
                                                $statusSql

						order  by 1 desc
						   ) t
					group by eventDateTime,user_name_v
					order by eventDateTime desc
					 

                        

                ";

            //  echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTop10CompaniesByType($type, $startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTop10CompaniesByType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $typeSql = "";

            if ($type != -1) {

                $typeSql = " AND d.type_id_n=$type";
            }


            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,c.location_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,customer_type_tab d
                 WHERE c.char_field_6 = d.type_id_n
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                 $typeSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), c.location_v
                 ORDER BY 3 DESC
                 LIMIT $maxElement

             

                     
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalAgentStats($userId, $teamId, $status, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalAgentStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $teamSql = "";

            if ($userId != -1) {

                $userSql = "AND a.user_id_n='$userId' ";
            }

            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }


            if ($teamId != -1) {

                $teamSql = " and s.team_id_n= $teamId";
            }


            $sqlQuery = "
                      
                 SELECT     eventDateTime
                           ,team_name_v
                           ,user_name_v
						   ,sum(INITIALISE) INITIALISE
						   ,sum(OUVERT) OUVERT
						   ,sum(CLOS)  CLOS
                                                   ,sum(UNPICKED)  UNPICKED
					   FROM (
						SELECT  date_format(event_datetime_d,'$granularity' ) eventDateTime
                                                       ,s.team_name_v
                                                       , c.user_name_v
							   ,case a.status_n
							  when -1  then 1 else 0
							 end INITIALISE
							   ,case a.status_n
							  when 2  then 1 else 0
							 end OUVERT
							   ,case a.status_n
							  when 3  then 1 else 0
							 end CLOS
                                                          ,case a.status_n
							  when 7  then 1 else 0
							 end UNPICKED
						FROM `crm_tickets_tab` a
							 , master_status_tab b
                                                         , master_users_tab c
                                                         ,group_details_tab g
                                                         ,scc_teams_tab s
						where a.status_n = b.status_n
                                                and c.user_id_n = a.user_id_n
                                                 and a.user_id_n = g.entity_name_v 
                                                and s.team_id_n = g.additionnal_info_v
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$userSql
                                                $statusSql
                                                $teamSql

						order  by 1 desc
						   ) t
					group by eventDateTime, team_name_v, user_name_v
					order by eventDateTime desc
					 

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCChannelType($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCChannelType()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE type_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   type_id_n
							,type_v
							,status_n
					FROM `customer_type_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTeamGlobalChannelsStats($teamId, $granularity, $startDate, $endDate) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getTeamGlobalChannelsStats()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $teamSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($teamId != -1) {

                $teamSql = " and s.team_id_n ='$teamId'";
            }






            $sqlQuery = "
                      
                 SELECT  date_format(event_datetime_d,'$granularity' ) eventDateTime
                                                           ,s.team_name_v
                                                           ,m.user_name_v
                                                           ,a.char_field_5
                                                           ,count(1) total
						FROM `crm_tickets_tab` a
							 , master_status_tab b
                                                         ,group_details_tab g
                                                         ,scc_teams_tab s
                                                         ,master_users_tab m
						where a.status_n = b.status_n
                                                and a.user_id_n = g.entity_name_v 
                                                and s.team_id_n = g.additionnal_info_v
                                                and a.user_id_n = m.user_id_n
						and event_datetime_d >='$startDate'
						and   event_datetime_d <='$endDate' 
						$teamSql
                                            group by date_format(event_datetime_d,'$granularity' ), s.team_name_v,m.user_name_v ,a.char_field_5
						order  by 1 desc
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalQOSStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalQOSStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                 select eventDate
                 , t.team_name_v
          ,sum(unpicked) totalUnpicked
          ,sum(picked) totalPicked
   from 
	   ( select date_format(c.event_datetime_d,'$granularity') eventDate
		            ,s.team_name_v
		            , case c.status_n
		              when 7 then 1 else 0
		              end unpicked
		            , case c.status_n
		              when 7 then 0 else 1
		              end picked
	   
		    from crm_tickets_tab c
		         ,group_details_tab g
		         ,scc_teams_tab s
		    where c.user_id_n = g.entity_name_v 
		    and s.team_id_n = g.additionnal_info_v 
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
		    $teamSql
		    ) t
   group by eventDate, t.team_name_v
   LIMIT $maxElement
           
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getDetailsQOSStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getDetailsQOSStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                 select date_format(c.event_datetime_d,'$granularity') eventDate
                            ,m.user_name_v
                            , count(1) total
                            , (select count(1) from crm_tickets_tab cr, group_details_tab g ,scc_teams_tab s , master_users_tab me where cr.user_id_n = g.entity_name_v and s.team_id_n = g.additionnal_info_v and cr.event_datetime_d >='$startDate' AND  cr.event_datetime_d <='$endDate' and me.user_id_n = cr.user_id_n and c.user_id_n = me.user_id_n  ) totalTicket
                            
		    from crm_tickets_tab c
		         ,group_details_tab ga
		         ,scc_teams_tab sa
                         , master_users_tab m
		    where c.user_id_n = ga.entity_name_v 
		    and sa.team_id_n = ga.additionnal_info_v 
                    and m.user_id_n = c.user_id_n
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
		    $teamSql
		    GROUP BY date_format(c.event_datetime_d,'$granularity'), m.user_name_v
           
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalQOSStatsPerTeam2($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalQOSStatsPerTeam2()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                 select eventDate
          ,sum(unpicked) totalUnpicked
          ,sum(picked) totalPicked
   from 
	   ( select date_format(c.event_datetime_d,'$granularity') eventDate
		            , case c.status_n
		              when 7 then 1 else 0
		              end unpicked
		            , case c.status_n
		              when 7 then 0 else 1
		              end picked
	   
		    from crm_tickets_tab c
		    where c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
		    ) t
   group by eventDate
   LIMIT $maxElement
           
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalDMCStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalDMCStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
		            ,s.team_name_v
                            ,min(p.duration) minTime
                            ,avg(p.duration) avgTime
                            ,max(p.duration) maxTime     
		    from crm_tickets_tab c
		         ,group_details_tab g
		         ,scc_teams_tab s
                         , master_cdr_tab p
		    where c.user_id_n = g.entity_name_v 
		    and s.team_id_n = g.additionnal_info_v 
                    and c.char_field_2 = p.uniqueid
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
		    $teamSql
                    GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v
                     LIMIT $maxElement
           
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getDetailsDMCStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getDetailsDMCStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
		            ,s.team_name_v
                            ,m.user_name_v
                            ,min(p.duration) minTime
                            ,avg(p.duration) avgTime
                            ,max(p.duration) maxTime     
		    from crm_tickets_tab c
		         ,group_details_tab g
		         ,scc_teams_tab s
                         , master_cdr_tab p
                         , master_users_tab m
		    where c.user_id_n = g.entity_name_v 
		    and s.team_id_n = g.additionnal_info_v 
                    and c.char_field_2 = p.uniqueid
                    and m.user_id_n = c.user_id_n
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
		    $teamSql
                    GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, m.user_name_v
                     LIMIT $maxElement
           
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getGlobalDMTStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getGlobalDMTStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
		            ,s.team_name_v
                            ,min(p.event_datetime_d - c.event_datetime_d) minTime
                            ,avg(p.event_datetime_d - c.event_datetime_d) avgTime
                            ,max(p.event_datetime_d - c.event_datetime_d) maxTime     
		    from crm_tickets_tab c
		         ,group_details_tab g
		         ,scc_teams_tab s
                         , crm_tickets_history_tab  p
		    where c.user_id_n = g.entity_name_v 
		    and s.team_id_n = g.additionnal_info_v 
                    and c.ticket_number_v = p.ticket_number_v
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
                    AND p.status_n = 3
		    $teamSql
                    GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v
                     LIMIT $maxElement
           
                ";

            //   echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getDetailsDMTStatsPerTeam($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getDetailsDMTStatsPerTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                select date_format(c.event_datetime_d,'$granularity') eventDate
		            ,s.team_name_v
                            ,m.user_name_v
                            ,min(p.event_datetime_d - c.event_datetime_d) minTime
                            ,avg(p.event_datetime_d - c.event_datetime_d) avgTime
                            ,max(p.event_datetime_d - c.event_datetime_d) maxTime     
		    from crm_tickets_tab c
		         ,group_details_tab g
		         ,scc_teams_tab s
                         , crm_tickets_history_tab  p
                         , master_users_tab m
		    where c.user_id_n = g.entity_name_v 
		    and s.team_id_n = g.additionnal_info_v 
                    and c.ticket_number_v = p.ticket_number_v
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
                    and c.user_id_n = m.user_id_n 
                    AND p.status_n = 3
		    $teamSql
                    GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, m.user_name_v
                     LIMIT $maxElement
           
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getResolvedFirstCall($teamId, $granularity, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getResolvedFirstCall()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                 select date_format(c.event_datetime_d,'$granularity') eventDate
                            ,m.user_name_v
                            , count(1) total
                            , (select count(1) from crm_tickets_tab cr, group_details_tab g ,scc_teams_tab s , master_users_tab me where cr.user_id_n = g.entity_name_v and s.team_id_n = g.additionnal_info_v and cr.event_datetime_d >='$startDate' AND  cr.event_datetime_d <='$endDate' and me.user_id_n = cr.user_id_n ) totalTicket
                            
		    from crm_tickets_tab c
		         ,group_details_tab ga
		         ,scc_teams_tab sa
                         , master_users_tab m
		    where c.user_id_n = ga.entity_name_v 
		    and sa.team_id_n = ga.additionnal_info_v 
                    and m.user_id_n = c.user_id_n
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
                    and c.status_n = 3
                    and c.ticket_number_v not in ( select distinct k.ticket_number_v from crm_tickets_history_tab k where k.status_n=10)
		    $teamSql
		    GROUP BY date_format(c.event_datetime_d,'$granularity'), m.user_name_v
           
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCSONECClass($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCSONECClass()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "WHERE classe_id_n = '$id'";
            }

            $sqlQuery = "
                  SELECT   classe_id_n
							,classe_name_v
							,status_n
					FROM `master_classes_tab` 
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddSCCExtendCRMData($opId, $id, $ticketNumber, $charExtend, $status) {
        $dbAccess = $this->getMysqlConnection();
        //  $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSCCExtendCRMData()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {


                $sqlQuery = "INSERT 
                INTO crm_ticket_data_tab (`item_id_n`, `ticket_number_v`, `ext_char_field_1`, `ext_char_field_2`, `ext_char_field_3`, `ext_char_field_4`, `ext_char_field_5`, `ext_char_field_6`, `ext_char_field_7`, `ext_char_field_8`, `ext_char_field_9`, `ext_char_field_10`, `ext_char_field_11`, `ext_char_field_12`, `ext_char_field_13`, `ext_char_field_14`, `ext_char_field_15`, `ext_char_field_16`, `ext_char_field_17`, `ext_char_field_18`, `ext_char_field_19`, `ext_char_field_20`)   VALUES (NULL,'$ticketNumber','$charExtend[0]','$charExtend[1]','$charExtend[2]','$charExtend[3]','$charExtend[4]','$charExtend[5]','$charExtend[6]','$charExtend[7]','$charExtend[8]','$charExtend[9]','$charExtend[10]','$charExtend[11]','$charExtend[12]','$charExtend[13]','$charExtend[14]','$charExtend[15]','$charExtend[16]','$charExtend[17]','$charExtend[18]','$charExtend[19]','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = " UPDATE  crm_ticket_data_tab
			               SET  ext_char_field_1='$charExtend[0]'
				           ,ext_char_field_2='$charExtend[1]'
				           ,ext_char_field_3='$charExtend[2]'
					   ,ext_char_field_4='$charExtend[3]'
					   ,ext_char_field_5='$charExtend[4]'
					   ,ext_char_field_6 ='$charExtend[5]' 
                                           ,ext_char_field_7='$charExtend[6]'
				           ,ext_char_field_8='$charExtend[7]'
					   ,ext_char_field_9='$charExtend[8]'
					   ,ext_char_field_10='$charExtend[9]'
					   ,ext_char_field_11 ='$charExtend[10]' 
                                           ,ext_char_field_12='$charExtend[11]'
				           ,ext_char_field_13='$charExtend[12]'
					   ,ext_char_field_14='$charExtend[13]'
					   ,ext_char_field_15='$charExtend[14]'
					   ,ext_char_field_16 ='$charExtend[15]' 
                                           ,ext_char_field_17='$charExtend[16]'
				           ,ext_char_field_18='$charExtend[17]'
					   ,ext_char_field_19='$charExtend[18]'
					   ,ext_char_field_20='$charExtend[19]'
                                           ,status_n ='$status'  
			     WHERE ticket_number_v='$id'";
            } else {

                $sqlQuery = " DELETE FROM   crm_ticket_data_tab where  ticket_number_v in ($id)";
            }



            // echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function SCCCheckExtendedData($crsId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCCheckExtendedData()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {




            $sqlQuery = "
                  SELECT  * from crm_ticket_data_tab WHERE ticket_number_v='$crsId'
					
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCConnexionHistory($teamId, $methodId, $startDate, $endDate, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCConnexionHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = "and s.team_id_n = $teamId";
            }



            $sqlQuery = "
                 select DATE_FORMAT(c.event_datetime_d,'%d/%m/%Y %H:%i:%s') eventDate
                            ,m.user_name_v
                            ,DATE_FORMAT(c.start_datetime_d,'%d/%m/%Y %H:%i:%s') startDate
                            ,DATE_FORMAT(c.end_datetime_d,'%d/%m/%Y %H:%i:%s') endDate
                            , (end_datetime_d - start_datetime_d) duration 
		    from scc_users_cnx_hist_tab c
		         ,group_details_tab ga
		         ,scc_teams_tab sa
                         , master_users_tab m
		    where c.user_id_n = ga.entity_name_v 
		    and sa.team_id_n = ga.additionnal_info_v 
                    and m.user_id_n = c.user_id_n
		    and c.event_datetime_d >='$startDate'
		    AND  c.event_datetime_d <='$endDate'
                    and c.method_id_n = $methodId
		    $teamSql
                        LIMIT $maxElement
           
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getAllSCCUsers($userId, $id, $option, $startLimit, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getAllSCCUsers()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $limitQuery = "";

            $usql = "";

            if ($userId != -1) {

                $userSql = "and a.user_id_n= $userId";
            }

            if ($option) {

                $limitQuery = "LIMIT $startLimit, $maxElement";
            }

            $sqlQuery = "
                    select a.user_id_n
                        ,a.user_name_v
                        ,a.first_name_v
                        ,a.last_name_v
			,a.profile_id_n
                        ,a.creation_date_d
                        ,a.mobile_phone_v
                        ,a.email_v
                 from master_users_tab a,
                    scc_users_tab b
                where a.user_id_n = b.user_id_n
                $userSql
	        $limitQuery	 

                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getModulesGlobalStatsByTeam($teamId, $startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonGlobalStatsByTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = " AND s.team_id_n=$teamId";
            }


            $sqlQuery = "
                
               
                 SELECT DISTINCT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,s.team_name_v
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,scc_modules_tab d
                      ,group_details_tab g
                      ,scc_teams_tab s
                 WHERE c.reason_category_n = d.motif_id_n
                 and c.user_id_n = g.entity_name_v 
                 and s.team_id_n = g.additionnal_info_v
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                  $teamSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement

             

                     
                ";

        // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSubModulesGlobalStatsByTeam($teamId, $startDate, $endDate, $granularity, $maxElement) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getCallReasonGlobalStatsByTeam()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $teamSql = "";

            if ($teamId != -1) {

                $teamSql = " AND s.team_id_n=$teamId";
            }


            $sqlQuery = "
                
               
                 SELECT date_format(c.event_datetime_d,'$granularity') eventDate
                       ,s.team_name_v
                       , d.motif_name_v
                       , count(1) total
                 FROM `crm_tickets_tab` c
                      ,master_sub_motifs_tab d
                      ,group_details_tab g
                      ,scc_teams_tab s
                 WHERE c.reason_n = d.motif_id_n
                 and c.user_id_n = g.entity_name_v 
                 and s.team_id_n = g.additionnal_info_v
                 AND c.event_datetime_d >='$startDate'
                 AND  c.event_datetime_d <='$endDate'
                  $teamSql
                 GROUP BY date_format(c.event_datetime_d,'$granularity'), s.team_name_v, d.motif_name_v
                 ORDER BY 1 DESC
                 LIMIT $maxElement
                     
                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddDelCalendar($opId, $id, $userId, $calendarName, $description, $dayslist, $monthsList, $mode, $calendarType, $startDate, $startTime, $endDate, $endTime) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddDelCalendar()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_calendars_tab (`calendar_id_n`, `creation_datetime_d`, `type_id_n`, `user_id_n`, `calendar_name_v`, `calendar_desc_v`, `start_date_d`, `start_time_d`, `end_date_d`, `end_time_d`, `fulltime_indicator_v`, `days_list_v`, `months_list_v`, `status_n`) VALUES (NULL, now(), '$calendarType', '$userId', '$calendarName', '$description', '$startDate', '$startTime', '$endDate', '$endTime', '$mode', '$dayslist', '$monthsList', '0')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_calendars_tab
			     SET type_id_n='$calendarType'
				,calendar_name_v='$calendarName'
                                ,calendar_desc_v='$description'
                                ,start_date_d='$startDate'
                                ,start_time_d='$startTime'
                                ,end_date_d='$endDate'
                                ,end_time_d='$endTime'
                                ,fulltime_indicator_v='$mode'
                                ,days_list_v='$dayslist'
                                ,months_list_v='$monthsList'
			     WHERE calendar_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_calendars_tab WHERE calendar_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            // echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function SCCGetCalendarDtlsById($itemId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCGetCalendarDtlsById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $itemSql = "";

            if ($itemId > 0) {

                $itemSql = " Where calendar_id_n = $itemId";
            }



            $sqlQuery = "
                
               SELECT `calendar_id_n`
                    ,`creation_datetime_d`
                    ,`type_id_n`
                    ,`user_id_n`
                    , `calendar_name_v`
                    ,`calendar_desc_v`
                    , DATE_FORMAT(`start_date_d`,'%Y-%m-%d') start_date_d
                    , `start_time_d`
                    , DATE_FORMAT(`end_date_d`,'%Y-%m-%d') end_date_d
                    ,`end_time_d`
                    , `fulltime_indicator_v`
                    ,`days_list_v`
                    , `months_list_v`
                    ,`status_n`
              FROM `scc_calendars_tab` 
              $itemSql
              
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function SCCUploadMailNotification($toList, $ccList, $subject, $content, $attachments) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec SCCUploadMailNotification()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "INSERT INTO mail_notifications_tab  (`item_id_n`, `event_datetime_d`, `to_list_v`, `cc_list_v`, `subject_v`, `content_v`, `attachment_list_v`, `status_n`) VALUES (NULL, now(),'$toList', '$ccList', '$subject', '$content', '$attachments', '0')";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getSCCTicketFwdBy($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketFileHistory()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and l.ticket_number_v='$ticketId' and l.status_n=10 order by l.event_datetime_d desc limit 1 ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCFwdTicketDetailsByTicket($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCFwdTicketDetailsByTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
                                                   ,c.email_v
                                                    ,a.reason_category_n
                                                   ,a.reason_n
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
                                                                                                    , (select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdBy
                                                   , (select date_format(l.event_datetime_d ,'%d/%m/%Y %H:%i:%s')  from crm_tickets_history_tab l where  a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1 ) fwdDate
                                                    , (select s.team_name_v from crm_tickets_history_tab l , scc_teams_tab s   where l.profile_id_n  = s.team_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdTo
			                FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
                                                  ,master_priorities_tab d
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.char_field_9 = 10
                                        and a.status_n not in  ('3','7')
                                        and  a.ticket_number_v='$ticketId'
				
                    order by a.event_datetime_d  desc
                    limit 1

                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCStdTicketDetailsByTicket($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCStdTicketDetailsByTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
                                                                                                    , (select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdBy
                                                   , (select date_format(l.event_datetime_d ,'%d/%m/%Y %H:%i:%s')  from crm_tickets_history_tab l where  a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1 ) fwdDate
                                                    , (select s.team_name_v from crm_tickets_history_tab l , scc_teams_tab s   where l.profile_id_n  = s.team_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdTo
                                                  ,d.short_desc_v priorityName
			                FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
                                                  ,master_priorities_tab d
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.char_field_4 = d.priority_id_n
                                        and  a.ticket_number_v='$ticketId'
				


                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }
    
    
    
      public function getSCCReclamtionTicketById($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCReclamtionTicketById()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
                                                                                                    , (select m.user_name_v from crm_tickets_history_tab l , master_users_tab m where l.user_id_n = m.user_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdBy
                                                   , (select date_format(l.event_datetime_d ,'%d/%m/%Y %H:%i:%s')  from crm_tickets_history_tab l where  a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1 ) fwdDate
                                                    , (select s.team_name_v from crm_tickets_history_tab l , scc_teams_tab s   where l.profile_id_n  = s.team_id_n and a.ticket_number_v=l.ticket_number_v and l.status_n=10 order by l.event_datetime_d desc limit 1) fwdTo
                                                  ,d.short_desc_v priorityName
			                FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
                                                  ,master_priorities_tab d
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.char_field_4 = d.priority_id_n
                                        and  a.ticket_number_v='$ticketId'
				


                        

                ";

            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }
    
    
    
    public function UpdateAddDelMugefciSupInfo($opId, $id, $ticketNumber, $employerName, $beneficiaryName, $beneficiaryId, $analysisCause, $complaintAnalysis, $analysisDecision, $status) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddMugefciSupInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            // Échappement des variables
    $employerName = mysql_real_escape_string($employerName);
    $beneficiaryName = mysql_real_escape_string($beneficiaryName);
    $beneficiaryId = mysql_real_escape_string($beneficiaryId);
    $analysisCause = mysql_real_escape_string($analysisCause);
    $complaintAnalysis = mysql_real_escape_string($complaintAnalysis);
    $analysisDecision = mysql_real_escape_string($analysisDecision);
    


            if ($opId == 0) {


                $sqlQuery = "INSERT INTO mugefci_sup_infos_tab (`item_id_n`, `ticket_number_v`, `employer_name_v`, `beneficiary_name_v`, `beneficiary_id_v`, `analysis_cause_v`, `complaint_analysis_v`, `analysis_decision_v`, `status_n`)"
                        . "VALUE (NULL,'$ticketNumber','$employerName','$beneficiaryName','$beneficiaryId','$analysisCause','$complaintAnalysis','$analysisDecision','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = " UPDATE  mugefci_sup_infos_tab
			               SET  employer_name_v='$employerName'
						       ,beneficiary_name_v='$beneficiaryName'
						       ,beneficiary_id_v='$beneficiaryId'
							   ,analysis_cause_v='$analysisCause'
							   ,complaint_analysis_v='$complaintAnalysis'
							   ,analysis_decision_v ='$analysisDecision' 
							 WHERE ticket_number_v='$ticketNumber'";
            } else {

                $sqlQuery = " DELETE FROM   mugefci_sup_infos_tab where  ticket_number_v in ($id)";
            }


            echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function UpdateAddDelMugefciSupInfoPrestataire($opId, $id, $ticketNumber, $objet, $incident, $decision, $analysePlainte, $status) {
        $dbAccess = $this->getMysqlConnection();
        $id = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddMugefciSupInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {


                $sqlQuery = "INSERT INTO mugefci_sup_infos_prestataire_tab(`item_id_n`, `ticket_number_v`, `objet_v`, `incident_v`, `decision_v`, `analysePlainte_v`, `status_n`)"
                        . "VALUE (NULL,'$ticketNumber','$objet','$incident','$decision','$analysePlainte','$status')";
            } elseif ($opId == 1) {

                $sqlQuery = " UPDATE  mugefci_sup_infos_prestataire_tab
			               SET objet_v='$objet'
						       ,incident_v='$incident'
						       ,decision_v='$decision'
							   ,analysePlainte_v='$analysePlainte'
							 WHERE ticket_number_v='$ticketNumber'";
            } else {

                $sqlQuery = " DELETE FROM   mugefci_sup_infos_prestataire_tab where  ticket_number_v in ($id)";
            }


             //echo $sqlQuery;
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //$id = mysql_insert_id($dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $id;
    }

    public function getSCCCmpltInprogressTicketDetails($userId, $right, $status) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCCmpltInprogressTicketDetails()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $profileSql = "";
            $userSql = "";
            $limitSql = "";
            $statusSql = "";
            $campaignSql = "";
            $date1Sql = "";
            $date2Sql = "";

            if ($status != -2) {
                $statusSql = "and a.status_n='$status'";
            }

            if (!$right) {

                $userSql = "and c.user_id_n='$userId'";
            }



            $sqlQuery = "
                      
                   SELECT   a.item_id_n
						   ,date_format(a.event_datetime_d,'%d/%m/%Y %H:%i:%s') event_datetime_d
						   ,a.first_name_v
						   ,a.last_name_v
						   ,c.user_name_v
						   ,(select d.motif_name_v from master_motifs_tab d where a.reason_n = d.motif_id_n) motif_name_v
						   ,a.mobile2_phone_v
						   ,a.location_v
						   ,a.mobile1_phone_v
						   ,a.char_field_2
						   ,a.ticket_number_v
						   ,b.description_v status_n
						   ,a.aknowledge_date_d
						   ,a.closure_date_d
						   ,a.char_field_5
						   ,a.ticket_reason_desc_v
						   ,a.char_field_7
                                                   ,case a.call_direction_n
						     when 0 then 'Entrant'
							 when 1 then 'Sortant'
							end call_direction
						    , (select comment_v from scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=0 limit 1) clientComment
						  , (select comment_v from  scc_ticket_comments_tab where ticket_number_v=a.ticket_number_v and comment_type_n=1 limit 1) agentComment
                                                  , ( select page_link_v from scc_forms_tab s where s.form_id_n = a.char_field_10) page_link_v
                                                  , d.employer_name_v
                                                  , d.beneficiary_name_v
                                                  , d.beneficiary_id_v
                                                  , d.analysis_cause_v
                                                  , d.complaint_analysis_v
                                                  , d.analysis_decision_v
					 FROM  crm_tickets_tab a
						  ,master_users_tab c
						  ,master_status_tab b
                                                  ,mugefci_sup_infos_tab d
					WHERE  a.user_id_n = c.user_id_n
					and a.status_n = b.status_n
                                        and a.status_n not in  ('3','7')
                                        and a.char_field_10 = 4
                                        and a.ticket_number_v = d.ticket_number_v
					$date1Sql
					$date2Sql
					$statusSql
                    $profileSql
                    $userSql
                    order by a.event_datetime_d  desc

                        

                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCMugefciSupInfo($ticketNumber) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCMugefciSupInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                  SELECT     employer_name_v
                            ,beneficiary_name_v
                            ,beneficiary_id_v
                            ,analysis_cause_v
                            ,complaint_analysis_v
                            ,analysis_decision_v 
                    FROM `mugefci_sup_infos_tab` 
                    WHERE ticket_number_v='$ticketNumber'
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getSCCMugefciSupInfoPrestataire($ticketNumber) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCMugefciSupInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {



            $sqlQuery = "
                  SELECT     objet_v
                            ,incident_v
                            ,decision_v
                            ,analysePlainte_v
                    FROM `mugefci_sup_infos_prestataire_tab` 
                    WHERE ticket_number_v='$ticketNumber'
                ";
            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }
    
    
    public function getSCCSLAInfo($id) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCSLAInfo()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            $idSql = "";
            if ($id > 0) {

                $idSql = "and c.sla_id_n  = '$id'";
            }

            $sqlQuery = "
                  SELECT   c.module_id_n
							,c.submodule_id_n
							,c.sla_level_v
                                                        ,c.sla_duration_n 
                                                        ,b.motif_name_v module_name_v
                                                        ,a.motif_name_v submodule_name_v
                                                        ,c.sla_id_n
                                                        ,c.sla_duration_to_s
					FROM `scc_modules_tab` b,
                                        master_sub_motifs_tab a,
                                        scc_sla_tab c
                         WHERE a.parent_motif_id_n = b.motif_id_n
                         and c.submodule_id_n = a.motif_id_n
                         
					$idSql
                ";
            // echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }

    public function UpdateAddSla($opId, $id, $moduleId, $subModuleId, $slaName, $slaDuration,$slaDurationToS) {
        $dbAccess = $this->connectMysqlDatabase();

        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec UpdateAddSla()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            if ($opId == 0) {

                $sqlQuery = "INSERT INTO scc_sla_tab (`sla_id_n`, `module_id_n`, `submodule_id_n`, `sla_level_v`, `sla_duration_n`,`sla_duration_to_s`, `status_n`) VALUES (NULL, '$moduleId', '$subModuleId', '$slaName', '$slaDuration','$slaDurationToS', '0')";
            } elseif ($opId == 1) {

                $sqlQuery = "UPDATE scc_sla_tab
                                SET module_id_n='$moduleId'
                                ,submodule_id_n='$subModuleId'
                                ,sla_level_v = '$slaName'
                                ,sla_duration_n = '$slaDuration'
                                ,sla_duration_to_s = '$slaDurationToS'
                            WHERE sla_id_n = '$id' ";
            } else {

                $sqlQuery = "DELETE FROM  scc_sla_tab WHERE sla_id_n in ($id)";
            }
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

          //   echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }
    
       
    
   public function getSLABySubMenuId($menuId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSLABySubMenuId()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {

            

            $sqlQuery = "  
                  SELECT * FROM `scc_sla_tab` WHERE  `submodule_id_n` = '$menuId' limit 1
                ";

            //echo $sqlQuery;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        return $this->mysqlRessourceJson($sqlResult);
    }
    
    
    
    
    public function getSCCTicketDetailByTicket($ticketId) {

        $dbAccess = $this->connectMysqlDatabase();

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec getSCCTicketDetailByTicket()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $this->msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {


            $sqlQuery = "
			
			 SELECT    item_id_n
						  ,event_datetime_d
						  ,ticket_number_v caller_ticket_id
						   ,mobile1_phone_v from_callerid_v
					           ,e.user_name_v  to_number_v
						  ,d.description_v
						  ,c.reason_n
                                                  ,c.reason_category_n
						  ,ticket_reason_desc_v
						  ,c.char_field_2
						  ,c.char_field_5
                                                  ,c.first_name_v
                                                  ,c.last_name_v
                                                  ,c.location_v location_v
                                                  ,c.mobile1_phone_v contact_v
                                                  ,c.mobile2_phone_v
                                                  ,c.gender_v
						  ,c.company_name_v
                                                  ,c.char_field_6 
                                                  ,c.email_id_v
                                                  ,c.status_n
                                                  ,c.char_field_3
                                                  ,c.char_field_4
                                                  ,c.char_field_10
                                                  ,c.user_id_n
                                                 
                                                  
                                                  
             FROM  crm_tickets_tab c
                         ,master_status_tab d
                         ,master_users_tab e
             WHERE c.status_n = d.status_n
             AND e.user_id_n = c.user_id_n
			 AND c.ticket_number_v = '$ticketId'
	         order by 1 desc
                 limit 1
			  ";

          //  echo  $sqlQuery ;
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

            //echo $sqlResult;
           // $queryData = mysql_fetch_array($sqlResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
            // print_r($queryData);
            // echo mysql_error();
        }

         return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTicketNumberByCallId($callId) {
        // Connexion à la base de données
        $dbAccess = $this->connectMysqlDatabase();
        $ticketNumber = null;
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getTicketNumberByCallId() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            // Requête pour récupérer le numéro du ticket
            $sqlQuery = "SELECT ticket_number_v FROM crm_tickets_tab WHERE item_id_n = '$callId'";
            
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            
            if ($queryResult) {
                // Récupérer le résultat de la requête
                $row = mysql_fetch_assoc($queryResult);
                if ($row) {
                    $ticketNumber = $row['ticket_number_v'];
                }
            }
            
            // Fermer la connexion à la base de données
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
    
        // Retourner le numéro de ticket ou null si non trouvé
        return $ticketNumber;
    }

    public function getReclamationTime($startDate, $endDate, $status, $granularity, $maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationTime() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            
            $statusSql = "";
            if ($status != -2) { // -2 pour "Tout" 
                $statusSql = "AND c.status_n = $status"; 
            }
    
            $sqlQuery = "
                SELECT 
                    DATE_FORMAT(c.event_datetime_d, '$granularity') AS eventDate, 
                    c.closure_date_d, 
                    c.ticket_number_v, 
                    c.last_name_v, 
                    TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) AS traitement_duration, 
                    p.description_v AS status
                FROM 
                    crm_tickets_tab c
                JOIN 
                    master_status_tab p ON p.status_n = c.status_n
                WHERE 
                    c.event_datetime_d >= '$startDate' 
                    AND c.event_datetime_d <= '$endDate'
                    $statusSql
                ORDER BY 
                    c.event_datetime_d DESC
                LIMIT 
                    $maxElement
            ";
    
            //echo $sqlQuery;  
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }
    
    
    
    public function getEfficientTeamsByPeriod($startDate,$endDate,$granularity,$maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getEfficientTeamsByPeriod() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        }else{

            
            $sqlQuery = "
            SELECT 
                DATE_FORMAT(c.event_datetime_d, '$granularity') AS DateTime,
                s.team_name_v AS team_name,
                COUNT(c.ticket_number_v) AS total_tickets,
                 SUM(
        CASE 
            WHEN c.status_n =3 THEN TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d)
            ELSE TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW())
        END
        ) AS  avg_resolution_time_seconds,
         SUM(
        CASE 
            WHEN c.status_n =3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) <= sla.sla_duration_to_s THEN 1
            WHEN c.status_n !=3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) <= sla.sla_duration_to_s THEN 1
            ELSE 0
        END
    ) / COUNT(c.ticket_number_v) * 100 AS pourcentage_dans_sla
            FROM 
                crm_tickets_tab c
            JOIN 
                scc_sla_tab sla ON sla.submodule_id_n =c.char_field_3
            JOIN 
                group_details_tab g ON c.user_id_n = g.entity_name_v
            JOIN 
                scc_teams_tab s ON g.additionnal_info_v = s.team_id_n
            WHERE 
                c.closure_date_d IS NOT NULL
                AND c.event_datetime_d >= '$startDate'
                AND c.event_datetime_d <= '$endDate'
            GROUP BY 
                s.team_name_v,DateTime
            ORDER BY 
                pourcentage_dans_sla ASC
                LIMIT $maxElement
        ";
       // echo $sqlQuery;
        $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
        $this->closeMysqlConnection($dbAccess['dbConnection']);

        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getReclamationOutSla($startDate, $endDate,$granularity,$status,$maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationOutSla() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        }else{

            $statusSql = "";
            if ($status != -2) {  
                $statusSql = "AND c.status_n = $status"; 
            }

            $sqlQuery = "
    SELECT 
        DATE_FORMAT(c.event_datetime_d, '$granularity') AS periode,
        p.description_v AS status_name,
        c.ticket_number_v,
        u.user_name_v AS agent_name,
        c.closure_date_d,
        c.reason_n,
        c.status_n,
        s.sla_duration_to_s,
    -- Calcul de la durée de traitement
CASE 
    WHEN c.status_n = 3 THEN TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d)
                    ELSE TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW())
END AS traitement_duration,
    -- Vérification si le ticket est en retard
    CASE 
        WHEN c.status_n = 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) > s.sla_duration_to_s THEN 'En Retard'
        WHEN c.status_n != 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) > s.sla_duration_to_s THEN 'En Retard'
        ELSE 'À Temps'
    END AS statut_retard
FROM 
    crm_tickets_tab c
JOIN 
    scc_sla_tab s ON s.submodule_id_n = c.char_field_3
JOIN
    master_status_tab p ON p.status_n = c.status_n
JOIN
    master_users_tab u ON u.user_id_n = c.user_id_n
WHERE 
    c.event_datetime_d >= '$startDate'
    AND c.event_datetime_d <= '$endDate'
    $statusSql
    AND (
        (c.status_n = 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) > s.sla_duration_to_s)
        OR 
        (c.status_n != 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) > s.sla_duration_to_s)
    )
GROUP BY 
        periode, c.ticket_number_v
ORDER BY 
    c.event_datetime_d DESC
     LIMIT $maxElement
        ";
        
        //echo $sqlQuery;
        $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
        $this->closeMysqlConnection($dbAccess['dbConnection']);

        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getReclamationOutAndInSla($startDate, $endDate, $granularity, $status, $maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationOutAndInSla() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $statusSql = "";
            if ($status != -2) {
                $statusSql = "AND c.status_n = $status";
            }
    
            $sqlQuery = "
                SELECT 
    DATE_FORMAT(c.event_datetime_d, '$granularity') AS periode,
    p.description_v AS status_name,
    c.ticket_number_v,
    u.user_name_v AS agent_name,
    c.last_name_v,
    d.motif_name_v,
    c.company_name_v,
    c.closure_date_d,
    c.reason_n,
    c.status_n,
    s.sla_duration_to_s,
    DATE_ADD(c.event_datetime_d, INTERVAL s.sla_duration_to_s SECOND) AS expire_at,

    -- Calcul de la durée de traitement
    CASE 
        WHEN c.status_n = 3 THEN TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d)
        ELSE TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW())
    END AS traitement_duration,

    -- Vérification du statut SLA
    CASE 
        WHEN c.status_n = 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) > s.sla_duration_to_s THEN 'En Retard'
        WHEN c.status_n != 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) > s.sla_duration_to_s THEN 'En Retard'
        ELSE 'Dans le délai'
    END AS statut_retard,

    -- Date de traitement de la réclamation (si fermée)
    CASE 
        WHEN c.status_n = 3 THEN c.closure_date_d
         ELSE 'Pas clôturé'
    END AS date_traitement

FROM 
    crm_tickets_tab c
JOIN 
    scc_sla_tab s ON s.submodule_id_n = c.char_field_3
JOIN
    master_status_tab p ON p.status_n = c.status_n
JOIN
    master_users_tab u ON u.user_id_n = c.user_id_n
JOIN
    scc_modules_tab d ON d.motif_id_n = c.reason_category_n
WHERE 
    c.event_datetime_d >= '$startDate'
    AND c.event_datetime_d <= '$endDate'
    $statusSql
GROUP BY 
    periode, c.ticket_number_v
ORDER BY 
    c.event_datetime_d DESC
LIMIT $maxElement;


            ";
    
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }
    

    public function getReclamationRetardSendMail() {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationOutSla() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        }else{


            $sqlQuery = "
    SELECT 
     event_datetime_d as periode
    ,ticket_number_v
    ,first_name_v
    ,last_name_v
    ,matricule
    ,user_name_v as agent_name
    ,motif_name_v
    ,sla_duration_n
    ,sla_duration_to_s
    ,expire_at
    ,(UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(expire_at)) delay_n
	,status_name
    
FROM (
	SELECT a.event_datetime_d
	      ,a.ticket_number_v
	      ,a.first_name_v
	      ,a.last_name_v
          ,a.company_name_v as matricule
	      ,c.user_name_v
	      ,d.motif_name_v
	      ,b.sla_duration_n
	      ,b.sla_duration_to_s 
	      ,DATE_ADD(a.event_datetime_d, INTERVAL 	sla_duration_to_s SECOND) AS expire_at	
          ,e.description_v AS status_name
	FROM  crm_tickets_tab a
	      ,scc_sla_tab b
	      ,master_users_tab c
	      ,scc_modules_tab d
          ,master_status_tab e
	where  a.status_n= 2 
	and a.char_field_3 = b.submodule_id_n 
	and c.user_id_n = a.user_id_n 
	and d.motif_id_n=a.reason_category_n 
    and e.status_n= a.status_n 
	and a.char_field_10 in ('4','5')
	HAVING expire_at < now()
	
	)
	t
        ";
        
        //echo $sqlQuery;
        $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
        $this->closeMysqlConnection($dbAccess['dbConnection']);

        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getTeamsTraitementNoTime($startDate, $endDate,$granularity,$maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getTeamsTraitementNoTime() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        }else{

           

            $sqlQuery = "
    SELECT
    DATE_FORMAT(c.event_datetime_d, '$granularity') AS periode,
    s.team_name_v AS equipe,
    COUNT(c.ticket_number_v) AS total_tickets,
    SUM(
        CASE 
            WHEN c.status_n = 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) > sla.sla_duration_to_s THEN 1
            WHEN c.status_n != 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) > sla.sla_duration_to_s THEN 1
            ELSE 0
        END
    ) AS tickets_en_retard,
    -- Calcul du pourcentage de tickets en retard
    ROUND(
        SUM(
            CASE 
                WHEN c.status_n = 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, c.closure_date_d) > sla.sla_duration_to_s THEN 1
                WHEN c.status_n != 3 AND TIMESTAMPDIFF(SECOND, c.event_datetime_d, NOW()) > sla.sla_duration_to_s THEN 1
                ELSE 0
            END
        ) / COUNT(c.ticket_number_v) * 100, 2
    ) AS pourcentage_retard
FROM 
    crm_tickets_tab c
JOIN 
    scc_sla_tab sla ON sla.submodule_id_n = c.char_field_3
JOIN 
    group_details_tab g ON g.entity_name_v = c.user_id_n
JOIN 
    scc_teams_tab s ON s.team_id_n = g.additionnal_info_v
WHERE 
    c.event_datetime_d >= '$startDate'
    AND c.event_datetime_d <= '$endDate'
GROUP BY 
    s.team_name_v,periode
HAVING 
    tickets_en_retard > 0
ORDER BY 
    pourcentage_retard DESC
    LIMIT $maxElement
        ";
       // echo $sqlQuery;
        $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
        $this->closeMysqlConnection($dbAccess['dbConnection']);

        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function apiavis($ticket,$firstname,$lastname,$matricule,$avis) {

        $dbAccess = $this->getMysqlConnection();
        $totalUser = 0;

        if (!$dbAccess['dbConnection']) {
            $logDebug = " Echec addNDC()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'] . " MSISDN :: $msisdn";
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            $sqlQuery = "INSERT INTO avis_mutualistes (first_name_v, last_name_v, ticket_number_v, avis, creation_date_d)
             VALUES ('$firstname','$lastname','$ticket','$avis',now())";
            $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            //echo $sqlQuery;
            // $totalUser = mysql_affected_rows($queryResult);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }

        if ($queryResult)
            $totalUser = 1;
        return $totalUser;
    }

    public function getVoteStatsVoteSatisfaction($startDate, $endDate, $granularity, $maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationTime() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            
    
    
            $sqlQuery = "
                SELECT 
                    DATE_FORMAT(c.creation_date_d, '$granularity') AS eventDate 
                    ,Round(avg(c.avis),2)  as avgNote                  
                FROM 
                    avis_mutualistes c              
                WHERE 
                    c.creation_date_d >= '$startDate' 
                    AND c.creation_date_d <= '$endDate'
                    $statusSql 
                ORDER BY 
                    c.creation_date_d DESC
                LIMIT 
                    $maxElement
            ";
    
            //echo $sqlQuery;  
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function getStatsDetailleVote($startDate, $endDate, $granularity, $maxElement) {
        $dbAccess = $this->connectMysqlDatabase();
    
        if (!$dbAccess['dbConnection']) {
            $logDebug = "Echec getReclamationTime() " . $dbAccess['errorMessage'] . " " . $dbAccess['errorCode'];
            $this->svaLog->writeSystemLog($logDebug);
            die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
        } else {
            
    
    
            $sqlQuery = "
                SELECT 
                    DATE_FORMAT(c.creation_date_d, '$granularity') AS eventDate
                    ,c.ticket_number_v
                    ,c.first_name_v
                    ,c.last_name_v
                    ,c.avis             
                FROM 
                    avis_mutualistes c              
                WHERE 
                    c.creation_date_d >= '$startDate' 
                    AND c.creation_date_d <= '$endDate'
                    $statusSql
                ORDER BY 
                    c.creation_date_d DESC
                LIMIT 
                    $maxElement
            ";
    
           // echo $sqlQuery;  
            $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
            $this->closeMysqlConnection($dbAccess['dbConnection']);
        }
    
        return $this->mysqlRessourceJson($sqlResult);
    }

    public function createSmsCampaign($campaignName, $startDate, $startTime, $endDate, $endTime, $ownerId){
    $dbAccess = $this->getMysqlConnection();
    $inserted = 0;

    if (!$dbAccess['dbConnection']) {
        $logDebug = "Echec createSmsCampaign()  " . $dbAccess['errorMessage'] . "  " . $dbAccess['errorCode'];
        $this->svaLog->writeSystemLog($logDebug);
        die("IMPOSSIBLE DE SE CONNECTER A LA BASE DE DONNEES");
    } else {
        $sqlQuery = "
            INSERT INTO master_campaigns_tab (
                campaign_id_n,
                creation_date_d,
                campaign_name_v,
                internal_code_v,
                start_date_d,
                start_time_d,
                end_date_d,
                end_time_d,
                owner_id_n,
                priority_n,
                sender_id_n,
                message_v,
                appid,
                module_id_n,
                char_field_1,
                char_field_2,
                char_field_3,
                char_field_4,
                char_field_5,
                char_field_6,
                char_field_7,
                char_field_8,
                char_field_9,
                char_field_10,
                status_n
            ) VALUES (
                NULL,
                NOW(),
                '$campaignName',
                NULL,
                '$startDate',
                '$startTime',
                '$endDate',
                '$endTime',
                '$ownerId',
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL, NULL, NULL, NULL, NULL, NULL,2, NULL, NULL, NULL,
                -1
            )";

        $queryResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

        if ($queryResult) {
            $inserted = mysql_insert_id(); // retourne l'ID si succès
        }

        $this->closeMysqlConnection($dbAccess['dbConnection']);
    }

    return $inserted; 
}


public function updateSmsCampaign($campaignId, $campaignName, $startDate, $startTime, $endDate, $endTime)
{
    $dbAccess = $this->connectMysqlDatabase();

    if (!$dbAccess['dbConnection']) {
        $logDebug = "Échec updateSmsCampaign() : " . $dbAccess['errorMessage'];
        $this->svaLog->writeSystemLog($logDebug);
        return false;
    }

    $sql = "
    UPDATE master_campaigns_tab
    SET campaign_name_v = '" . mysql_real_escape_string($campaignName) . "',
        start_date_d = '" . mysql_real_escape_string($startDate) . "',
        start_time_d = '" . mysql_real_escape_string($startTime) . "',
        end_date_d = '" . mysql_real_escape_string($endDate) . "',
        end_time_d = '" . mysql_real_escape_string($endTime) . "'
    WHERE campaign_id_n = " . intval($campaignId);
     

    $result = mysql_query($sql, $dbAccess['dbConnection']);

    if (!$result) {
        $logDebug = "Erreur SQL updateSmsCampaign : " . mysql_error();
        $this->svaLog->writeSystemLog($logDebug);
    }

    $this->closeMysqlConnection($dbAccess['dbConnection']);

    return $result ? true : false;
}

public function deleteAllCampaignPhones($campaignId)
{
    $dbAccess = $this->connectMysqlDatabase();

    if (!$dbAccess['dbConnection']) {
        $logDebug = "Échec deleteAllCampaignPhones() : " . $dbAccess['errorMessage'];
        $this->svaLog->writeSystemLog($logDebug);
        return false;
    }

    $sql = "DELETE FROM queues_processor_tab WHERE campaign_id_n = " . intval($campaignId);

    $result = mysql_query($sql, $dbAccess['dbConnection']);

    if (!$result) {
        $logDebug = "Erreur SQL deleteAllCampaignPhones : " . mysql_error();
        $this->svaLog->writeSystemLog($logDebug);
    }

    $this->closeMysqlConnection($dbAccess['dbConnection']);

    return $result ? true : false;
}



public function getSCCSmsDetails($ownerId) {
    $dbAccess = $this->connectMysqlDatabase();
    $result = array();

    if (!$dbAccess['dbConnection']) {
        return $result;
    }

    $sql = "SELECT 
                campaign_id_n,
                creation_date_d,
                campaign_name_v,
                status_n,
                CASE 
                    WHEN status_n = -1 THEN 'Initialisée'
                    WHEN status_n = 6 THEN 'DEMARREE'
                    WHEN status_n = 3 THEN 'Clôturée'
                    WHEN status_n = 4 THEN 'PAUSE'
                    ELSE 'Inconnu'
                END AS description_v
            FROM master_campaigns_tab
            WHERE char_field_7 = 2"; 

    if ($ownerId > 1) {
        $sql .= " AND owner_id_n = '$ownerId'";
    }

    $sql .= " ORDER BY creation_date_d DESC";

    $queryResult = mysql_query($sql, $dbAccess['dbConnection']);

    while ($row = mysql_fetch_assoc($queryResult)) {
        $result[] = $row;
    }

    $this->closeMysqlConnection($dbAccess['dbConnection']);
    return $result;
}

public function updateSmsCampaignStatus($campaignId, $newStatus)
{
    $dbAccess = $this->connectMysqlDatabase();

    if (!$dbAccess['dbConnection']) {
        $logDebug = "Échec updateSmsCampaignStatus() - " . $dbAccess['errorMessage'] . " | " . $dbAccess['errorCode'];
        $this->svaLog->writeSystemLog($logDebug);
        die("Impossible de se connecter à la base de données");
    }

    $campaignId = mysql_real_escape_string($campaignId);
    $newStatus = mysql_real_escape_string($newStatus);

    $logDebug = "updateSmsCampaignStatus() : campaign_id=$campaignId => status=$newStatus";
    $this->svaLog->writeSystemLog($logDebug);

    $sqlQuery = "
        UPDATE master_campaigns_tab
        SET status_n = '$newStatus'
        WHERE campaign_id_n = '$campaignId'
    ";

    $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);

    $this->closeMysqlConnection($dbAccess['dbConnection']);

    return ($sqlResult !== false);
}

public function getSCCSmsCampaignById($campaignId)
{
    $dbAccess = $this->connectMysqlDatabase();

    if (!$dbAccess['dbConnection']) {
        $logDebug = "Échec getSCCSmsCampaignById() - " . $dbAccess['errorMessage'] . " | " . $dbAccess['errorCode'];
        $this->svaLog->writeSystemLog($logDebug);
        die("Impossible de se connecter à la base de données");
    }

    $sqlQuery = "
        SELECT 
            campaign_id_n,
            campaign_name_v,
            DATE_FORMAT(start_date_d, '%Y-%m-%d') AS start_date,
            DATE_FORMAT(end_date_d, '%Y-%m-%d') AS end_date,
            TIME_FORMAT(start_time_d, '%H:%i:%s') AS start_time,
            TIME_FORMAT(end_time_d, '%H:%i:%s') AS end_time,
            owner_id_n
        FROM master_campaigns_tab
        WHERE campaign_id_n = '" . mysql_real_escape_string($campaignId) . "'
    ";

    $sqlResult = mysql_query($sqlQuery, $dbAccess['dbConnection']);
    $this->closeMysqlConnection($dbAccess['dbConnection']);

    return $this->mysqlRessourceJson($sqlResult);
}
 
    
}

?>
