<?php

require_once "config.php";
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $ckode = $_GET["cKode"];

        $stmt = $conn->prepare("
            SELECT * 
            FROM tbbarang 
            WHERE cKode = ? 
              AND cFileImage IS NOT NULL 
              AND cFileImage != ''
        ");

        $stmt->bind_param("s", $ckode);
        $stmt->execute();
        $result = $stmt->get_result();

        $rows = [];

        while ($item = $result->fetch_assoc()) {
            // Format harga beli (kalau ada)
            if (isset($item['nHrgBeli']) && $item['nHrgBeli'] !== null) {
                $item['nHrgBeli'] = number_format((float)$item['nHrgBeli'], 2, ',', '.');
            }

            // Format minimal eceran ke integer
            if (isset($item['nMinEcer']) && $item['nMinEcer'] !== null) {
                $item['nMinEcer'] = (int)$item['nMinEcer'];
            }

            // Format berat ke float
            if (isset($item['nberat']) && $item['nberat'] !== null) {
                $item['nberat'] = (float)$item['nberat'];
            }

            $rows[] = $item;
        }

        if (!empty($rows)) {
            // Return just the first item as a JSON object
            echo json_encode($rows[0]);
        } else {
            // If no data found, return a message
            echo json_encode([
                "message" => "Barang tidak ditemukan"
            ]);
        }
        break;
}

$conn->close();
