<?php
require __DIR__ . '/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

$action = $_GET['action'] ?? '';
if ($action === '') {
    $input  = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
}

try {
    switch ($action) {
        case 'list':
            $rows = $db->query("SELECT * FROM parsil ORDER BY createdat DESC")->fetchAll();
            echo json_encode(['status' => 'success', 'data' => $rows]);
            break;

        case 'create':
            $input      = json_decode(file_get_contents('php://input'), true);
            $nama       = trim($input['nama'] ?? '');
            $status     = $input['status_kepemilikan'] ?? 'SHM';
            $luas       = isset($input['luas_m2']) ? (float)$input['luas_m2'] : null;
            $geom       = $input['geom'] ?? null;

            if (!$nama) {
                echo json_encode(['status' => 'error', 'message' => 'Nama parsil wajib diisi.']);
                break;
            }
            $validStatus = ['SHM','HGB','HGU','HP'];
            if (!in_array($status, $validStatus)) $status = 'SHM';

            // Validasi dan konversi geometri Polygon
            $geojson = null;
            if (is_array($geom)) {
                if (isset($geom['type']) && $geom['type'] === 'Polygon' && isset($geom['coordinates'])) {
                    $geojson = json_encode($geom);
                } elseif (isset($geom[0]) && is_array($geom[0])) {
                    // array of rings [[lng,lat],...]
                    $geojson = json_encode([
                        'type' => 'Polygon',
                        'coordinates' => $geom
                    ]);
                }
            } elseif (is_string($geom)) {
                $decoded = json_decode($geom, true);
                if ($decoded && isset($decoded['type']) && $decoded['type'] === 'Polygon') {
                    $geojson = $geom;
                } else {
                    echo json_encode(['status'=>'error','message'=>'Format geometri tidak valid.']);
                    break;
                }
            }

            if (!$geojson) {
                echo json_encode(['status' => 'error', 'message' => 'Geometri tidak valid. Harus berupa GeoJSON Polygon atau array koordinat.']);
                break;
            }

            $stmt = $db->prepare("INSERT INTO parsil (nama, status_kepemilikan, luas_m2, geom) VALUES (?, ?, ?, ?)");
            $stmt->execute([$nama, $status, $luas, $geojson]);
            echo json_encode(['status'=>'success','message'=>'Data parsil berhasil disimpan!','id'=>$db->lastInsertId()]);
            break;

        case 'update':
            $input      = json_decode(file_get_contents('php://input'), true);
            $id         = (int)($input['id'] ?? 0);
            $nama       = trim($input['nama'] ?? '');
            $status     = $input['status_kepemilikan'] ?? 'SHM';
            $geom = $input['geom'] ?? null;
            $luas = isset($input['luas_m2']) ? (float)$input['luas_m2'] : null;

            if (!$id)   { echo json_encode(['status'=>'error','message'=>'ID tidak valid.']); break; }
            if (!$nama) { echo json_encode(['status'=>'error','message'=>'Nama parsil wajib diisi.']); break; }
            $validStatus = ['SHM','HGB','HGU','HP'];
            if (!in_array($status, $validStatus)) $status = 'SHM';

            // If geometry provided, validate/convert to GeoJSON string
            $geojson = null;
            if ($geom) {
                if (is_array($geom)) {
                    if (isset($geom['type']) && $geom['type'] === 'Polygon' && isset($geom['coordinates'])) {
                        $geojson = json_encode($geom);
                    } elseif (isset($geom[0]) && is_array($geom[0])) {
                        $geojson = json_encode(['type'=>'Polygon','coordinates'=>$geom]);
                    }
                } elseif (is_string($geom)) {
                    $decoded = json_decode($geom, true);
                    if ($decoded && isset($decoded['type']) && $decoded['type'] === 'Polygon') $geojson = $geom;
                }
                if (!$geojson) { echo json_encode(['status'=>'error','message'=>'Format geometri tidak valid untuk update.']); break; }
            }

            // Build update query dynamically
            $fields = ['nama = ?', 'status_kepemilikan = ?', 'updatedat = NOW()'];
            $params = [$nama, $status];
            if ($luas !== null) { $fields[] = 'luas_m2 = ?'; $params[] = $luas; }
            if ($geojson !== null) { $fields[] = 'geom = ?'; $params[] = $geojson; }
            $params[] = $id;

            $sql = "UPDATE parsil SET " . implode(', ', $fields) . " WHERE id=?";
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            echo json_encode(['status'=>'success','message'=>'Data parsil berhasil diperbarui.']);
            break;

        case 'delete':
            $input = json_decode(file_get_contents('php://input'), true);
            $id    = (int)($input['id'] ?? 0);
            if (!$id) { echo json_encode(['status'=>'error','message'=>'ID tidak valid.']); break; }
            $stmt = $db->prepare("DELETE FROM parsil WHERE id=?");
            $stmt->execute([$id]);
            echo json_encode(['status'=>'success','message'=>'Data parsil berhasil dihapus.']);
            break;

        default:
            echo json_encode(['status'=>'error','message'=>'Aksi tidak dikenali.']);
    }
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>'Database error: '.$e->getMessage()]);
}