<?php

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

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $searchTerm = strtolower(trim($_GET['query']));
        $cDepartment = strtolower(trim($_GET['cDepartment']));

            if (strlen($searchTerm) < 3) {
                echo json_encode([]); 
                break;
            }
            
            if (empty($cDepartment) || $cDepartment === 'semua kategori') {
                echo json_encode([]);
                break;
            }

            $stmt = $conn->prepare("SELECT cDepartment, cNama  
                                    FROM tbbarang 
                                    WHERE cFileImage IS NOT NULL 
                                      AND cFileImage != '' 
                                      AND cNama LIKE ?
                                      AND cDepartment <> ? 
                                    GROUP BY cDepartment");
            
            $searchParam = '%' . $searchTerm . '%';
            $stmt->bind_param("ss", $searchParam, $cDepartment);

            $stmt->execute();
            $result = $stmt->get_result();

            $items = [];

            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $items[] = [
                        'cDepartment' => $row['cDepartment'],
                        'cNama' => $row['cNama']
                    ];
                }

                echo json_encode($items);
            } else {
                echo json_encode(['error' => 'Query gagal: ' . $conn->error]);
            }

            $stmt->close();
        break;

    default:
        echo json_encode(['error' => 'Invalid request method.']);
        break;
}

$conn->close();
?>
