<?php
// api/fetch_user_data.php
session_start();
header('Content-Type: application/json');

include 'db_connect.php'; // <--- UBAH PATH INI: 'db_connect.php' karena sudah berada di folder yang sama

$response = ['success' => false, 'message' => ''];

// Pastikan user sudah login dan session user_id tersedia
if (!isset($_SESSION['user_id'])) {
    $response['message'] = 'User not logged in.';
    echo json_encode($response);
    exit();
}

$user_id = $_SESSION['user_id'];

try {
    // Ambil data dari tabel users
    $stmt = $conn->prepare("SELECT full_name, nik, address, village, rt, rw, coordinates FROM users WHERE id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user_data) {
        $response['success'] = true;
        $response['data'] = $user_data;
    } else {
        $response['message'] = 'User data not found.';
    }

} catch (PDOException $e) {
    $response['message'] = 'Database error: ' . $e->getMessage();
}

echo json_encode($response);
?>