<?php

require_once "config.php";
header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $cjenis = $_GET['cjenis'];
        $search = isset($_GET['search']) ? $_GET['search'] : '';

        $searchParam = $search ? '%' . $search . '%' : '';

        if (empty($cjenis) || strtolower($cjenis) === 'semua kategori') {
            if (empty($search)) {
                $stmt = $conn->prepare("SELECT * FROM tbbarang WHERE cFileImage IS NOT NULL AND cFileImage != '' LIMIT 80");
            } else {
                $stmt = $conn->prepare("SELECT * FROM tbbarang WHERE cFileImage IS NOT NULL AND cFileImage != '' AND cNama LIKE ? LIMIT 80");
                $stmt->bind_param("s", $searchParam);
            }
        } else {
            if (empty($search)) {
                $stmt = $conn->prepare("SELECT * FROM tbbarang WHERE cDepartment = ? AND cFileImage IS NOT NULL AND cFileImage != ''  LIMIT 80");
                $stmt->bind_param("s", $cjenis);
            } else {
                $stmt = $conn->prepare("SELECT * FROM tbbarang WHERE cDepartment = ? AND cFileImage IS NOT NULL AND cFileImage != '' AND cNama LIKE ?  LIMIT 80");
                $stmt->bind_param("ss", $cjenis, $searchParam);
            }
        }

        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);

        foreach ($data as &$item) {
            if (isset($item['nHrgJualPerPcs'])) {
                $item['nHrgJualPerPcs'] = number_format((float) $item['nHrgJualPerPcs'], 2, ',', '.');

            }
            if (isset($item['nMinEcer']) && $item['nMinEcer'] !== null) {
                $item['nMinEcer'] = (int) $item['nMinEcer'];
            }
        }

        if (empty($data)) {
            echo json_encode([]);  
        } else {
            echo json_encode($data);
        }

        $stmt->close();
        break;

    default:
        echo json_encode(array("error" => "Invalid request method"));
        break;
}

mysqli_close($conn);
?>
