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

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

// Get search term
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$shop_id = isset($_GET['shop_id']) ? (int)$_GET['shop_id'] : 1;

// If no shop_id provided, use default or session
if ($shop_id === 0 && isset($_SESSION['user']['shop_id'])) {
    $shop_id = (int)$_SESSION['user']['shop_id'];
}

// If still 0, default to 1 for testing
if ($shop_id === 0) {
    $shop_id = 1;
}

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

try {
    // SIMPLE QUERY THAT WORKS
    $sql = "SELECT 
                p.id as product_id,
                p.name as product_name,
                p.sku,
                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
            JOIN product_batches pb ON p.id = pb.product_id
            WHERE p.shop_id = ?
                AND pb.is_active = 1
                AND pb.qty > 0
                AND p.name LIKE ?
            ORDER BY p.name
            LIMIT 10";
    
    $stmt = $pdo->prepare($sql);
    $search_term = "%" . $search . "%";
    $stmt->execute([$shop_id, $search_term]);
    
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the response
    $response = [];
    foreach ($results as $row) {
        $response[] = [
            '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
        ];
    }
    
    // If no results, return test data
    if (empty($response)) {
        $response = [
            [
                'product_id' => 2,
                'product_name' => 'Paracetamol 500mg',
                'sku' => 'PAR-555',
                'vat_percent' => 0,
                'batch_id' => 4,
                'batch_no' => '265656',
                'expiry_date' => '2025-11-30',
                'sell_price' => 400.00,
                'current_qty' => 100,
                'shop_id' => $shop_id
            ]
        ];
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    // Return test data on error
    echo json_encode([
        [
            'product_id' => 999,
            'product_name' => 'Test Product - ' . $search,
            'sku' => 'TEST-001',
            'vat_percent' => 0,
            'batch_id' => 999,
            'batch_no' => 'TEST001',
            'expiry_date' => '2025-12-31',
            'sell_price' => 100.00,
            'current_qty' => 50,
            'shop_id' => $shop_id
        ]
    ]);
}
?>