<?php
// public/api/search_contacts.php
require_once '../../functions.php';

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

// Check Authentication
if (!isset($_SESSION['user_id']) && !isset($_SESSION['admin_id'])) {
    echo json_encode(['results' => []]);
    exit;
}

global $pdo;

$term = $_GET['term'] ?? '';
$search = "%$term%";

// Determine User Context
$user_id = null;
if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
} elseif (isset($_SESSION['admin_id']) && isset($_GET['user_id'])) {
    // Admin can search specific user logs if needed, or global
    // For now, let's assume admin wants to search all logs or specific user logs
    $user_id = $_GET['user_id'];
}

$results = [];

try {
    $query = "SELECT DISTINCT recipient_number FROM sms_logs WHERE recipient_number LIKE ?";
    $params = [$search];

    // If user_id is set (normal user or admin filtering by user), add simple filter
    if ($user_id) {
        $query .= " AND user_id = ?";
        $params[] = $user_id;
    }

    // Limit results for performance
    $query .= " LIMIT 20";

    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $numbers = $stmt->fetchAll(PDO::FETCH_COLUMN);

    foreach ($numbers as $num) {
        $results[] = ['id' => $num, 'text' => $num];
    }

} catch (PDOException $e) {
    // Log error if needed
}

echo json_encode(['results' => $results]);
?>