<?php
require_once 'functions.php';

// get filter inputs safely
$wadmkk_id = isset($_GET['wadmkk_id']) && $_GET['wadmkk_id'] !== '' ? intval($_GET['wadmkk_id']) : 0;
$namobj = isset($_GET['namobj']) ? $mysqli->real_escape_string(trim($_GET['namobj'])) : '';
$kkop_filter = isset($_GET['kkop_filter']) ? $mysqli->real_escape_string(trim($_GET['kkop_filter'])) : '';

// pagination
$per_page = 20;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $per_page;

// build WHERE clauses
$where_clauses = [];

if ($wadmkk_id) {
    $where_clauses[] = "r.adm_unit_id = " . intval($wadmkk_id);
}
if ($namobj !== '') {
    $where_clauses[] = "r.namobj LIKE '%" . $mysqli->real_escape_string($namobj) . "%'";
}
if ($kkop_filter !== '') {
    $kf = $mysqli->real_escape_string($kkop_filter);
    $where_clauses[] = "JSON_UNQUOTE(JSON_EXTRACT(r.attributes,'$.kkop_1')) = '" . $kf . "'";
}

$where_sql = '';
if (count($where_clauses) > 0) $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);

// count total
$count_sql = "SELECT COUNT(*) AS cnt FROM rtrw_object r " . $where_sql;
$res = $mysqli->query($count_sql);
if (!$res) die('Query error: ' . $mysqli->error);
$total_row = $res->fetch_assoc();
$total = intval($total_row['cnt']);
$res->free();

$units = get_adm_units($mysqli);
$kkops = get_distinct_kkop($mysqli);

// fetch rows
$data_sql = "SELECT r.id, r.objectid, r.namobj, r.attributes, r.luasha, r.shape_area, a.wadmkk
            FROM rtrw_object r
            JOIN adm_unit a ON r.adm_unit_id = a.id
            " . $where_sql . " ORDER BY a.wadmkk, r.namobj LIMIT " . intval($per_page) . " OFFSET " . intval($offset);

$result = $mysqli->query($data_sql);
if (!$result) die('Query error: ' . $mysqli->error);
?>
<form method="get" class="filters">
  <label>Wilayah (wadmkk):
    <select name="wadmkk_id">
      <option value="">-- Semua --</option>
      <?php foreach($units as $u): ?>
        <option value="<?php echo $u['id'] ?>" <?php if($wadmkk_id==$u['id']) echo 'selected' ?>><?php echo htmlspecialchars($u['wadmkk']) ?></option>
      <?php endforeach; ?>
    </select>
  </label>
  <label>Nama Objek:
    <input type="text" name="namobj" value="<?php echo htmlspecialchars($namobj) ?>">
  </label>
  <label>Kategori kkop_1:
    <select name="kkop_filter">
      <option value="">-- Semua --</option>
      <?php foreach($kkops as $k): ?>
        <option value="<?php echo htmlspecialchars($k) ?>" <?php if($kkop_filter===$k) echo 'selected' ?>><?php echo htmlspecialchars($k) ?></option>
      <?php endforeach; ?>
    </select>
  </label>
  <button type="submit">Filter</button>
</form>

<div class="summary">
  <p>Menampilkan <strong><?php echo $total ?></strong> hasil. Halaman <?php echo $page ?></p>
</div>

<table class="results">
  <thead><tr><th>#</th><th>Nama Objek</th><th>Wilayah</th><th>Luas (ha)</th><th>Aksi</th></tr></thead>
  <tbody>
    <?php $i = $offset + 1; while ($row = $result->fetch_assoc()): ?>
      <?php $attrs = json_decode($row['attributes'], true); ?>
      <tr>
        <td><?php echo $i++ ?></td>
        <td><?php echo htmlspecialchars($row['namobj']) ?></td>
        <td><?php echo htmlspecialchars($row['wadmkk']) ?></td>
        <td><?php echo is_null($row['luasha']) ? '-' : number_format($row['luasha'],3) ?></td>
        <td><a href="detail.php?id=<?php echo $row['id'] ?>">Detail</a></td>
      </tr>
    <?php endwhile; ?>
  </tbody>
</table>

<div class="pagination">
  <?php
    $total_pages = max(1, ceil($total / $per_page));
    for ($p=1;$p<=$total_pages;$p++) {
      $qs = $_GET; $qs['page']=$p;
      $url = '?' . http_build_query($qs);
      if ($p == $page) echo '<strong>'.$p.'</strong> ';
      else echo '<a href="'.$url.'">'.$p.'</a> ';
    }
  ?>
</div>
