<?php
App::uses('AppModel', 'Model');
/**
 * Doc Model
 *
 */
class Mailing extends AppModel {
    
/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'file_name';
	
	/**
	 * belongsTo associations
	 *
	 * @var array
	 */
	public $belongsTo = array(
	        'User' => array(
	                'className' => 'User',
	                'foreignKey' => 'user_id',
	                'conditions' => '',
	                'fields' => '',
	                'order' => ''
	        ));

	/**
	 * Valida o modelo de Mailing para importar nos moldes do arquivo 
	 * selecionado pelo cliente
	 */
	function import($filename, $user_id, $model) {

	    // Nome;DDD;Telefone
	    if ($model == 1) {  
	        return $this->model1($user_id, $filename);
	    }
	    
	    // Nome;DDD+Telefone
	    else if ($model == 2) {
	        return $this->model2($user_id, $filename);
	    }
	    
	    // Nome;DDD;Telefone;Param1;Param2;Param3;Param4;Param5;
	    else if ($model == 3) {
	        return $this->model3($user_id, $filename);
	    }
	    
	    // Nome;DDD+Telefone;Param1;Param2;Param3;Param4;Param5;	    
	    else if ($model == 4) {
	        return $this->model4($user_id, $filename);
	    }
	    
	    // Nome;DDD+Telefone1;DDD+Telefone2;DDD+Telefone3;DDD+Telefone4; 
	    else if ($model == 5) {
	        return $this->model5($user_id, $filename);
	    }
	    
	    // Nome;DDD+Telefone1;DDD+Telefone2;DDD+Telefone3;DDD+Telefone4; ...
	    //        ... Param1;Param2;Param3;Param4;Param5;
	    else if ($model == 6) {
	        return $this->model6($user_id, $filename);
	    }
	    return null;
	}	
	
	/**
	 * Nome;DDD;Telefone
	 * obs: DDD e Telefone em campos SEPARADOS
	 */
	private function model1($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	     
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	         
	        $num = count($data);
	        
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o 
	         * modelo
	         */
	        if (($row == 1) && ($num != 3)) {
                return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	         
	        if (($row >= 2) && ($data[2] != null) && (trim($data[2])!= "")) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1] . $data[2]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        $row++;
	    }
	     
	    fclose($handle);
	    
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	     * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	     * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	     */
	    $file = new File($filedata);
	    $file->delete();
	     
	    return $this->Mailing['Mailing']['id'];
	}
	
	/**
	 * Nome;DDD+Telefone
	 * obs: DDD e Telefone JUNTOS no mesmo campo
	 */
	private function model2($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	     
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	         
	        $num = count($data);
	    
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o
	         * modelo
	         */
	        if (($row == 1) && ($num != 2)) {
	            return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	        
	        if (($row >= 2) && (trim($data[1])!= "") && ($data[1] != null)) {	            
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        $row++;
	    }
	    
	    fclose($handle);
	     
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	    * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	    * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	    */
	    $file = new File($filedata);
	    $file->delete();
	    
	    return $this->Mailing['Mailing']['id'];
	}	
	
	/**
	 * Nome;DDD;Telefone;Param1;Param2;Param3;Param4;Param5;
	 * obs: DDD e Telefone em campos SEPARADOS
	 */
	private function model3($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	    
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	    
	        $num = count($data);
	    
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o 
	         * modelo
	         */
	        if (($row == 1) && ($num != 8)) {
                return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	         
	        if (($row >= 2) && (trim($data[2])!= "") && ($data[2] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1] . $data[2]));
	            $ItemMailing->set('parameter1', $data[3]);
	            $ItemMailing->set('parameter2', $data[4]);
	            $ItemMailing->set('parameter3', $data[5]);
	            $ItemMailing->set('parameter4', $data[6]);
	            $ItemMailing->set('parameter5', $data[7]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        $row++;
	    }
	    
	    fclose($handle);
	     
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	    * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	    * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	    */
	    $file = new File($filedata);
	    $file->delete();
	    
	    return $this->Mailing['Mailing']['id'];
	}
	
	/**
	 * Nome;DDD+Telefone;Param1;Param2;Param3;Param4;Param5;
	 * obs: DDD e Telefone JUNTOS no mesmo campo 
	 */
	private function model4($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	    
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	    
	        $num = count($data);
	    
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o 
	         * modelo
	         */
	        if (($row == 1) && ($num != 7)) {
                return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	         
	        if (($row >= 2) && (trim($data[1])!= "") && ($data[1] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1]));
	            $ItemMailing->set('parameter1', $data[2]);
	            $ItemMailing->set('parameter2', $data[3]);
	            $ItemMailing->set('parameter3', $data[4]);
	            $ItemMailing->set('parameter4', $data[5]);
	            $ItemMailing->set('parameter5', $data[6]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        $row++;
	    }
	    
	    fclose($handle);
	     
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	    * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	    * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	    */
	    $file = new File($filedata);
	    $file->delete();
	    
	    return $this->Mailing['Mailing']['id'];
	}
	
	/**
	 * Nome;DDD+Telefone1;DDD+Telefone2;DDD+Telefone3;DDD+Telefone4;
	 * obs: DDD e Telefone JUNTOS no mesmo campo 
	 */
	private function model5($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	    
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	    
	        $num = count($data);
	    
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o 
	         * modelo
	         */
	        if (($row == 1) && (count($data) != 5)) {
                return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	         
	        if (($row >= 2) && (trim($data[1])!= "") && ($data[1] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[2])!= "") && ($data[2] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[2]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[3])!= "") && ($data[3] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[3]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[4])!= "") && ($data[4] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[4]));
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
            $row++;
	    }
	    
	    fclose($handle);
	     
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	    * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	    * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	    */
	    $file = new File($filedata);
	    $file->delete();
	    
	    return $this->Mailing['Mailing']['id'];
	}
	
	/**
  	 * Nome;DDD+Telefone1;DDD+Telefone2;DDD+Telefone3;DDD+Telefone4; ...
	 *        ... Param1;Param2;Param3;Param4;Param5;
	 * obs: DDD e Telefone JUNTOS no mesmo campo 
	 */
	private function model6($user_id, $filename) {
	    $filedata = WWW_ROOT . 'uploads' . DS . $filename;
	    $handle = fopen($filedata, "r");
	    $mailing = array();
	    
	    $row = 1;
	    
	    $this->create();
	    $this->set('filename', $filename);
	    $this->set('user_id', $user_id);
	    $this->Mailing = $this->save();
	    
	    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
	    
	        $num = count($data);
	    
	        /*
	         * Validacao para saber se a primeira linha do arquivo bate com o 
	         * modelo
	         */
	        if (($row == 1) && (count($data) != 10)) {
                return "Falha: Arquivo Inválido para o modelo Selecionado!";
	        }
	         
	    if (($row >= 2) && (trim($data[1])!= "") && ($data[1] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[1]));
	            $ItemMailing->set('parameter1', $data[5]);
	            $ItemMailing->set('parameter2', $data[6]);
	            $ItemMailing->set('parameter3', $data[7]);
	            $ItemMailing->set('parameter4', $data[8]);
	            $ItemMailing->set('parameter5', $data[9]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[2])!= "") && ($data[2] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[2]));
	            $ItemMailing->set('parameter1', $data[5]);
	            $ItemMailing->set('parameter2', $data[6]);
	            $ItemMailing->set('parameter3', $data[7]);
	            $ItemMailing->set('parameter4', $data[8]);
	            $ItemMailing->set('parameter5', $data[9]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[3])!= "") && ($data[3] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[3]));
	            $ItemMailing->set('parameter1', $data[5]);
	            $ItemMailing->set('parameter2', $data[6]);
	            $ItemMailing->set('parameter3', $data[7]);
	            $ItemMailing->set('parameter4', $data[8]);
	            $ItemMailing->set('parameter5', $data[9]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        
	        if (($row >= 2) && (trim($data[4])!= "") && ($data[4] != null)) {
	            $ItemMailing = ClassRegistry::init('ItemMailing');
	            $ItemMailing->create();
	            $ItemMailing->set('name', $data[0]);
	            $ItemMailing->set('phone', $this->normalizePhone($data[4]));
	            $ItemMailing->set('parameter1', $data[5]);
	            $ItemMailing->set('parameter2', $data[6]);
	            $ItemMailing->set('parameter3', $data[7]);
	            $ItemMailing->set('parameter4', $data[8]);
	            $ItemMailing->set('parameter5', $data[9]);
	            $ItemMailing->set('mailing_id', $this->Mailing['Mailing']['id']);
	            $ItemMailing->save();
	        }
	        $row++;
	    }
	    
	    fclose($handle);
	     
	    /*
	     * Remove o arquivo apos sua importacao, no padrao CakePHP
	    * http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html
	    * @filedata e o nome do arquivo no padrao /dir/do/arquivo/nome.csv
	    */
	    $file = new File($filedata);
	    $file->delete();
	    
	    return $this->Mailing['Mailing']['id'];
	}
	
/**
 * Limpa o telefone para caracteres válidos
 */
	private function normalizePhone($phone) {
	    return str_replace(" ", "", $phone);
	}
}

