<?php
require_once 'functions.php';
header('Content-Type: application/json; charset=utf-8');

$action = isset($_GET['action']) ? $_GET['action'] : 'wadmkk';

if ($action === 'wadmkk') {
    // total objects per wadmkk
    $sql = "SELECT a.id AS adm_unit_id, a.wadmkk, COUNT(r.id) AS total_objects, SUM(r.luasha) AS total_area FROM rtrw_object r JOIN adm_unit a ON r.adm_unit_id=a.id GROUP BY a.id, a.wadmkk ORDER BY total_objects DESC";
    $res = $mysqli->query($sql);
    $out = [];
    while ($row = $res->fetch_assoc()) $out[] = $row;
    echo json_encode($out);
    exit;
} elseif ($action === 'namobj') {
    // require wadmkk_id param
    $wadm = isset($_GET['wadmkk_id']) ? intval($_GET['wadmkk_id']) : 0;
    $sql = "SELECT r.namobj, COUNT(*) AS total_objects, SUM(r.luasha) AS total_area FROM rtrw_object r WHERE r.adm_unit_id = " . intval($wadm) . " GROUP BY r.namobj ORDER BY total_objects DESC LIMIT 50";
    $res = $mysqli->query($sql);
    $out = [];
    while ($row = $res->fetch_assoc()) $out[] = $row;
    echo json_encode($out);
    exit;
} elseif ($action === 'category') {
    $cat = isset($_GET['category']) ? $mysqli->real_escape_string($_GET['category']) : 'kkop_1';
    $wadm = isset($_GET['wadmkk_id']) ? intval($_GET['wadmkk_id']) : 0;
    $where = '';
    if ($wadm) $where = "WHERE a.id = " . intval($wadm);
    $sql = "SELECT a.wadmkk, JSON_UNQUOTE(JSON_EXTRACT(r.attributes, '$.".$cat."')) AS category_value, COUNT(*) AS total_objects, SUM(r.luasha) AS total_area FROM rtrw_object r JOIN adm_unit a ON r.adm_unit_id=a.id " . $where . " GROUP BY a.id, category_value ORDER BY total_objects DESC LIMIT 100";
    $res = $mysqli->query($sql);
    $out = [];
    while ($row = $res->fetch_assoc()) $out[] = $row;
    echo json_encode($out);
    exit;
} else {
    echo json_encode(['error'=>'unknown action']);
    exit;
}
?>