<?php
session_start();
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'petugas'])) {
    header('Content-Type: application/json');
    http_response_code(403);
    echo json_encode(['status'=>'error','message'=>'Akses ditolak.']);
    exit;
}

include '../koneksi.php';
header('Content-Type: application/json');

$nama_parsil       = trim($_POST['nama_parsil']       ?? '');
$status_kepemilikan= trim($_POST['status_kepemilikan']?? '');
$luas_tanah        = trim($_POST['luas_tanah']        ?? '0');
$koordinat         = trim($_POST['koordinat']         ?? '');

if (!$nama_parsil || !$status_kepemilikan || !$koordinat) {
    echo json_encode(['status'=>'error','message'=>'Field wajib tidak boleh kosong.']);
    exit;
}

$decoded = json_decode($koordinat, true);
if (!$decoded || ($decoded['geometry']['type'] ?? '') !== 'Polygon') {
    echo json_encode(['status'=>'error','message'=>'Format GeoJSON tidak valid.']);
    exit;
}

$valid_status = ['SHM','HGB','HGU','HP'];
if (!in_array($status_kepemilikan, $valid_status)) {
    echo json_encode(['status'=>'error','message'=>'Status kepemilikan tidak valid.']);
    exit;
}

try {
    $stmt = $pdo->prepare(
        "INSERT INTO polygon (nama_parsil, status_kepemilikan, luas_tanah, koordinat)
         VALUES (?, ?, ?, ?)"
    );
    $stmt->execute([$nama_parsil, $status_kepemilikan, $luas_tanah, $koordinat]);
    $id   = $pdo->lastInsertId();
    
    $stmtSelect = $pdo->prepare("SELECT * FROM polygon WHERE id=?");
    $stmtSelect->execute([$id]);
    $data = $stmtSelect->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode(['status'=>'success','data'=>$data]);
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>
