<?php

//order_fetch.php


// include('function.php');

$query = '';

$output = array();

$query .= "
	SELECT * FROM staff WHERE 
";

if($_SESSION['type'] == 'admin')
{
	$query .= 'user_id = "'.$_SESSION["user_id"].'" AND ';
}

if(isset($_POST["search"]["value"]))
{
	$query .= '(national_id LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR fname LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR other_names LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR phone LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR gender LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR eamil LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR rank LIKE "%'.$_POST["search"]["value"].'%") ';
}

if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY id DESC ';
}

if($_POST["length"] != -1)
{
	$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}


$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
	
	$status = '';
	if($row['status'] == 'active')
	{
		$status = '<span class="label label-success">Active</span>';
	}
	else
	{
		$status = '<span class="label label-danger">Disabled</span>';
	}
	$sub_array = array();
	$sub_array[] = $row['national_id'];
	$sub_array[] = $row['fname'];
	$sub_array[] = $row['email'];
	$sub_array[] = $row['phone'];
	$sub_array[] = $status;
	$sub_array[] = $row['account'];
	/*
	if($_SESSION['type'] == 'master')
	{
		$sub_array[] = get_user_name($connect, $row['user_id']);
	}
	*/
	$sub_array[] = '<a href="view_order.php?pdf=1&order_id='.$row["id"].'" class="btn btn-info btn-xs">View PDF</a>';
	$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete" data-status="'.$row["status"].'">Delete</button>';
	$data[] = $sub_array;
}

function get_total_all_records($connect)
{
	$statement = $connect->prepare("SELECT * FROM staff");
	$statement->execute();
	return $statement->rowCount();
}

$output = array(
	"draw"    			=> 	intval($_POST["draw"]),
	"recordsTotal"  	=>  $filtered_rows,
	"recordsFiltered" 	=> 	get_total_all_records($connect),
	"data"    			=> 	$data
);	

echo json_encode($output);

?>