<?php
// ajax/search_pharmacy_inventory.php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0); // Set to 1 for debugging

include '../layouts/dbconn.php'; // Adjust path if needed

$q = trim($_GET['q'] ?? '');
$page = intval($_GET['page'] ?? 1);
$limit = 20; // Results per page
$offset = ($page - 1) * $limit;

// Validate input
if (strlen($q) < 2) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
    exit;
}

// Build query for fuzzy search on item_name and generic_name
$sql = "SELECT 
    inventory_id AS id, 
    item_name AS text,
    item_name,
    generic_name,
    strength,
    dosage_form,
    current_stock,
    unit_of_measure,
    selling_price,
    CASE 
        WHEN current_stock <= 0 THEN 'OUT_OF_STOCK'
        WHEN current_stock <= 10 THEN 'LOW_STOCK'  -- Adjust threshold as needed
        ELSE 'IN_STOCK'
    END AS stock_status
FROM pharmacy_inventory 
WHERE (item_name LIKE ? OR generic_name LIKE ? OR strength LIKE ?)
ORDER BY item_name ASC
LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false], 'error' => $conn->error]);
    exit;
}

$searchTerm = "%$q%";
$stmt->bind_param("sssii", $searchTerm, $searchTerm, $searchTerm, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    // Ensure numeric fields are properly typed
    $row['current_stock'] = intval($row['current_stock']);
    $row['selling_price'] = floatval($row['selling_price']);
    $items[] = $row;
}

// For pagination: Get total count (optional; enables "more" results)
$countSql = "SELECT COUNT(*) as total FROM pharmacy_inventory WHERE (item_name LIKE ? OR generic_name LIKE ? OR strength LIKE ?)";
$countStmt = $conn->prepare($countSql);
$countStmt->bind_param("sss", $searchTerm, $searchTerm, $searchTerm);
$countStmt->execute();
$total = $countStmt->get_result()->fetch_assoc()['total'];
$more = ($offset + $limit) < $total;

echo json_encode([
    'results' => $items,
    'pagination' => ['more' => $more]
]);

$stmt->close();
$countStmt->close();
$conn->close();
?>