<?php
	include ('includes/bootstrap.inc.php');
	
	if(empty(Data::getSession('uid'))){
		header('Location: login.php?op=e');
		die();
	}
	
	$op 	= Data::getGet ( 'op' );
	$pid 	= Data::getGet ( 'pid' );
	
	// create a new user object
	$p = new Pet( $pid );
	$bs = new Bootstrap();
	
	
	$layout_pet	= new Template( _DEFAULT_THEME_PATH . _DEFAULT_THEME . "/generic_content.tpl" );
	
	switch ($op){
		// handle json / ajax call
		case 'f':
			/**
			 * Creates a new template for the pet's form.
			 * and fills it with user login form.
			 */
			
			
			
			$date = DateTime::createFromFormat( _DEFAULT_DATE_SHORT_FORMAT, '26/03/1972' );
			
			/**
			 * Check user permission to edit pet's data. log the error
			 */
			if( Security::checkByUid( Security::ROLE_USER, $_SESSION['uid'] ) == false ){
				$layout->set ( "message-box", $bs->message( LANG_SECURITY_ACCESS_DENIED, Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('pet.php', 3500) );
				Watchdog::write( 'Access denied ', 'attempt to modify pet data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
				break;
			}
			
			
			// $pet_logic			= '<script type="text/javascript" src="assets/js/pet.logic.js"></script>';
			// $pet_form			= pet_form( $pid );
			// $pet_form_submit	= $bs->addButton( 'save', _("save"), _("save"), "$('#form-pet-form').submit()" );
		
			
			$pet_form = $bs->openForm( 'pet-form', $_SERVER['PHP_SELF'] . '?op=s&pid=' . $pid, 'POST', '', 'data-parsley-validate' );
			$pet_form .= pet_form_elements( $pid );
			$pet_form .= $bs->addSubmit( 'save', _("save") );
			$pet_form .= $bs->closeForm();
			
			// @todo: delete pet or logically set a status = 0 ??? what about their visit ? by now we don't allow deleteing...
			/*
			$pet_form_delete 		= $bs->addButton( 'delete', 'delete' );
			$pet_form_delete_logic = $bs->confirm('button-delete', _( 'Do you want to delete (deactivate) selected pet ?' ), $_SERVER['PHP_SELF'] . '?op=d&oid=' . $oid);
			*/
			
			$layout_pet->set( "generic-content", $pet_form );
			
			// assign form output to the content container
			$layout->set ( "content", $layout_pet->output() );
			
			break;
		
		case 's':
			if( Security::checkByUid( Security::ROLE_USER, $_SESSION['uid'] ) == false ){
				$layout->set ( "message-box", $bs->message( LANG_SECURITY_ACCESS_DENIED, Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('pet.php', 3500) );
				Watchdog::write( 'Access denied ', 'attempt to modify pet data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
				break;
			}
			
			
			$p->tsn								= Data::getPost( 'species' );
			$p->oid								= Data::getPost( 'oid', 0 );
			$p->name							= Data::getPost( 'name' );
			$p->gender							= Data::getPost( 'gender' );
			$p->date_of_birth_timestamp			= Data::isNull( Data::DateToUnixTimestamp( Data::getPost( 'date_of_birth' ) ), 'NULL');
			$p->date_of_green_meadows_timestamp	= Data::isNull( Data::DateToUnixTimestamp( Data::getPost( 'date_of_green_meadows' ) ), 'NULL');
			$p->description						= Data::getPost( 'description' );
			$p->color							= Data::getPost( 'color' );
			$p->microchip						= Data::getPost( 'microchip' );
			$p->microchip_timestamp				= Data::isNull( Data::DateToUnixTimestamp( Data::getPost( 'microchip-date' ) ), 'NULL' );
			$p->microchip_location				= Data::getPost( 'microchip-location' );
			$p->tatuatge						= Data::getPost( 'tatuatge' );
			$p->tatuatge_timestamp				= Data::isNull( Data::DateToUnixTimestamp( Data::getPost( 'tatuatge-date' ) ), 'NULL' );
			
			$rv = $p->save();
			
			if($rv == true){
				// set a global message
				$message->set( _( "Pet saved" ), Message::MESSAGE_TYPE_SUCCESS);
				$layout->set ( "content", $bs->dialog( _( "Saving Pet" ) ) . $bs->redirect('pet.php', 3000) );
			}else{
				Watchdog::write( Watchdog::TYPE_DATABASE, 'cannot save pet data', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
				$layout->set ( "message-box", $bs->message( _("Cannot save Pet. Please check form again or contact application support."), Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('pet.php?op=f&pid=' . $p->pid, 3500) );
			}
			break;
		
		case 'd':
			/**
			 * Check user permission to delete pet. Show a message and log the error
			 */
			if( Security::checkByUid( Security::ROLE_USER, $_SESSION['uid'] ) == false ){
				$layout->set ( "message-box", $bs->message( LANG_SECURITY_ACCESS_DENIED, Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('pet.php', 3500) );
				Watchdog::write( 'Access denied ', 'attempt to delete pet', $_SESSION['uid'], Watchdog::WATCHDOG_WARNING );
				break;
			}
			
			$rv = $o->delete();
			
			if($rv == true){
				// set a global message
				$message->set(LANG_OWNER_FORM_DELETE_SUCCESS, Message::MESSAGE_TYPE_SUCCESS);
				$layout->set ( "content", $bs->dialog(LANG_OWNER_FORM_DELETE_IN_PROGRESS) . $bs->redirect('pet.php', 3000) );
			}else{
				$layout->set ( "message-box", $bs->message( LANG_OWNER_FORM_DELETE_ERROR, Bootstrap::ALERT_DANGER, 3000 ));
				$layout->set ( "content", $bs->redirect('pet.php?op=f&uid=' . $u->uid, 3500) );
			}
			
			break;
		
		default:
			// $p = Connection::entity_load('pets', array('pid', 'name', 'microchip', 'description', 'color'), array(), 'name ASC');
			
			$con = new Connection();
			$sql = "SELECT 
						p.pid, 
						p.name, 
						b.familiar_name as species, 
						p.microchip, 
						p.description, 
						p.color as color
					FROM pets p, species b
					WHERE p.tsn = b.tsn";
		
			$pets = $con->execute( $sql );
			
			unset($con);
			unset($sql);
			
			// create a Datatable object and populate with data taken from User table
			$DT = new Datatable('pets');
			
			// populate datatable
			$DT->addRows($pets);
			
			/**
			 * Check user permission to create table action.
			 */
			if( Security::checkByUid( Security::ROLE_USER, $_SESSION['uid'] ) == true ){
				$DT->addAction( _( 'edit' ), $_SERVER['PHP_SELF'] . '?op=f&pid=%s', array('pid'));
				$DT->addAction( _( 'visit' ), 'visit.php?pid=%s', array('pid'));
			}
			// @todo: add a View action
			// $DT->addAction('view', $_SERVER['PHP_SELF'] . '?op=view&uid=%s', array('pid'));
			
			// render the Datatable object and put the HTML output into a variable
			$output = $DT->output();
			
			if( Security::checkByUid( Security::ROLE_USER, $_SESSION['uid'] ) == true ){
				$output .= '<a href="'.$_SERVER['PHP_SELF'].'?op=f">' . $bs->addButton('add', 'add') . '</a>';
			}
			
			
			$layout_pet->set( "generic-content", $output );
			
			// assign form output to the content container
			$layout->set ( "content", $layout_pet->output() );
			break;
	}
	
	
	
	
	/**
	 * Set page layout
	 */
	$layout->set ( "section-name", _( "Pets" ) );
	
	// create the search input using Typeahead suggestion library
	$search_logic = '<script type="text/javascript" src="assets/js/search.logic.js"></script>';

	$bso = new BootstrapInput( 'input-search', '' );
	$bso->placeholder = _('Search...');
	$search_input = $bso->output();

	$layout->set ( "search", $search_logic . $search_input );

	
	/**
	 * Outputs the page with the set Layout.
	 */
	echo template_common_header();
	echo $layout->output();
	echo template_common_footer();
?>
