<?php
include_once("../config.php");

if (!isset($_SESSION['client_id']) || empty($_SESSION['client_id']) || !is_numeric($_SESSION['client_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated or session expired']);
    exit;
}
$clientId = (int)$_SESSION['client_id'];

$search_word_filter = "";
$limit = "LIMIT 10"; // Ensures only 10 results are returned

if(isset($_GET['search']) && !empty($_GET['search'])){
    $search_word = mysqli_real_escape_string($db, $_GET['search']); // Prevent SQL injection
    $search_word_filter = "AND attri_name LIKE '%$search_word%'";
}

// $query = "SELECT attri_name FROM `contact_attributes` 
//           WHERE client_id='$_SESSION[user_id]' $search_word_filter 
//           GROUP BY attri_name 
//           $limit";

$query = "SELECT attri_name FROM `contact_attributes` 
          WHERE client_id='$clientId' $search_word_filter 
          GROUP BY attri_name 
          $limit";

$getAttributes = mysqli_query($db, $query);

$attributes = [];

while ($row = mysqli_fetch_assoc($getAttributes)) {
    $attributes[] = $row['attri_name'];
}

// Return JSON response
echo json_encode($attributes);
?>
