<?php
class Lead extends CFormModel
{
	
	public $groupIn='-1';
	public $filter = 'null';    //поиск по слову
    public $sort = 'null';      //имя поля по которому сортировать
	public $desc = 0; 

	// attributes
	public $Id;
	public $spName;
	public $ClientName;
	public $Priority;
	public $Remind;
	public $Comment;
	public $CommentDate;
	public $State;
	public $StateInSystem;
	public $Country;
	public $Language;
	public $CreationDate;
	public $Phone;
	public $Email;
	public $Source;
	public $Parent;
	
	// filter attributes
	public $RemindStart;
	public $RemindEnd;
	public $CommentDateStart;
	public $CommentDateEnd;
	public $CreationDateStart;
	public $CreationDateEnd;
	public $itemsOnPage = 25;
	public $current = 1;
	
	// static data
	private $st_Priority = array('0'=>'94_low', '1'=>'95_high');
	private $st_State = array('0'=>'116_new_user','1'=>'96_in_procces', '2'=>'97_wrong_number', '3'=>'98_no_answer');
	private $st_StateInSystem = array('0'=>'116_new_user','1'=>'96_in_procces', '2'=>'97_wrong_number', '3'=>'98_no_answer');  // rewrite from sonin
	private $st_Source = array('0'=>'118_csv', '1'=>'119_from');
	private $st_itemsOnPage = array( '25'=>25, '50'=>50, '100'=>100);
	// language - in wlParams "langs"
	
    private $pathSerializedFileLeads = '';// for serialized Leads
    private $pathSerializedFileLeadsBackUp  = ''; //BackUp old file
    private $LeadsList = array(); // init list Leads
    private $countLeadsList = 0;
    private $spList = array();
    private $isSP = false;
	
	
	public function rules(){ 
		// sp - sales person role
		// sv - supevisor role
		
		// filter  - validation rule for filter
		
		$Registration = new Registration('registration');
		
		return array(
            array('phone, email','comparedates','on'=>'sv'),
            array('phone, email','comparedatesUpdate','on'=>'svUpdate'),                    
			array('itemsOnPage, filter, current, remindStart, remindEnd, commentDateStart, commentDateEnd, creationDateStart, creationDateEnd, sort, desc', 'required', 'on'=>'filter', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('spName, language, clientName, comment', 'length', 'min'=>0, 'max'=>255, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is"), 'allowEmpty'=>false),			
			array('country', 'in', 'range' => $Registration->GetCountry(), 'message' => Yii::t("sp","120_not_listed")),
			//array('priority', 'in', 'range' => array_keys($this->getStaticArray('priority')), 'message' => Yii::t("sp","120_not_listed")),
			//array('state', 'in', 'range' => array_keys($this->getStaticArray('state')), 'message' => Yii::t("sp","120_not_listed")),
			//array('stateInSystem', 'in', 'range' => array_keys($this->getStaticArray('stateInSystem')), 'message' => Yii::t("sp","120_not_listed")),
			//array('source', 'in', 'range' => array_keys($this->getStaticArray('source')), 'message' => Yii::t("sp","120_not_listed")),			
			array('creationDate, commentDate, remind', 'type', 'type' => 'date', 'dateFormat' => 'M/d/yyyy', 'message'=>Yii::t("sp","121_incorrec_date")),
			array('email', 'email', 'message' => Yii::t("main","22_this_email_address_is_not_a_valid")),
			array('phone', 'match', 'pattern' => '/^(\+?\d+)?\s*(\(\d+\))?[\s-]*([\d-]*)$/', 'message' => Yii::t("main","35_incorrect_phone_number")),
			array('id', 'numerical', 'integerOnly'=>true, 'message' => Yii::t("main","371_numbers_allowed")),	

			array('ClientName, Phone, Email, Country, Remind, Comment', 'length', 'on'=>'UserLead', 'min'=>0, 'max'=>255, 'tooShort'=>Yii::t("main","528_min_length_is"), 'tooLong'=>Yii::t("main","529_max_length_is"), 'allowEmpty'=>true),			
			array('ClientName, Phone, Email, Country, Remind, Comment', 'match', 'pattern' => '/^[a-z0-9`~!"@№%#\$;:\?\/\\&\*\+-_\(\)=\{\}\[\]\'|\<\>\s]*$/i','on'=>'UserLead','message' => Yii::t("main","34_only_latin_characters_allowed_for")), 
			array('Priority', 'in', 'range' => array_keys(array_merge(array(''=>''),$this->getStaticArray('Priority'))), 'message' => Yii::t("sp","120_not_listed")),
			array('Source', 'in', 'range' => array_keys(array_merge(array(''=>''),$this->getStaticArray('Source'))), 'message' => Yii::t("sp","120_not_listed")),
			array('State', 'in', 'range' => array_keys(array_merge(array(''=>''),$this->getStaticArray('State'))), 'message' => Yii::t("sp","120_not_listed")),
			array('Language', 'in', 'range' => $this->getStaticArray('Language'), 'message' => Yii::t("sp","120_not_listed")),
		);
	}
        public function comparedates(){
            /*if(empty($this->email) && empty($this->phone) && !$this->getError('email') ){
                $this->addError('email', Yii::t("main","36_cannot_be_blank",array('{attribute}'=>'Email')));
            }
            if(empty($this->email) && empty($this->phone) && !$this->getError('phone') ){
                $this->addError('phone', Yii::t("main","36_cannot_be_blank",array('{attribute}'=>'Phone')));
            }*/
        }
	 public function comparedatesUpdate(){
           /* if(empty($this->email) && empty($this->phone) && !$this->getError('email') ){
                $this->addError('email', Yii::t("sp","141_leadUpdate"));
            }
            if(empty($this->email) && empty($this->phone) && !$this->getError('phone') ){
                $this->addError('phone', Yii::t("sp","141_leadUpdate"));
            }*/
        }
	
	public function attributeLabels(){
		return array(
				'spName' => Yii::t("sp",'102_spname'),
				'clientName' => Yii::t("sp",'103_clientName'),
				'country' => Yii::t("sp",'104_country'),
				'priority' => Yii::t("sp",'105_priority'),
				'remind' => Yii::t("sp",'106_remind'),				
				'comment' => Yii::t("sp",'107_comment'),				
				'commentDate' => Yii::t("sp",'108_commentDate'),
				'state' => Yii::t("sp",'109_state'),
				//'stateInSystem' => Yii::t("sp",'110_stateInSystem'),
				'creationDate' => Yii::t("sp",'111_creationDate'),
				'language' => Yii::t("sp",'122_language'),
				'phone' => Yii::t("sp",'112_phone'),
				'email' => Yii::t("sp",'113_email'),
				'source' => Yii::t("sp",'114_source'),
				'itemsOnPage' => Yii::t("main",'357_show_per_page'),
				'id' => Yii::t("sp",'132_id'),
		);
	}
	
	public function init(){
              $account = new Account();
              $info = $account->GetInfo();
              $code = $info->Code;
              if($info->Type == 3){ 
                    $Account = new Account();		
                    $code = $Account->GetParentCode();
                    $this->isSP = true; 
                    $this->spList[$info->Code] = $info->Name;
                    $this->spName = $info->Code;
              }else{
                    $list = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Accounts/GetIBAccounts?guid=' . Yii::app()->user->id . '&groupID=-1&needOnlyAcc=false&filter=null&sort=null&platformID=-1&desc=0&page=0&countRowsTable=1000000&type=1');
                    foreach($list->reportList as $sale){
                            $this->spList[$sale->Code] = $sale->Name;
                    }
              }
	}
        public function getList(){  
            $sort = ($this->sort=='null')?$this->sort:ucfirst($this->sort);
            $page = $this->current -1;
            

            
			//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups=0&needWithUsers=0');
            $tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.urlencode($this->filter).'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups=0&needWithUsers=0');
 //           echo Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.urlencode($this->filter).'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups=0&needWithUsers=0';
//var_dump($tmp);die();
			//echo Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.$this->filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups=0&needWithUsers=0';
             $this->LeadsList = $tmp->reportList;
             $this->countLeadsList = $tmp->count;

            return $this->LeadsList;
        }
        
	public function add(){
            /*$this->id = count($this->LeadsList)+1;
            $this->LeadsList[$this->id] = array(
                        'id'=>$this->id,
                        'clientName'=>$this->clientName,
                        'spName'=>$this->spName,
                        'priority'=>empty($this->priority)?0:$this->priority,
                        'remind'=>$this->remind,
                        'comment'=>$this->comment,
                        'commentDate'=>$this->commentDate,
                        'state'=> empty($this->state)?0:$this->state,
                        'stateInSystem'=>empty($this->stateInSystem)?0:$this->stateInSystem,
                        'creationDate'=>date("m/d/Y"),
                        'country'=>$this->country,
                        'language'=> empty($this->state)?'en':$this->language,
                        'phone'=>$this->phone,
                        'email'=>$this->email,
                        'source'=>1
                    );
            $this->save();*/
        }
        public function addLidsFromFile($file){
           /* $data = file($file);
            if(is_array($data)){
               
                    $sep = ';';
                    if(strstr($data[0],':')){
                        $sep = ':';
                    }elseif(strstr($data[0],',')){
                        $sep = ',';
                    }
    
                     $itemsAllow = array(
                         'clientName'=>array('clientname','name','user','client','first name','last name','firstname','lastname'),
                         'spName'=>array('spname','sale','sales','salesperson'),
                         'priority'=>array('priority'),
                         'remind'=>array('remind'),
                         'comment'=>array('comment'),
                         'commentDate'=>array('commentdate'),
                         'state'=>array('state'),
                         'stateInSystem'=>array('stateinsystem'),
                         'creationDate'=>array('creationdate'),
                         'country'=>array('country'),
                         'language'=>array('language'),
                         'phone'=>array('phone','mobile','mobile phone'),
                         'email'=>array('email','e-mail','email'),
                         'source'=>array('source')
                     );
                     $whoIs = array();
                foreach ($data as $k=>$string){
                    if(strlen($string)>10){
                            $items = explode($sep, $string);
                            if($k==0){
                                foreach ($items  as $i=>$item) {
                                    preg_match('#[\w\s]+#sim', $item, $item2);
                                    $item = trim($item2[0]);
                                    foreach($itemsAllow as $h=>$arr){
                                        if(in_array(strtolower($item), $arr)){ $whoIs[$i]=$h;}
                                    }
                                }
                            }else{
                                 $id = count($this->LeadsList)+1;
                                 $initArr = array(
                                        'id'=>$id,
                                        'clientName'=>'',
                                        'spName'=>$this->spName,
                                        'priority'=>0,
                                        'remind'=>'',
                                        'comment'=>'',
                                        'commentDate'=>'',
                                        'state'=>0,
                                        'stateInSystem'=>0,
                                        'creationDate'=>date("m/d/Y"),
                                        'country'=>'',
                                        'language'=>'en',
                                        'phone'=>'',
                                        'email'=>'',
                                        'source'=>0
                                    );
                                  
                                
                                $is = false;
                                foreach($items  as $i=>$item) {
                                    $item = trim(str_replace('  ', ' ', $item));
                                    preg_match('#[\w\s\d@.\+-]+#sim', $item, $item2);
                                    if(isset ($item2[0]) && !empty($item2[0])){
                                        $is = true;
                                        $item = trim(str_replace('  ', ' ', $item2[0]));
                                        if(isset($whoIs[$i])){
                                            if($whoIs[$i] != 'spName' OR $this->isSP == false){
                                                if(empty($initArr[$whoIs[$i]])){
                                                    $initArr[$whoIs[$i]] = $item;
                                                }else{
                                                    $initArr[$whoIs[$i]] = $initArr[$whoIs[$i]].' '.$item;
                                                }
                                            }
                                        }
                                    }
                                }
                                if($is){ $this->LeadsList[$id] = $initArr;}
                            }
                    }
                }
//                print_r($whoIs);
//                echo '<pre>';
//                 print_r($this->LeadsList);
//                echo '___'.$i;
//                exit();
                if (file_exists($this->pathSerializedFileLeads)) {
                copy($this->pathSerializedFileLeads, $this->pathSerializedFileLeadsBackUp);
                }
                $this->save();
            }
            return $this->LeadsList;*/
        }
        public function update(){
           /* $this->commentDate = date("m/d/Y");
            $this->creationDate = $this->LeadsList[$this->id]['creationDate'];
            $this->source= $this->LeadsList[$this->id]['source'];
            $this->LeadsList[$this->id] = $this->attributes;
            $this->save();*/
	}
	public function save(){  
                /*$f = fopen($this->pathSerializedFileLeads,"w");
                foreach($this->LeadsList as $st){
                    $str = json_encode($st)."\n";
                    if(strlen($str)>10){fwrite($f,$str);}
                }
                fclose($f); */
        }

        public function getSpList(){  
            /*return $this->spList; */
        }
        
	public function getStaticData($attribute,  $dataId = ''){			
		if($attribute == 'Language'){
			$langs  = wlParams::get('langs');
                        $lan = $dataId == ''?$langs[0]:$dataId;
			return $lan;
		}
                
                $Id = $dataId;// == ''?0:$dataId;
				$name = 'st_'.$attribute;
                $arr = $this->$name;
                
                if(isset($arr[$Id])){
                    $arr = $arr[$Id];
                    return Yii::t("sp", $arr);
                }else{ 
                    return '';
                }
                
	}
        public function getStaticArray($attribute){			
            if($attribute == 'Language'){
                $tmpLangs = array();
                $langs  = wlParams::get('langs');
                foreach($langs as $lang){
                    $tmpLangs[$lang] = $lang;
                }
                return $tmpLangs;
            }
            $name = 'st_'.$attribute;
            $data = array();
            foreach($this->$name as $key => $st_pr){
                    $data[$key] = Yii::t("sp", $st_pr);
            }
            return $data;
	}
	
    public function setFilter(){
 
           $itemsAllow = array('Id','ClientName','Parent','Priority','Comment','State','Country','Language','Phone','Email','Source');

						
            foreach ($itemsAllow as $value){
                if(strlen($this->$value)>0){
                     foreach($this->LeadsList as $k=>$lead){
                        if($this->$value != $lead->$value){
                              if($this->isSP == false){
                                $this->current = 1;
                              }
                            unset($this->LeadsList[$k]);
                         }
                     }
                }
            }
        /*
            $itemsTime = array('remindStart'=>'remind','remindEnd'=>'remind','commentDateStart'=>'commentDate','commentDateEnd'=>'commentDate','creationDateStart'=>'creationDate','creationDateEnd'=>'creationDate');
            foreach ($itemsTime as $key=>$value) {
                if(strlen($this->$key)>0){
                     foreach($this->LeadsList as $k=>$lead){
                         $dateR = $this->$key;
                         $dateLead = $lead[$value];
//                         var_dump($dateR);
//                         var_dump($dateLead);
//                         var_dump( strtotime($dateR) >= strtotime($dateLead));
               
                         if(strstr($key,'Start')){
                             if( strtotime($dateR) >= strtotime($dateLead) ){
                                unset($this->LeadsList[$k]);
                             }
                         }else{
                             if( strtotime($dateR) <= strtotime($dateLead) ){
                                unset($this->LeadsList[$k]);
                             }
                         }
                         
                         
                     }
                }
            }*/
	}
        

 
                
    public function setSort()
	{			
          /*  if(!empty($this->sort)){
                global $sort,$desc;
                $sort = $this->sort;
                $desc = $this->desc;
                function cmp($a, $b) { 
                    global $sort,$desc;                    
                    $aP = $a[$sort];
                    $bP = $b[$sort];
                    if ($aP == $bP) {return 0;}
                    if($desc){
                        return ($aP > $bP) ? -1 : 1;
                    }else{
                        return ($aP < $bP) ? -1 : 1;
                    }
                }
                    
                uasort($this->LeadsList, "cmp");
                
            } */
                
            
	}
  
	
	public function getLeadsTable(){

		$Registration = new Registration('registration');
		$country = $Registration->GetCountry();
		unset($country['']);
		
//		$tbody = '';
//		$tbody = '<tr class="filter">
//			<td class="th_srch plus__ znak__">+</td> 
//			<td class="th_srch id" ><span class="table_leads_input">'.CHtml::textField('Lead[id]', $this->Id, array()).'</span></td> 
//			<td class="th_srch clientName" >'.CHtml::textField('Lead[ClientName]', $this->ClientName, array()).'</td> 
//			<td class="th_srch spName" >'.CHtml::textField('Lead[Parent]', $this->Parent, array()).'</td> 
//			<td class="th_srch priority" >'.CHtml::dropDownList('Lead[Priority]', $this->Priority, $this->getStaticArray('Priority'), array('empty'=>'')).'</td> 
//			<td class="th_srch remind" >'.CHtml::textField('Lead[RemindStart]', $this->Remind, array('placeholder'=>Yii::t("sp","123_from"))) . CHtml::textField('Lead[RemindEnd]', $this->RemindEnd, array('placeholder'=>Yii::t("sp","124_to"))).'</td> 
//			<td class="th_srch comment" ><span class="table_leads_input">'.CHtml::textField('Lead[Comment]', $this->Comment, array()).'</span></td> 
//			<td class="th_srch commentDate" >'.CHtml::textField('Lead[CommentDateStart]', $this->CommentDate, array('placeholder'=>Yii::t("sp","123_from"))) . CHtml::textField('Lead[CommentDateEnd]', $this->CommentDateEnd, array('placeholder'=>Yii::t("sp","124_to"))).'</td> 
//			<td class="th_srch state" >'.CHtml::dropDownList('Lead[StateInSystem]', $this->StateInSystem, $this->getStaticArray('StateInSystem'), array('empty'=>'')).'</td>
//			<td class="th_srch creationDate" >'.CHtml::textField('Lead[CreationDateStart]', $this->CreationDate, array('placeholder'=>Yii::t("sp","123_from"))) . CHtml::textField('Lead[CreationDateEnd]', $this->CreationDateEnd, array('placeholder'=>Yii::t("sp","124_to"))).'</td> 
//			<td class="th_srch country" >'.CHtml::dropDownList('Lead[Country]', $this->Country, $country, array('empty'=>'')).'</td> 
//			<td class="th_srch language" >'.CHtml::dropDownList('Lead[Language]', $this->Language, $this->getStaticArray('Language'), array('empty'=>'')).'</td> 			
//			<td class="th_srch phone" ><span class="table_leads_input">'.CHtml::textField('Lead[Phone]', $this->Phone, array()).'</span></td> 
//			<td class="th_srch email" ><span class="table_leads_input">'.CHtml::textField('Lead[Email]', $this->Email, array()).'</span></td> 
//			<td class="th_srch source" >'.CHtml::dropDownList('Lead[Source]', $this->Source, $this->getStaticArray('Source'), array('empty'=>'')).'</td>
//			<td class="th_srch actions"></td>
//		</tr>';
                
		$tbody = '<tr class="filter">
			<td class="th_srch plus__ znak__">+</td> 
			<td class="th_srch id" ><span class="table_leads_input">'.CHtml::textField('Lead[id]', $this->Id, array()).'</span></td> 
			<td class="th_srch clientName" >'.CHtml::textField('Lead[ClientName]', $this->ClientName, array()).'</td> 
			<td class="th_srch spName" >'.CHtml::textField('Lead[Parent]', $this->Parent, array()).'</td> 
			<td class="th_srch priority" >'.CHtml::dropDownList('Lead[Priority]', $this->Priority, $this->getStaticArray('Priority'), array('empty'=>'')).'</td> 
			<td class="th_srch remind Dnone" ></td> 
			<td class="th_srch comment" ><span class="table_leads_input">'.CHtml::textField('Lead[Comment]', $this->Comment, array()).'</span></td> 
			<td class="th_srch commentDate Dnone" ></td> 
			<td class="th_srch state" >'.CHtml::dropDownList('Lead[StateInSystem]', $this->StateInSystem, $this->getStaticArray('StateInSystem'), array('empty'=>'')).'</td>
			<td class="th_srch creationDate Dnone" ></td> 
			<td class="th_srch country" >'.CHtml::dropDownList('Lead[Country]', $this->Country, $country, array('empty'=>'')).'</td> 
			<td class="th_srch language" >'.CHtml::dropDownList('Lead[Language]', $this->Language, $this->getStaticArray('Language'), array('empty'=>'')).'</td> 			
			<td class="th_srch phone" ><span class="table_leads_input">'.CHtml::textField('Lead[Phone]', $this->Phone, array()).'</span></td> 
			<td class="th_srch email" ><span class="table_leads_input">'.CHtml::textField('Lead[Email]', $this->Email, array()).'</span></td> 
			<td class="th_srch source" >'.CHtml::dropDownList('Lead[Source]', $this->Source, $this->getStaticArray('Source'), array('empty'=>'')).'</td>
			<td class="th_srch actions"></td>
		</tr>';
		
                $itemsAllow = array('Id','ClientName','Parent','Priority','Remind','Comment','CommentDate','StateInSystem','CreationDate','Country','Language','Phone','Email','Source');
		
            $this->setFilter();
            $this->setSort();
				
                foreach($this->getList() as $lead){
			$tbody .= '<tr id="'.$lead->Id.'"><td class="plus__">+</td>';
			foreach($itemsAllow as $key){

				if($key == 'spName' && $this->getScenario() == 'sp'){ continue; }
				if(in_array($key, array('Priority', 'StateInSystem', 'Language'))){
					$tbody .= '<td><div class="valued">'.$this->getStaticData($key, $lead->$key).'</div><div class="editable" style="display:none;">'.CHtml::dropDownList('Lead['.$key.']', $lead->$key, $this->getStaticArray($key), array('disabled'=>'dosabled','empty'=>'')).'</div></td>';
				}elseif($key == 'Source'){
					$tbody .= '<td>'.$this->getStaticData($key, $lead->$key).'</td>';
				}elseif($key == 'Parent'){
                    /*$sp = isset($this->spList[$lead[$key]])?$this->spList[$lead[$key]]:'';
					$tbody .= '<td><div class="valued">'.$sp.'</div><div class="editable" style="display:none;">'.CHtml::dropDownList('Lead['.$key.']', isset($this->spList[$lead[$key]])?$lead[$key]:0, $this->spList, array('disabled'=>'dosabled','empty'=>'')).'</div></td>'; 
					*/
					$tbody .= '<td><span id='.$key.'>'.$lead->$key.'</span></td>';
				}elseif($key == 'creationDate' || $key == 'commentDate' || $key == 'Id'){
					$tbody .= '<td><span id='.$key.'>'.$lead->$key.'</span></td>';
				}elseif($key == 'country'){
					$tbody .= '<td><div class="valued">'.$lead->$key.'</div><div class="editable" style="display:none;">'.CHtml::dropDownList('Lead['.$key.']', $lead->$key, $country, array('disabled'=>'dosabled')).'</div></td>';
				}elseif(in_array($key, $itemsAllow)){
					$tbody .= '<td><div class="valued">'.$lead->$key.'</div><div class="editable" style="display:none;">'.CHtml::textField('Lead['.$key.']', $lead->$key, array('disabled'=>'dosabled')).'</div></td>';
				
				} 
			}
			$tbody .= '<td class="edit_button"><div class="lead_edit">'.Yii::t("main","374_edit").'</div><div class="lead_save" style="display:none;">'.Yii::t("sp","131_save").'</div><div class="lead_cancel" style="display:none;">'.Yii::t("main","373_cancel").'</div></td></tr>';
		
		}
		
		return $tbody;
	}
	
	public function GetPagination(){

		$pagination['current']      	=   $this->current;
		$pagination['count']        	=   $this->countLeadsList;
		$pagination['itemsOnPage']  	=   $this->itemsOnPage;
		
		return $pagination;
	}
	
	public function parseCsv($fileName){
		/*$Registration = new Registration('registration');
		$countries = $Registration->GetCountry();
		
		$row = 1;
		$handle = fopen($fileName, "r");
		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
			$row = explode(';', $data[0]);
			$this->clientName = $row[0].' '.$row[1];
			$this->phone = $row[2];
			$this->email = $row[3];
			$this->country = array_search($row[4], $countries);
			$this->language = array_search($row[5], $this->getStaticData('language'));
			$this->source = '2';
			$this->stateInSystem = '0';
			$this->creationDate = date("m/d/Y");
			var_dump($this->attributes);die();
			if(!empty($this->phone) || !empty($this->email)){
				$this->update();	
			}
 
		}
		fclose($handle);
		
		return $data;*/
	}
	
	public function initParamsFromUserList($params){
		$params = (array)$params;
		$this->attributes = $params;
		$this->ClientName = $params['Name'];
		//var_dump($params['LeadRemind'], strtotime($params['LeadRemind']));die();
		$this->Remind = !(strtotime($params['LeadRemind'])) ? '' : date('m/d/Y', strtotime($params['LeadRemind']));
		$this->Priority = $params['LeadPriority'];
		$this->Comment = $params['LastComment'];
		$this->Id = $params['LeadID'];
	}
	
	public function checkDefaultLeadValues(){
		$defaultValues = array(
			'Comment'=>'',
			'Remind'=>'', // from server - 0001-01-01T00:00:00 | to server - 0 | from cActiveForm = ''
			'Priority'=>0,
			'Source'=>'',
			'State'=>0,
		);
		
		foreach($defaultValues as $key=>$value){
			
			//var_dump($this->$key, $value, $this->$key !== $value);
			if($this->$key !== $value){
				return false;
			}
		}
		return true;
		//die('-----');
	}
	
	public function AddCRMLeadData(){
		$this->Remind = ($this->Remind == '') ? 0 : strtotime($this->Remind);
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/AddCRMLeadData?guid='.Yii::app()->user->id.'&clientName='.$this->ClientName.'&phone='.$this->Phone.'&email='.$this->Email.'&country='.$this->Country.'&remind='.$this->Remind.'&priority='.$this->Priority.'&language='.$this->Language.'&comment='.$this->Comment.'&source='.$this->Source);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/AddCRMLeadData?guid='.Yii::app()->user->id.'&clientName='.$this->ClientName.'&phone='.$this->Phone.'&email='.$this->Email.'&country='.$this->Country.'&remind='.$this->Remind.'&priority='.$this->Priority.'&language='.$this->Language.'&comment='.$this->Comment.'&source='.$this->Source);
		//var_dump($result);die();
		return $result;
	}
	
	public function UpdateCRMLeadData(){
		$this->Remind = ($this->Remind == '') ? 0 : strtotime($this->Remind);
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/UpdateCRMLeadData?guid='.Yii::app()->user->id.'&id='.$this->Id.'&clientName='.$this->ClientName.'&phone='.$this->Phone.'&email='.$this->Email.'&country='.$this->Country.'&remind='.$this->Remind.'&priority='.$this->Priority.'&language='.$this->Language.'&comment='.$this->Comment.'&source='.$this->Source.'&state='.$this->State);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/UpdateCRMLeadData?guid='.Yii::app()->user->id.'&id='.$this->Id.'&clientName='.$this->ClientName.'&phone='.$this->Phone.'&email='.$this->Email.'&country='.$this->Country.'&remind='.$this->Remind.'&priority='.$this->Priority.'&language='.$this->Language.'&comment='.$this->Comment.'&source='.$this->Source.'&state='.$this->State);
		//var_dump($result);die();
		return $result;
	}
	
	public function ApplyLeadToUser($userID, $id){
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/ApplyLeadToUser?guid='.Yii::app()->user->id.'&userID='.$userID.'&id='.$id);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/ApplyLeadToUser?guid='.Yii::app()->user->id.'&userID='.$userID.'&id='.$id);
		//var_dump($result);die();
		return $result;
	}
	
}