<?php

require_once('include/MVC/View/views/view.list.php');
require_once('include/Sugar_Smarty.php');
function display() {
    
}
class Cont__centro_llamadasViewList extends ViewList {
    /**
     * @see ViewList::preDisplay()
     */
    public function preDisplay() {
        parent::preDisplay();

    }

    function listViewProcess(){
        set_time_limit(0);
        ini_set("memory_limit","250M");
        // asign variable de list templates
        $this->lv->ss->assign('dataListOpcRespuestas',$this->view_object_map['dataListOpcRespuestas']);//assign to smarty.
        $this->lv->ss->assign('dataListStuTiendas',$this->view_object_map['dataListStuTiendas']);//assign to smarty.
        $this->lv->ss->assign('strMsjResponse',$this->view_object_map['strMsjResponse']);//assign to smarty.
        $this->lv->ss->assign('request_custom',$_REQUEST);//assign to smarty.
        
        $this->processSearchForm();
        
        // get las condiciones
        $this->params['custom_where'] .= $this->getCondiSearchF();
        //$this->lv->searchColumns = $this->searchForm->searchColumns;
        //echo '<pre>'.print_r($this->params,true).'</pre>';
        //echo '<pre>'.print_r($this->params,true).'</pre>';exit;
        if(!$this->headers)
            return;
        if(empty($_REQUEST['search_form_only']) || $_REQUEST['search_form_only'] == false){
            $this->lv->setup($this->seed, 'modules/cont__centro_llamadas/tpl/ListViewGeneric.tpl', $this->where, $this->params);
            $savedSearchName = empty($_REQUEST['saved_search_select_name']) ? '' : (' - ' . $_REQUEST['saved_search_select_name']);
            echo get_form_header($GLOBALS['mod_strings']['LBL_LIST_FORM_TITLE'] . $savedSearchName, '', false);
            echo $this->lv->display();
        }
    }
    
    /**
     * 
     * @return string
     * @throws Exception
     */
    private function getCondiSearchF(){
        try{
            $where = "";
            
            
            if(isset($_REQUEST['ult_compra_list_c_basic']) && $_REQUEST['ult_compra_list_c_basic']!=""){
                
                
                $lastOrderTimeStamp=$_REQUEST['ult_compra_list_c_basic'][0]*30.5*24*60*60;
                
                $now = new DateTime();
                        
                $date=$now->getTimestamp()-$lastOrderTimeStamp;               
               
                //print $where;die();
            }
            
            if(isset($_REQUEST['cont__centro_llamadas_contacts_name_basic']) && $_REQUEST['cont__centro_llamadas_contacts_name_basic']!=""){
                $where .= " AND UPPER(con.first_name) LIKE '%".strtoupper($_REQUEST['cont__centro_llamadas_contacts_name_basic'])."%' ";
            }
            if(isset($_REQUEST['cont__centro_llamadas_contactscontacts_ida_basic']) && $_REQUEST['cont__centro_llamadas_contactscontacts_ida_basic']!=""){
                $where .= " AND con.id = '".$_REQUEST['cont__centro_llamadas_contactscontacts_ida_basic']."' ";
            }
            if(isset($_REQUEST['phone_home_basic']) && $_REQUEST['phone_home_basic']!=""){
                $where .= " AND con.phone_home LIKE '%".$_REQUEST['phone_home_basic']."%' ";
            }
            if(isset($_REQUEST['phone_mobile_basic']) && $_REQUEST['phone_mobile_basic']!=""){
                $where .= " AND con.phone_mobile LIKE '%".$_REQUEST['phone_mobile_basic']."%' ";
            }
            // estado gestion
            if(isset($_REQUEST['estado_gestion_basic']) && $_REQUEST['estado_gestion_basic']!=""){
                switch($_REQUEST['estado_gestion_basic']){
                    case "1":
                        $where .= " AND opc.name IS NULL ";
                        break;
                    case "2":
                        $where .= " AND opc.name IS NOT NULL ";
                        break;
                    case "a3714054-b810-ac7f-2321-55c6f0432000":
                        $where .= " AND centro.cont__opciones_respuestas_id_c = 'a3714054-b810-ac7f-2321-55c6f0432000' ";
                        $numDesde = null;
                        $numHasta = null;
                        if(isset($_REQUEST['txtFechaDesdeProxLlamada']) && $_REQUEST['txtFechaDesdeProxLlamada']!=""){
                            $numDesde = $this->getFechaClean($_REQUEST['txtFechaDesdeProxLlamada']);
                        }
                        if(isset($_REQUEST['txtFechaHastaProxLlamada']) && $_REQUEST['txtFechaHastaProxLlamada']!=""){
                            $numHasta = $this->getFechaClean($_REQUEST['txtFechaDesdeProxLlamada']);
                        }
                        if($numDesde != null){
                            $where .= " AND centro.proxima_llamada >= '".$numDesde." 00:00:00' ";
                        }
                        if($numHasta != null){
                            $where .= " AND centro.proxima_llamada <= '".$numHasta." 23:59:59' ";
                        }
                        break;
                    case "4":
                        $where .= " AND con.deleted = 0 AND con.do_not_call = 1 ";
                        break;
                    default:
                        $where .= " AND centro.cont__opciones_respuestas_id_c = '".$_REQUEST['estado_gestion_basic']."' ";
                }
            }
            // date_entered
            $numDesde = null;
            $numHasta = null;
            if(isset($_REQUEST['txtFechaDesdeCreacion']) && $_REQUEST['txtFechaDesdeCreacion']!=""){
                $numDesde = $this->getFechaClean($_REQUEST['txtFechaDesdeCreacion']);
            }
            if(isset($_REQUEST['txtFechaHastaCreacion']) && $_REQUEST['txtFechaHastaCreacion']!=""){
                $numHasta = $this->getFechaClean($_REQUEST['txtFechaHastaCreacion']);
            }
            if($numDesde != null){
                $where .= " AND centro.date_entered >= '".$numDesde." 00:00:00' ";
            }
            if($numHasta != null){
                $where .= " AND centro.date_entered <= '".$numHasta."  23:59:59' ";
            }
            
            // creado por
            if(isset($_REQUEST['created_by_basic']) && $_REQUEST['created_by_basic']!=""){
                $strId = '';
                for($i=0;$i<count($_REQUEST['created_by_basic']);$i++){
                    $strId .= "'".$_REQUEST['created_by_basic'][$i]."',";
                }
                $strId = substr($strId,0,strlen($strId)-1);
                if($strId!=""){
                    $where .= " AND centro.created_by IN(".$strId.") ";
                }
            }
            
            // modificado por
            if(isset($_REQUEST['modified_user_id_basic']) && $_REQUEST['modified_user_id_basic']!=""){
                $strId = '';
                for($i=0;$i<count($_REQUEST['modified_user_id_basic']);$i++){
                    $strId .= "'".$_REQUEST['modified_user_id_basic'][$i]."',";
                }
                $strId = substr($strId,0,strlen($strId)-1);
                if($strId!=""){
                    $where .= " AND centro.modified_user_id IN(".$strId.") ";
                }
            }
            
            // tienda
            if(isset($_REQUEST['stu_tiendas_name_basic']) && $_REQUEST['stu_tiendas_name_basic']!=""){
                $where .= " AND (
                                SELECT
                                    stu.stu_tiendas_contactsstu_tiendas_ida
                                FROM
                                    stu_tiendas_contacts_c stu
                                WHERE
                                    stu.stu_tiendas_contactscontacts_idb = con.id
                                LIMIT 1
                              ) = '".$_REQUEST['stu_tiendas_name_basic']."' ";
            }
            
            // vip
            if(isset($_REQUEST['cliente_vip_c_basic']) && $_REQUEST['cliente_vip_c_basic']!=""){
                $where .= " AND cstm.cliente_vip_c = '".$_REQUEST['cliente_vip_c_basic']."' ";
            }
            
            // cedula
            if(isset($_REQUEST['cedula_nit_c_basic']) && $_REQUEST['cedula_nit_c_basic']!=""){
                $where .= " AND cstm.cedula_nit_c LIKE '%".$_REQUEST['cedula_nit_c_basic']."%' ";
            }
            
            // email
            if(isset($_REQUEST['email_address_basic']) && $_REQUEST['email_address_basic']!=""){
                $where .= " AND (
                            SELECT
                                em.email_address
                            FROM
                                email_addr_bean_rel rel
                                    INNER JOIN
                                        email_addresses em ON
                                            rel.email_address_id = em.id
                            WHERE
                                rel.bean_module = 'Contacts' AND
                                rel.deleted = 0 AND
                                rel.primary_address = 1 AND
                                rel.bean_id = con.id
                          ) LIKE '%".$_REQUEST['email_address_basic']."%' ";
            }
            
            // fecha cumple mes
            if(isset($_REQUEST['fecha_cumples_basic']) && $_REQUEST['fecha_cumples_basic']!=""){
                $where .= " AND MONTH(con.birthdate) = '".$_REQUEST['fecha_cumples_basic']."' ";
            }else{
                if(
                    isset($_REQUEST['selRangoMesCumplesDe']) && $_REQUEST['selRangoMesCumplesDe']!="" &&
                    isset($_REQUEST['selRangoDiaCumplesDe']) && $_REQUEST['selRangoDiaCumplesDe']!="" &&
                    isset($_REQUEST['selRangoMesCumplesHasta']) && $_REQUEST['selRangoMesCumplesHasta']!="" &&
                    isset($_REQUEST['selRangoDiaCumplesHasta']) && $_REQUEST['selRangoDiaCumplesHasta']!=""
                ){
                    $where .= " AND CAST(CONCAT(LPAD(MONTH(con.birthdate),2,'0'),LPAD(DAY(con.birthdate),2,'0')) AS UNSIGNED) >= '".str_pad($_REQUEST['selRangoMesCumplesDe'],2,'0',STR_PAD_LEFT).str_pad($_REQUEST['selRangoDiaCumplesDe'],2,"0",STR_PAD_LEFT)."' ";
                    $where .= " AND CAST(CONCAT(LPAD(MONTH(con.birthdate),2,'0'),LPAD(DAY(con.birthdate),2,'0')) AS UNSIGNED) <= '".str_pad($_REQUEST['selRangoMesCumplesHasta'],2,"0",STR_PAD_LEFT).str_pad($_REQUEST['selRangoDiaCumplesHasta'],2,"0",STR_PAD_LEFT)."' ";
                }
            }
            
            if($where == ''){
                $where .= "AND (cstm.cedula_nit_c = '204520299' OR true) ";
            }
            //echo $where;exit;
            return $where;
        } catch (Exception $ex) {
            throw $ex;
        }
    }
    
    /**
     * 
     * @param type $fecha
     * @return type
     * @throws Exception
     */
    private function getFechaClean($fecha){
        try{
            $ampm = substr($fecha,strlen($fecha)-5);
            $arrF = explode(" ",$fecha);
            $arrHour = explode(":",$arrF[1]);
            if($arrHour[0] == 12){
                $arrHour[0] = '00';
            }else{
                if($ampm == 'p.m.'){
                    $arrHour[0] += 12;
                }
            }
            $arrF[1] = $arrHour[0].":".$arrHour[1].':00';
            
            return $arrF[0]." ".$arrF[1];
        } catch (Exception $ex) {
            throw $ex;
        }
    }
}