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

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

// Check if user is logged in
if (!isset($_SESSION['user']['shop_id'])) {
    die(json_encode(['results' => []]));
}

// Get parameters
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$shop_id = $_SESSION['user']['shop_id'];

// If search is too short, return empty
if (strlen($search) < 2) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
    exit;
}

try {
    $search_term = "%$search%";
    
    // SIMPLE QUERY - Test if basic query works
    $sql = "
        SELECT DISTINCT
            p.id as product_id,
            p.name as product_name,
            p.vat_percent,
            pb.id as batch_id,
            pb.batch_no,
            pb.sell_price,
            pb.qty as current_qty,
            pb.expiry_date
        FROM products p
        JOIN product_batches pb ON p.id = pb.product_id
        WHERE p.shop_id = ?
            AND p.is_active = 1
            AND pb.is_active = 1
            AND pb.qty > 0
            AND (p.name LIKE ? OR pb.batch_no LIKE ?)
        ORDER BY p.name, pb.expiry_date
        LIMIT 20
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$shop_id, $search_term, $search_term]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format for Select2
    $items = [];
    foreach ($results as $row) {
        $stock_qty = (float)$row['current_qty'];
        
        // Skip if no stock
        if ($stock_qty <= 0) {
            continue;
        }
        
        $items[] = [
            'id' => $row['batch_id'],
            'text' => $row['product_name'] . ' - Batch: ' . ($row['batch_no'] ?? 'N/A'),
            'product_id' => (int)$row['product_id'],
            'product_name' => $row['product_name'],
            'batch_id' => (int)$row['batch_id'],
            'batch_no' => $row['batch_no'] ?? 'N/A',
            'expiry_date' => !empty($row['expiry_date']) && $row['expiry_date'] != '0000-00-00' 
                ? date('Y-m-d', strtotime($row['expiry_date'])) 
                : 'N/A',
            'sell_price' => (float)$row['sell_price'],
            'current_qty' => $stock_qty,
            'vat_percent' => (float)$row['vat_percent']
        ];
    }
    
    echo json_encode([
        'results' => $items,
        'pagination' => ['more' => false]
    ]);
    
} catch (Exception $e) {
    error_log("Select2 search error: " . $e->getMessage());
    echo json_encode([
        'results' => [],
        'pagination' => ['more' => false],
        'error' => $e->getMessage()
    ]);
}
exit;