<?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/models/User.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Job.inc.php" );
	
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.job_languages.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.job_servicetypes.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.job_custom_recipients.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.job_quotes.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/migrate/migrate.job_notifications.inc.php" );

	class AdminMigrateJobs extends AdminMigrate {
		protected $iRecords;
		protected $email = null;
		protected $orig_name = null;
		protected $orig_contact_phone = null;

		protected $submit_abandon = null;
		protected $submit_orig = null;
		protected $submit_new = null;
		protected $new_user = false;

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


		protected function buildUserMigrateForm( $datas = false ) {
			$this->aP = array();
			$this->job_title = new AdminTextbox( "job_title" , $this );
			$this->job_title->setWidth( 290 );
			$this->email = new AdminTextbox( "email" , $this );
			$this->email->setWidth( 290 );
			$this->orig_name = new AdminTextbox( "orig_name" , $this );
			$this->orig_contact_phone = new AdminTextbox( "orig_contact_phone" , $this );
			$this->submit_orig = new AdminButton( "smb_orig" , $this );
			$this->submit_orig->setValue( "original" );
			$this->submit_orig->setAttribute("onclick",sprintf( "AdminMigrateJobsSubmit('%s','original');",$this->getId()));
			$this->new_name = new AdminTextbox( "new_name" , $this );
			$this->new_contact_phone = new AdminTextbox( "new_contact_phone" , $this );
			$this->submit_new = new AdminButton( "smb_new" , $this );
			$this->submit_new->setValue( "new" );
			$this->submit_new->setAttribute("onclick",sprintf( "AdminMigrateJobsSubmit('%s','new');",$this->getId()));

			$this->submit_abandon = new AdminButton( "smb_abandon" , $this );
			$this->submit_abandon->setValue( "abandon" );
			$this->submit_abandon->setAttribute("onclick",sprintf( "AdminMigrateJobsSubmit('%s','abandon');",$this->getId()));
			if (!$datas) return;
			$this->email->setValue( $datas["orig"]["email"] );
			$this->job_title->setValue( $datas["new"]["job_title"] );
			$this->orig_name->setValue( $datas["orig"]["user_name"] );
			$this->orig_contact_phone->setValue( $datas["orig"]["contact_phone"] );
			$this->new_name->setValue( $datas["new"]["user_name"] );
			$this->new_contact_phone->setValue( $datas["new"]["contact_phone"] );
			$this->setParam( "job_id" , $this->aM["job_id"] );
			$this->setParam( "job_title_text" , $datas["new"]["job_title"] );
			$this->setParam( "debug_backtrace" , FNTH_da( FNTH_dbt( false , true ) , false , true ) );
		}

		protected function handleUserMigrateForm() {
			$this->new_user = false;
			if (!isset( $this->aM["task"] )) return true;
			switch ($this->aM["task"]) {
			case "abandon":
				return true;
				break;
			case "original":
				$this->new_user = array(
					"email" => $this->aM["email"],
					"user_name" => $this->aM["orig_name"],
					"contact_phone" => $this->aM["orig_contact_phone"] );
				break;
			case "new":
				$this->new_user = array(
					"email" => $this->aM["email"],
					"user_name" => $this->aM["new_name"],
					"contact_phone" => $this->aM["new_contact_phone"] );
				break;
			default:
				$this->queueMessage( "error stuff" );
				// $this->queueMessage( FNTH_da( $this->aM , false , true ));
				return false;
				break;
			}
			return true;
		}

		protected function isUserExists( $row ) {
			$query = sprintf( "select user_id from users where email='%s'" , FNTH_db_addslashes( $row["email"] ) );
			$val = FNTH_db_get_field( $query , "user_id" );
			return $val;
		}

		protected function trimPhone( $str ) {
			$retval = "";
			$len = strlen( $str );
			for ($i=0;$i<$len;$i++) {
				$chr = substr( $str , $i , 1 );
				if ($chr<"0" || $chr>"9") continue;
				$retval.=$chr;
			}
			return $retval;
		}

		protected function mifasz( $log ) {
			$file = fopen( "/tmp/fordit.mirgator" , "a" );
			if (!$file) return;
			fprintf( $file , sprintf( "%s\n" , $log ) );
			fclose( $file );
		}

		protected function isUserSame( $row ) {
			$query = sprintf( "select * from users where email='%s'" , FNTH_db_addslashes( $row["email"] ) );
			$new = FNTH_db_get_row( $query );
			$retval = array();
			$retval["new"]=array(
				"user_name"=>$row["name"],
				"email" => $row["email"],
				"contact_phone"=>$row["phone"],
				"job_title" => $row["title"] );
			$retval["orig"]=array(
				"user_name"=>$new["user_name"],
				"email" => $new["email"],
				"contact_phone"=>$new["contact_phone"] );

			// par csekk
			// ha az ujnal nincs kitoltve a telefonszam, de a reginel igen
			if (!strlen( trim( $retval["new"]["contact_phone"] )) &&
				 strlen( trim( $retval["orig"]["contact_phone"] )))
				$retval["new"]["contact_phone"]=$retval["orig"]["contact_phone"];

			if ($this->trimPhone( $retval["new"]["contact_phone"]) ==
				$this->trimPhone( $retval["orig"]["contact_phone"]))
				$retval["new"]["contact_phone"]=$retval["orig"]["contact_phone"];
		
			$same = true;

			if ($retval["orig"]["user_name"]!=$retval["new"]["user_name"]) $same = false;
			if ($retval["orig"]["contact_phone"]!=$retval["new"]["contact_phone"]) $same = false;
			$retval["same"]=$same;
			return $retval;
		}

		protected function migrateJob( $row ) {
			$fields = array( "task" , "job_id" , "new_contact_phone" , "new_name" , "orig_contact_phone" , "orig_name" , "job_title" );
			// eloszor is, ha a task abandon, akkor megy a rakba a cumoka
			if (isset( $this->aM["task"] ) && $this->aM["task"]=="abandon") {
				// abandon job
				$job = new JobModel();
				$job->abandonOldJob( $this->aM["job_id"] );
				foreach ($fields as $f) unset( $this->aM[$f] );
				return true;
			}
			foreach ($fields as $f) unset( $this->aM[$f] );

			// vajon mar foglalkoztunk vele?
			$query = sprintf( "select count(*) as num from jobs where oldid=%d" , $row["id"] );
			$val = FNTH_db_get_field( $query , "num" );
			if ($val>0) return true;

			// mar szerepelt
			$job = new JobModel();
			if ($job->isOldJobAbandoned( $row["id"] )) return true;

			// meg nem foglalkoztunk vele sosem

			$p = array();
			$p["oldid"]=$row["id"];
			if (isset( $row["ctstamp"] ) && $row["ctstamp"]>="1970-01-01 00:00:00") {
				$p["ctstamp"]=$row["ctstamp"];
			}
			if (isset( $row["userid"] )) {
				// ha mar van user_id, akkor probaljunk meg oldid-bol gyujteni
				$user = new UserModel();
				$user_id = $user->getUserIdFromOldId( $row["userid"] );
				if ($user_id) $p["poster_user_id"]=$user_id;
				$this->mifasz( sprintf( "oldschool (%d)" , $row["id"] )  );
			} else {
				// nincs hozzarendelve, akkor megprobaljuk megoldani

				if ($this->new_user) {
					// formbol jottunk
					// we need to update the user
					$upd = array();
					$upd["user_name"]=sprintf( "'%s'" , FNTH_db_addslashes( $this->new_user["user_name"] ));
					$upd["contact_phone"]=sprintf( "'%s'" , FNTH_db_addslashes( $this->new_user["contact_phone"] ));
					$q = FNTH_db_generate_update_query( "users" , $upd , sprintf( "email='%s'" , FNTH_db_addslashes( $this->new_user["email"] ) ) );
					FNTH_db_free_result( FNTH_db_query( $q ) );
					// get the id, and make it to the poster user
					$query = sprintf( "select user_id from users where email='%s'" , FNTH_db_addslashes( $this->new_user["email"] ) );
					$p["poster_user_id"]=FNTH_db_get_field( $query , "user_id" );
					$this->mifasz( sprintf( "formbol (#%d) => %d" , $row["id"] , $p["poster_user_id"] )  );
					$this->new_user = false;
				} else {
					// nem formbol jottunk, akkor letezik mar nalunk?
					$user_id = $this->isUserExists( $row );
					if ($user_id) {
						// letezik mar nalunk
						$user_same = $this->isUserSame( $row );
						if ($user_same["same"]) {
							$p["poster_user_id"] = $user_id;
							$this->mifasz( sprintf( "sameuser (#%d) => %d" , $row["id"] , $p["poster_user_id"] )  );
						} else {
							// adat-nemegyezes
							$this->aM["job_id"]=$row["id"];
							$this->buildUserMigrateForm( $user_same );
							$this->renderForm( ".usermigrate" );
							return false;
						}
					} else {
						// nem letezik meg nalunk
						if (fo3_is_email_valid( trim($row["email"]))) {
							// es az email cim is valid, akkor megoldjuk
							$d = array();
							$d["user_name"]=$row["name"];
							$d["email"]=$row["email"];
							$d["pwd"]=uniqid("");
							$d["contact_phone"]=$row["phone"];
							$um = new UserModel();
							$p["poster_user_id"] = $user_id = $um->addUser( $d );
							$this->mifasz( sprintf( "brandnew (#%d) => %d" , $row["id"] , $p["poster_user_id"] )  );
						} else {
							return true;	// FIXME hagyjuk ki a picsaba
							$user_same = $this->isUserSame( $row );
							if (!$user_same["same"]) {
								// nem ugyanaz
								$this->aM["job_id"]=$row["id"];
								$this->buildUserMigrateForm( $user_same );
								$this->renderForm( ".usermigrate" );
								return false;
							}
						}
					}
				}
			}
			if (isset( $row["oldid"] ) && $row["oldid"] ) {
				$p["job_version"]=1.0;
			} else {
				$p["job_version"]=2.0;
			}
			$p["poster_name"]=$row["name"];
			$p["poster_email"]=$row["email"];
			$p["poster_phone"]=$row["phone"];
			$p["poster_cellular"]=$row["cellular"];
			$p["poster_show_phone"]=$row["show_phone"];
			$p["job_title"]=$row["title"];
			$p["job_size"]=$row["sizeofoffer"];
			if (isset( $row["deadline"] ) && $row["deadline"]!="0000-00-00")
				$p["job_quote_deadline"]=$row["deadline"];

			if (isset( $p["job_quote_deadline"] ))
				$p["job_deadline"]=$p["job_quote_deadline"];
			$p["job_description"]=$row["description"];
			$p["job_mainaspects"]=$row["mainaspects"];
			$p["job_recipients"]=array();
			switch ($row["offertype"]) {
			case "translators":$p["job_recipients"]["type"]="freelancers";break;
			case "offices":$p["job_recipients"]["type"]="agencies";break;
			case "all":
			case "custom":
				$p["job_recipients"]["type"]=$row["offertype"];
				break;
			default:
				$p["job_recipients"]["type"]="all";
				break;
			}
			$p["poster_acknowledged"]=$row["acknowledged"];
			$p["admin_acknowledged"]=$row["admin_acknowledged"];
			$p["is_revoked"]=$row["revoked"];
			if (isset( $row["rtstamp"] ) && $row["rtstamp"]>="1970-01-01 00:00:00") $p["revoked_at"]=$row["rtstamp"];
			$p["is_sent"]=$row["sent"];
			if (isset( $row["ststamp"] ) && $row["rtstamp"]>="1970-01-01 00:00:00") $p["sent_at"]=$row["ststamp"];
			if (isset( $row["ipaddress"] ) && strlen( trim( $row["ipaddress"] ))) $p["ipaddress"]=$row["ipaddress"];
			if (isset( $row["agent"] ) && strlen( trim( $row["agent"] ))) $p["useragent"]=$row["agent"];
			$p["hash"]=$row["hash"];
			$p["send_status"]=$row["send_status"];
			$p["source"]=$row["source"];


			$p = fo3_migrate_job_languages( $this->olddb , $p , $row["id"] );

			$job = new JobModel();
			$job_id = $job->addJob( $p );
			// fo3_migrate_job_languages( $this->olddb , $job_id , $row["id"] );
			fo3_migrate_job_servicetypes( $this->olddb , $job_id , $row["id"] );
			fo3_migrate_job_custom_recipients( $this->olddb , $job_id , $row["id"] );
			fo3_migrate_job_quotes( $this->olddb , $job_id , $row["id"] );
			fo3_migrate_job_notifications( $this->olddb , $job_id , $row["id"] );
			return true;
		}

		public function handleMigratorEvent() {
			if (!isset( $this->aM["offset"] )) {
				// first run
				$this->aM["offset"] = 0;
				$this->aM["records"] = FNTH_db_get_field( "select count(*) as num from fo_offer where id>7108" , "num" , $this->olddb );
				$this->initAdminMigrate( $this->aM["records"] );
			}
			if (!$this->handleUserMigrateForm()) return false;


			$batchsize = 2;
			$query = sprintf( "select * from fo_offer where id>7108 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->migrateJob( $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;
		}

	}
?>
