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

$where 	= " WHERE 1=1 ";


$query_string = "";

$button_value 	= "Add";
$table_name		= "invoice";

$next_page_condition 	= "";

if($_REQUEST['hide_top']){
	$next_page_condition.="&hide_top=1";
}
if($_REQUEST['hide_left']){
	$next_page_condition.="&hide_left=1";
}
if($_REQUEST['job_id']){
	$job_id = $_REQUEST['job_id'];
	$where 	.= " AND job_id = $job_id ";
	$next_page_condition.="&job_id=".$job_id;
}

/*if(isset($_REQUEST['source'])){
	$source = $_REQUEST['source'];
	$next_page_condition.="&source=$source";
}*/

$invoice_number = $gsi->getInvoiceNumber($_REQUEST['job_id']);
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
	//$next_page_condition.="&start=$start";
}
$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
################################################## SEND INVOICE ######################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'send_invoice'){
	$id= $_REQUEST['id'];
	$job_id= $_REQUEST['job_id'];
	$admin_id = utility::getTableFieldById("job_admin_mapping","admin_id","job_id",$job_id);
	$mail_format_subject = utility::getTableFieldById("mail_format","mail_format_subject","mail_format_name","send_invoice");
	$mail_format_body = strip_tags(utility::getTableFieldById("mail_format","mail_format_body","mail_format_name","send_invoice"));
	
	$first_name = utility::getTableFieldById("job","first_name","id",$job_id);
	$last_name = utility::getTableFieldById("job","last_name","id",$job_id);
	/* $first_name2 = utility::getTableFieldById("job","first_name2","id",$job_id);
	$last_name2 = utility::getTableFieldById("job","last_name2","id",$job_id);
	if(isset($first_name1) &&  $first_name1 !=""){
		$name = ucfirst($first_name1)." ".ucfirst($last_name1);
	}else{
		$name = ucfirst($first_name2)." ".ucfirst($last_name2);
	}
	$email_id = utility::getTableFieldById("job","email","id",$job_id);
	$email_id_test = "shoebahmad999@gmail.com"; */
	
	if(isset($first_name) &&  $first_name !=""){
		$name = ucfirst($first_name)." ".ucfirst($last_name);
	}
	$email_id = utility::getTableFieldById("job","invoice_email","id",$job_id);
	$email_id_decript = utility::app_crypt($email_id,'d');
	if(!(isset($email_id_decript) && $email_id_decript !="")){
		$email_id = utility::getTableFieldById("job","email","id",$job_id);
		$email_id_decript = utility::app_crypt($email_id,'d');
	}
	$email_id_test = "shoebahmad999@gmail.com";
	
	$find_array = array("[user_name]");
	$replace_array = array($name);
	$mail_format_body = str_replace($find_array,$replace_array,$mail_format_body);
	$email_date = date("Y-m-d");
	
	$file_path 		= array();
	///////////////////// Curl to genrate invoice ////////////////////////////
	$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$config->frontEndURL."/invoice/invoice.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,"signature_block=$signature_block&pdf_genrate=1&id=".base64_encode(base64_encode(base64_encode(base64_encode(base64_encode(base64_encode($id)))))));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $server_output = curl_exec ($ch);
    curl_close ($ch);
	
	$my_path = $_SERVER['DOCUMENT_ROOT']."/beb/payment_invoice/";
	$doc_name = "invoice_".$id.".pdf";
	array_push($file_path,$my_path.$doc_name);
	//print_r($file_path);
	//die;
	////////////////////////////// End Curl to genrate invoice /////////////////////////
	//////////////////////// send mail ////////////////////
	//$file_path 		= array();
	$site_email = $config->siteEmail;
	if(utility::mailSMTP($email_id, $mail_format_subject, $functions->HTMLemailWithoutSignatureBlock($mail_format_body,$admin_id), $file_path,$site_email,$site_email,"","","",$admin_id)){
		utility::mailSMTP($email_id_test, $mail_format_subject, $functions->HTMLemailWithoutSignatureBlock($mail_format_body,$admin_id), $file_path,$site_email,$site_email,"","","",$admin_id);
		$sql = "INSERT INTO email_track(job_id,invoice_id,email_subject,email_body,email_id,email_date) VALUES('$job_id','$id','$mail_format_subject','$mail_format_body','$email_id','$email_date')";
		mysqli_query($conn,$sql);
		mysqli_query($conn,"UPDATE invoice SET is_send = 1 WHERE id = $id");
		$_SESSION['message'] = ucfirst("invoice send sucessfully");
	}else{
		$_SESSION['message']	= ucfirst("There is some error");
		///////////////// To run on local //////////////////////////////////////
		//$sql = "INSERT INTO email_track(job_id,invoice_id,email_subject,email_body,email_id,email_date) VALUES('$job_id','$id','$mail_format_subject','$mail_format_body','$email_id','$email_date')";
		//mysqli_query($conn,$sql);
		//mysqli_query($conn,"UPDATE invoice SET is_send = 1 WHERE id = $id");
	}
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : $_SERVER['QUERY_STRING'];
  	$query_string = str_ireplace("action=send_invoice", "", $query_string);
	$query_string = "&".$query_string;
	
	$redirect = "index?page=view_invoice$query_string";
	header("Location: $redirect");
	exit();
	///////////////// End send mail  //////////////////////
}
################################################## END SEND INVOICE ##################################################
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
	$action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit invoice";	
		
    $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'];
    $admin_id= $row_edit['admin_id'];
	$invoice_text= $row_edit['invoice_text'];
	$invoice_date= $row_edit['invoice_date'];
	$invoice_status= $row_edit['invoice_status'];
	$amount= $row_edit['amount'];
	$due_date= $row_edit['due_date'];
	$company_name = utility::getTableFieldById('job','company_name','id',$job_id);
	$initial_company_name = $gsi->getInitialOfCompanyName($company_name);
	$invoice_number= ($row_edit['invoice_number'] != "") ? $row_edit['invoice_number'] : $initial_company_name."/".date("m",strtotime($invoice_date))."/".date("y",strtotime($invoice_date))."/".$id;
}
################################################# END EDIT ################################################# 


################################################## START update ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string"));
	$id= $_REQUEST['id'];
    $job_id= $_REQUEST['job_id'];
    //$admin_id= $_REQUEST['admin_id'];
	$lead_consultant = utility::getTableFieldById('job','lead_consultant','id',$job_id);
	if($lead_consultant > 0){
		$admin_id = $lead_consultant;
	}else{
		$admin_id = utility::getTableFieldById("job_admin_mapping","admin_id","job_id",$job_id);
	}
    $invoice_text= $_REQUEST['invoice_text'];
	$invoice_date = utility::setFormatedDate($_REQUEST['invoice_date']);
	$invoice_status = $_REQUEST['invoice_status'];
	$amount= $_REQUEST['amount'];
	$due_date= utility::setFormatedDate($_REQUEST['due_date']);
	$invoice_number = $_REQUEST['invoice_number'];
	$updated_by = $_SESSION['user_id'];

    $sql= "UPDATE invoice SET job_id = '$job_id',admin_id = '$admin_id',invoice_text = '$invoice_text',invoice_date = '$invoice_date',invoice_status = '$invoice_status',amount = '$amount',due_date = '$due_date',invoice_number = '$invoice_number',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("invoice updated sucessfully");
	$redirect = "index?page=view_invoice$query_string";
	header("Location: $redirect");
	exit();
	
}
################################################# END update ################################################# 
//$custome_limit = 2;
###########################################  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 = "invoice Management ";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################

	
    
################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	    
	utility::addslashesOnAllInput(array("query_string"));
    $job_id = $_REQUEST['job_id'];	
    //$admin_id = $_SESSION['user_id'];
	$lead_consultant = utility::getTableFieldById('job','lead_consultant','id',$job_id);
	if($lead_consultant > 0){
		$admin_id = $lead_consultant;
	}else{
		$admin_id = utility::getTableFieldById("job_admin_mapping","admin_id","job_id",$job_id);
	}
	$invoice_text = $_REQUEST['invoice_text'];
	$invoice_date	 = utility::setFormatedDate($_REQUEST['invoice_date']);
	$invoice_status = $_REQUEST['invoice_status'];
	$amount= $_REQUEST['amount'];
	$due_date= utility::setFormatedDate($_REQUEST['due_date']);
	$invoice_number= $_REQUEST['invoice_number'];
	$created_on = date("Y-m-d");
		
    $sql= "INSERT INTO $table_name (job_id,admin_id,invoice_text,invoice_date,invoice_status,amount,due_date,invoice_number,updated_by,created_on) VALUES('$job_id','$admin_id','$invoice_text','$invoice_date','$invoice_status','$amount','$due_date','$invoice_number','".$_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("invoice added sucessfully");
	$redirect = "index?page=view_invoice&name=$name$query_string";
	header("Location: $redirect");
	exit();
}
################################################# END INSERT #################################################


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 ='$admin_id_search' ";
	$next_page_condition.="&admin_id_search=".$_REQUEST['admin_id_search'];
}
$from_invoice_date = isset($_REQUEST['from_invoice_date']) ? utility::setFormatedDate($_REQUEST['from_invoice_date']) : "";
$to_invoice_date = isset($_REQUEST['to_invoice_date']) ? utility::setFormatedDate($_REQUEST['to_invoice_date']) : "";
if($from_invoice_date && $to_invoice_date){
	$where .= " AND invoice_date BETWEEN '$from_invoice_date 00:00:00' and '$to_invoice_date 23:59:59' ";
    $next_page_condition.="&from_invoice_date=".$_REQUEST['from_invoice_date']."&to_invoice_date=".$_REQUEST['to_invoice_date']." ";
}else if($from_invoice_date){
	$where.= " AND invoice_date >= '$from_invoice_date' ";
	$next_page_condition.="&from_invoice_date=".$_REQUEST['from_invoice_date'];
}else if($to_invoice_date){
	$where.= " AND invoice_date <= '$to_invoice_date' ";
	$next_page_condition.="&to_invoice_date=".$_REQUEST['to_invoice_date'];
}

$query = "SELECT * FROM $table_name $where ORDER BY invoice_date DESC LIMIT $eu, $limit ";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

#################################   DELETE    #########################################
// when we click on delete this area of php invoice will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	$id	= $_REQUEST['id'];
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
	
	$query_string =  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	$query_string = str_ireplace(array("action=delete"), array(""), $query_string);
	$query_string = "&".$query_string;
	
	$_SESSION['message']	= ucfirst("invoice deleted sucessfully");
	$redirect = "index?page=view_invoice";
	header("Location: $redirect$query_string");
	exit();
}
#################################  END DELETE    #########################################
?>

<section class="content-header hide">
  <h1>
	<? echo str_replace(array("_"),array(" "),$page_header); ?>
  </h1>		
</section>
<!----------------------- 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">
				<div class="row" style="padding:0px 10px;">
					<?php include_once('add_invoice.inc.php');?>
				</div>
				<!--<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">-->					
				<form action="?page=view_invoice&name=<?=$name?>" method="post" name="form1" id="form1">
				<? if($result>0){
				?>
					<!-- Start  records header -->
				<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>Due Date</th>
							<th>Inv. Pay. Status</th>
							<th>Paid Amount (&pound;)</th>
							<th>Send Invoice / View Invoice</th>
							<th>Edit</th>						
							<th>Delete</th>
						</tr>
					</thead>
					<tbody>
					<!-- End records header -->
					<?
					while($row = mysqli_fetch_array($sql)){
					?>
					<!-- Start data -->
					<tr>
						<td><?php echo $row['job_id']; ?></td>
						<td><?php echo $row['invoice_text']; ?></td>
						<!--<td><?php //echo $gsi->getEnqQuoteJobById($row['job_id']); ?></td>-->
						<td><?php echo Admin::getAdminsById($row['admin_id']); ?></td>
						<td><?php echo $gsi->getInvoiceStatusById($row['invoice_status']); ?></td>
						<td><?php echo number_format($row['amount'],2); ?></td>
						<td><?php echo utility::getFormatedDateReturn($row['invoice_date']); ?></td>
						<td><?php echo utility::getFormatedDateReturn($row['due_date']); ?></td>
						<td><?php echo $gsi->getInvoicePaymentStatusById($row['id']); ?></td>
						<td><?php echo $gsi->getInvoicePaymentAmountById($row['id']); ?></td>
						<td>
						<?
							$is_send_color = (utility::getTableFieldById("invoice","is_send","id",$row['id']) == 1) ? "red" : "";
						?>
						<a style="color:<?=$is_send_color;?>" href="index?page=view_invoice&action=send_invoice&id=<?=$row['id'].$next_page_condition.$paging;?>">Send Invoice</a> / 
						<a href="<?=$config->frontEndURL;?>/invoice/invoice.php?id=<?=base64_encode(base64_encode(base64_encode(base64_encode(base64_encode(base64_encode($row['id']))))))?>" target="_blank">View Invoice</a>
						</td>
						<td><a href="index?page=view_invoice&action=edit&id=<?=$row['id'].$next_page_condition.$paging;?>"> <img src="../images/edit.gif" border="0" /> </a></td>
						<td><a
							href="index?page=view_invoice&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>
					<!-- End data -->
					<? 
					}?>
					
					<?}else{?>
					<tr>
						<td colspan="6">No invoice found...</td>
					</tr>
					<?php }?>
					</tbody>
					
				</table>
					<!-- Paging starts here  -->
					<? 
					$next_page_condition .="&page=view_invoice";
					include("paging/paging_row.inc.php") ?>
					<!-- Paging ends starts here  -->
						
					<!--</table>-->
					</form>
					</div>
				</div>
			</div>
		</div>
	</section>
		