<?php
require_once "config.php";

$limit = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$offset = ($page-1)*$limit;

$where = "1";
if($filter !== 'all'){
  if(in_array($filter,['sale','rent'])) $where = "type='$filter'";
  else $where = "category='$filter'";
}

$totalRows = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE $where")->fetch_assoc()['cnt'];
$totalPages = ceil($totalRows / $limit);

$result = $conn->query("SELECT * FROM properties WHERE $where ORDER BY id DESC LIMIT $offset,$limit");
$properties = [];
while($row = $result->fetch_assoc()){
  $properties[] = $row;
}

echo json_encode([
  'properties'=>$properties,
  'currentPage'=>$page,
  'totalPages'=>$totalPages
]);
?>
