<?php
$message = (isset($_SESSION['message'])) ? $_SESSION['message'] :"";
$action = (isset($_REQUEST['action'])) ? $_REQUEST['action'] : "insert";

$collapse_payment_area = "collapse";
$collapse_invoice_area = "collapse";

$where 					= " WHERE 1=1 ";

$query_string = "";
$button_value 	= "Add";
$table_name		= "payment";

$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
}
$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$collapse_payment_area = "";
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	$action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit Payment";	
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $id= $row_edit['id'];
    $job_id= $row_edit['job_id'];
    $invoice_id= $row_edit['invoice_id'];
    $admin_id= $row_edit['admin_id'];
	$payment_text= $row_edit['payment_text'];
	$payment_date= $row_edit['payment_date'];
	$payment_status= $row_edit['payment_status'];
	$amount= $row_edit['amount'];
}
################################################# END EDIT ################################################# 

################################################## START update ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string"));
	$id= $_REQUEST['id'];
    $job_id= $_REQUEST['job_id'];
    $invoice_id= $_REQUEST['invoice_id'];
    $admin_id= $_SESSION['user_id'];
    $payment_text= $_REQUEST['payment_text'];
	$payment_date	 = utility::setFormatedDate($_REQUEST['payment_date']);
	$payment_status = $_REQUEST['payment_status'];
	$amount= $_REQUEST['amount'];
	$updated_by = $_SESSION['user_id'];

    $sql= "UPDATE payment SET job_id = '$job_id',invoice_id = '$invoice_id',admin_id = '$admin_id',payment_text = '$payment_text',payment_date = '$payment_date',payment_status = '$payment_status',amount = '$amount',updated_by = '$updated_by' WHERE id = $id";
    mysqli_query($conn,$sql);
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace(array("page=add","action=edit"), array("page=list",""), $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['message']	= ucfirst("Payment updated sucessfully");
	$redirect = "index?page=view_payment_main$query_string";
	header("Location: $redirect");
	exit();
	
}
################################################# END update ################################################# 

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	 
	
	utility::addslashesOnAllInput(array("query_string"));
    $job_id = $_REQUEST['job_id'];	
    $invoice_id = $_REQUEST['invoice_id'];	
    $admin_id = $_SESSION['user_id'];
	$payment_text = $_REQUEST['payment_text'];
	$payment_date	 = utility::setFormatedDate($_REQUEST['payment_date']);
	$payment_status = $_REQUEST['payment_status'];
	$amount= $_REQUEST['amount'];
	$created_on = date("Y-m-d");
		
    $sql= "INSERT INTO $table_name (job_id,invoice_id,admin_id,payment_text,payment_date,payment_status,amount,updated_by,created_on) VALUES('$job_id','$invoice_id','$admin_id','$payment_text','$payment_date','$payment_status','$amount','".$_SESSION['user_id']."','$created_on')";
    mysqli_query($conn,$sql);
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace("page=add", "page=list", $query_string);
	$query_string = "&".$query_string;
	$tmp = ucfirst(str_replace("_"," ", $table_name));
	
	$_SESSION['message']	= ucfirst("payment added sucessfully");
	$redirect = "index?page=view_payment_main$query_string";
	header("Location: $redirect");
	exit();
}
################################################# END INSERT #################################################

###########################################  STRAT FILTER CONITIONS    #####################################
/*$search 	= isset($_REQUEST['search']) ? $_REQUEST['search'] : "";
if($search) {
    $where	.= " AND (id = '$search' OR company_name LIKE '%$search%' OR first_name1 LIKE '%$search%' OR last_name1 LIKE '%$search%' OR first_name2 LIKE '%$search%' OR last_name2 LIKE '%$search%' OR email LIKE '%$search%' OR postcode LIKE '%$search%') ";
    $next_page_condition.="&search=$search";
}*/
if($_REQUEST['job_id_search']){
	$job_id_search = $_REQUEST['job_id_search'];
	$where 	.= " AND job_id ='$job_id_search' ";
	$next_page_condition.="&job_id_search=".$_REQUEST['job_id_search'];
}

if($_REQUEST['admin_id_search']){
	$admin_id_search = $_REQUEST['admin_id_search'];
	//$where 	.= " AND admin_id LIKE '$admin_id_search%' ";
	$sql = "SELECT * FROM job_admin_mapping WHERE admin_id = '$admin_id_search' ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		while($data = mysqli_fetch_assoc($rs)){
			$lead_consultant = utility::getTableFieldById('job','lead_consultant','id',$data["job_id"]);
			if($lead_consultant == $admin_id_search){
				$job_ids .= $data["job_id"].",";
			}
		}
		$job_ids = substr($job_ids,0,-1);
	}
	
	$where 	.= " AND job_id IN ($job_ids) ";
	$next_page_condition.="&admin_id_search=".$_REQUEST['admin_id_search'];
}

$from_payment_date = isset($_REQUEST['from_payment_date']) ? utility::setFormatedDate($_REQUEST['from_payment_date']) : "";
$to_payment_date = isset($_REQUEST['to_payment_date']) ? utility::setFormatedDate($_REQUEST['to_payment_date']) : "";
if($from_payment_date && $to_payment_date){
	$where .= " AND payment_date BETWEEN '$from_payment_date 00:00:00' and '$to_payment_date 23:59:59' ";
    $next_page_condition.="&from_payment_date=".$_REQUEST['from_payment_date']."&to_payment_date=".$_REQUEST['to_payment_date']." ";
}else if($from_payment_date){
	$where.= " AND payment_date >= '$from_payment_date' ";
	$next_page_condition.="&from_payment_date=".$_REQUEST['from_payment_date'];
}else if($to_payment_date){
	$where.= " AND payment_date <= '$to_payment_date' ";
	$next_page_condition.="&to_payment_date=".$_REQUEST['to_payment_date'];
}

###########################################  	END  FILTER CONITIONS 	#####################################
###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page

$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";
$page_header = "Payment Management";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
$query = "SELECT * FROM $table_name $where ORDER BY payment_date DESC LIMIT $eu, $limit";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_payments = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
##############################################################################################################
#################################   DELETE    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	$id	= $_REQUEST['id'];
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
	
	$_SESSION['message']	= ucfirst("Payment deleted sucessfully");
	$redirect = "index?page=view_payment_main";
	header("Location: $redirect");
	exit();
}
#################################  END DELETE    #########################################
?>
 <section class="content-header">
  <h1>
	<?=$page_header;?>
  </h1>
</section>
<div style="clear:both;"></div>
<!----------------------- Message ------------------------------->
<? if(isset($_SESSION['message'])){ ?>
	<section class="content-header">
	  <div class="alert alert-info alert-dismissable" style="margin-bottom:0px;">
		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
		<? echo $_SESSION['message'];
			unset($_SESSION['message']);
		?>
	  </div>
	</section>
	<? } ?>
<!----------------------- End Message ------------------------------->
<section class="content">
	<div class="row">
		<div class="col-xs-12">
			<div class="box">
				<div class="box-body">
				<!-- search form -->
				<?php include_once('payment_management_search_options.inc.php');?>
				<!-- /.search form -->
				<!--------- Color codeing --------------------------------->
				<div class="col-xs-6">
					<div style="float:left;clear:right;font-weight:bold;">Payment Status</div>
					<?
						foreach(gsi::$paymentModeColorArray as $key => $value){
							$mode_of_payment_value = gsi::$paymentStatus[$key];
							$modeOfPaymentStatus[$mode_of_payment_value] = $value;
						}
						foreach($modeOfPaymentStatus as $k => $v){	
							echo "<div style='background:$v;width:auto;height:auto;float:left;clear:right;margin-left:5px;border:1px solid;padding:0 3px 0 3px;'>$k</div>";
						}
					?>
					<br><br>Total No. of payments <?=$total_no_of_payments;?>
				</div>
				<!--<div class="col-xs-6">
					<div style="float:left;clear:right;font-weight:bold;">Invoice Status</div>
					<?
						/*foreach(gsi::$invoiceModeColorArray as $key => $value){
							$mode_of_invoice_value = gsi::$invoiceStatus[$key];
							$modeOfInvoiceStatus[$mode_of_invoice_value] = $value;
						}
						foreach($modeOfInvoiceStatus as $k => $v){	
							echo "<div style='background:$v;width:auto;height:auto;float:left;clear:right;margin-left:5px;border:1px solid;padding:0 3px 0 3px;'>$k</div>";
						}*/
					?>
				</div>-->
				<div style="clear:both;margin-bottom:10px;"></div>
				<!--------- End Color codeing --------------------------------->
					<form action="index?page=add" method="post" name="form1" id="form1">
					<? if($result>0){?>
					 <table id="example1" class="table table-bordered table-striped">
						<thead>
						  <tr>
							<th>Job Id</th>
							<th>Description</th>
							<th>Consultant</th>
							<th>Status</th>
							<th>Amount (&pound;)</th>
							<th>Date</th>
							<th>For Invoice</th>
							<th>Edit</th>						
							<th>Delete</th>
						  </tr>
						</thead>
						<tbody>
							<?
								$payment_amount = 0;
								while($row =mysqli_fetch_array($sql)){ 
									$payment_amount = $payment_amount + $row['amount'];
									//$bg_color = gsi::$paymentModeColorArray[utility::getTableFieldById("payment","payment_status","job_id",$row["id"])];
									$bg_color = gsi::$paymentModeColorArray[$gsi->getMaxPaymentStatusByJobId($row["job_id"])];
							?>
							<tr style="background-color:<?=$bg_color;?>;">
								<td><?php echo $row['job_id']; ?></td>
								<td><?php echo $row['payment_text']; ?></td>
								<td><?php echo Admin::getAdminsById($row['admin_id']); ?></td>
								<td><?php echo $gsi->getPaymentStatusById($row['payment_status']); ?></td>
								<td><?php echo number_format($row['amount'],2); ?></td>
								<td><?php echo utility::getFormatedDateReturn($row['payment_date']); ?></td>
								<td><?php echo $gsi->getInvoiceById($row['invoice_id']); ?></td>
								<td><a href="index?page=view_payment_main&action=edit&id=<?=$row['id'].$next_page_condition.$paging;?>"> <img src="../images/edit.gif" border="0" /> </a></td>
								<td><a href="index?page=view_payment_main&action=delete&id=<?=$row['id'].$next_page_condition.$paging; ?>" onclick=" javascript:return confirm('Are you sure! You want to delete');"><img src="../images/del.gif" border="0"/></a></td>
							</tr>
							<? } ?>
							<tr>
								<td colspan="5" style="text-align:right;"><b>Total</b><td>
								<td colspan="4"><b><?=number_format($payment_amount,2);?></b><td>
							</tr>
							<!-- Paging starts here  -->
							<? 
								$next_page_condition .="&page=view_payment_main";
								include("paging/paging_row.inc.php") ?>
							<!-- Paging ends starts here  -->
						</tbody>
					 </table>
					 <? }else{ ?>
						No payment found...
					 <? } ?>
				</div>
				</form>
			</div>
		</div>
	</div>
</section>
<script type="text/javascript">
$(function () {
	$(".invoice1").click(function(){	
		$("#myModalLabel").text("Invoice Management");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var job_id = $(this).attr("alt");		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/payment_management/index?page=view_invoice&source=e&job_id="+job_id+hide_top_left);
	});
	$(".payment").click(function(){	
		$("#myModalLabel").text("Payment Management");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var job_id = $(this).attr("alt");		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/payment_management/index?page=view_payment_main&source=e&job_id="+job_id+hide_top_left);
	});
	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
		location.reload();
	});
});
</script>