<?php
// modules/sales/search_products_select2.php
session_start();
require_once "../assets/db_connect.php";

header('Content-Type: application/json');

// Get parameters
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$shop_id = isset($_GET['shop_id']) ? (int)$_GET['shop_id'] : 1;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// If search is too short, return empty
if (strlen($search) < 2) {
    echo json_encode(['items' => [], 'total_count' => 0]);
    exit;
}

try {
    // Simple query without counting for now
    $sql = "
        SELECT 
            p.id as product_id,
            p.sku,
            p.name as product_name,
            COALESCE(p.vat_percent, 0) as vat_percent,
            p.selling_price,
            pb.id as batch_id,
            pb.batch_no,
            pb.expiry_date,
            COALESCE(pb.sell_price, p.selling_price) as sell_price,
            pb.qty as current_qty
        FROM products p
        INNER JOIN product_batches pb ON p.id = pb.product_id 
            AND pb.is_active = 1
            AND pb.qty > 0
        WHERE p.shop_id = ?
            AND p.is_active = 1
            AND p.name LIKE ?
        ORDER BY p.name, pb.expiry_date
        LIMIT ?
    ";
    
    $search_term = "%$search%";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$shop_id, $search_term, $limit]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format for Select2
    $items = [];
    foreach ($results as $row) {
        $items[] = [
            'id' => $row['batch_id'], // Use batch_id as unique ID
            'text' => $row['product_name'] . ' - ' . $row['batch_no'],
            'product_id' => (int)$row['product_id'],
            'product_name' => $row['product_name'],
            'sku' => $row['sku'],
            'vat_percent' => (float)$row['vat_percent'],
            'batch_id' => (int)$row['batch_id'],
            'batch_no' => $row['batch_no'],
            'expiry_date' => $row['expiry_date'],
            'sell_price' => (float)$row['sell_price'],
            'current_qty' => (int)$row['current_qty'],
            'shop_id' => $shop_id
        ];
    }
    
    echo json_encode([
        'items' => $items,
        'total_count' => count($items) // Simplified count
    ]);
    
} catch (Exception $e) {
    // Return empty on error
    echo json_encode([
        'items' => [],
        'total_count' => 0
    ]);
}
?>