<?php
//user_fetch.php
include('db_con.php');
$query = '';
$output = array();
$query .= "
SELECT r.pay_id,r.dated,a.acc_name name,r.description,r.pay_status, r.amount FROM pay_voucher r, accounts a WHERE
r.v_id=a.acc_no AND r.paid_by='Cheque' AND";
if(isset($_POST["search"]["value"]))
{
	$query .= '(a.acc_name LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR description LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR a.acc_name LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR r.dated LIKE "%'.$_POST["search"]["value"].'%" ';
	$query .= 'OR amount LIKE "%'.$_POST["search"]["value"].'%")';
	
	
}
if(isset($_POST["order"]))
{
	$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
	$query .= 'ORDER BY pay_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["pay_status"] == 'Cleared')
	{
		$status = '<span class="btn btn-sm btn-success disabled">Cleared</span>';
	}
	else
	{
		$status = '<span class="btn btn-sm btn-danger disabled">Not Cleared</span>';
	}
	$sub_array = array();
	$sub_array[] = $row['pay_id'];
	$sub_array[] = $row['dated'];
	$sub_array[] = $row['name'];
	
	$sub_array[] = $row['description'];
	$sub_array[] = $row['amount'];
	
	$sub_array[] = $status;
$sub_array[] = '<a href="ap_cheque_payment_edit.php?update=1&id='.$row["pay_id"].'"><span class="btn btn-warning"><i class="fa fa-edit"></i></span></a>';
	$sub_array[] = '<button type="button" name="delete" id="'.$row["pay_id"].'" class="btn btn-danger btn-xs delete" ><i class="fa fa-remove"></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 pay_voucher");
	$statement->execute();
	return $statement->rowCount();
}
?>