<?php
require_once __DIR__ . '/../config/auth.php';
header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$q = trim($_GET['q'] ?? '');
if (strlen($q) < 1) {
    echo json_encode(['success' => true, 'products' => []]);
    exit;
}

try {
    $pdo = getDB();
    $currency_symbol = getSetting('currency_symbol', 'Rs.');
    $search = "%$q%";

    $stmt = $pdo->prepare("
        SELECT p.id, p.product_code, p.product_name, p.category_id, p.brand_id, p.supplier_id,
               p.product_type, p.model, p.sku, p.barcode, p.cost_price, p.selling_price,
               p.wholesale_price, p.current_stock, p.low_stock_qty, p.product_image,
               p.warranty_period_days, p.status,
               c.category_name, b.brand_name, s.company_name as supplier_name
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN brands b ON p.brand_id = b.id
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        WHERE p.status = 1 AND (p.product_name LIKE ? OR p.sku LIKE ? OR p.barcode LIKE ? OR p.model LIKE ?)
        ORDER BY p.product_name LIMIT 50
    ");
    $stmt->execute([$search, $search, $search, $search]);
    $name_results = $stmt->fetchAll();

    $imei_results = [];
    $imei_stmt = $pdo->prepare("
        SELECT p.id, p.product_code, p.product_name, p.category_id, p.brand_id, p.supplier_id,
               p.product_type, p.model, p.sku, p.barcode, p.cost_price, p.selling_price,
               p.wholesale_price, p.current_stock, p.low_stock_qty, p.product_image,
               p.warranty_period_days, p.status,
               c.category_name, b.brand_name, s.company_name as supplier_name
        FROM product_imei pi
        JOIN products p ON pi.product_id = p.id
        LEFT JOIN categories c ON p.category_id = c.id
        LEFT JOIN brands b ON p.brand_id = b.id
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        WHERE pi.imei_number LIKE ? AND pi.status = 'Available' AND p.status = 1
        GROUP BY p.id LIMIT 10
    ");
    $imei_stmt->execute([$search]);
    $imei_results = $imei_stmt->fetchAll();

    $all = array_merge($name_results, $imei_results);
    $seen = [];
    $result = [];

    foreach ($all as $p) {
        if (isset($seen[$p['id']])) continue;
        $seen[$p['id']] = true;

        $type = $p['product_type'];
        $stock_ok = false;

        if ($type === 'phone') {
            $imei_count = $pdo->prepare("SELECT COUNT(*) FROM product_imei WHERE product_id = ? AND status = 'Available'");
            $imei_count->execute([$p['id']]);
            $available_imei = (int)$imei_count->fetchColumn();
            $stock_ok = $available_imei > 0;
            $p['available_imei'] = $available_imei;
            $p['display_stock'] = $available_imei;
        } else {
            $stock_ok = $p['current_stock'] > 0;
            $p['available_imei'] = 0;
            $p['display_stock'] = $p['current_stock'];
        }

        if (!$stock_ok) continue;

        $p['selling_price_formatted'] = $currency_symbol . ' ' . number_format($p['selling_price'], 2);
        $p['display_type'] = ($type === 'phone' ? 'Phone' : ($type === 'accessory' ? 'Accessory' : 'Spare Part'));
        $result[] = $p;
    }

    echo json_encode(['success' => true, 'products' => $result]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Search failed']);
}
