<?php
	include "db_connection/db_connection.php";
	include "config/config.php";
	$page   = isset($_GET['page'])     ? intval($_GET['page']) : 1;
	$limit  = isset($_GET['limit'])    ? intval($_GET['limit']) : 100;
	$search = isset($_GET['search'])   ? mysqli_real_escape_string($connect, $_GET['search']) : "";
	$sortBy = isset($_GET['sortBy'])   ? $_GET['sortBy'] : "id";
	$sortDir= isset($_GET['sortDir'])  ? $_GET['sortDir'] : "DESC";

	$offset = ($page - 1) * $limit;

	$allowedCols = ['id','member_days','member_type','statu_s'];
	if(!in_array($sortBy, $allowedCols)) $sortBy = 'id';
	$sortDir = ($sortDir == "ASC") ? "ASC" : "DESC";

	$where = "";

	if ($search != "") {

		$search = mysqli_real_escape_string($connect, $search);

		$where = "WHERE 
			member_days LIKE '%$search%' 
			OR member_type LIKE '%$search%'
			OR statu_s LIKE '%$search%'";
	}

	$totalQuery = mysqli_query($connect, "SELECT COUNT(*) AS cnt FROM member_types $where");
	$total = mysqli_fetch_assoc($totalQuery)['cnt'];
	$pages = ceil($total / $limit);

	$sql = "SELECT * FROM member_types $where 
			ORDER BY $sortBy $sortDir 
			LIMIT $limit OFFSET $offset";

	$result = mysqli_query($connect, $sql);

	$data = "";
	$loop=1;
	if(mysqli_num_rows($result)>0){
	while($row = mysqli_fetch_assoc($result)){
		if($row['statu_s'] == 'Active'){ $sts_s = 1; } else { $sts_s = 2; }
			if($loop%2 != "0")
				$bg = "#ffffff";
			else
				$bg = "#f2f2f2";
		$data .= "<tr style='background-color:".$bg."'>
					<td style='text-align:center;'>".$loop."</td>
					<td>".$row['member_type']."</td>
					<td>".$row['member_days']."</td>
					<td><div id='ajaxres_".$loop."'>
				<a href='javascript:0'
				   onfocus='foc(this.id)'
				   onblur='stnon(this.id)'
				   onclick='des_act_mem(\"".$row['id']."\",\"".$sts_s."\",\"".$loop."\");'>
				   ".$row['statu_s']."
				</a>
			</div></td>
				  </tr>";
				  $loop ++;
	}
	} else {
		$data .= "<tr><td colspan='7' style='text-align:center;'>There are no records in the category</td></tr>";
		
	}
	$response = [
		"rows"   => $data,
		"pages"  => $pages,
		"total"  => $total
	];

	echo json_encode($response);
