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

$collapse_area = "collapse";
$add_btn_hide = "";
$cancel_btn_hide = "";
$search_list = "block";
$listing = "block";

$where 	= " WHERE 1=1 ";
$button_value 	= "Add";
$table_name		= "keycode";

$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
}
$except = array('oder');
utility::addslashesOnAllInput($except);

if(isset($_REQUEST['set_order']) && $_REQUEST['set_order'] =='Set Order'){
	foreach($_REQUEST['oder'] as $key =>$val){
		mysqli_query($conn,"UPDATE keycode SET ord='$val' WHERE id='$key' ");		
	}
	$_SESSION['message'] = "Updated successfully";
}


################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$collapse_area = "";
	$add_btn_hide = "hide";
	$cancel_btn_hide = "hide";
	$search_list = "none";
	$listing = "none";
	
	$action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit keycode";	
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM keycode WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $id= $row_edit['id'];
    $name= $row_edit['name'];
    $code= $row_edit['code'];
    $description= $row_edit['description'];
}
################################################# END EDIT ################################################# 


################################################## START update ################################################## 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	
	$id= $_REQUEST['id'];
    $name= $_REQUEST['name'];
    $code= $_REQUEST['code'];
    $description= $_REQUEST['description'];

    $sql= "UPDATE keycode SET id = '$id', name = '$name', code = '$code', description = '$description' WHERE id = $id";
    mysqli_query($conn,$sql);

	$_SESSION['message']	= ucfirst(str_replace("_"," ",$name)." updated successfully");
	$redirect = "index?page=view_masterdata&name=$name";
	header("Location: $redirect");
	exit();
	
}
################################################# END update ################################################# 

###########################################  STRAT FILTER CONITIONS    #####################################
$name 	= isset($_REQUEST['name']) ? $_REQUEST['name'] : "";
if($name) {
    $where	.= " AND name ='$name' ";
    $next_page_condition.="&name=$name";
}


if($_REQUEST['status'] == 2){
	 //$where	.= " AND status ='2' ";
	 $status	=2;
	 $next_page_condition.="&status=2";
}else{
	$where	.= " AND status ='1' ";
	$next_page_condition.="&status=1";
}

$code_search 	= isset($_REQUEST['code_search']) ? $_REQUEST['code_search'] : "";
if($code_search) {
    $where	.= " AND code LIKE '%$code_search%' ";
    $next_page_condition.="&code_search=$code_search";
}

$description 	= isset($_REQUEST['description']) ? $_REQUEST['description'] : "";
if($description) {
    $where	.= " AND description LIKE '%$description%' ";
    $next_page_condition.="&description=$description";
}

###########################################  	END  FILTER CONITIONS 	#####################################

################################################## START INSERT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	    
	
	$name = $_REQUEST['name'];
    $code = $_REQUEST['code'];
    $description = $_REQUEST['description'];
	
	
	$max_order = "SELECT MAX(ord)+1 as ord FROM $table_name  $where ";
	$ord = 1;
    $result_max_order = mysqli_query($conn,$max_order);
	if(mysqli_num_rows($result_max_order)){
		$row_max_order = mysqli_fetch_array($result_max_order);
		if($row_max_order['ord'])
		$ord =  $row_max_order['ord'];
	}
	
    $sql= "INSERT INTO $table_name (name,code,description,ord,updated_by) VALUES('$name','$code','$description','$ord','".$_SESSION['user_id']."')";
    mysqli_query($conn,$sql);
	$_SESSION['message']	= ucfirst(str_replace("_"," ",$name)." added successfully");
	$redirect = "index?page=view_masterdata&name=$name";
	header("Location: $redirect");
	exit();
}
################################################# END INSERT #################################################
###########################################  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 = ucfirst($name) . " Management ";
include("paging/paging_query.inc.php");
############################################ END PAGING WITH PER PAGE  #######################################
$query = "SELECT * FROM $table_name $where ORDER BY code ASC LIMIT $eu, $limit ";
$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_data = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete'){
	$id	= $_REQUEST['id'];
	//$sql=mysqli_query($conn,"DELETE FROM $table_name WHERE id = $id ");
	if($_REQUEST['undelete']){
		mysqli_query($conn,"UPDATE $table_name SET `status` = '1' WHERE id = $id ");
	}else{
		mysqli_query($conn,"UPDATE $table_name SET `status` = '2' WHERE id = $id ");
	}
	
	$_SESSION['message']	= ucfirst(str_replace("_"," ",$name)." deleted successfully");
	$redirect = "index?page=view_masterdata&name=$name";
	header("Location: $redirect");
	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"><? echo str_replace(array("_"),array(" "),$page_header); ?></h1>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>
<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-lg-12">
				<div class="card">

				<div class="card-body">
				<div class="" style="padding:0px 10px;">
					<?php include_once('add_quick_master_data.inc.php');?>
				</div>
				<?php
					$name = isset($_REQUEST['name']) ? htmlspecialchars($_REQUEST['name']) : 'Record';
                    
					if($name =='title'){$name = $name.'s';}
					$total_message = "Total no. of " . ucfirst($name).': '.$total_no_of_data;
					echo $total_message;
					?>

				<!--<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">-->					
				<form action="?page=view_masterdata&name=<?=$name?>" method="post" name="form1" id="form1">
				<? if($result>0){
					$hidden = ($_SESSION['is_super_admin']==1)?'':'hidden';
					//echo Keycode::getKeycodeListValue("source", $id="", $width = 250, "source", "id", "code", "source","");
				?>
					<!-- Start  records header -->
				<div id="listing" style="display:<?=$listing;?>;">
				<table id="example1" class="table table-bordered table-striped">
					<thead>
						<tr>
							<th class="<?=$hidden?>">Name</th>
							<th><?=ucwords(str_replace('_', ' ', $name));?></th>
							<!--<th class="<?=$hidden?>">Description</th>-->
							<!--<th>Order</th>-->
							<th>Edit</th>						
							<th>Delete</th>
						</tr>
					</thead>
					<tbody>
					<!-- End records header -->
					<?
					$tabindex = 1;
					while($row = mysqli_fetch_array($sql)){
					$mark_undelete = "";
					if(isset($_SESSION['is_super_admin'])){ 
						$mark_undelete = ($row['status'] == 2) ? "&undelete=1" : "";
						$mark_undelete_color = ($row['status'] == 2) ? "red" : "black";
					}
					?>
					<!-- Start data -->
					<tr style="color:<?=$mark_undelete_color;?>">
						<td class="<?=$hidden?>"><?php echo ucfirst($row['name']); ?></td>
						<td>
							<?php 
								if($row['name'] == "mileage_rate"){
									echo number_format($row['code'],2);
								}else{
									echo ucfirst($row['code']); 
								}
							?>
						</td>
						<!--<td class="<?=$hidden?>"><?php echo ucfirst($row['description']); ?></td>-->
						<!--<td ><input style="width:42px;" tabindex="<?//=$tabindex;?>"  type="text" name="oder[<?//=$row['id']?>]" value="<?//=$row['ord']?>" /></td>-->
						<td><a href="index?page=view_masterdata&action=edit&id=<?=$row['id'].$next_page_condition.$paging;?>"> <i class="fa fa-fw fa-edit text-primary"></i> </a></td>
						<td><a
							href="index?page=view_masterdata&action=delete&id=<?=$row['id'].$next_page_condition.$paging.$mark_undelete; ?>" onclick=" javascript:return confirm('Are you sure! You want to delete');"><i class="fa fa-fw fa-trash text-danger"></i> </a></td>
					</tr>
					<!-- End data -->
					<? 
					$tabindex++;
					}?>
					
					<?}else{?>
					<!--<tr bgcolor="#000000">
						<td height="33" colspan="7" align="center" bgcolor="#000000"></td>
					</tr>-->
					<tr>
						<td colspan="6">No	keycode found...</td>
					</tr>
					<?php }?>
					<tr>
						<td colspan="6">
							<!--<button type="submit" name="set_order" value="Set Order" class="btn btn-primary">Set Order</button>-->
						</td>
					</tr>	
					<input type="hidden" id="keycode_value" name="keycode_value" value="<?=$_REQUEST['keycode']?>" />
					</tbody>
					
				</table>
				</div>
					<!-- Paging starts here  -->
					<? 
					$next_page_condition .="&page=view_masterdata";
					include("paging/paging_row.inc.php") ?>
					<!-- Paging ends starts here  -->
						
					<!--</table>-->
					</form>
					</div>
				</div>
			</div>
		</div>
	</section>
		