<?php
require_once '../includes/auth.php';
require_once 'functions.php';
header('Content-Type: application/json; charset=utf-8');
try {
    pic_ensure_schema($conn);
    pic_refresh_used_flags($conn);
    $q = trim((string)($_GET['q'] ?? ''));
    $like = '%' . $q . '%';
    if ($q === '') {
        $stmt = $conn->prepare("SELECT * FROM product_import_catalog ORDER BY is_used ASC, updated_at DESC, id DESC LIMIT 30");
    } else {
        $stmt = $conn->prepare("SELECT * FROM product_import_catalog WHERE internal_name LIKE ? OR internal_slug LIKE ? OR barcode LIKE ? ORDER BY is_used ASC, internal_name ASC LIMIT 30");
        $stmt->bind_param('sss', $like, $like, $like);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    $items = [];
    while ($row = $res->fetch_assoc()) {
        $items[] = [
            'id' => (int)$row['id'],
            'internal_name' => (string)$row['internal_name'],
            'internal_slug' => (string)$row['internal_slug'],
            'barcode' => (string)$row['barcode'],
            'price' => (float)$row['price'],
            'is_used' => (int)$row['is_used'] === 1,
            'linked_product_id' => $row['linked_product_id'] ? (int)$row['linked_product_id'] : null,
        ];
    }
    echo json_encode(['success'=>true,'items'=>$items], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
