<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

	require "../_container/container_top.php";
	require_once ('business/LeaseContentMgr.php');
	require_once ('business/TenancyMgr.php');
	require_once("config/Tagger.php");

	$leaseContentMgr = new LeaseContentMgr();
	$tenancyMgr = new TenancyMgr();
	$tagger = new Tagger();
	
	$action = getPost('action');

	$selectTenancy = getPost('selectTenancy');
	$arrTenancy = $tenancyMgr->getTenancys();
	if (count($arrTenancy) == 0) {
	?>
		<div class="alert alert-error">
			<h1><small><?php echo $tr->translate("msgNoTenancy"); ?></small></h1>
			<p><?php echo $tr->translate("msgAddTenancy"); ?></p>
			<p class="">
				<a href="tenancyDetail.php" class="btn btn-large btn-primary"><i class="icon-chevron-left icon-white"></i> <?php echo $tr->translate("AddTenancy"); ?></a>
			</p>
			<div class="clearfix"></div>
		</div>
	<?php
	}else{

		if (empty($selectTenancy)){
			$selectTenancy = $arrTenancy[0]->tenancy_id;
		}

		function getDesc($description) {
			foreach ($_POST as $l => $w) {
				$descID = str_replace("desc_myDiv", "", $l);
				if (is_numeric($descID)) {
					if ($description == $descID) {
						return $w;
					}
				}
			}
		}
		if (!empty($action) && ($action == "update" || $action == "save" || $action == "delete_lease" || $action == "copy" || $action == "add_image" || $action == "add_signing" || $action == "delete_image" || $action == "delete_signing")) {
			if ($action == "update" || $action == "save") {
				$index = '0';
				$res = $leaseContentMgr->deleteLeaseByTenancy($selectTenancy);
				foreach ($_POST as $k => $v) {
					$h_ID = str_replace("header_myDiv", "", $k);
					if (is_numeric($h_ID)) {
						$index = $index + 1;
						$head = $v;
						$desc = getDesc($h_ID);
						$res = $leaseContentMgr->addBlock($selectTenancy, $index, $head, $desc);
					}
				}
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}
			if ($action == "delete_lease") {
				$res = $leaseContentMgr->deleteLeaseByTenancy($selectTenancy);
				if ($res > 0) {
					$msgType = "success";
					$msg = $tr->translate("msgSuccess");
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
			}
			if ($action == "copy") {
				$res = $leaseContentMgr->deleteAllLeaseExcept($selectTenancy);
				$curLease = $leaseContentMgr->getLease($selectTenancy);
				foreach ($arrTenancy as $tenancy) {
					if ($tenancy->tenancy_id <> $selectTenancy) {
						foreach ($curLease as $lease){
							$res = $leaseContentMgr->addBlock($tenancy->tenancy_id, $lease->position, $lease->header, $lease->content);
						}
						if (!empty($_POST['cbLogo']) &&  ($_POST['cbLogo'] == 'yes')){
							copy(LEASE_IMAGE_PATH . "/lease_" . $selectTenancy . ".jpg", LEASE_IMAGE_PATH . "/lease_" . $tenancy->tenancy_id . ".jpg");
						}
						if (!empty($_POST['cbSigning']) &&  ($_POST['cbSigning'] == 'yes')){
							copy(LEASE_IMAGE_PATH . "/signing_" . $selectTenancy . ".jpg", LEASE_IMAGE_PATH . "/signing_" . $tenancy->tenancy_id . ".jpg");
						}
					}
				}
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}

			if ($action == "add_image") {
				require_once("lib/myUpload.php");
				$upload = new MYUPLOAD('uploadfile_image');
				$upload->set_directory(ROOT . "data/img/lease");
				$upload->set_file_name("lease_" . $selectTenancy . ".jpg");
				$res = $upload->copy_file();
				if ($res && ($res[0] != 'error')){
					$msgType = $res[0];
					$msg = $res[1];
					$upload->resize(200,100);
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
			}
			if ($action == "add_signing") {
				require_once("lib/myUpload.php");
				$upload = new MYUPLOAD('uploadfile_signing');
				$upload->set_directory(ROOT . "data/img/lease");
				$upload->set_file_name("signing_" . $selectTenancy . ".jpg");
				$res = $upload->copy_file();
				if ($res && ($res[0] != 'error')){
					$msgType = $res[0];
					$msg = $res[1];
					$upload->resize(200,50);
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
			}
			if ($action == "delete_image") {
				if(file_exists(LEASE_IMAGE_PATH . "/lease_" . $selectTenancy . ".jpg")){
					$res = unlink(LEASE_IMAGE_PATH . "/lease_" . $selectTenancy . ".jpg");
					if ($res){
						$msgType = "success";
						$msg = $tr->translate("msgSuccess");
					}else{
						$msgType = "error";
						$msg = $tr->translate("msgError") . ": " . $e->getMessage() ;
					}
				}
			}
			if ($action == "delete_signing") {
				if(file_exists(LEASE_IMAGE_PATH . "/signing_" . $selectTenancy . ".jpg")){
					$res = unlink(LEASE_IMAGE_PATH . "/signing_" . $selectTenancy . ".jpg");
					if ($res){
						$msgType = "success";
						$msg = $tr->translate("msgSuccess");
					}else{
						$msgType = "error";
						$msg = $tr->translate("msgError");
					}
				}
				
			}
			echo '<div class="alert alert-' . $msgType . '">
				<strong>' . $msg . '</strong>
				</div>';
		}

		$arrLeaseContent = $leaseContentMgr->getLease($selectTenancy);

	?>
		<div>
			<ul class="breadcrumb">
				<li><a href="./"><?php echo $tr->translate("menuHome"); ?></a> <span class="divider">/</span></li>
				<li class="active"><?php echo $tr->translate("menuLease"); ?></li>
			</ul>
		</div>
		<div class="sortable row-fluid">
			<a data-rel="tooltip" title="<?php echo $tr->translate('AddReserv'); ?>" class="well span2 top-block btn-action" href="#" name="newReservation" id="newReservation" _page="reservationDetail.php" _action="Add">
				<i class="icon-red icon-user"></i>
				<div><?php echo $tr->translate("AddReserv"); ?></div>
				<div></div>
			</a>
			<a data-rel="tooltip" title="<?php echo $tr->translate("AddPayment"); ?>" class="well span2 top-block btn-action" href="#" name="newPayment" id="newPayment" _page="paymentDetail.php" _action="Add">
				<i class="icon-cog"></i>
				<div><?php echo $tr->translate("AddPayment"); ?></div>
				<div></div>
			</a>
		</div>
	<form enctype="multipart/form-data" class="form-horizontal" method="post" name="filterForm" id="filterForm" action="lease.php">
	<input type="hidden" id="action" name="action" value="">
	<input type="hidden" id="selectTenancy" name="selectTenancy" value="<?php echo $selectTenancy; ?>">
	<input type="hidden" id="theValue" name="theValue" value="<?php echo count($arrLeaseContent); ?>" />

		<div class="row-fluid sortable">
			<div class="box span12">
				<div class="box-header well" data-original-title>
					<h2><i class="icon-picture"></i> <?php echo $tr->translate("thTagList"); ?></h2>
					<div class="box-icon">
						<a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-down"></i></a>
					</div>
				</div>
				<div class="box-content" style="display:none;">
					<div class="tabbable">
						<ul class="nav nav-tabs">
							<?php $arrTags = Tagger::getTagList(); foreach ($arrTags as $tag) { ?>
								<li class="<?php if (reset($arrTags) == $tag) echo "active"; ?>"><a href="#tag_<?php echo $tag; ?>" data-toggle="tab"><?php echo $tr->translate('tagName_'.$tag); ?></a></li>
							<?php } ?>
						</ul>
						<div class="tab-content">
						<?php $arrTags = Tagger::getTagList(); foreach ($arrTags as $tag) { ?>
							<div class="tab-pane <?php if (reset($arrTags) == $tag) echo "active"; ?>" id="tag_<?php echo $tag; ?>">
								<table id="tableLeasetagList" name="tableLeaseTagList" class="table table-bordered table-striped table-condensed">
									<thead>
										<tr>
											<th style="width:55px;"><?php echo $tr->translate("thTagName"); ?></th>
											<th><?php echo $tr->translate("thTagDescription"); ?></th>
										</tr>
									</thead>
									<tbody>
									<?php foreach(Tagger::getTag($tag) as $tagName){ ?>
										<tr><td><code><?php echo htmlentities($tagName); ?></code></td>
											<td><?php echo $tr->translate($tagName); ?></td></tr>
									<?php } ?>
									</tbody>
								</table>
							</div>
						<?php } ?>
						</div>
					</div>
				</div>
			</div><!--/span-->
		</div><!--/row-->

		<div class="row-fluid sortable">
			<div class="box span12">
				<div class="box-header well" data-original-title>
					<h2><i class="icon-user"></i> <?php echo $tr->translate('Filter'); ?></h2>
				</div>
				<div class="box-content">
					
					<fieldset>
						<div class="control-group">
							<label class="control-label" for="focusedInput"><?php echo $tr->translate('thLeaseTenancy'); ?></label>
							<div class="controls input-medium">
								<select id="selectTenancy" name="selectTenancy" data-rel="chosen" class="filter-action">
									<?php $tenancy_img = $arrTenancy[0]->imagepath;
										$tenancy_name = $arrTenancy[0]->name;
										foreach ($arrTenancy as $tenancy) {
										echo "<option value='" . $tenancy->tenancy_id . "'";
										if ($selectTenancy == $tenancy->tenancy_id) {echo " selected";$tenancy_img = $tenancy->imagepath;$tenancy_name = $tenancy->name;}
										echo ">" . $tenancy->name . "</option>";
									} ?>
								</select>
							</div>
						</div>
						<div class="control-group">
							<div class="controls">
								<button class="btn btn-warning btn-mini" id="copy" name="copy" onclick="goAction('copy')"><?php echo $tr->translate('btnLeaseCopy'); ?> <i class=" icon-white icon-retweet"></i> </button>
								<?php
									if (is_file(LEASE_IMAGE_PATH . "/lease_" . $selectTenancy . ".jpg")) {
										echo '(<input type="checkbox" id="cbLogo" name="cbLogo" value="yes" />' . $tr->translate('msgIncludeLogo') . ')';
									}
									if (is_file(LEASE_IMAGE_PATH . "/signing_" . $selectTenancy . ".jpg")) {
										echo '(<input type="checkbox" id="cbSigning" name="cbSigning" value="yes" />' . $tr->translate('msgIncludeSigning') . ')';
									}
								?>
								<?php echo $tr->translate('thLeaseCopyText'); ?> <strong><?php echo $tr->translate('thLeaseNonReverseOperation'); ?></strong>
							</div>
							<div class="controls">
								<button class="btn btn-warning btn-mini" id="delete_lease" name="delete_lease" onclick="goAction('delete_lease')"><?php echo $tr->translate('btnLeaseDelete'); ?> <i class=" icon-white icon-trash"></i> </button> <strong><?php echo $tr->translate('thLeaseNonReverseOperation'); ?></strong>
							</div>
						</div>
						
						<div class="control-group">
							<label class="control-label" for="currentImage"><?php echo $tr->translate('thLeaseCurrentImage'); ?></label>
							<div class="controls">
								<?php if (is_file(LEASE_IMAGE_PATH . "/lease_" . $selectTenancy . ".jpg")) { ?>
									<img src='<?php echo LEASE_IMAGE_PATH_RESS."/lease_";?><?php echo $selectTenancy;?>.jpg' />
									<button class="btn btn-danger btn-mini" id="delete_image" name="delete_image" onclick="goAction('delete_image')"><?php echo $tr->translate('btnLeaseDeleteImage'); ?> <i class=" icon-white icon-trash"></i> </button>
								<?php }else{ ?>
									<span class='info'><?php echo $tr->translate('thLeaseImageNotDefined'); ?></span>
								<?php } ?>
							</div>
						</div>
						<div class="control-group">
							<div class="controls">
								<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo UPLOAD_FILE_SIZE; ?>" />
								<input type="file" id="uploadfile_image" name="uploadfile_image" size="24" title="<?php echo $tr->translate("ChooseFileTitle"); ?>" />
								<span class='info'><?php echo $tr->translate("thLeaseFileInfo"); ?></span>
							</div>
							<label class="control-label"></label>
							<div class="controls">
								<button class="btn btn-primary btn-mini" id="add_image" name="add_image" onclick="goAction('add_image')"> <?php echo $tr->translate('btnLeaseNewImage'); ?> <i class=" icon-white  icon-picture"></i> </button>
							</div>
						</div>

						<div class="control-group">
							<label class="control-label" for="currentImage"><?php echo $tr->translate('thLeaseSigningCurrentImage'); ?></label>
							<div class="controls">
								<?php if (is_file(LEASE_IMAGE_PATH . "/signing_" . $selectTenancy . ".jpg")) { ?>
									<img src='<?php echo LEASE_IMAGE_PATH_RESS."/signing_";?><?php echo $selectTenancy;?>.jpg' />
									<button class="btn btn-danger btn-mini" id="delete_signing" name="delete_signing" onclick="goAction('delete_signing')"><?php echo $tr->translate('btnLeaseSigningDeleteImage'); ?> <i class=" icon-white icon-trash"></i> </button>
								<?php }else{ ?>
									<span class='info'><?php echo $tr->translate('thLeaseSigningImageNotDefined'); ?></span>
								<?php } ?>
							</div>
						</div>
						<div class="control-group">
							<div class="controls">
								<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo UPLOAD_FILE_SIZE; ?>" />
								<input type="file" id="uploadfile_signing" name="uploadfile_signing" size="24" title="<?php echo $tr->translate("ChooseFileTitle"); ?>" />
								<span class='info'><?php echo $tr->translate("thLeaseSigningFileInfo"); ?></span>
							</div>
							<label class="control-label"></label>
							<div class="controls">
								<button class="btn btn-primary btn-mini" id="add_image" name="add_image" onclick="goAction('add_signing')"> <?php echo $tr->translate('btnLeaseSigningNewImage'); ?> <i class=" icon-white  icon-picture"></i> </button>
							</div>
						</div>
					</fieldset>
				</div>
			</div>
		</div>
		<?php if (isset($arrLeaseContent)) { ?>
		<div class="row-fluid sortable">
			<div class="box span12">
				<div class="box-header well" data-original-title>
					<h2><i class="icon-user"></i> <?php echo $tr->translate("thLease"); ?></h2>
				</div>
				<div class="box-content">

						<button class="btn btn-primary" id="add" name="add" onclick="goAction('add')"><?php echo $tr->translate("thLeaseActionAdd"); ?> <i class="icon-white icon-plus"></i> </button>
						<button class="btn btn-primary" id="save" name="save" onclick="goAction('save')"><?php echo $tr->translate("thLeaseActionSave"); ?> <i class="icon-white icon-ok-sign"></i> </button>
						<button class="btn btn-success" id="preview" name="preview" onclick="goAction('preview')"><?php echo $tr->translate("thLeaseActionPreview"); ?> <i class="icon-white icon-zoom-in"></i></button>

						<div id="myDiv" name="myDiv">

							<table id="mainTable" name="mainTable">
							<tbody>
								<?php
									foreach ($arrLeaseContent as $leaseContent) {
								?>
								<tr>
									<td>
										<table>
											<tr>
												<td>
													<input class="input-xxlarge" type="text" id="header myDiv<?php echo $leaseContent->position; ?>" name="header myDiv<?php echo $leaseContent->position; ?>" value="<?php echo $leaseContent->header; ?>">
												</td>
												<td style="text-align:right;">
													<img src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/arrow_up_green.png" height="20" onClick="goAction('');swapRowUp(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)" title="<?php echo $tr->translate("thLeaseBlockUp"); ?>" />
													<img src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/arrow_down_green.png" height="20" onClick="goAction('');swapRowDown(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode)" title="<?php echo $tr->translate("thLeaseBlockDown"); ?>" />
													<img src="<?php echo CONTEXT_ROOT_RESS;?>/styles/img/cancel.png" height="20" onClick="goAction('');deleteRow(this.parentNode.parentNode.parentNode.parentNode)" title="<?php echo $tr->translate("thLeaseBlockDelete"); ?>" />
												</td>
											</tr>
											<tr>
												<td colspan="2">
													<textarea class="input-xxlarge" rows="10" id="desc myDiv<?php echo $leaseContent->position; ?>" name="desc myDiv<?php echo $leaseContent->position; ?>"><?php echo $leaseContent->content; ?></textarea>
												</td>
											</tr>
										</table>
										<p>&nbsp;</p>
									</td>
								</tr>
								<?php } ?>
							</tbody>
							</table>
						</div>

						<button class="btn btn-primary" id="add" name="add" onclick="goAction('add')"><?php echo $tr->translate("thLeaseActionAdd"); ?> <i class="icon-white icon-plus"></i> </button>
						<button class="btn btn-primary" id="save" name="save" onclick="goAction('save')"><?php echo $tr->translate("thLeaseActionSave"); ?> <i class="icon-white icon-ok-sign"></i> </button>
						<button class="btn btn-success" id="preview" name="preview" onclick="goAction('preview')"><?php echo $tr->translate("thLeaseActionPreview"); ?> <i class="icon-white icon-zoom-in"></i></button>
				</div>
			</div><!--/span-->

		</div><!--/row-->
		<?php } ?>
	</form>

		<div class="row-fluid sortable" id="editUser">
		</div><!--/row-->
	<?php } ?>
<?php require "../_container/container_bottom.php"; ?>
<script>
    var mainTable = document.getElementById("mainTable");
    function swapRowUp(chosenRow) {
        if (chosenRow.rowIndex != 0) {
            moveRow(chosenRow, chosenRow.rowIndex-1);
            document.filterForm.submit();
        }
    }
    function swapRowDown(chosenRow) {
        if (chosenRow.rowIndex != mainTable.rows.length-1) {
            moveRow(chosenRow, chosenRow.rowIndex+1);
            document.filterForm.submit();
        }
    }
    //moves the target row object to the input row index
    function moveRow(targetRow, newIndex) {
        //since we are not actually swapping
        //but simulating a swap, have to "skip over"
        //the current index
        if (newIndex > targetRow.rowIndex) {
            newIndex++;
        }
        //establish proper reference to the table
        var mainTable = document.getElementById('mainTable');
        //insert a new row at the new row index
        var theCopiedRow = mainTable.insertRow(newIndex);
        //copy all the cells from the row to move
        //into the new row
        for (var i=0; i<targetRow.cells.length; i++) {
            var oldCell = targetRow.cells[i];
            var newCell = document.createElement("TD");
            newCell.innerHTML = oldCell.innerHTML;
            theCopiedRow.appendChild(newCell);
            copyChildNodeValues(targetRow.cells[i], newCell);
        }
        //delete the old row
        mainTable.deleteRow(targetRow.rowIndex);
    }
    function copyChildNodeValues(sourceNode, targetNode) {
        for (var i=0; i < sourceNode.childNodes.length; i++) {
            try{
                targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
            }
            catch(e){
                                 
            }
        }
    }
	function addRow(tableID) {
		var ni = document.getElementById('mainTable');
		var numi = document.getElementById('theValue');
		var num = document.getElementById("theValue").value + 1;
		numi.value = num;
		var divIdName = "myDiv"+num;

		var table = document.getElementById(tableID);

		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount);
		row.style.display = 'none';
		var cell1 = row.insertCell(0);

		var element1 = document.createElement("input");
		element1.type = "text";
		element1.id = "header " + divIdName;
		element1.name = "header " + divIdName;
		cell1.appendChild(element1);


		var cell3 = row.insertCell(1);
		var element2 = document.createElement("textarea");
		element2.id = "desc " + divIdName;
		element2.name = "desc " + divIdName;
		element2.cols = 80;
		element2.rows = 8;
		cell3.appendChild(element2);

		var element1 = document.createElement("img");
		element1.src = "img/arrow_up.png";
		element1.height="20";
		element1.setAttribute("onClick", "swapRowUp(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);");
		element1.title="<?php echo $tr->translate("thLeaseBlockUp"); ?>";
		cell1.appendChild(element1);

		var element1 = document.createElement("img");
		element1.src = "img/arrow_down.png";
		element1.height="20";
		element1.setAttribute("onClick", "swapRowDown(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);");
		element1.title="<?php echo $tr->translate("thLeaseBlockDown"); ?>";
		cell1.appendChild(element1);

		var element1 = document.createElement("img");
		element1.src = "img/cancel.png";
		element1.height="20";
		element1.setAttribute("onClick", "deleteRow(this.parentNode.parentNode.parentNode.parentNode);");
		element1.title="<?php echo $tr->translate("thLeaseBlockDelete"); ?>";
		cell1.appendChild(element1);

		var element1 = document.createElement("img");
		element1.src = "img/add.png";
		element1.height="20";
		element1.setAttribute("onClick", "addRow(\'mainTable\');");
		element1.title="<?php echo $tr->translate("thLeaseBlockAdd"); ?>";
		cell1.appendChild(element1);

		$("#action").val("update");
		document.filterForm.submit();
	}

	function deleteRow(r) {
		var i=r.parentNode.parentNode.rowIndex;
		document.getElementById('mainTable').deleteRow(i);
		document.filterForm.submit();
	}
	
	$(".filter-action").change(function(){
		$("#filterForm").attr("action", "lease.php");
	});

	function goAction(action) {
		$("#filterForm").attr("action", "lease.php");
		$("#action").val("update");
		if (action == "copy") {
			$("#action").val("copy");
			blockUI();
		}
		if (action == "add") {
			$("#action").val("update");
			addRow('mainTable');
			blockUI();
		}
		if (action == "add_image") {
			$("#action").val("add_image");
			blockUI();
		}
		if (action == "delete_image") {
			$("#action").val("delete_image");
			blockUI();
		}
		if (action == "add_signing") {
			$("#action").val("add_signing");
			blockUI();
		}
		if (action == "delete_signing") {
			$("#action").val("delete_signing");
			blockUI();
		}
		if (action == "save") {
			$("#action").val("update");
			blockUI();
		}
		if (action == "preview") {
			$("#filterForm").attr("action", "leasePreview.php");
			$("#action").val("preview");
			$("#selectTenancy").val("0");
		}
		if (action == "delete_lease") {
			$("#action").val("delete_lease");
			blockUI();
		}
	}
	
</script>