<?

class ServerController extends Controller {
	
	public function IndexAction() {
		
		//ServerController::PerMinuteAction();

	}
	
	
	public function CheckStatus() {
		
	}
	

	
	public function PerHourAction() {
		
		ServerController::CheckInactiveUser();
		

		// Przyznawanie nagr�d
		$array = RatingDAL::CountRating(true, true);
//		var_dump($array);
		
		foreach($array as $row) {
			if($row && isset($row['id_type'])) {
				$className = Type::GetTypeClassName($row['id_type']).'DAL';
//				echo $className.' - '.$row['id_content'];
				eval('$obj='.$className.'::GetResult(array("'.Type::GetTypeSQLIdName($row['id_type']).'" => '.$row['id_content'].'), 1);');
//				print_r($obj);

				if(isset($obj[0])) {
					eval($className.'::AddAward($obj[0]);');
				}
			}	
		}
		//Koniec przyznawania nagr�d.
	}
	
	public function PerMinuteAction() {
		ServerController::SendInfoMail();
		
	}
	
	public function CheckInactiveUser() {
		MailingDAL::ClearInactiveUser();
	}

	public function CountRating() {
		
	
	
	}
	
	public function SendInfoMail() {
		$logger = LoggerManager::getLogger(__CLASS__);
		$objMailing = MailingDAL::GetMailingToSend();
		//while (($objMailing = MailingDAL::GetMailingToSend())) {

		//		}
		if (is_object($objMailing)) {
			$logger = LoggerManager::getLogger(__CLASS__);
			$limit = $objMailing->GetLastSend() + 50;
			$mailList = array();
			$logger->info("limit: $limit ".$objMailing->GetLastSend());
			$mailList = MailingDAL::GetMailingAddressList(2, $objMailing->GetLastSend(), 50);
			MailingDAL::UpdateLastSend($objMailing->GetId(), $limit);
			//Utils::ArrayDisplay($mailList);

			// pobiera z tabeli user (jezeli taka istnije w tym przypadku nie potrzebna)
			//			if (!is_array($mailList) || count($mailList) < 50 && $objMailing->GetType() == 1) {
			//				MailingDAL::UpdateLastSend($objMailing->GetId(), 0);
			//				MailingDAL::UpdateType($objMailing->GetId());
			//
			//			}

			if (!is_array($mailList) || count($mailList) < 50 && $objMailing->GetType() == 2) {
				MailingDAL::UpdateLastSend($objMailing->GetId(), 0);
				MailingDAL::SetExecuted($objMailing->GetId());
			}


			//$this->smarty->assign('content', $objMailing->GetText());
			//$txtmessage = $this->smarty->fetch('MailTxt.tpl');
			//Utils::ArrayDisplay($mailList);

			foreach ($mailList as $key => $arrayPackage) {
				foreach ($arrayPackage as $keyPackege => $value) {
					$subjet = " Mediaflex - ".$objMailing->GetTitle();
					$mail = new PHPMailer();
					$mail -> CharSet = "utf-8";
					$mail -> Subject = $subjet;
					$mail -> SMTPAuth = true;
					$mail -> Mailer = 'smtp';

					$mail -> Host = HOST_MAIL;
					$mail -> Port = 25;
					$mail ->From = FROM_MAIL;
					$mail -> FromName = FROM_NAME_MAIL;
					$mail -> Username = USER_MAIL;
					$mail -> Password = PASS_MAIL;
					//$mail->AddAddress('maciek@formix.pl', 'Maciej Kloch');
					$mail->AddAddress($value['email'], $value['name']);

					$mail -> AddBCC("maciek@formix.pl", "Mailing  - ".FROM_NAME_MAIL." ".$value['email']."- ".$value['name']." ".$key."-".$keyPackege);
					$mail -> Body = $objMailing->GetText();
					$mail -> Send();
				}
				//sleep(2);
			}
		}
	}
	
	
	    public function GenerateModelAction($param) {
        MFLog::Info(__FUNCTION__);
        require_once('../core/lib/Smarty/Smarty.class.php');
        $smarty = new Smarty();
        $smarty->template_dir = Config::Get('PATH_SMARTY_TEMPLATE');
        $smarty->compile_dir = Config::Get('PATH_SMARTY_COMPILE');

        $db = Registry::Get('db');

        $sql = " select table_name from information_schema.tables where table_schema <> 'information_schema' ";
        $stmt = $db->prepare($sql)
                        ->execute($sql);

        $tables = $stmt->FetchAllRow();
        foreach ($tables as $table) {

            $tableName = $table[0];
            $className = ucfirst(Utils::SQLName2PHPName($tableName));

            $smarty->assign('tableName', $tableName);
            $smarty->assign('className', $className);

            // zależne obiekty/tabele działa dopiero od mySQL 5.1.16
//			$sql = " select table_name from referential_constraints where constraint_schema <> 'information_schema' and referenced_table_name = '$tableName' ";
//			$stmt = $db->prepare($sql)
//			->execute($sql);
//
//			$refTableNames = array();
//
//			$refTables = $stmt->FetchAllRow();
//			foreach ($refTables as $refTable) {
//				$tmp_name = Utils::SQLName2PHPName($refTable[0]);
//				$refTables[$refTable[0]] = $tmp_name;
//			}
//
//			$smarty->assign('refTables', $refTables);
            // kolumny tabeli dla obiektu

            $sql = " select column_name from information_schema.columns where table_name='$tableName'; ";
            $stmt = $db->prepare($sql)
                            ->execute($sql);

            $columnNames = array();

            $columns = $stmt->FetchAllRow();
            foreach ($columns as $column) {
                if ($column[0] === 'id_' . $tableName) {
                    $tmp_name = 'id';
                } else {
                    $tmp_name = Utils::SQLName2PHPName($column[0]);
                }
                $columnNames[$column[0]] = $tmp_name;
            }


            $smarty->assign('columnNames', $columnNames);

            $output = '<?php' . $smarty->fetch('templateModel.tpl') . '?>';
            $file = fopen(PATH_MODEL_TMP . $className . '.class.php', "w");
            fwrite($file, $output);
            fclose($file);

            $outputDAL = '<?php' . $smarty->fetch('templateModelDAL.tpl') . '?>';
            $file = fopen(PATH_MODEL_TMP . $className . 'DAL.class.php', "w");
            fwrite($file, $outputDAL);
            fclose($file);
        }
    }
	
	
	

	public function preDispatch() {
		$this->disableTemplates = true;

	}

}

?>