<?php
/**
 * MaterioIndustrialUserMigration
 * 
 */
class MaterioIndustrialContactUserMigration extends MaterioBasicMigration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Migrate Materio Industrials Contact Users');

		// provide better description for source fields
		// and add new field source not from sql
    $source_fields = array(
      'id_industrial' => t('Industrial id from source'),
			'memo'=>t('memo'),
    );

	  $query = db_select(MIG_MAT_SRC_DB .'.industrial_id', 'iid');
		$query->join(MIG_MAT_SRC_DB .'.industrial_info', 'iinf', 'iid.id_industrial = iinf.id_industrial');
		
		$query
			->fields('iid', array('id_industrial', 'date_creation', 'date_modif'))
			->fields('iinf', array('company', 'email_contact'))
			->condition('email_contact', '', '<>')
			->orderBy('iid.id_industrial', 'DESC');
		
		$query->groupBy('iid.id_industrial');
		
	  $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationUser();
	  
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id_industrial' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'OLD Unique industrial ID',
          'alias' => 'iid',
        )
      ),
      MigrateDestinationUser::getKeySchema()
    );

	  // Make the mappings
	  $this->addFieldMapping('name')->defaultValue('aname');
	  $this->addFieldMapping('pass')->defaultValue(NULL);
	  $this->addFieldMapping('mail', 'email_contact');
		# NOTE : maybe if we provide only init mail, we wiil be able to ask email confirmation for users
	  $this->addFieldMapping('init', 'email_contact');
	  $this->addFieldMapping('language')->defaultValue('');
	  $this->addFieldMapping('theme')->defaultValue('');
	  $this->addFieldMapping('signature')->defaultValue('');
	  $this->addFieldMapping('signature_format')->defaultValue('filtered_html');
	 	$this->addFieldMapping('created', 'date_creation');
	  $this->addFieldMapping('access', 'date_modif');
	  $this->addFieldMapping('login')->defaultValue(0);
	  $this->addFieldMapping('status')->defaultValue(0);
	  $this->addFieldMapping('picture')->defaultValue(0);
	  $this->addFieldMapping('timezone')->defaultValue(NULL);
	  // $this->addFieldMapping('path')->issueGroup(t('DNM'));
	  $this->addFieldMapping('pathauto')->defaultValue(1);
		$this->addFieldMapping('roles')->defaultValue(array(5));
		$this->addFieldMapping('is_new')->defaultValue(TRUE);
	
		$this->addFieldMapping('field_memo', 'memo');
			
		$this->addFieldMapping('field_company', 'company');
	
	}
	
	public function prepareRow($cr) {

		if($cr->email_contact == "")
			return false;

		$cr->company = trim($cr->company);
		if(count(taxonomy_get_term_by_name($cr->company.'-'.$cr->id_industrial)))
			$cr->company .= '-'.$cr->id_industrial;
		
		$cr->memo = "#contact";
			
    return TRUE;
    // return FALSE if you wish to skip a particular row
  }
	
}


/**
 * MaterioIndustrialProfile2Migration
 */
class MaterioIndustrialContactProfile2Migration extends MaterioBasicMigration {
  public function __construct() {
    parent::__construct();
		global $user;
    $this->description = t('Migrate Materio Industrials Contact Profiles2');

		// provide better description for source fields
		// and add new field source not from sql
    $source_fields = array(
      'id_industrial' => t('Industrial id from source'),
			'contact_quality'=> t('en-fr contat quality implemented on prepare'),
			'language'=> t('en-fr langauge description, used in prepare'),
			'tels_contact'=>'',
			'ccodes_contact'=>'',
			'memo' => ','
    );
		
		
	  $query = db_select(MIG_MAT_SRC_DB .'.industrial_id', 'iid');
		$query->join(MIG_MAT_SRC_DB .'.industrial_info', 'iinf', 'iid.id_industrial = iinf.id_industrial');
		
		$ilfr_select = db_select(MIG_MAT_SRC_DB .'.industrial_lang', 'ilfr_select')
			->fields('ilfr_select')->condition('ilfr_select.id_locale',1)->orderBy('ilfr_select.id_industrial', 'DESC')->distinct();
		$query->join($ilfr_select, 'ilfr', 'iid.id_industrial = ilfr.id_industrial');
		
		$ilen_select = db_select(MIG_MAT_SRC_DB .'.industrial_lang', 'ilen_select')
			->fields('ilen_select')->condition('ilen_select.id_locale',2)->orderBy('ilen_select.id_industrial', 'ASC')->distinct();
		$query->join($ilen_select, 'ilen', 'iid.id_industrial = ilen.id_industrial'); 
		
		
		$query
			->fields('iid', array('id_industrial', 'date_creation', 'date_modif'))
			->fields('iinf', array('contact', 'contact_title', 'email_contact', 'tel1_contact', 'ccode1_contact', 'tel2_contact', 'ccode2_contact'));

		$query->addField('ilfr', 'contact_quality', 'contact_quality_fr');

		$query->addField('ilen', 'contact_quality', 'contact_quality_en');

		$query
			->condition('email_contact', '', '<>')
			->groupBy('iid.id_industrial')
			->orderBy('iid.id_industrial', 'DESC');
		
		
	  $this->source = new MigrateSourceSQL($query, $source_fields);
		// $this->dependencies = array('MaterioIndustrialUser');
    $this->destination = new MigrateDestinationProfile2('contact_operationnel');
	  
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id_industrial' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'OLD Unique industrial ID',
          'alias' => 'iid',
        )
      ),
      MigrateDestinationProfile2::getKeySchema()
    );

	  // Connecting the profile2 to the user:
	  $this->addFieldMapping('uid', 'id_industrial')
	    ->sourceMigration('MaterioIndustrialContactUser')  // If your user migration class was named 'MyUserMigration', the string is 'MyUser'
	    ->description(t('The assignment of profile2-items to the respective Contact user'));

		$this->addFieldMapping('revision_uid', 'id_industrial')
			->sourceMigration('MaterioIndustrialContactUser');

	  // Make the mappings
		$this->addFieldMapping('language')->defaultValue('');
	
		$this->addFieldMapping('field_private_name', 'contact');
		$this->addFieldMapping('field_private_name_title', 'contact_title');
		
		// see on prepareRow()
		$this->addFieldMapping('field_private_quality', 'contact_quality');		
		$this->addFieldMapping('field_private_quality:language', 'language');		
		$this->addFieldMapping(NULL, 'contact_quality_en');
		$this->addFieldMapping(NULL, 'contact_quality_fr');
		
		
		
		$this->addFieldMapping('field_private_email', 'email_contact'); // http://drupal.org/node/1232028
		
		$arguments = array(
			'number' => array('source_field' => 'tel1_contact'),
			// 'extension' => array('source_field' => 'ccode1_contact'),
		);
		$this->addFieldMapping('field_private_phone', 'ccode1_contact')
			->arguments($arguments);
			
		$this->addFieldMapping(NULL, 'tel1_contact');
		// $this->addFieldMapping(NULL, 'ccode1_contact');
		$this->addFieldMapping(NULL, 'tel2_contact');
		$this->addFieldMapping(NULL, 'ccode2_contact');

		$this->addFieldMapping('field_memo', 'memo');
			
	}


	public function prepareRow($cr) {
		if($cr->email_contact == "")
			return false;


		$cr->contact_quality = array($cr->contact_quality_en, $cr->contact_quality_fr);
		$cr->language = array('en', 'fr');
		
		$ccs = cck_phone_countrycodes();
		$match = 0;
		foreach ($ccs as $cc => $cc_values) {
			if('+'.preg_replace('/^\+/', '', $cr->ccode1_contact) == $cc_values['code']){
				$cr->ccode1_contact = $cc;
				$match++;
			}
			if('+'.preg_replace('/^\+/', '', $cr->ccode2_contact) == $cc_values['code']){
				$cr->ccode2_contact = $cc;
				$match++;
			}
			if($match == 2) 
				break;
		}
		
		if(strlen($cr->ccode1_contact) > 2 && $cr->tel1_contact != "" ){
			$cr->memo .= "\n".'tel1 contact : '. $cr->ccode1_contact .' '. $cr->tel1_contact;
			$cr->tel1_contact = NULL;
			$cr->ccode1_contact = NULL;
		}
		
		if(strlen($cr->tel1_contact) > 15){
			$cc = cck_phone_countrycodes($cr->ccode1_contact);
			$cr->memo .= "\n".'tel1 contact : '. $cc['country'] . ' (' . $cc['code'] . ')' .' '. $cr->tel1_contact;
			$cr->tel1_contact = NULL;
			$cr->ccode1_contact = NULL;
		}
		
		if($cr->tel2_contact != ''){
			$cc = cck_phone_countrycodes($cr->ccode2_contact);
			$cr->memo .= "\n".'tel2 contact : '. $cc['country'] . ' (' . $cc['code'] . ')' .' '. $cr->tel2_contact;
		}
		
		// dsm($cr, '- - - - $cr - - - -');
		
    return TRUE;
    // return FALSE if you wish to skip a particular row
	}


	
	// public function prepare($node, stdClass $row) {
	// 	// dsm('-- prepare --');
	// 	// dsm($node, '$node');
	// 	// dsm($row, '$row');
	// 	
	// 	// $node->field_private_email = array('und'=>array($row->email_contact));
	// 	
	//   }
	
  
	
}