<?php
// modules/search_ajax.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';

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

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$type = $_GET['type'] ?? ''; 
$term = trim($_GET['term'] ?? '');

if (empty($type) || strlen($term) < 2) {
    echo json_encode(['results' => []]);
    exit;
}

// جلوگیری از تداخل نام ستون‌ها
$allowed_types = ['customer_name', 'account_username'];
if (!in_array($type, $allowed_types)) {
    echo json_encode(['results' => []]);
    exit;
}

try {
    $sql = "SELECT DISTINCT $type as text FROM transactions WHERE ";
    $params = [];

    if (!$isAdmin) {
        $sql .= "user_id = ? AND ";
        $params[] = $userId;
    }

    $sql .= "$type LIKE ? LIMIT 15";
    $params[] = "%$term%";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted = [];
    foreach ($data as $row) {
        $formatted[] = ['id' => $row['text'], 'text' => $row['text']];
    }

    // خروجی نهایی باید داخل کلید results باشد
    echo json_encode(['results' => $formatted]);

} catch (PDOException $e) {
    echo json_encode(['results' => [], 'error' => $e->getMessage()]);
}
exit;