<?php
session_start();
include '../config/db.php';

try {
    // Check if there's a search parameter
    $search = isset($_GET['search']) ? $_GET['search'] : '';
    
    if ($search) {
        // Query with search and limit
        $query = "SELECT id, drug_name, quantity, selling_price, volume_price, image_path, barcode 
                 FROM drugs 
                 WHERE drug_name LIKE :search 
                 AND quantity > 0 
                 ORDER BY drug_name ASC 
                 LIMIT 20";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute(['search' => "%$search%"]);
    } else {
        // Query without search but with limit
        $query = "SELECT id, drug_name, quantity, selling_price, volume_price, image_path, barcode 
                 FROM drugs 
                 WHERE quantity > 0 
                 ORDER BY drug_name ASC 
                 LIMIT 20";
        
        $stmt = $pdo->prepare($query);
        $stmt->execute();
    }
    
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    header('Content-Type: application/json');
    echo json_encode($products);
    
} catch (PDOException $e) {
    header('Content-Type: application/json');
    http_response_code(500);
    echo json_encode([
        'error' => true,
        'message' => 'Error fetching products: ' . $e->getMessage()
    ]);
}