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

		// provide better description for source fields
		// and add new field source not from sql
    $source_fields = array(
      'id_login' => t('Member id from source'),
			'memo'=>t('memo'),
			'roles'=>t('roles'),
			'user_name' => 'User name',
    );

	  $query = db_select(MIG_MAT_SRC_DB .'.login_id', 'lid');
		$query->join(MIG_MAT_SRC_DB .'.member_id', 'mid', 'mid.id_member = lid.id_member');
		// $query->join(MIG_MAT_SRC_DB .'.locale_id', 'locid', 'lid.def_locale = locid.id_locale');
		$query->join(MIG_MAT_SRC_DB .'.member_info', 'minf', 'mid.id_member = minf.id_member');
		$query
			->fields('lid', array('id_login', 'status', 'date_creation', 'date_modif', 'date_end', 'type', 'email', 'news_letter', 'def_locale'))
			->fields('mid', array('memo'))
			// ->fields('locid', array('name', 'short_name', 'suffix'))
			->fields('minf', array('activity'))
			// ->condition('email_general', '', '<>')
			->orderBy('lid.id_login', 'DESC');
			
		// $query->groupBy('lid.id_member');
		
	  $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationUser();
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id_login' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'OLD Unique member ID',
        'alias' => 'lid',
        )
      ),
      MigrateDestinationUser::getKeySchema()
    );
  
	  // Make the mappings
	  $this->addFieldMapping('name', 'user_name');
	  $this->addFieldMapping('pass')->defaultValue(NULL);
	  $this->addFieldMapping('mail', 'email');
		# NOTE : maybe if we provide only init mail, we wiil be able to ask email confirmation for users
	  $this->addFieldMapping('init', 'email');
	  $this->addFieldMapping('language', 'def_locale');
	  $this->addFieldMapping('theme')->defaultValue('');
	  $this->addFieldMapping('signature')->defaultValue('');
	  $this->addFieldMapping('signature_format')->defaultValue('filtered_html');
	 	$this->addFieldMapping('created', 'date_creation');
	  $this->addFieldMapping('access')->defaultValue(0);//, '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', 'roles');// 7 = utilisateur, 6 = adherent, 8 = premium; ->defaultValue(array(6)); // adhérent
		$this->addFieldMapping('is_new')->defaultValue(TRUE);
	
		$this->addFieldMapping('field_newsletter', 'news_letter');

		$this->addFieldMapping('field_memo', 'memo');
	
		$this->addFieldMapping(NULL, 'activity');
		
		$this->addUnmigratedDestinations(array(
			'role_names', 'data', 'field_memo:language', 
			'field_company', 'field_company:source_type',	'field_company:create_term', 'field_company:ignore_case',
			'path',
		));

		$this->addUnmigratedSources(array(
			'status', 'date_end', 'type', 
		));
	}
	
	public function prepareRow($cr) {

		# change roles by end date
		if($cr->date_end == ''){
			$roles[] = 7;
		}else{
			$today = time();
			$time_end = strtotime($cr->date_end);
			// dsm($time_end, 'time_end');

			$roles = array();
			if($time_end > $today){
				$roles[] = 6;
			}else{
				$roles[] = 7;
			}			
		}
		// dsm($roles, 'roles');
		$cr->roles = $roles;
		
		#user name
		$cr->user_name = $this->getUserName($cr->email);
		// TODO: set role expiration

		#duplicate email
		if($this->checkDupEmail($cr->email)){
			$memo[] = "@dup-email : ".$cr->email;
		}

		#language
		$cr->def_locale = $cr->def_locale == 1 ? 'en' : 'fr';

		#memo
		$memo[] = "@imported";
		
		#statuts
		$memo[] = "statut : ".$cr->status;

		#statuts
		$memo[] = "type : ".$cr->type;

		#statuts
		$memo[] = "activity : ".$cr->activity;

		#memo
		$cr->memo = implode("\n", $memo) ."\n\n". $cr->memo;

    return true;
    // return FALSE if you wish to skip a particular row
  }

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

	public function complete($user, $row) {
		// dsm('-- complete --');
    // Do what you need to do to 
		// dsm($row, '$row');
		// dsm($user, '$user');

		if(in_array(6, $user->roles)){
			$time_end = strtotime($row->date_end);
			$min = strtotime('2013 01 30');
			if($time_end < $min)
				$time_end = $min;

			uc_roles_grant($user, 6, $time_end, FALSE, TRUE);
		}
		
	
  }


  /**
   * helpers
   */


  private function getUserName($email){
  	// Default implementation of name generation.
    $new_name = preg_replace('/@.*$/', '', $email);
    // Remove unwanted characters.
    $new_name = preg_replace('/[^a-zA-Z0-9.-]/', '', $new_name);

    // if username generated from email record already exists, append underscore and number eg:(chris_123)
    if ((bool) db_query("SELECT 1 FROM {users} WHERE LOWER(name) = LOWER(:new_name)", array(':new_name' => $new_name))->fetchField()) {
      $name_idx = db_query_range("SELECT SUBSTRING_INDEX(name,'_',-1) FROM {users} WHERE name REGEXP :search ORDER BY CAST(SUBSTRING_INDEX(name,'_',-1) AS UNSIGNED) DESC", 0, 1, array(':search' => '^' . $new_name . '_[0-9]+$'))->fetchField();

      $new_name .= '_' . ($name_idx + 1);
    }

    return $new_name;
  }

  private function checkDupEmail($email){
    if ((bool) db_query("SELECT 1 FROM {users} WHERE mail = :email", array(':email' => $email))->fetchField()) {
    	return true;
    }
    return false;
  }
}

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

		// provide better description for source fields
		// and add new field source not from sql
    $source_fields = array(
      'id_login' => t('Member id from source'),
      'member_name' => t('Main member name'),
      'member_firstname' => t('Main member first name'),
			'premise'=>'',
			'sub_premise'=>'',
    );
		
		
	  $query = db_select(MIG_MAT_SRC_DB .'.login_id', 'lid');
		$query->join(MIG_MAT_SRC_DB .'.member_id', 'mid', 'mid.id_member = lid.id_member');
		$query->join(MIG_MAT_SRC_DB .'.member_info', 'minf', 'mid.id_member = minf.id_member');
		
		$query
			->fields('lid', array('id_login', 'status', 'name',))
			// ->fields('mid', array('memo', 'cgv'))
			->fields('minf', array(
				'con_title', 'con_name1', 'con_name2', 'con_quality', 'con_service', 'con_ccode1', 'con_tel1', 
				'organization', 'employee', 'naf', 'siret', 'web', 'address', 'city', 'zip', 'country', )
			)
			// ->condition('status', 'A')
			->orderBy('lid.id_login', 'DESC');
			
		// $query->groupBy('lid.id_member');
		
		
	  $this->source = new MigrateSourceSQL($query, $source_fields);
		// $this->dependencies = array('MaterioIndustrialUser');
    $this->destination = new MigrateDestinationProfile2('adherent');
	  
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id_login' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'OLD Unique Member ID',
          'alias' => 'lid',
        )
      ),
      MigrateDestinationProfile2::getKeySchema()
    );

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

		$this->addFieldMapping('revision_uid', 'id_login')
			->sourceMigration('MaterioAdherentUser');

	  // Make the mappings
		$this->addFieldMapping('language')->defaultValue('');
	
		$this->addFieldMapping('field_name', 'member_name');
		$this->addFieldMapping('field_first_name', 'member_firstname');
		$this->addFieldMapping(NULL, 'con_name1');
		$this->addFieldMapping(NULL, 'con_name2');
		$this->addFieldMapping(NULL, 'name');
		
		
		$this->addFieldMapping('field_private_quality', 'con_quality'); // http://drupal.org/node/1232028
		$this->addFieldMapping('field_private_name_title', 'con_title');
		
		$arguments = array(
			'number' => array('source_field' => 'con_tel1'),
		);
		$this->addFieldMapping('field_private_phone', 'con_ccode1')
			->arguments($arguments);
		// field_private_phone:number
		// field_private_phone:extension
		$this->addFieldMapping(NULL, 'con_tel1');

		$this->addFieldMapping(NULL, 'status');

		$arguments = array(
      'thoroughfare' => array('source_field' => 'address'),
      'premise' => array('source_field' => 'premise'),
      'sub_premise' => array('source_field' => 'sub_premise'),
      'locality' => array('source_field' => 'city'),
      'postal_code' => array('source_field' => 'zip'),
    );
		$this->addFieldMapping('field_adresse', 'country')
			->arguments($arguments);
			
		$this->addFieldMapping(NULL, 'address');
		$this->addFieldMapping(NULL, 'premise');
		$this->addFieldMapping(NULL, 'sub_premise');
		$this->addFieldMapping(NULL, 'city');
		$this->addFieldMapping(NULL, 'zip');
		$this->addFieldMapping(NULL, 'country');

		$this->addFieldMapping('field_organization', 'organization');
		$this->addFieldMapping('field_service', 'con_service');
		$this->addFieldMapping('field_employee', 'employee');
		$this->addFieldMapping('field_naf', 'naf');
		$this->addFieldMapping('field_siret', 'siret');


		$this->addFieldMapping('field_user_website', 'web');

		$this->addUnmigratedDestinations(array(
			'field_private_quality:language', 'field_first_name:language', 'field_name:language',
			'field_organization:language', 'field_activity:language', 'field_service:language', 'field_naf:language', 'field_siret:language',
			'field_private_phone:number',  'field_private_phone:extension',

		));
		
			
	}


	public function prepareRow($cr) {

		if($cr->status == 'A'){
			# nom prenom
			$cr->member_name = $cr->con_name1;
			$cr->member_firstname = $cr->con_name2;

			#telephone
			if($cr->con_ccode1 != ''){
				$ccs = cck_phone_countrycodes();
				$cc_founded = false;
				foreach ($ccs as $cc => $cc_values) {
					if('+'.preg_replace('/^\+/', '', trim($cr->con_ccode1)) == $cc_values['code']){
						$cr->con_ccode1 = $cc;
						$cc_founded = true;
						break;
					}
				}	
				if(!$cc_founded){
					// dsm($cr->con_ccode1, '$cr->con_ccode1');
					$cr->con_ccode1 = null;
				}
			}
			

		}else{
			$name = explode(' ', $cr->name);
			$cr->member_name = array_shift($name);
			$cr->member_firstname = implode(' ', $name);
			$cr->con_quality = '';
			$cr->con_title = '';
			$cr->con_ccode1 = '';
			$cr->con_tel1 = '';
		}

		$cr->organization = trim($cr->organization);

		
		$cr->address = preg_replace('/\\n/', ', ', $cr->address);
		if(strlen($cr->address) > 255){
			$adress = $cr->address;
			$cr->address = substr($adress, 0, 250);
			$cr->premise = substr($adress, 250, 500);
			$sub = substr($adress, 500, 750);
			$cr->sub_premise = $sub ? $sub : '';
		}else{
			$cr->premise = '';
			$cr->sub_premise = '';
		}
		
		$cr->city = preg_replace('/\\n/', ' ', $cr->city);

		if($cr->country != ''){
			require_once DRUPAL_ROOT . '/includes/locale.inc';
			$countries = country_get_list();

			$c_founded = false;
			foreach ($countries as $cc => $c) {
				if(stristr($cr->country, $c)){
					$cr->country = $cc;
					$c_founded = true;
					break;
				}
			}
			
			if(!$c_founded){
				$nonISO_cc = array(
					'liban' => 'LB',
					'uk' => 'GB',
					'usa' => 'US',
					'korea, south' => 'KR',
					'brésil' => 'BR',
				);
				foreach ($nonISO_cc as $n => $cc) {
					if(stristr($cr->country, $n)){
						$cr->country = $cc;
						$c_founded = true;
						break;
					}
				}

				if(!$c_founded){
					// dsm($cr->country, '$cr->country');
					$cr->country = null;
				}
				
			}
		}


    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));
	// 	
	//   }
}