<?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 id, namaspbu, nomorwa, statusbuka, 
                                JSON_EXTRACT(koordinat, '$.coordinates[1]') as lat,
                                JSON_EXTRACT(koordinat, '$.coordinates[0]') as lng,
                                koordinat 
                                FROM spbu ORDER BY createdat DESC")->fetchAll();
            foreach ($rows as &$r) {
                $r['lat'] = (float)$r['lat'];
                $r['lng'] = (float)$r['lng'];
            }
            echo json_encode(['status' => 'success', 'data' => $rows]);
            break;

        case 'create':
            $input      = json_decode(file_get_contents('php://input'), true);
            $namaspbu   = trim($input['namaspbu']  ?? '');
            $nomorwa    = trim($input['nomorwa']   ?? '');
            $statusbuka = $input['statusbuka']     ?? 'limited';
            $koordinat  = $input['koordinat']      ?? null;

            if (!$namaspbu) {
                echo json_encode(['status'=>'error','message'=>'Nama SPBU wajib diisi.']);
                break;
            }
            if (!in_array($statusbuka, ['full','limited'])) $statusbuka = 'limited';

            // Validasi dan konversi geometri
            $geojson = null;
            if (is_array($koordinat)) {
                // Cek apakah sudah dalam format GeoJSON Point
                if (isset($koordinat['type']) && $koordinat['type'] === 'Point' && isset($koordinat['coordinates'])) {
                    $geojson = json_encode($koordinat);
                } 
                // Mungkin hanya array [lng, lat]
                elseif (isset($koordinat[0]) && isset($koordinat[1])) {
                    $geojson = json_encode([
                        'type' => 'Point',
                        'coordinates' => [(float)$koordinat[0], (float)$koordinat[1]]
                    ]);
                }
                // Mungkin objek dengan lat,lng
                elseif (isset($koordinat['lat']) && isset($koordinat['lng'])) {
                    $geojson = json_encode([
                        'type' => 'Point',
                        'coordinates' => [(float)$koordinat['lng'], (float)$koordinat['lat']]
                    ]);
                }
            } elseif (is_string($koordinat)) {
                // Coba parse JSON
                $decoded = json_decode($koordinat, true);
                if ($decoded && isset($decoded['type']) && $decoded['type'] === 'Point') {
                    $geojson = $koordinat;
                } else {
                    echo json_encode(['status'=>'error','message'=>'Format koordinat tidak valid.']);
                    break;
                }
            }

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

            $stmt = $db->prepare("INSERT INTO spbu (namaspbu, nomorwa, statusbuka, koordinat) VALUES (?, ?, ?, ?)");
            $stmt->execute([$namaspbu, $nomorwa, $statusbuka, $geojson]);
            echo json_encode(['status'=>'success','message'=>'Data berhasil disimpan!','id'=>$db->lastInsertId()]);
            break;

        case 'update':
            $input      = json_decode(file_get_contents('php://input'), true);
            $id         = (int)($input['id'] ?? 0);
            $namaspbu   = trim($input['namaspbu'] ?? '');
            $nomorwa    = trim($input['nomorwa'] ?? '');
            $statusbuka = $input['statusbuka'] ?? 'limited';
            $koordinat  = $input['koordinat'] ?? null;

            if (!$id) {
                echo json_encode(['status'=>'error','message'=>'ID tidak valid.']);
                break;
            }

            // ===============================
            // JIKA ADA KOORDINAT → UPDATE KOORDINAT
            // ===============================
            if ($koordinat) {
                $geojson = json_encode($koordinat);

                $stmt = $db->prepare("UPDATE spbu SET koordinat=?, updatedat=NOW() WHERE id=?");
                $stmt->execute([$geojson, $id]);

                echo json_encode(['status'=>'success','message'=>'Koordinat berhasil diperbarui!']);
                break;
            }

            // ===============================
            // UPDATE DATA BIASA
            // ===============================
            if (!$namaspbu) {
                echo json_encode(['status'=>'error','message'=>'Nama SPBU wajib diisi.']);
                break;
            }

            $stmt = $db->prepare("UPDATE spbu SET namaspbu=?, nomorwa=?, statusbuka=?, updatedat=NOW() WHERE id=?");
            $stmt->execute([$namaspbu, $nomorwa, $statusbuka, $id]);

            echo json_encode(['status'=>'success','message'=>'Data 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 spbu WHERE id=?");
            $stmt->execute([$id]);
            echo json_encode(['status'=>'success','message'=>'Data 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()]);
}