<?php
require_once "connection.php";

// Check if 'userId' is set in the URL parameters
if (isset($_GET['userId'])) {
    // Sanitize the input to prevent SQL injection
    $userId = $con->real_escape_string($_GET['userId']);
    
    // Prepare the SQL query to fetch the data
    $sql = "SELECT statusPinjaman, plafond, jenisKredit, tanggalPengajuan, namaLengkap FROM pinjaman WHERE userId = '$userId'";

    // Execute the query
    $result = $con->query($sql);

    // Check if query was successful and if there are results
    if (!$result) {
        echo json_encode(["error" => "Error in executing query."]);
    } else {
        // If results exist
        if ($result->num_rows > 0) {
            $data = [];
            // Fetch and store the results in an array
            while($row = $result->fetch_assoc()) {
                // Store the data in the 'hasil' key
                $data["hasil"][] = [
                    "statusPinjaman" => $row['statusPinjaman'],
                    "plafond" => $row['plafond'],
                    "jenisKredit" => $row['jenisKredit'],
                    "tanggalPengajuan" => $row['tanggalPengajuan'],
                    "namaLengkap" => $row['namaLengkap']
                ];
            }
            // Return the results as a JSON array
            echo json_encode($data);
        } else {
            // If no results are found
            echo json_encode(["message" => "Tidak ada data pengajuan."]);
        }
    }
}
?>
