<?php
session_start();
$where 					= " WHERE 1=1  ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
} 
$restricted_groups = [13];
$can_view = !in_array($_SESSION['admin_group_id'], $restricted_groups);
##################################  STRAT FILTER CONITIONS    ###############################

$order_ref 	= isset($_REQUEST['order_ref']) ? $_REQUEST['order_ref'] : "";
if($order_ref) {
	$order_ref = trim($order_ref);
    $where	.= " AND order_ref ='$order_ref' ";
    $next_page_condition.="&order_ref=$order_ref";
}
$supplier_id 	= isset($_REQUEST['supplier_id']) ? $_REQUEST['supplier_id'] : "";
if($supplier_id) {
	$supplier_id=trim($supplier_id);
    $where	.= " AND supplier_id = '$supplier_id' ";
    $next_page_condition.="&supplier_id=$supplier_id";
}

################################# END FILTER CONDITIONS ################################

###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "purchase_order";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT * FROM $table_name  $where ";

$page_header = "Purchase Order";
include("paging/paging_query.inc.php");
################################## END PAGING WITH PER PAGE  ################################
$query = "SELECT * FROM $table_name $where ORDER BY id DESC LIMIT $eu, $limit";

$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_purchase_order = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	
	mysqli_query($conn,"DELETE FROM purchase_order_items_mapping WHERE po_id = '".$_REQUEST['id']."' "); 
	
	$_SESSION['info_message'] = "Purchase Order deleted successfully";
	header("location: $file_name?page=view".$next_page_condition.$paging);
	exit();
}
#################################  END DELETE    #########################################
?>


<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0"><?=$page_header;?></h1>
            </div>
        </div>
    </div>
</div>
<section class="content">
	<div class="container-fluid">
	<div class="row">
		<div class="col-lg-12">
		<div class="">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<div class="card">
				<div class="card-body">
				<!-- search form -->
				<?php include_once('purchase_order_search_options.inc.php');?>
				<!-- /.search form -->
				Total No. of Purchase Order: <?=$total_no_of_purchase_order;?>
				
					<form action="index?page=add" method="post" name="form1" id="form1">
					<?php if($can_view){ ?>
					<div class="card-footer">
					   <button type="submit" name="add" class="btn btn-primary">Add Purchase Order</button>
					</div>
					<?php } ?>
					<? if($result>0){?>
					<div class="table-responsive">
					 <table id="example1" class="table table-bordered table-striped">
						<thead>
						  <tr>
							<th>Order Ref</th>
							<th class="text-center">Supplier</th>
							<th class="text-center">PO Created Date</th>
							<th class="text-center">Status</th>
							<th  class="text-center">Order Received</th>
							<th class="text-center">PDF</th>
							<th class="text-center">Email</th>
							<?php if($can_view){ ?>
							<th class="text-center">Edit</th>
							<th class="text-center">Delete</th>
							<?php } ?>
						  </tr>
						</thead>
						<tbody>
							<?
								while($row =mysqli_fetch_array($sql)){ 
								$row=utility::validate_crypt_data($row);
							?>
						  <tr>			
							<td ><?php echo $row["order_ref"];?></td>
							<td class="text-center"><?php echo $gsi->getSuppliersById($row["supplier_id"]);?></td>
							<td class="text-center"><?php echo utility::getFormatedDateReturn($row["created_on"]);?></td>
							<td class="text-center">
								<?php if ($row['order_status'] == 1): ?>
									<i class="fa fa-clock text-danger"></i> Pending
								<?php elseif ($row['order_status'] == 2): ?>
									<i class="fa fa-times-circle text-danger"></i> Problem (Broken)
								<?php elseif ($row['order_status'] == 3): ?>
									<i class="fa fa-times-circle text-danger"></i> Problem (Lost)
								<?php elseif ($row['order_status'] == 4): ?>
									<i class="fa fa-check-circle text-success"></i> Completed 
								<?php endif; ?>
							</td>
							<td class="text-center"><a href="index?page=item_status&po_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>" class=" btn btn-info"> View  </a></td>
							<td>
							<?php
								$enc_po_id = urlencode(utility::app_crypt($row['id'], 'e'));
								?>

								<?php if($_SERVER['HTTP_HOST'] =="localhost"){?>						
									<a href="<?=$config->frontEndURL;?>/admin/purchase_order/index?page=view_purchase_order_pdf&po_id=<?=$enc_po_id;?>&hide_top=1&hide_left=1" target="_blank">
										<i class="fa fa-fw fa-file-pdf text-primary"></i>
									</a>
								<?}else{?>
									<a href="<?=$config->frontEndURL;?>/purchase_order_pdf.php?po_id=<?=$enc_po_id;?>&pdf_name=purchase_order" target="_blank">
										<i class="fa fa-fw fa-file-pdf text-primary"></i>
									</a>
								<?}?>
							</td>
							<?php
							$supplier = mysqli_fetch_assoc(mysqli_query($conn, "
								SELECT contact_1_email_address 
								FROM supplier_management 
								WHERE id='".$row['supplier_id']."'
							"));

							$supplier_email = $supplier['contact_1_email_address'];
							$supplier_email = utility::app_crypt($supplier_email, 'd');

							$pdf_link = $config->frontEndURL .
    "/purchase_order_pdf.php?po_id=" . urlencode(utility::app_crypt($row['id'], 'e')) .
    "&pdf_name=" . urlencode(utility::app_crypt('purchase_order', 'e'));

$body = rawurlencode(
    "Dear Supplier,\r\n\r\n" .
    "Please find our Purchase Order: " . $row['order_ref'] . "\r\n" .
    $pdf_link . "\r\n\r\n" .
    "Please confirm receipt at your earliest convenience.\r\n\r\n" .
    "Many Thanks"
);

$subject = rawurlencode("Purchase Order " . $row['order_ref']);
$mailto_link = "mailto:" . $supplier_email . "?subject=" . $subject . "&body=" . $body;
							?>

							<td class="text-center">
    <a href="<?= $mailto_link ?>" 
       class="btn <?= ($row['is_emailed'] == 1) ? 'btn-success' : 'btn-warning' ?> email-btn" 
       data-po-id="<?= $row['id'] ?>"
       id="email_btn_<?= $row['id'] ?>">
        <i class="fa fa-envelope"></i>
    </a>
</td>
							<?php if($can_view){ ?>
							<td class="text-center"><a href="index?page=add&action=edit&po_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>" <?=$edit_delete_display;?>> <i class="fa fa-fw fa-edit text-primary"></i> </a></td>
							<td class="text-center"><a href="index?page=view&action=delete&id=<?=$row['id'].$next_page_condition.$paging; ?>"onclick=" javascript:return confirm('Are you sure you want to delete?');" <?=$edit_delete_display;?>><i class="fa fa-fw fa-trash text-danger"></i> </a></td>
							<?php } ?>
						  </tr>
							<? } ?>
							
						</tbody>
					 </table>
					 </div>
					 <? }else{ ?>
						No purchase order found...
					 <? } ?>
					 <div class="box-footer clearfix">
						<? 
							$next_page_condition .="&page=view";
							include("paging/paging_row.inc.php") 
						?>
					</div>
				</div>
				<?php if($can_view){ ?>
				<div class="card-footer hide">
                   <button type="submit" name="add" class="btn btn-primary">Add Purchase Order</button>
                </div>
				<?php } ?>
				</form>
			</div>
		</div>
		</div>
	</div>
	</div>
</section>

<script type="text/javascript">
$(function () {
	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
		location.reload();
	});
	$(document).on('click', '.email-btn', function () {
        var poId = $(this).data('po-id');
        var btn = $(this);

        $.ajax({
            type: 'POST',
            url: site_url + '/modules/purchase_order/index.php?page=ajax_actions&action=mark_email_sent',
            data: { po_id: poId },
            success: function (result) {
                var res = jQuery.parseJSON(result);
                if (res.status === 'success') {
                    btn.removeClass('btn-warning').addClass('btn-success');
                }
            }
        });
    });
	$(".add_po_document").click(function(){
		var purchase = $(this).attr("data-purchase");
		$("#myModalLabel").html("Purchase Documents  <span style='color:Tomato'>"+purchase+"</span>");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var purchase_order_id = $(this).attr("alt");	
		$('.modal-dialog').css({"max-width":"76%"});		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/modules/fileuploads/image-files.php?purchase_order_id="+purchase_order_id+"&page=view&source=po"+hide_top_left);
	});
	$(".Mail_send").click(function(){
		var order_ref = $(this).attr("data-order_ref");
		$("#myModalLabel").html("Send to Supplier for <span style='color:Tomato'>"+order_ref+"</span>");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var purchase_order_id = $(this).attr("alt");
		$('.modal-dialog').css({"max-width":"80%"});
		$(".modal_iframe").addClass("jspopup").attr("src","<?=$config->frontEndURL?>/admin/purchase_order/index?page=send_mail_to_client_for_po&purchase_order_id="+purchase_order_id+hide_top_left);
	});
});


</script>