<?php
require_once __DIR__ . '/config/db.php';

$q = trim($_GET['q'] ?? '');
if ($q === '') exit;

$columns = $pdo->query("SHOW COLUMNS FROM products")->fetchAll(PDO::FETCH_COLUMN);

if (in_array('name_ar', $columns) && in_array('name_en', $columns)) {
    $sql = "SELECT id, name_ar, name_en, price, stock FROM products 
            WHERE name_ar LIKE :q OR name_en LIKE :q LIMIT 10";
} elseif (in_array('name_ar', $columns)) {
    $sql = "SELECT id, name_ar AS name_en, price, stock FROM products 
            WHERE name_ar LIKE :q LIMIT 10";
} else {
    $sql = "SELECT id, name_en AS name_ar, price, stock FROM products 
            WHERE name_en LIKE :q LIMIT 10";
}

$stmt = $pdo->prepare($sql);
$stmt->execute([':q' => "%$q%"]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/json');
echo json_encode($products);
