<?php
class Lead extends CFormModel
{
	public $groupIn='-1';
	public $filter = 'null';
    public $sort = 'null';     
	public $desc = 0; 

	// attributes
	public $Id;
	public $ClientName;
	public $Priority = -1;
	public $Remind = 0;
	public $Comment;
	public $CommentDate;
	public $State = -1;
	public $StateInSystem;
	public $Country = '';
	public $Language = '';
	public $CreationDate;
	public $Phone;
	public $Email;
	public $Source = -1;
	public $Parent = -1;
	
	// filter attributes
	public $RemindStart;
	public $RemindEnd;
	public $CommentDateStart;
	public $CommentDateEnd;
	public $CreationDateStart;
	public $CreationDateEnd;
	public $itemsOnPage = 25;
	public $current = 1;
	public $needWithUsers = 2; // 0 - all; 1 - with users; 2 - without
	public $UserID;
	public $needGroups = 1; // 1 - his and his childs; 0 - only his
    public $countLeadsList = 0;
	
	// static data
	/*
		language keys(names) from arrays must be in /messages/{lang}/sp.php
	*/
	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('1'=>'source_1', '2'=>'source_2', '3'=>'source_3', '4'=>'source_4', '5'=>'source_5','6'=>'source_6', '7'=>'source_7', '8'=>'source_8', '9'=>'source_9', '13'=>'source_13', '14'=>'source_14', '15'=>'source_15', '16'=>'source_16', '17'=>'source_17');
	//private $st_Source;
	private $st_itemsOnPage = array( '25'=>25, '50'=>50, '100'=>100);
	private $st_needWithUsers = array('0'=>'161_all', '1'=>'162_with_user', '2'=>'163_without_user');
	// language - in wlParams "langs"
	
    private $pathSerializedFileLeads = '';// for serialized Leads
    private $pathSerializedFileLeadsBackUp  = ''; //BackUp old file
    private $LeadsList = array(); // init list Leads
    private $spList = array();
    private $isSP = false;
	
	public function attributeLabels(){
		return array(
			'Parent' => 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'),
			'ItemsOnPage' => Yii::t("main",'357_show_per_page'),
			'Id' => Yii::t("sp",'132_id'),
			'UserID' => Yii::t("sp",'165_user_id'),
		);
	}
	public function rules(){ 
		$Registration = new Registration('registration');
		
		//var_dump(array_merge(array(''=>'', '-1'=>''),array_keys($this->getStaticArray('Source'))));die();
		
		return array(
            array('ClientName, Comment, Remind, Phone, Email, Priority, StateInSystem, Country, Language, Id','comparedatesUpdate','on'=>'svUpdate'),  
            array('Phone, Email','comparedates','on'=>'sv'),
			array('ItemsOnPage, Filter, Current, RemindStart, RemindEnd, CommentDateStart, CommentDateEnd, CreationDateStart, CreationDateEnd, Sort, Desc', 'required', 'on'=>'filter', 'message'=> Yii::t("main","36_cannot_be_blank")),
			array('Parent, 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('Parent', 'numerical', 'integerOnly'=>true, 'message' => Yii::t("main","371_numbers_allowed")),
            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\))?[\s-]*([\d-\s]*)$/', '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('Country', 'in', 'range' => $Registration->GetCountry(), 'message' => Yii::t("sp","120_not_listed")),
            array('Priority', 'in', 'range' => array_merge(array(''=>''),array_keys($this->getStaticArray('Priority'))), 'message' => Yii::t("sp","120_not_listed")),
			array('Source', 'in', 'range' => array_merge(array(''=>'', '-1'=>''),array_keys($this->getStaticArray('Source'))), 'message' => Yii::t("sp","120_not_listed")),
			array('StateInSystem', 'in', 'range' => array_merge(array(''=>''),array_keys($this->getStaticArray('StateInSystem'))), 'message' => Yii::t("sp","120_not_listed")),
			array('Language', 'in', 'range' => array_merge(array(''=>''),array_keys($this->getStaticArray('Language'))), 'message' => Yii::t("sp","120_not_listed")),
			array('State', 'in', 'range' => array_merge(array(''=>''),array_keys($this->getStaticArray('State'))), '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}'=>$this->getAttributeLabel('Email'))));
		}
		if(empty($this->Email) && empty($this->Phone) && !$this->getError('Phone') ){
			$this->addError('Phone', Yii::t("main","36_cannot_be_blank",array('{attribute}'=>$this->getAttributeLabel('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 init(){
		if (!Yii::app()->user->isGuest){
              $account = new Account();
              $info = $account->GetInfo();
              $code = $info->Code;
			  if($info->Type != 6){
				  if($info->Type == 3){ 
						$Account = new Account();		
						$code = $Account->GetParentCode();
						$this->isSP = true; 
						//var_dump($info);die();
						$this->spList[$info->ID] = $info->Name;
						$this->Parent = $info->ID; 
				  }else{
						//var_dump(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');
						$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&innerGroupsLevel=0');
						//var_dump($list);

                      if(isset($list->reportList)){
                          foreach($list->reportList as $sale){
                                    $this->spList[$sale->GrId] = $sale->Name;
                            }
                      }
				  }
			  }
		}
		//$this->st_Source = $this->getSourceList();
	}
	public function getList(){  
		$sort = ($this->sort=='null')?$this->sort:ucfirst($this->sort);
		$page = $this->current -1;
		$filter = strlen($this->filter)>0?urlencode($this->filter):'null';
		$this->State = ($this->State == '') ? -1 : $this->State;
		$this->Priority = ($this->Priority == '') ? -1 : $this->Priority;
		$this->Source = ($this->Source == '') ? -1 : $this->Source;
		$this->Remind = ($this->Remind == '') ? -1 : $this->Remind;
		$this->Parent = ($this->Parent == '') ? -1 : $this->Parent;
		$sort = 'CreationDate';
		$this->desc = 1;
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.$filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&needWithUsers='.$this->needWithUsers.'&state='.$this->State.'&priority='.$this->Priority.'&language='.$this->Language.'&source='.$this->Source.'&country='.$this->Country.'&reminder='.$this->Remind.'&parentID='.$this->Parent);
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetLeads?guid='.Yii::app()->user->id.'&filter='.$filter.'&sort='.$sort.'&desc='.$this->desc.'&countRowsTable='.$this->itemsOnPage.'&page='.$page.'&idsForReport='.$this->groupIn.'&needGroups='.$this->needGroups.'&needWithUsers='.$this->needWithUsers.'&state='.$this->State.'&priority='.$this->Priority.'&language='.$this->Language.'&source='.$this->Source.'&country='.$this->Country.'&reminder='.$this->Remind.'&parentID='.$this->Parent);
		//var_dump($tmp);die();
		
	
		foreach ($tmp->reportList as $k=>$v){
			$v->Remind = (strtotime($v->Remind) == 0) ? '' : $v->Remind;
			$this->LeadsList[$v->Id] = $v;
		}
		$this->countLeadsList = $tmp->count;

		return $this->LeadsList;
	}
	
	public function GetLeadDataByID($id){
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetLeadDataByID?guid='.Yii::app()->user->id.'&leadId='.$id);
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetLeadDataByID?guid='.Yii::app()->user->id.'&leadId='.$id);
		//var_dump($tmp);die();
		$this->LeadsList[$tmp->Id] = $tmp;
		return $this->LeadsList;

	}
	
	public function add(){     
	   $this->Priority = empty($this->Sriority)?0:$this->Sriority;
	   $this->State = empty($this->State)?0:$this->State;
	   $this->StateInSystem = empty($this->StateInSystem)?0:$this->StateInSystem;
	   $this->Language = empty($this->Language)?'en':$this->Language;
	   $this->Remind = empty($this->Remind)?'0':$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=1&parentId='.$this->Parent);
	   $tmp = 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=1&parentId='.$this->Parent);
       /* if ($_SERVER['REMOTE_ADDR'] == '77.222.143.18' || $_SERVER['REMOTE_ADDR'] == '46.98.252.74' || $_SERVER['REMOTE_ADDR'] == '46.98.223.246') {
	    var_dump($tmp, 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=1&parentId='.$this->Parent);die();

        }*/

        /*if ($_SERVER['REMOTE_ADDR'] == '46.98.223.246') {
        }*/
		//var_dump($tmp);die();
		return $tmp;
	}
		
	public function addLeadWithoutLogin(){  
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/AddDefaultCRMLeadData?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.'&parentId='.$this->Parent);
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/AddDefaultCRMLeadData?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.'&parentId='.$this->Parent);
		//var_dump($tmp);die();
		return $tmp;
	}
		
	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'),
					 'Parent'=>array('Parent','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'=>'',
									'Parent'=>$this->Parent,
									'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] != 'Parent' 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->getList($this->Id);

		$this->GetLeadDataByID($this->Id);
		//var_dump($this->LeadsList);die();
		if($this->LeadsList[$this->Id]->Comment != $this->Comment){
			$this->CommentDate = date("m/d/Y");
		}
		$this->CreationDate = $this->LeadsList[$this->Id]->CreationDate;
		$this->Source= ($this->LeadsList[$this->Id]->Source == '') ? -1 : $this->LeadsList[$this->Id]->Source;
		//var_dump('222', $this->Remind);
		$this->Remind = ($this->Remind == '') ? 0 : strtotime($this->Remind);
		$this->LeadsList[$this->Id] = $this->attributes;
		$this->State = ($this->State == '') ? -1 : $this->State;
		$this->Priority = ($this->Priority == '') ? -1 : $this->Priority;
		$this->Parent = ($this->Parent == '') ? -1 : $this->Parent;
		
		
		$Account = new Account();
		$info = $Account->getInfo();
		
		//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);die();
		$tmp = 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);
		
		if($info->Type == 2 && isset($this->Parent) && !empty($this->Parent)){
			$spAsignRez = $this->ChangeOfficeCRMLeadGroup($this->Id, $this->Parent);
		}
		//var_dump($tmp);die();
//            echo 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;
//            print_r($tmp);
//            print_r($this->attributes);
//            exit();
		   // public $StateInSystem;
		return $tmp; 

	}
	
	public function writeComment($userNameForComment = 'System'){
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/UpdateCRMComment?email='.$this->Email.'&comment='.$this->Comment.'&userNameForComment='.$userNameForComment.'&userID=null');
		
		return $tmp;
	}
	
	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'){
			//var_dump($attribute, $dataId, $this->attributes);die();
			if($dataId == ''){return '';}
			$langs  = wlParams::get('langnames');
            $lan = $dataId == ''?array_shift($langs):$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 getSourceList(){
		$sourceList = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/Registration/GetRegistrationSourceList');
		$dynamicSrcList = array();
		foreach($sourceList as $src){
			$dynamicSrcList[$src->Id] = 'source_'.$src->Id;
		}
		//var_dump($dynamicSrcList);die();
		return $dynamicSrcList;
		
	}
	
	public function getStaticArray($attribute){			
		if($attribute == 'Language'){
			$tmpLangs = array();
			$langs  = wlParams::get('langnames');
			foreach($langs as $k=>$lang){
				$tmpLangs[$k] = $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(){
		$account = new Account();
		$info = $account->GetInfo();
		$Registration = new Registration('registration');
		$country = $Registration->GetCountry();
		unset($country['']);

		$tbody = '<tr class="filter">
			<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 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>'; 
		if($info->Type == 2){
			$tbody .= '<td class="th_srch Parent" >'.CHtml::dropDownList('Lead[Parent]', $this->Parent, (array('-1' => '') + $this->spList), array()).'</td>'; 
		}
		//var_dump($this->Remind, date('m/d/Y',strtotime($this->Remind)), $this->Remind );die();
		//var_dump($this->Remind);die();
		$Remind = ($this->Remind == -1 || $this->Remind == '') ? '' : date('m/d/Y',$this->Remind);
		//var_dump($Remind, $this->Remind);die();

		
		$tbody .= '<td class="th_srch priority" >'.CHtml::dropDownList('Lead[Priority]', $this->Priority, $this->getStaticArray('Priority'), array('empty'=>'')).'</td> 
			<td class="th_srch State" >'.CHtml::dropDownList('Lead[State]', $this->State, $this->getStaticArray('State'), array('empty'=>'')).'</td>
			<td class="th_srch comment" ><span class="table_leads_input">'.CHtml::textArea('Lead[Comment]', $this->Comment, array()).'</span></td> 
			<td class="th_srch commentDate" ></td> 
			<td class="th_srch remind" ><span class="table_leads_input">'.CHtml::textField('Lead[Remind]', $Remind, array()).'</span></td> 
			<td class="th_srch country" >'.CHtml::dropDownList('Lead[Country]', $this->Country, $country, array('empty'=>'')).'</td> 
			<td class="th_srch creationDate" ></td> 
			<td class="th_srch language" >'.CHtml::dropDownList('Lead[Language]', $this->Language, $this->getStaticArray('Language'), array('empty'=>'')).'</td> 			
			<td class="th_srch source" >'.CHtml::dropDownList('Lead[Source]', $this->Source, $this->getStaticArray('Source'), array('empty'=>'')).'</td>
			<td class="th_srch UserID" >'.CHtml::textField('Lead[UserID]', $this->UserID, array()).'</td>
			<td class="th_srch actions absoluteTD"></td>
			<td class="th_srch tr_remove"></td>
		</tr>';
		
            $itemsAllow = array('Id','ClientName','Phone','Email','Parent','Priority','State','Comment','CommentDate','Remind','Country','CreationDate','Language','Source','UserID');
		
            $this->setFilter();
            $this->setSort();
		
		$getList = $this->getList();
		if(isset($getList) && !empty($getList)){		
			foreach($getList as $lead){
				$tbody .= '<tr id="'.$lead->Id.'">';
				foreach($itemsAllow as $key){
					if($key == 'Parent' && ($this->getScenario() == 'sp' || $info->Type != 2)){ continue; }
					if(in_array($key, array('Priority', 'State', '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'=>'disabled','empty'=>'')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></div></td>';
					}elseif($key == 'Source'){
						$tbody .= '<td>'.$this->getStaticData($key, $lead->$key).'</td>';
					}elseif($key == 'Comment'){
						//var_dump($lead->Comment);die();
						/* if(!isset($lead->$key)){
							var_dump($lead);die();
						} */
						$viewComment = !empty($lead->$key) ? '<div class="action_icon icon-93viewcomments view_comments" title="'.Yii::t("sp","166_view_all_comments").'"></div>' : '';
						$shortViewComText = (strlen(format::substr_word($lead->$key, 6)) == strlen($lead->$key)) ? $lead->$key : format::substr_word($lead->$key, 6).'...';
						$tbody .= '<td><div class="valued"><div class="valHTML">'.$shortViewComText.'</div>'.$viewComment.'</div><div class="editable" style="display:none;">'.CHtml::textArea('Lead['.$key.']', $lead->$key, array('disabled'=>'disabled')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></div></td>';
					}elseif($key == 'UserID'){
						$UserID = isset($lead->UserID) ? $lead->UserID : '';
						$tbody .= '<td>'.$UserID.'</td>';
					}elseif($key == 'Parent'){
						$sp = isset($this->spList[$lead->$key])?$this->spList[$lead->$key]:'';
						//var_dump($sp, $this->spList);die();
						$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'=>'disabled','empty'=>'')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></div></td>'; 
					}elseif($key == 'Id'){
						$tbody .= '<td><span id='.$key.'>'.$lead->$key.'</span></td>';
					}elseif($key == 'CreationDate' || $key == 'CommentDate'){
						$lDate = ($lead->$key=='0001-01-01T00:00:00' || $lead->$key == '') ? '' : date('m/d/Y',strtotime($lead->$key));					
						$tbody .= '<td><span id='.$key.'>'.$lDate.'</span></td>';
					}elseif($key == 'Remind'){ 
						$lDate = ($lead->$key=='0001-01-01T00:00:00' || $lead->$key == -1 || $lead->$key == '') ? '' : date('m/d/Y',strtotime($lead->$key));					
						$tbody .= '<td><div class="valued">'.$lDate.'</div><div class="editable" style="display:none;">'.CHtml::textField('Lead['.$key.']', $lDate, array('disabled'=>'disabled')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></div></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'=>'disabled')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></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'=>'disabled')).'<div class="tooltip"></div><div class="input_tooltip__" style="display:none;"><div class="delta"></div><div class="cl_report_error_block_v1"></div></div></div></td>';			
					} 
				}
				$editHtml = (!isset($lead->UserID)) ? '<div 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>' : '';
				$tbody .= '<td class="absoluteTD">'.$editHtml;
				if(!isset($lead->UserID)){
					$tbody .= '<div class="lead_link icon-1link action_icon" title="'.Yii::t("sp","154_lead_with_user").'"></div>';
					$removeButton = '<td class="remove_td"><span class="remove_button icon-57delete"></span></td></div>';
				}else{
					$removeButton = '<td class="remove_td" style="display:none;"><span class="remove_button icon-57delete"></span></td>';
				}
				$tbody .='</td>'.$removeButton.'</tr>';		 
			}
		}else{
			$tbody .='<tr><td style="text-align: center; display:table-cell;" colspan="0"><br>'.Yii::t("main","441_no_results").'<br>&nbsp;</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);
		
		$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.'&parentId='.$this->Parent);
		//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);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;
	}
	
	public function GetUserForCRMData($id){
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetUserForCRMData?guid='.Yii::app()->user->id.'&id='.$id);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetUserForCRMData?guid='.Yii::app()->user->id.'&id='.$id);
		//var_dump($result);
		return $result;
	}
	
	
	
	public function GetLeadComments($id){ 
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/GetLeadComments?guid='.Yii::app()->user->id.'&leadId='.$id);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/GetLeadComments?guid='.Yii::app()->user->id.'&leadId='.$id);
		//var_dump($result);die();
		return $result;
	}
	
	public function RemoveLeadData($id){
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/RemoveLeadData?guid='.Yii::app()->user->id.'&leadId='.$id);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/RemoveLeadData?guid='.Yii::app()->user->id.'&leadId='.$id);
		//var_dump($result);die();
		return $result;
	}
	
	public function ChangeOfficeCRMLeadGroup($id, $groupID){
		//var_dump(Yii::app()->params['json_server'] . '/API/CRM/ChangeOfficeCRMLeadGroup?guid='.Yii::app()->user->id.'&id='.$id.'&groupID='.$groupID);
		$result = Yii::app()->curl->get(Yii::app()->params['json_server'] . '/API/CRM/ChangeOfficeCRMLeadGroup?guid='.Yii::app()->user->id.'&id='.$id.'&groupID='.$groupID);
		//var_dump($result);die();
		return $result;
	}
	
	public function GetCommentsHistoryView($commentsArray){
		$account = new Account();
		$info = $account->getInfo();

		$membersArray = array();
		$comView = '<div class="comWrapper">';
		foreach($commentsArray as $comment){
			$comClass = ($info->Name == $comment->UserName) ? 'selfCom' : 'otherCom';
			$comView .= '<div class="LeadComWrap"><div class="LeadCom '.$comClass.'"><div class="comBlock"><div class="comUserName">'.$comment->UserName.':</div><div class="comComment">'.$comment->Comment.'</div></div><div class="comTime">'.date('m/d/Y G:i',strtotime($comment->Timestamp)).'</div></div><div class="clr"></div></div>';
		}
		$comView .= '</div>';
		
		return $comView;
	}
	
	public function getShortUserListTable($list){
			if(!empty($list)){
				$table = '<div class="tableOuter"><table id="short_user_list__">
								<thead>
									<tr>
										<th class="pc">'.Yii::t("main","20_Login").'</th>
										<th class="pc">'.Yii::t("main","123_name").'</th>
										<th class="pc">'.Yii::t("main","131_email").'</th>
										<th class="pc">'.Yii::t("main","130_phone").'</th>
										<th class="pc">'.Yii::t("main","129_country").'</th>
										<th class="pc">'.Yii::t("main","133_address").'</th>
									</tr>
								</thead>
								<tbody>';
							
				foreach($list as $key=>$user){
					$table .= '<tr>
								<td><input type="radio" name="linkedUser" id="radio'.$user->UserID.'" value="'.$user->UserID.'" /><label for="radio'.$user->UserID.'">'.$user->UserID.'</label></td>
								<td>'.$user->Name.'</td>
								<td>'.$user->Email.'</td>
								<td>'.$user->Phone.'</td>
								<td>'.$user->Country.'</td>
								<td>'.$user->Address.'</td></tr>';
				}
				
				$table .= '</tbody>
				</table>
				</div>
				<div class="tfoot hide-if-no-paging">
					<div id="page-preloader"><?php echo Yii::t("main","125_loading_data"); ?>...</div>
					<div id="pagination_dialog"></div>
				</div>';
		}else{
			$table = 'empty table';
		}
		
		return $table;
	}
	
	public function ExportLeadsToExcel(){
		//var_dump(Yii::app()->params['json_server'].'/API/CRM/ExportLeadsToExcel?guid='.Yii::app()->user->id.'&idsForReport=-1&needGroups='.$this->needGroups.'&needWithUsers='.$this->needWithUsers);die();
		$tmp = Yii::app()->curl->get(Yii::app()->params['json_server'].'/API/CRM/ExportLeadsToExcel?guid='.Yii::app()->user->id.'&idsForReport=-1&needGroups='.$this->needGroups.'&needWithUsers='.$this->needWithUsers);
		//var_dump(tmp);die();
		return $tmp;		
	}
	
}