<?php

/**
 * $Id: AdminDAL.mod.php 773 2008-07-01 06:19:05Z dakl $
 * Klasa do obs�ugi odwo�a� do bazy danych:
 * - pobieranie danych
 * - usuwanie
 * - dodawanie
 * - edycja
 * - modyfikacja has�a
 *
 */
class AdminDAL extends DefaultDAL {

// <editor-fold defaultstate="collapsed" desc="Ustawienia tabeli na której operuje DAL">
	protected static $objClassName;
	protected static $objClassTable;
	protected static $objClassTablePK;
	private static $optClass;

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Funkcje pobierające nazwy tabeli, klucza głównego, nazwy klasy na której operuje DAL">

	/**
	 * @return string
	 *
	 */
	public static function GetObjClassName() {
		if (self::$objClassName != '') {
			$class = self::$objClassName;
		} else {
			$class = str_replace('DAL', '', __CLASS__);
		}
		return $class;
	}

	/**
	 * @return string
	 *
	 */
	public static function GetOptClass() {
		if (self::$optClass != null) {
			return self::$optClass;
		} else {
			return self::GetObjClassName();
		}
	}

	/**
	 * @return string
	 *
	 */
	public static function GetObjClassTablePK() {
		if (self::$objClassTablePK != '') {
			$return = self::$objClassTablePK;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetClassTablePK();
		}
		return $return;
	}

	/**
	 * @return string
	 *
	 */
	public static function GetObjClassTable() {
		if (!is_null(self::$objClassTable)) {
			$return = self::$objClassTable;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetTableName();
		}
		return $return;
	}

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Domyślne metody wymagane przez IDefaultDAL">

	/**
	 * @param User $obj
	 *
	 */
	public static function Save($obj) {
		if ($obj->GetId() == -1) {
			return self::Insert($obj);
		} else {
			return self::Update($obj);
		}
	}

	/**
	 * @param User $obj
	 *
	 */
	public static function Insert($obj) {
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObj($obj);
		return self::DefaultInsert($dalData);
	}

	/**
	 * @param User $obj
	 *
	 */
	public static function Update($obj) {
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		return self::DefaultUpdate($dalData);
	}

	/**
	 *
	 * @param integer $id
	 *
	 */
	public static function Delete($obj) {
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		$dalData->setId($obj->GetId());
		return self::DefaultDelete($dalData);
	}

	public static function GetDalDataObj() {
		$dalData = new DalData();
		$dalData->setObjClassName(self::GetObjClassName());
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setOptClass(self::GetOptClass());
		return $dalData;
	}

	/**
	 *
	 * @param integer $id
	 * @return User
	 */
	public static function GetById($id) {
		$result = self::GetResult(array(self::GetObjClassTablePK() => $id), array(), 1);
		if (is_object($result[0])) {
			return $result[0];
		} else {
			throw new Exception('Brak rekordu w tablicy ' . self::GetObjClassTable() . ' o id <b>' . $id . '</b>!');
		}
	}

	/**
	 * pobiera liste rekordow
	 * @param <array> $data - pola do where
	 * @param <array> $queryFields - pobierane pola
	 * @param <string> $limit - limit rekordow
	 * @param <string> $sortBy - sortowanie
	 * @param <bool> $count - czy ma zwracac ilosc rekordow
	 * @return <array> - tablica obiektow lub jesli usawiony count liczba rekordow
	 */
	public static function GetResult($data = array(), $queryFields = array(), $limit = 0, $sortBy = null, $count = null) {
		$dalData = new DalData();
		$dalData->setObjClassName(self::GetObjClassName());
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setOptClass(self::GetOptClass());
		$dalData->setCondition($data);
		$dalData->setQueryFields($queryFields);
		$dalData->setLimit($limit);
		$dalData->setSortBy($sortBy);
		$dalData->setCount($count);

		return self::DefaultGetResult($dalData, false);
	}

// </editor-fold>

	public static function GetArrayAccess($obj) {

		$db = Registry::Get('db');
		$sql = "SELECT access from mf_admin_access where role=:1";
		$stmt = $db->Prepare($sql)
						->BindParam(1, $obj->getRole())
						->Execute();

		$access = array();
		while ($row = $stmt->FetchArray()) {
			$access[$row['access']] = true;
		}
		return $access;
	}

	/**
	 * Pobieranie listy rol
	 *
	 * @return array
	 */
	public static function GetArrayObjRoles() {

		$db = Registry::Get('db');
		$sql = "SELECT DISTINCT role from mf_admin_access";
		$stmt = $db->execute($sql);
		return $stmt->FetchAllAssoc();
	}

	public static function UpdateAvatar($id, $files) {
		$filename = PhotoDAL::SimplePhotoUpload($files, "avatar", 100, 100, 90, "_$id");
		$db = Registry::Get('db');
		$sql = "UPDATE " . self::GetObjClassTable() . " set avatar=:*#1#* WHERE " . self::GetObjClassTablePK() . "=:*#2#*";
		$stmt = $db->prepare($sql)
						->bindParam("*#1#*", $filename)
						->bindParam("*#2#*", $id)
						->execute();
	}

	/**
	 * Zmiana hasla
	 *
	 * @param integer $id
	 * @param string $password
	 * @param string $oldPassword
	 */
	public static function UpdatePassword($id, $password, $oldPassword = null) {
		$db = Registry::Get('db');
		$sql = "UPDATE " . self::GetObjClassTable() . " set password=:1 WHERE " . self::GetObjClassTablePK() . "=:2";
		$stmt = $db->prepare($sql)
						->bindParam(1, $password)
						->bindParam(2, $id)
						->bindParam(3, $oldPassword)
						->execute();
	}

	public static function CheckPassword($id, $password) {
		$db = Registry::Get('db');
		$sql = "select count(*) from " . self::GetObjClassTable() . " WHERE password=:1 AND " . self::GetObjClassTablePK() . "=:2";
		$stmt = $db->prepare($sql)
						->bindParam(1, $password)
						->bindParam(2, $id)
						->execute();

		$result = $stmt->FetchRow();

		return $result[0];
	}

	public static function DoActivity($obj) {
		$db = Registry::Get('db');
		$sql = "UPDATE " . self::GetObjClassTable() . " SET last_activity = NOW() WHERE " . self::GetObjClassTablePK() . "=:*#1#*";
		$stmt = $db->prepare($sql)
						->bindParam('*#1#*', $obj->GetId())
						->execute();

		return $obj->GetId();
	}

	public static function GetResultByLink($table, $id, $data = array(), $limit = 0, $sortBy = null, $count = null) {
		if (!is_array($data)) {
			$data = array();
		}

		$db = Registry::Get('db');
		if ($count == true)
			$select = 'count(*) as count';
		else
			$select = " " . SQL::ToSelect('Admin') . " ";

		$sql = " SELECT $select FROM " . self::GetObjClassTable() . " INNER JOIN mf_link ON " . self::GetObjClassTable() . "." . self::GetObjClassTablePK() . "=mf_link.id_destination WHERE  mf_link.destination_type='" . self::GetObjClassTable() . "' AND  mf_link.source_type='$table' AND mf_link.id_source=$id ";

		foreach ($data as $key => $value) {
			if ($key == "id")
				$key = 'id_mf_admin';

			if (is_array($value))
				$sql .= ( is_numeric($value['value']) || $value ? " AND " . $key . " " . $value['condition'] . " " . $value['value'] : "");
			else
				$sql .= ( is_numeric($value) || $value ? " AND " . $key . " = " . $value : "");
		}
		$sql .= ( trim($sortBy) ? " ORDER BY $sortBy " : "") .
						( $limit ? " LIMIT " . $limit : "") .
						" ";
		$stmt = $db->prepare($sql)
						->execute();
		$array = $stmt->fetchAllAssoc();

		if ($count == true)
			return $array[0]['count'];

		$done = array();
		for ($i = 0; $i < count($array); $i++) {
			$obj = new Admin();
			$obj->FromArray($array[$i], 1);
			$done[$obj->GetId()] = $obj;
		}
		return $done;
	}

	public static function GetLinkedProfiles($id, $limit) {
		return self::GetResult(array(self::GetObjClassTablePK() => array('condition' => '<>', 'value' => $id)), array(), $limit);
	}

	public static function NewMessageNotify($userId, $subject = null, $sender = null, $smarty, $messageId = null) {
		$admin = new Admin();
		$admin = self::GetById($userId);
//    	$physSet = new ProfileSettings();
//    	$physSet = ProfileSettingsDAL::GetByAdminId($userId);
//    	if($physSet -> GetNotifyNewMessage() == 1){
		$smarty->assign('msgId', $messageId);
		$smarty->assign('subject', $subject);
		$smarty->assign('sender', $sender);
		$mail = new Mailer();
		$mail->AddAddress($admin->GetEmail(), $admin->GetEmail());
		$mail->SendEmail($smarty->fetch('partial/Mail/Newmessage.tpl'), '', 'Nowa wiadomość w Twojej skrzynce odbiorczej');
//    	}
	}

}

?>