<?php
/**
 * Core Function of Villa Portal
 */
Class VillaPortal {

    /**
     * URL to back to the last page, usefull for redirect header
     * @var string
     */
    public $linkBack;

    /**
     * Url Admin, usefull to set redirect
     * <br />eg. /wp-admin/admin.php?page=vp-property
     * @var string 
     */
    public $urlAdmin;

    /**
     * Property ID
     * @var array|bool Property ID
     */
    public $propertyIdentifier;

    /**
     * Array of Configuration
     * @var array
     */
    public $config;

    /**
     * Array of Plugin PATH
     * @var array
     */
    public $path;

    /**
     * array of link page
     * @var string
     */
    public $linkpage;

    // Construct
    function VillaPortal($path, $linkpage) {
		// Configuration
		$query = 'SELECT * FROM `vm_sys_config`';
		$result = mysql_query($query);
		
		while ( $row = mysql_fetch_assoc($result) ) {
			$this->config = array( $row['config_name'] => $row['config_value'] );
		}

		// Path
		$this->path = $path;
		$this->path['dir_tpl'] = $this->path['dir'].'templates/'.$this->config['tpl_dir'].'/';
		$this->path['dir_inc'] = $this->path['dir'].'includes/';
		$this->path['url_tpl'] = $this->path['url'].'templates/'.$this->config['tpl_dir'].'/';
		$this->path['url_ico'] = $this->path['url'].'icon/';

		// linkpage
		$this->linkpage = $linkpage;

		// Load Extention
		$this->loadExtention('DBAPI');
    }

     function loadExtention($extName, $arrConstruct=null){
	$construct = ($arrConstruct)? implode(', ', $arrConstruct) : $arrConstruct;

	// Database API
	switch ($extName){
	    case 'DBAPI' :
		if(!require $this->path['dir_inc'].'inc.db.php')
			return false;
		$this->db = new DBAPI;
		return true;
		break;
	    case 'Property':
		if(!require $this->path['dir_inc'].'inc.property.php')
			return false;
		$this->property = new Property($construct);
		$this->propertyIdentifier =& $this->property->identifier;
		return true;
		break;
	    case 'Room':
		if(!require_once $this->path['dir_inc'].'inc.room.php')
			return false;
		$this->room = new Room($construct);
		$this->propertyIdentifier =& $this->property->identifier;
		return true;
		break;
	    default:
		return false;
		break;
	}
    }

    function listLocation() {
	$resultCountry = mysql_query("
	    SELECT *
	    FROM `vm_sys_location`
	    WHERE `loc_parent` = '0'
	    ");

	if (mysql_num_rows($resultCountry) != 0 ) {
	    echo '<ul class="list-location">';
	    while ( $row = mysql_fetch_assoc($resultCountry) ) {
		echo '<li>';
		echo '<span>'.$row['loc_name'].'
			<a href="?page=vp-config-country&mode=addlocation&do=add&parent='.$row['loc_id'].'">
			    <img src="'.$this->path['url_ico'].'action_add.png" title="Add Child" />
			</a>
			<a href="?page=vp-config-country&mode=addlocation&do=edit&id='.$row['loc_id'].'">
			    <img src="'.$this->path['url_ico'].'file.png" title="Edit" />
			</a>
			<a href="?page=vp-config-country&mode=deletelocation&id='.$row['loc_id'].'">
			    <img src="'.$this->path['url_ico'].'action_delete.png" title="Delete" />
			</a>
			</span>';

		$resultArea = mysql_query('
		    SELECT *
		    FROM `vm_sys_location`
		    WHERE `loc_parent` = \''.$row['loc_id'].'\'
		    ');
		if ( mysql_num_rows($resultArea) != 0) {
		    echo '<ul>';
		    while ( $rowArea = mysql_fetch_assoc($resultArea) ) {
			echo '<li>';
			echo '<span>'.$rowArea['loc_name'].'
				<a href="?page=vp-config-country&mode=addlocation&do=add&parent='.$rowArea['loc_id'].'">
				    <img src="'.$this->path['url_ico'].'action_add.png" title="Add Child" />
				</a>
				<a href="?page=vp-config-country&mode=addlocation&do=edit&id='.$rowArea['loc_id'].'">
				    <img src="'.$this->path['url_ico'].'file.png" title="Edit" />
				</a>
				<a href="?page=vp-config-country&mode=deletelocation&id='.$rowArea['loc_id'].'">
				    <img src="'.$this->path['url_ico'].'action_delete.png" title="Delete" />
				</a>
			</span>';

			$resultCity = mysql_query('
			    SELECT *
			    FROM `vm_sys_location`
			    WHERE `loc_parent` = \''.$rowArea['loc_id'].'\'
			    ');
			if ( mysql_num_rows($resultCity) != 0 ) {
			    echo '<ul>';
			    while ( $rowCity = mysql_fetch_assoc($resultCity) ) {
				echo '<li>'.$rowCity['loc_name'].'
				    <a href="?page=vp-config-country&mode=addlocation&do=edit&id='.$rowCity['loc_id'].'">
					<img src="'.$this->path['url_ico'].'file.png" title="Edit" />
				    </a>
				    <a href="?page=vp-config-country&mode=deletelocation&id='.$rowCity['loc_id'].'">
					<img src="'.$this->path['url_ico'].'action_delete.png" title="Delete" />
				    </a>
				    </li>';
			    }
			    echo '</ul>';
			}

			echo '</li>';
		    }

		    echo '</ul>';
		}
		echo '</li>';
	    }
	    echo '</ul>';
	}	
    }    

    function saveLocation($callback){
		$data['loc_id']	    = $_POST['thisId'];
		$data['loc_parent'] = $_POST['parentId'];
		$data['loctype_id'] = $_POST['thisTypeId'];
		$data['loc_name']   = $_POST['thisName'];

		if ($data['loc_id'] == '') { // mode Add
			$data['loc_id'] = 'null';
			$this->db->insert('vm_sys_location', $data);
		} else { // mode edit	    
			$this->db->update('vm_sys_location', $data, 'loc_id='.$data['loc_id']);
		}

		header('Location: '.$callback);
    }

    function deleteLocation($id, $callback) {
		$data['loc_id']	= $_GET['id'];
		$this->db->delete('vm_sys_location', "loc_id=$id");

		header('Location: '.$callback);
    }

    function formAddLocation($target) {
	if ($_GET['do'] == 'add') {
	    $parent = ( isset($_GET['parent']) )? $_GET['parent'] : 0;
	    $parentId = $parent;
	    $thisId = '';
	    $thisName = '';
	    if ($parent==0){
		$thisTypeId = 1;
	    } else {		
		$thisTypeId = $this->getLocType($parent)+1;		
	    }
	} else if ($_GET['do'] == 'edit') {
	    $id = $_GET['id'];
	    $parentId = $this->getLocation($id, 'loc_parent');
	    $thisTypeId = $this->getLocation($id, 'loctype_id');
	    $thisId = $this->getLocation($id, 'loc_id');
	    $thisName = $this->getLocation($id, 'loc_name');
	}
	
	$search = array(
	    'target' => $target,
	    'thisId' => $thisId,
	    'parentId' => $parentId,
	    'thisTypeId' => $thisTypeId,
	    'thisName' => $thisName
	    );
	
	$return = $this->parseChunk('form-addlocation.php', $search, '[+', '+]'); //
	print $return;
	
    }

    function getLocation ($loc_id, $field) {
	$result = $this->dbResult('vm_sys_location', $field, "loc_id=$loc_id");
	while ($row = mysql_fetch_assoc($result)) {
	    $return = $row[$field];
	}

	return $return;
	mysql_free_result($result);
    }

    function getLocType ($loc_id) {
	$result = $this->dbResult('vm_sys_location', '*', "loc_id=$loc_id");
	while ($row = mysql_fetch_assoc($result)) {
	    $return = $row['loctype_id'];
	}

	return (int)$return;
    }
    
    function getListLocation($tpl, $parent=0) {
	$result = $this->dbResult('vm_sys_location', '*', "loc_parent=$parent");
	
	if ( mysql_num_rows($result) != 0 ) {	    
	    while ( $row = mysql_fetch_assoc($result) ) {
		$return .= $this->parseChunk($tpl, array('id' => $row['loc_id'],
							'name' => $row['loc_name']) );		
	    }
	}

	return $return;
	mysql_free_result($result);
    }

    function dbResult ($table, $select, $condition='', $limit='', $orderBy='') {
	$table = "FROM $table ";
	$select = "SELECT $select ";
	$condition = ($condition != '')? "WHERE $condition " : $condition;
	$limit = ($limit != '')? "LIMIT $limit " : $limit;
	$orderBy = ($orderBy != '')? "ORDER BY $orderBy " : $orderBy;

	$query = $select.$table.$condition.$orderBy.$limit;
	return mysql_query($query);
    }

    /**
     * Show List Property
     * @param string $tpl Template
     * @param string $tplWrap Template Wrap
     * @param int $limit Limit Show, DEFAULT: NULL
     * @return string
     */
    function propertyList($tpl, $tplWrap, $limit=null) {
	$fetch = $this->db->fetch('vm_property');
	
	foreach ($fetch as $key=>$value) {
	    $fetch[$key] = $this->addPropertyKey($value);
	}

	foreach ($fetch as $value) {
	    $data .= $this->parseChunk($tpl, $value);
	}
	$property['list'] = $data;
	$property['urlAdd'] = $this->linkpage['property'].'&show=propertyedit';
	$template = $this->parseChunk($tplWrap, $property);
	return $template;
    }
    
    function propertyEdit($tpl) {
	if($this->propertyIdentifier){
	    $fetch = $this->property->data;
	}else{
	    $fieldName = $this->db->getTableFields('vm_property');
	    while ($row = mysql_fetch_assoc($fieldName) ){
		$fetch[ $row['Field'] ] = '';
	    }	    
	}

	// Aditional Data
	$fetch['listCountry']	= $this->getFormLocation(1, 'country', 'country');
	$fetch['listProvince']	= $this->getFormLocation(3, 'province', 'province');
	$fetch['listCity']	= $this->getFormLocation(4, 'city', 'city');
	$fetch['formAction']	= '?page=vp-property&show=action&action=update&id='.$this->propertyIdentifier;
	
	$return = $this->parseChunk($tpl, $fetch);
	return $return;
    }

    function getFormLocation($typeLocation, $className, $selectName){
	$fetch = $this->db->fetch('vm_sys_location', '*', 'loctype_id='.$typeLocation);
	if ( count($fetch) ){
	    $return = '<select class="'.$className.'" name="'.$selectName.'">';
	    $return .= '<option value="">------</option>';
	    foreach($fetch as $value){
		if ( $value['loc_id'] == $this->property->getLocationIdByType($typeLocation) ){
		    $return .= '<option value="'.$value['loc_id'].'" selected="selected">'.$value['loc_name'].'</option>';
		}else{
		    $return .= '<option value="'.$value['loc_id'].'">'.$value['loc_name'].'</option>';
		}
	    }
	    $return .= '</select>';
	}
	return $return;
    }

    function addPropertyKey($data) {
	$id = $data['id'];
	$data['link'] = $this->linkpage['property'].'&show=property'."&id=$id";
	$data['actionEdit'] = $this->linkpage['property'].'&show=propertyedit'."&id=$id";
	$data['actionDelete'] = $this->linkpage['property'].'&show=action'.'&action=delete'."&id=$id";
	$data['actionViewRoom'] = $this->linkpage['property'].'&show=property'."&id=$id";
	$data['action'] = $this->getIcon(
			    'icon.php',
			    array('viewroom','edit','delete'),
			    array($data['actionViewRoom'],$data['actionEdit'], $data['actionDelete'])
			);
	return $data;
    }

    

    function getIcon($tpl, $arrIcon, $arrLinkAction) {
	$path = $this->path['url_ico'];
	$listIcon   = array(
			'delete'    => $path.'action_delete.png',
			'edit'	    => $path.'file.png',
			'viewroom'  => $path.'application.png',
			'setPrice'  => $path.'reply.png'
			);
	foreach ($arrIcon as $key=>$value) {
	    $data['name']   = $value;
	    $data['image']  = $listIcon[$value];
	    $data['link']   = $arrLinkAction[$key];
	    $return .= $this->parseChunk($tpl, $data);
	}

	return $return;
    }

    /*------- Chunk Template System ----------*/    
    function parseChunk($chunkName, $chunkArr, $prefix= "[+", $suffix= "+]") {
        if ( !is_array($chunkArr) ) {
            return false;
        }	
        $chunk = $this->getChunk($chunkName);
        foreach ($chunkArr as $key=>$value) {
            $chunk = str_replace($prefix.$key.$suffix, $value, $chunk);
        }
        return $chunk;
    }

    function getChunk($chunkName) {
	$read = $this->path['dir_tpl'].$chunkName;
	
	if ( file_exists($read) ) {
	    $content = file_get_contents($read);
	} else {
	    return false;
	}
	
	return $content;
    }

    /**
     *	Print Document Parser
     * @param string $tpl Template Name
     * @param array $arrData Data to be sent
     */
    function parser($tpl, $arrData) {
	print $this->parseChunk($tpl, $arrData);
    }

    function registerCSS(){
	// Register CSS
	wp_register_style('villa-portal-style', $this->path['url_tpl'].'style.css', null, '0.1' );
	wp_enqueue_style('villa-portal-style');
    }

    function registerScript(){
	// Tyny MCE
	wp_register_script('tinymce', $this->path['url'].'extention/tiny_mce/jquery.tinymce.js', null, '0.1' );
	wp_enqueue_script('tinymce');
	
	wp_register_script('villa-portal-script', $this->path['url'].'site.js', null, '0.1' );
	wp_enqueue_script('villa-portal-script');	
    }
    
    function getProperty($tpl, $propertyId=null) {
	$propertyId = ($propertyId)? $propertyId : $this->propertyIdentifier;

	$return = $this->parseChunk($tpl, $this->property->data);
	return $return;
    }

    function propertyUpdate($data) {	
	if( $this->db->update('vm_property', $data, 'id='.$this->propertyIdentifier) ){
	    return true;
	}else{
	    return false;
	}	
    }

    function propertyInsert($data) {
	$this->db->insert('vm_property', $data);
    }

    /**
     * Delete Property
     * @return bool Return true on success
     */
    function propertyDelete() {
	if ($this->propertyIdentifier) {
	    $this->db->delete('vm_property', 'id='.$this->propertyIdentifier);
	    return true;
	}
    }

    function showRoom($tpl, $tplWrap, $limit=null) {
	if ($this->propertyIdentifier) {
	    $return = '<h2>List Room</h2>';
	    $return .= '<a href="'.$this->urlAdmin.'&show=roomaction&roomaction=create&id='.$this->propertyIdentifier.'" class="button">Create Room</a>';
	    $data['listRoom'] = '';	    

	    $result = $this->db->select('vm_room', '*', 'property_id='.$this->propertyIdentifier);
	    if ( mysql_num_rows($result) ) {
		while ( $row =  mysql_fetch_assoc($result) ){
		    $row['url'] = $this->urlAdmin.'&show=roomaction&roomaction=create&id='.$this->propertyIdentifier.'&roomid='.$row['id'];
		    $row['price'] = $this->getRoomPrice($row['id']);
		    $row['action'] = $this->getRoomAction( $row['id'], "<td>%s</td>", $row['url'] );
		    $data['listRoom'] .= $this->parseChunk($tpl, $row);		    
		}
		$return .= $this->parseChunk($tplWrap, $data);
	    }
	    
	    print($return);
	}	
    }

    function getRoomAction($id, $wrap, $linkBase){
	$data['actionEdit'] = $linkBase; //
	$data['actionDelete'] = str_replace('&roomaction=create', '&roomaction=dodelete', $linkBase);
	$data['actionSetPrice'] = str_replace(
				    array('&show=roomaction', '&roomaction=create'),
				    array('&show=roomprice', ''),
				    $linkBase
				    );
	$action = $this->getIcon(
			    'icon.php',
			    array('edit','delete','setPrice'),
			    array($data['actionEdit'],$data['actionDelete'], $data['actionSetPrice'])
			);
	return $action;	
    }

    function getRoomPrice($roomId){
	
    }

    function room_delete($roomId) {
	$this->db->delete('vm_room', 'id='.$roomId);
    }

    function listRate($roomId=null, $yearMonth=null ) {
	$roomId = ($roomId)? $roomId : $this->room->identifier;
	$yearMonth = ($yearMonth)? $yearMonth : $_SESSION['rateDate'];
	$yearMonth = ($yearMonth)? $yearMonth : date('Y-m');

	$rate = $this->room->generateRate($yearMonth);
	foreach ($rate as $value) {
	    $data['listRate'] .= $this->parseChunk('roomrate.php', $value);
	}
	
	$data['link-property'] = $this->urlAdmin.'&show=property&id='.$this->propertyIdentifier;
	$data['link-formaction'] = $this->urlAdmin.'&show=roomprice&roomprice=update&id='.$this->propertyIdentifier.'&roomid='.$this->room->identifier;
	$data['listSelectMonth'] = $this->genSelectMonth();
	$data['listSelectYear'] = $this->genSelectYear();
	
	$return = $this->parseChunk('roomrate-wrap.php', $data);
	return $return;
    }
    
    function genSelectMonth() {
	$monthArry = array(
	    '01' => 'January',
	    '02' => 'February',
	    '03' => 'March',
	    '04' => 'April',
	    '05' => 'May',
	    '06' => 'June',
	    '07' => 'July',
	    '08' => 'August',
	    '09' => 'September',
	    '10' => 'October',
	    '11' => 'November',
	    '12' => 'December'
	);	
	$monthNow = Date('m');	
	foreach ($monthArry as $key=>$value) {
	    $selected = ($key == $monthNow)? 'selected="selected"' : '';
	    $return .= '<option value="'.$key.'" '.$selected.'>'.$value.'</option>';
	}
	return $return;
    }
    
    function genSelectYear() {
	$year = (int)Date('Y');	
	for ($i=0; $i < 4; $i++) {
	    $yearIncrement = $year + $i;
	    $return .= '<option value="'.$yearIncrement.'">'.$yearIncrement.'</option>';
	}	
	return $return;
    }
    
    function configListFacility() {
	$i = 1;
	$result = $this->db->select('vm_facility');
	if( mysql_num_rows($result) ) {
	    $data = $this->db->fetch('vm_facility');
	    foreach($data as $key=>$value) {
		$data[$key]['actionDelete'] = '<a href="/wp-admin/admin.php?page=vp-config-facility&action=delete&id='.$data[$key]['id'].'">
					    <img src="'.$this->path['url_ico'].'action_delete.png" /></a>';
	    }
	    $i++;
	}
	foreach ($data as $key=>$value) {
	    $parser['listFacility'] .= $this->parseChunk('config-facility.php', $value);
	}
	
	$return = $this->parseChunk('config-facility-wrap.php', $parser);
	print($return);
    }
    
    function showFacility(){
	if ( $_POST['action'] == 'facility' ) {
	    unset($_POST['action']);
	    $this->propertyFacilityUpdate($_POST);
	}
	
	$data['title'] = 'Facility';
	$data['propertyId'] = $this->propertyIdentifier;
	$data['listFacility'] = $this->genListFacility();
	$return = $this->parseChunk('facility-wrap.php', $data);
	print $return;
    }
    
    function genListFacility() {
	$arrFacility = $this->db->fetch('vm_facility');
	$arrPropertyFacility = explode(',', $this->db->result('vm_property', 'facility', 'id='.$this->propertyIdentifier));
	foreach ($arrFacility as $facility) {
	    foreach ($arrPropertyFacility as $propertyFacility) { // Check if the Facility ID is included in this property facility
		if ($facility['id'] == $propertyFacility) {
		    $facility['checked'] = 'checked="checked"';
		    break;
		}else{
		    $facility['checked'] = '';
		}		
	    }
	    $return .= $this->parseChunk('facility.php', $facility);
	}
	return $return;
    }
    
    function propertyFacilityUpdate($data) {
		$data = implode(',', $data['facility']);
		$update['facility'] = $data;
		$this->db->update('vm_property', $update, 'id='.$this->propertyIdentifier, $debug=false);	
    }
}
?> 