<?php $_SESSION['redirect'] = $_SERVER['REQUEST_URI'];
	//find user id
	$getRoomId = $_GET['room'];
	if($_GET['receipt']){$getExpensesId = $_GET['receipt'];}
?>
<div class="right_col" role="main">
    <div class="">
        <div class="row">
            <div class="col-md-6 col-sm-12 col-xs-12">
                <div class="x_panel">
					<div class="x_title">
						<h2>Expenses Details</h2>
						<div class="clearfix"></div>
					</div>
					<div class="x_content">

						<form class="form-horizontal form-label-left" method="post">

							  <div class="form-group">
								<label class="control-label col-md-2 col-sm-2 col-xs-12">Type</label>
								<div class="col-md-6 col-sm-6 col-xs-12">
								  <select class="form-control" name="type">
									  <?php
									  	$result = mysqli_query($conn, "SELECT * FROM expenses_type");
									  	while($row = mysqli_fetch_assoc($result)){
									  ?>
									<option value="<?php echo $row['et_id']; ?>"><?php echo $row['et_title']; ?></option>
									  <?php } ?>
								  </select>
								</div>
								  <?php $redirectUrl = urlencode("?pagecontent=room_inventory&room=".$getId); ?>
								 <a href="?pagecontent=expenses_type"><button type="button" class="btn btn-primary">Add Type</button></a>
							  </div>
							
							<div class="item form-group">
								<label class="control-label col-md-2 col-sm-2 col-xs-12" for="roomno">Date</label>
							  <div class="col-md-6 col-sm-6 col-xs-12">
								  <?php $date = date("Y-m-d"); if($_GET['date']){ $date = $_GET['date'];} ?>
									<input id="roomno" class="form-control col-md-7 col-xs-12" name="date" type="date" value="<?php echo $date;?>">
							  </div>
							</div>
						
							<div class="item form-group">
								<label class="control-label col-md-2 col-sm-2 col-xs-12" for="roomno">Title</label>
							  <div class="col-md-6 col-sm-6 col-xs-12">
								  
									<input id="roomno" class="form-control col-md-7 col-xs-12" name="title" type="text" value="">
							  </div>
							</div>
							
							<div class="item form-group">
								<label class="control-label col-md-2 col-sm-2 col-xs-12" for="note">Note</span>
								</label>
								<div class="col-md-9 col-sm-9 col-xs-12">
									<textarea id="message" class="form-control" name="note"></textarea>
								</div>
							</div>
						
							<div class="item form-group">
								<label class="control-label col-md-2 col-sm-2 col-xs-12" for="roomno">Amount</label>
							  <div class="col-md-6 col-sm-6 col-xs-12">
								  
									<input id="roomno" class="form-control col-md-7 col-xs-12" name="amount" type="currency" value="">
							  </div>
							</div>
							
							<div class="ln_solid"></div>
							<div class="form-group">
								<div class="col-md-6 col-md-offset-2">
									<button id="send" type="submit" name="submit" class="btn btn-success">Submit</button>
									<button type="submit" class="btn btn-primary" onclick="javascript:window.location='index.php?pagecontent=dashboard'">Cancel</button>
								</div>
							</div>
						</form>
					</div>
                </div>
            </div>

	  <div class="col-md-6 col-sm-6 col-xs-12">
		<div class="x_panel">
		  <div class="x_title">
			<h2>Report</h2>
			<ul class="nav navbar-right panel_toolbox">
			  <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
			  </li>
			  <li class="dropdown">
				<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
				<ul class="dropdown-menu" role="menu">
				  <li><a href="#">Settings 1</a>
				  </li>
				  <li><a href="#">Settings 2</a>
				  </li>
				</ul>
			  </li>
			  <li><a class="close-link"><i class="fa fa-close"></i></a>
			  </li>
			</ul>
			<div class="clearfix"></div>
		  </div>
		  <div class="x_content">

			<table class="table table-striped">
			  <thead>
				<tr>
				  <th>#</th>
				  <th>Description</th>
				  <th>Amount</th>
				</tr>
			  </thead>
			  <tbody>
				<tr>
				  <th scope="row">1</th>
				  <td>Total spent on expenses</td>
				  <td>RM <?php echo totalExpenses('',$getRoomId)['total']; ?></td>
				</tr>
			  </tbody>
			</table>

		  </div>
		</div>
	  </div>
		
		
		<?php 
				if($_REQUEST['receipt']){
					if(getDetailByTable('room_expenses',$getExpensesId)['re_filename']){ ?>
			<div class="col-md-6 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<img src="uploads/expenses/<?php echo getDetailByTable('room_expenses',$getExpensesId)['re_filename']; ?>" width="100%">
					</div>
					
					<div class="x_content">
						
						<form class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
							<div class="item form-group">
								<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Upload 
								</label>
								<div class="col-md-3 col-sm-3 col-xs-12">
									<input id="night" class="form-control col-md-3 col-xs-12" name="fileToUpload" type="file" >
								</div>
							</div>

							<div class="ln_solid"></div>

							<div class="form-group">
								<div class="col-md-6 col-md-offset-3">
									<button id="send" type="submit" class="btn btn-success" name="uploadBtn">Upload</button>

									<button type="submit" class="btn btn-danger" name="removePhoto">Remove</button>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<?php }else{ ?>
			<div class="col-md-6 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
					<form class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
						<div class="item form-group">
							<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Upload 
							</label>
							<div class="col-md-3 col-sm-3 col-xs-12">
								<input id="night" class="form-control col-md-3 col-xs-12" name="fileToUpload" type="file" >
							</div>
						</div>

						<div class="ln_solid"></div>

						<div class="form-group">
							<div class="col-md-6 col-md-offset-3">
								<button id="send" type="submit" class="btn btn-success" name="uploadBtn">Upload</button>
							</div>
						</div>
					</form>
					</div>
				</div>
			</div>
			
			<?php }} ?>
			
              <div class="clearfix"></div>

              <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
                  <div class="x_title">
                    <h2>Expenses list</h2>
                    <ul class="nav navbar-right panel_toolbox">
                      <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                      </li>
                      <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                        <ul class="dropdown-menu" role="menu">
                          <li><a href="#">Settings 1</a>
                          </li>
                          <li><a href="#">Settings 2</a>
                          </li>
                        </ul>
                      </li>
                      <li><a class="close-link"><i class="fa fa-close"></i></a>
                      </li>
                    </ul>
                    <div class="clearfix"></div>
                  </div>

                  <div class="x_content">

                    <div class="table-responsive">
                      <table class="table table-striped jambo_table bulk_action">
                        <thead>
                          <tr class="headings">
                            <th class="column-title">Title</th>
                            <th class="column-title">Type </th>
                            <th class="column-title">Date </th>
                            <th class="column-title">Amount </th>
                            <th class="column-title">Receipt</th>
                            <th class="column-title no-link last"><span class="nobr">Action</span>
                            </th>
                            <th class="bulk-actions" colspan="7">
                              <a class="antoo" style="color:#fff; font-weight:500;">Bulk Actions ( <span class="action-cnt"> </span> ) <i class="fa fa-chevron-down"></i></a>
                            </th>
                          </tr>
                        </thead>

                        <tbody>
							<?php
								$result=mysqli_query($conn, "SELECT * FROM room_expenses WHERE r_id=$getRoomId") or die (mysql_error());
								while($row = mysqli_fetch_array($result)){
							?>
                          <tr class="even pointer">
							  
                            <td class=" "><?php echo urldecode($row['re_note']); ?></td>
                            <td class=" "><?php echo getDetailByTable('expenses_type',$row['re_type'])['et_title']; ?></td>
                            <td class=" "><?php echo $row['re_date']; ?></td>
                            <td class=" "><?php $qty = $row['re_amount']; echo $qty; ?></td>
                            <td class=" "><?php if(!getDetailByTable('room_expenses',$row['re_id'])['re_filename']){
								?>
									<a href="?pagecontent=expenses&receipt=<?php echo $row['re_id']; ?>"><button class="btn btn-xs btn-primary">Upload</button></a>
								<?php
							}else{ ?>
									<a href="?pagecontent=expenses&receipt=<?php echo $row['re_id']; ?>"><button class="btn btn-xs btn-warning">View</button></a>
								<?php
							}; ?></td>
                            <td class=" last"><a href="?pagecontent=room_expenses&remove=<?php echo $row['re_id']; ?>&room=<?php echo $row['r_id']; ?>">Delete</a>
                            </td>
                          </tr>
							<?php } ?>
                        </tbody>
                      </table>
                    </div>
							
						
                  </div>
                </div>
              </div>
        </div>
    </div>
</div>

<?php
	if(isset($_REQUEST['remove'])){
		
		$expensesId = $_REQUEST['remove'];
		
		if(getDetailByTable("room_expenses",$expensesId)['re_filename']){
			$expensesFilename = getDetailByTable("room_expenses",$expensesId)['re_filename'];
			unlink("uploads/expenses/".$expensesFilename);
			
			mysqli_query($conn,"DELETE FROM room_expenses WHERE re_id=$expensesId") or die (mysql_error());
		}
		
		header('Location: ?pagecontent=room_expenses&room='.$getRoomId); 
	}

	if(isset($_POST['submit']))
	{
		$postType = $_POST['type'];
		$postDate = $_POST['date'];
		$postAmount = $_POST['amount'];
		$postTitle = urlencode($_POST['title']);
		$postNote = urlencode($_POST['note']);
		
		$adminId = $_SESSION['admin'][0];
		
		mysqli_query($conn, "INSERT INTO room_expenses (r_id, re_type,re_title, re_note, re_date, re_amount, a_id)
		VALUES (0,$postType,'$postTitle','$postNote','$postDate','$postAmount', $adminId)") or die (mysql_error());
		
		header('Location: ?pagecontent=expenses');
	}
	
	//REMOVE RECEIPT
	if(isset($_POST['removePhoto'])){
		
		if(getDetailByTable("room_expenses",$getExpensesId)['re_filename']){
			$expensesFilename = getDetailByTable("room_expenses",$getExpensesId)['re_filename'];
			unlink("uploads/expenses/".$expensesFilename);
			
			mysqli_query($conn, "UPDATE room_expenses SET re_filename='' WHERE re_id=$getExpensesId");
		}
		
		if($_SESSION['redirect']){ $redirectUrl = $_SESSION['redirect'];
			header("Location: $redirectUrl");
		}
	}

	//UPLOAD RECEIPT
	if(isset($_POST['uploadBtn'])){
		
		if(getDetailByTable("room_expenses",$getExpensesId)['re_filename']){
			$expensesFilename = getDetailByTable("room_expenses",$getExpensesId)['re_filename'];
			unlink("uploads/expenses/".$expensesFilename);
		}
			
		//image resize
		if(is_array($_FILES)) {

			$uploadedFile = $_FILES['fileToUpload']['tmp_name']; 
			$sourceProperties = getimagesize($uploadedFile);
			$imageType = $sourceProperties[2];

			switch ($imageType) {

				case IMAGETYPE_PNG:
					$imageSrc = imagecreatefrompng($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;           

				case IMAGETYPE_JPEG:
					$imageSrc = imagecreatefromjpeg($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;

				case IMAGETYPE_GIF:
					$imageSrc = imagecreatefromgif($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;

				default:
					echo "Invalid Image type.";
					exit;
					break;
			}
		}

		  //upload receipt
		  $errors = array();
		  $file_name = $_FILES['fileToUpload']['name'];
		  $file_size =$_FILES['fileToUpload']['size'];
		  $file_tmp = $_FILES['fileToUpload']['tmp_name'];
		  $file_type = $_FILES['fileToUpload']['type'];

		  $file_ext = strtolower(end(explode('.',$_FILES['fileToUpload']['name'])));

		  $extensions = array("jpeg","jpg","png");

		  if(in_array($file_ext,$extensions)=== false){
			 $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
		  }

		  if($file_size > 2097152){
			 $errors[] = 'File size must be excately 2 MB';
		  }

			$file_name = $getExpensesId."_".time().".".$file_ext;
			$filePath = "uploads/expenses/".$file_name;

		  if(empty($errors) == true){

			 if(move_uploaded_file($file_tmp,$filePath)){

				 mysqli_query($conn, "UPDATE room_expenses SET re_filename='$file_name' WHERE re_id=$getExpensesId");

				 $adminName = $_SESSION['admin'][1];
				 $expensesTitle = getDetailByTable("room_expenses",$getExpensesId)['re_title'];

				 sendMessage2(-1001209156913,$adminName." upload receipt for

Expenses Id : ".$getExpensesId."
Title : ".urldecode($expensesTitle)."
");
				 sendPhoto(-1001209156913,"https://admin.homestay.dzvisual.my/production/".$filePath);
			 }
		  }
		
		//$postMonthYear = date("F / Y",strtotime(getDetailByTable("utilities",$getUtilityId)['u_date']));
		//utilityLog(0,$getRoomId,$getUtilityTypeId,$_SESSION['admin'][1]." add photo for ".$postMonthYear);
		
		if($_SESSION['redirect']){ $redirectUrl = $_SESSION['redirect'];
			header("Location: $redirectUrl");
		}
	}

	function imageResize($imageSrc,$imageWidth,$imageHeight) {

		$newImageWidth =200;
		$newImageHeight =200;

		$newImageLayer=imagecreatetruecolor($newImageWidth,$newImageHeight);
		imagecopyresampled($newImageLayer,$imageSrc,0,0,0,0,$newImageWidth,$newImageHeight,$imageWidth,$imageHeight);

		return $newImageLayer;
	}
?>