<?php
	require_once( $GLOBALS["site_root"] . "/includes/migrate/AdminMigrate.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminTextbox.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/widgets/AdminButton.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.user_properties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.user_specialties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );

	class AdminMigrateMembers extends AdminMigrate {
		protected $iRecords;
		protected $testtext = null;
		protected $submit1 = null;
		protected $submit2 = null;

		protected $language_ordering = array();


		protected function fakeInit() {
			$classes = array( "AdminButton" , "AdminTextbox" );
			foreach ($classes as $c) { $x = new $c( "" , null );$x->loadAllInheritedDesignFiles(); }
		}


		protected function buildUserMigrateForm() {
			$this->testtext = new AdminTextbox( "testtext" , $this );
			$this->submit1 = new AdminButton( "smb_user1" , $this );
			$this->submit1->setValue( "egyik" );
			$this->submit1->setAttribute("onclick",sprintf( "AdminMigrateJobsSubmit('%s','elso');",$this->getId()));
			$this->submit2 = new AdminButton( "smb_user2" , $this );
			$this->submit2->setValue( "masik" );
			$this->submit2->setAttribute("onclick",sprintf( "AdminMigrateJobsSubmit('%s','masodik');",$this->getId()));
		}

		public function usortMemberLanguages( $a , $b ) {
			$ra = (isset( $this->language_ordering[$a] )) ? $this->language_ordering[$a] : 0;
			$rb = (isset( $this->language_ordering[$b] )) ? $this->language_ordering[$b] : 0;
			if ($ra==$rb) return 0;
			return ($ra>$rb) ? 1 : -1;
		}

		protected function migrateMemberLanguages( $oldid , $member_id ) {
			$lm = new LanguagesModel();
			$mm = new MemberModel();
			// load languages
			$query = sprintf( "select lmlangid from fo_xref_user_languages where user_id=%d" , $oldid );
			$member_langs = FNTH_db_get_column( $query , "lmlangid" , $this->olddb );
			// sort languages
			usort( $member_langs , array( $this , "usortMemberLanguages" ) );
			// save languages
			$mm->setMemberLanguages( $member_id , $member_langs );

			// load language pairs 
			$query = sprintf( "select * from fo_user_langpairs where user_id=%d" , $oldid );
			$data = FNTH_db_get_resultset( $query , $this->olddb );
			$lp = array();
			foreach ($data as $row) {
				$s = $row["src_lang_id"];
				$t = $row["dst_lang_id"];
				$e = $row["servicetype_id"];
				if (!isset( $lp[$e] )) $lp[$e]=array();
				if (!isset( $lp[$e][$s] )) $lp[$e][$s]=array();
				$lp[$e][$s][$t]=true;
			}
			$mm->setMemberLanguagePairs3D( $member_id , $lp );
		}

		protected function migrateMember( $row ) {
			$user = new UserModel();
			$member = new MemberModel();

			$query = sprintf( "select member_id from members where oldid=%d" , $row["id"] );
			$member_id = FNTH_db_get_field( $query , "member_id" );
			if ($member_id) {
				$row["status_senttstamp"]=(isset( $row["status_senttstamp"] )) ? $row["status_senttstamp"] : "";
				$m = $row;
				$m["member_type"]=($row["utype"]=="translator") ? "freelancer" : "agency";unset( $row["utype"] );
				$m["member_username"]=$row["username"];
				$m["member_aliasname"]=$row["aliasname"];
				$m["notifications"]=$row["newsletter"];
				$m["useragent"]=$row["agent"];
				$m["capacity"]=$row["availability"];
				$m["is_deleted"]=($row["deleted"]>0);
				$member->updateMember( $member_id , $m );

				$this->migrateMemberLanguages( $row["id"] , $member_id );
				return true;
			}

			if ($row["acknowledged"]) $row["is_acknowledged"]=1;	
			$row["status_senttstamp"]=(isset( $row["status_senttstamp"] )) ? $row["status_senttstamp"] : "";
			$row["is_admin_acknowledged"]=true;
			$row["user_name"]=$row["name"];unset( $row["name"] );
			$row["contact_phone"]=$row["phone"];
			$old_user_id = $row["id"];
			$user_id = $user->addUser( $row );

			// insert member
			$row["member_type"]=($row["utype"]=="translator") ? "freelancer" : "agency";unset( $row["utype"] );
			$row["member_username"]=$row["username"];
			if ($row["reg_tstamp"]=="0000-00-00 00:00:00") unset( $row["reg_tstamp"] );
			$row["member_aliasname"]=$row["aliasname"];unset( $row["aliasname"] );
			$row["notifications"]=$row["newsletter"];unset( $row["newsletter"] );
			$row["useragent"]=$row["agent"];unset( $row["agent"] );
			$row["capacity"]=$row["availability"];unset( $row["availability"] );
			$row["is_deleted"]=($row["deleted"]>0);unset( $row["deleted"] );
			// FIXME nem ide jon
			$row["native_language"]=$row["motherlang"];
			$row["haspicture"]=($row["haspicture"]>0) ? true : false;
			if (isset( $row["agent"] )) {
				$row["useragent"]=$row["agent"];unset( $row["agent"] );
			}
			if (isset( $row["availability"] )) {
				$row["capacity"]=$row["availability"];unset( $row["availability"] );
			}

			$member_id = $member->addMember( $user_id , $row );
			$member->setMemberOldId( $member_id , $old_user_id );

			// migrate user languages
			$this->migrateMemberLanguages( $old_user_id , $member_id );
			// migrate user properties
			fo3_migrate_user_properties( $this->olddb , $old_user_id , $member_id );
			// migrate user specialties
			fo3_migrate_user_specialties( $this->olddb , $old_user_id , $member_id );

			// migrate services and references
			for ($slang=1;$slang<3;$slang++) {
				// service
				$query = sprintf( "select service from fo_user_service where user_id=%d and lang_id=%d",$old_user_id , $slang );
				$srow = FNTH_db_get_row( $query , $this->olddb );
				if ($srow)
					$member->setMemberExtendedPropertyFromId( $member_id , 5 , $srow["service"] , $slang );
				// reference
				$query = sprintf( "select reference from fo_user_reference where user_id=%d and lang_id=%d",$old_user_id , $slang );
				$srow = FNTH_db_get_row( $query , $this->olddb );
				if ($srow)
					$member->setMemberExtendedPropertyFromId( $member_id , 6 , $srow["reference"] , $slang );
			}

			// migrate cv
			if (isset( $row["cv_filename"] ) && ($row["cv_on_page"]>0)) {
				$oldurl = sprintf( "http://www.fordit.hu/media/translators/%d/%d/%s" , (int)($old_user_id/100) , $old_user_id , $row["cv_filename"] );
				// FNTH_db_sql_error( $oldurl );

				$file = file_get_contents( $oldurl );
				$m = uniqid("");
				$temppath = sprintf( "/tmp/%s" , $m );
				file_put_contents( $temppath , $file );
				if (file_exists( $temppath ) && filesize( $temppath )) {
					$att = array();	
					$att["filename"]=$row["cv_filename"];
					$att["real_path"]=$temppath;
					$att["comment"]="CV";
					$p = pathinfo( $row["cv_filename"] );
					$ext = $p["extension"];
					$mime = "";
					switch ($ext) {
					case "doc":$mime = "application/msword";break;
					case "pdf":$mime = "application/pdf";break;
					case "rtf":$mime = "application/rtf";break;
					}
					$att["mime_type"]=$mime;
					$member->addMemberAttachment( $member_id , $att );
				}
				if (file_exists( $temppath )) unlink( $temppath );
			}


			// migrate picture
			if (isset( $row["haspicture"] ) && $row["haspicture"]) {
				$oldurl = sprintf( "http://www.fordit.hu/media/translators/%d/%d/%s" , (int)($old_user_id/100) , $old_user_id , $row["member_aliasname"].".jpg" );
				$fullpath = $GLOBALS["site_root"] . $member->getAttachmentPath( $member_id );
				if (!is_dir( $fullpath )) mkdir( $fullpath , 0777 , true );
				

				$newurl = sprintf( "%s%s/%s",
					$GLOBALS["site_root"],
					$member->getAttachmentPath( $member_id ),
					sprintf( "%s.jpg" , $row["member_aliasname"] ) );
				if (file_exists( $newurl )) unlink( $newurl );
				copy( $oldurl , $newurl );

				$toldurl = sprintf( "http://www.fordit.hu/media/translators/%d/%d/%s" , (int)($old_user_id/100) , $old_user_id , $row["member_aliasname"]."-thumbnail.jpg" );

				$tnewurl = sprintf( "%s%s/%s",
					$GLOBALS["site_root"],
					$member->getAttachmentPath( $member_id ),
					sprintf( "%s-thumbnail.jpg" , $row["member_aliasname"] ) );
				if (file_exists( $tnewurl )) unlink( $tnewurl );
				copy( $toldurl , $tnewurl );
			}
			$member->setMemberDirty( $member_id , true );
			return true;
		}

		protected function initEnvironment() {
			$lm = new LanguagesModel();
			$langs = $lm->getLanguageOptions( false , 1 , false );
			$lo = array();
			$i = 1;
			foreach ($langs as $langid => $name) {
				$lo[$langid]=$i;
				$i++;
			}
			$this->language_ordering = $lo;
		}

		public function handleMigratorEvent() {
			$this->initEnvironment();
			if (!isset( $this->aM["offset"] )) {
				// first run
				$query = sprintf( "select count(*) as num from fo_user where current_status<>'archive'" );
				$this->aM["offset"] = 0;
				$this->aM["records"] = FNTH_db_get_field( $query , "num" , $this->olddb );
				$this->initAdminMigrate( $this->aM["records"] );
			}
			if (isset( $this->aM["task"] )) {
				$this->buildUserMigrateForm();
				$this->refreshChildValuesFromArray( $this->aM );
				$params = array();
				$params["textbox"] = $this->testtext->getValue();
				$params["task"] = $this->aM["task"];
				$this->queueMessage( FNTH_da( $params , false , true ) );
				return false;
			}


			$batchsize = 2;
			$query = sprintf( "select * from fo_user where current_status<>'archive' order by id limit %d offset %d",
				$batchsize , $this->aM["offset"] );
			$ds = FNTH_db_get_resultset( $query , $this->olddb );
			$clen = count( $ds );
			if ($batchsize>$clen) $batchsize=$clen;
			$i=0;
			while ($batchsize) {
				$row = $ds[$i];
				$this->setProgressBarCurrent( "pb1" , $this->aM["offset"] );

				if (!$this->migrateMember( $row )) return false;

				$this->aM["offset"]++;
				if ($this->aM["offset"]>=$this->aM["records"]) break;
				$batchsize--;
				$i++;
			}
			$this->setProgressBarCurrent( "pb1" , $this->aM["offset"] );
			if ($this->aM["offset"]<$this->aM["records"]) return true;
			$this->finishAdminMigrate();
			return false;
		}

	}




?>
