<?php
require 'db.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed.']);
    exit;
}

$id = $_POST['id'] ?? null;
$nama_pemilik = $_POST['nama_pemilik'] ?? null;
$status_kepemilikan = $_POST['status_kepemilikan'] ?? null;
$luas_m2 = $_POST['luas_m2'] ?? null;
$koordinat = $_POST['koordinat'] ?? null;

if ($id === null || $nama_pemilik === null || $status_kepemilikan === null || $luas_m2 === null || $koordinat === null) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields.']);
    exit;
}

$decoded = json_decode($koordinat, true);
if ($decoded === null) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid koordinat JSON.']);
    exit;
}

$sql = "UPDATE tb_parsil SET nama_pemilik = ?, status_kepemilikan = ?, luas_m2 = ?, koordinat = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);

if ($stmt->execute([$nama_pemilik, $status_kepemilikan, (float)$luas_m2, $koordinat, (int)$id])) {
    echo json_encode(['status' => 'success', 'message' => 'Parsil updated.']);
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Failed to update parsil.']);
}
