<?php
//user_fetch.php
include('db_con.php');
if (isset($_SESSION['user_id'])) {
		$user_type = $_SESSION['user_type'];
		$user_id = $_SESSION['user_id'];
		$user_name = $_SESSION['user_name'];
		$branch_id = $_SESSION['branch_id'];
		$branch_name = $_SESSION['branch_name'];
		$store_id = $_SESSION['store_id'];
    $store_name = $_SESSION['store_name'];
}else{
	header('Location: login');
	die();
}
$query = '';
$output = array();
$query .= "
SELECT * FROM accounts
WHERE acc_type = 'CREDITOR' AND
";
if(isset($_POST["search"]["value"]))
{
	$query .= '(acc_name LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR city LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR address LIKE "%'.$_POST["search"]["value"].'%" ';
	
	$query .= 'OR phone LIKE "%'.$_POST["search"]["value"].'%") ';
	
}
if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY acc_no 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">Inactive</span>';
	}
	$sub_array = array();
	$sub_array[] = $row['acc_no'];
	$sub_array[] = $row['acc_name'];
	$sub_array[] = $row['address'];
	$sub_array[] = $row['city'];
	
	$sub_array[] = $row['phone'];
	
	$sub_array[] = $status;
	$sub_array[] = '<button type="button" name="update" id="'.$row["acc_no"].'" class="btn btn-warning btn-xs update"><i class="fa fa-edit"></i></button>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["acc_no"].'" class="btn btn-danger btn-xs delete" data-status=""><i class="fa fa-trash-o"></i></button>';
	$data[] = $sub_array;
}
$output = array(
	"draw"				=>	intval($_POST["draw"]),
	"recordsTotal"  	=>  $filtered_rows,
	"recordsFiltered" 	=> 	get_total_all_records($connect),
	"data"    			=> 	$data
);
echo json_encode($output);
function get_total_all_records($connect)
{
	$statement = $connect->prepare("SELECT * FROM accounts WHERE acc_type = 'CREDITOR'" );
	$statement->execute();
	return $statement->rowCount();
}
?>