<?php

class Note extends PhpObject {
	
	const NOTE_TABLE = 'notes';
	
	/**
	 * DB
	 * @var Db
	 */
	private $oDb;
	
	private $iNoteId;
	private $iUserId;
	private $iCourseId;
	
	public function __construct(Db &$oDb, $iUserId, $iCourseId)
	{
		parent::__construct(__CLASS__, Settings::DEBUG);
		$this->oDb = &$oDb;
		$this->setNoteId(0);
		$this->setUserCourseId($iUserId, $iCourseId);
	}
	
	public function setNoteId($iNoteId) {
		$this->iNoteId = $iNoteId;
	}
	
	public function setUserCourseId($iUserId, $iCourseId) {
		$this->iUserId = $iUserId;
		$this->iCourseId = $iCourseId;
	}
	
	private function getNoteKeys() {
		return array(Db::getId(Auth::USER_TABLE) => $this->iUserId, Db::getId(Course::COURSE_TABLE) => $this->iCourseId);
	}
	
	public function getNote() {
		$asCourse = $this->oDb->selectRow(self::NOTE_TABLE, $this->getNoteKeys());
		if(!empty($asCourse)) {
			$asCourse['notes'] = json_decode($asCourse['notes'], true);
			$asCourse['led_date'] = date('d/m/Y', strtotime($asCourse['led']));
			$asCourse['led_time'] = date('H:i');
		}
		
		return $asCourse;
	}
	
	public function setNote($asOps) {
		$sError = '';
		
		if($this->iUserId > 0 && $this->iCourseId > 0) {
			$asData = array_merge($this->getNoteKeys(), array('notes'=>json_encode($asOps)));
			$iNoteId = $this->oDb->insertUpdateRow(self::NOTE_TABLE, $asData, array_keys($this->getNoteKeys()));
			if(!$iNoteId) $sError = $this->oDb->getLastError();
		}
		else $sError = 'Course ID not set';
		
		return $sError;
	}
}