<?php
require_once 'db.php';
session_start();

if (!isset($_SESSION['logged_in_user'])) {
    exit(json_encode(["status" => "error", "message" => "Unauthorized access"]));
}

$loggedInUser = $_SESSION['logged_in_user'];
$query = isset($_GET['q']) ? trim($_GET['q']) : '';

if (empty($query)) {
    exit(json_encode(["status" => "empty", "message" => ""])); // Return an empty response for no search term
}

// ✅ Wildcard search setup
$searchQuery = "%{$query}%";
$stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, tracking_source, created_at 
                       FROM users 
                       WHERE referrer_id = ? 
                       AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR user_id LIKE ?) 
                       LIMIT 10");
$stmt->execute([$loggedInUser, $searchQuery, $searchQuery, $searchQuery, $searchQuery]);
$referrals = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Handle No Results
if (!$referrals) {
    exit(json_encode(["status" => "not_found", "message" => "No referrals found."]));
}

// ✅ Format and return full data
$formatted = [];
foreach ($referrals as $row) {
    $formatted[] = [
        'first_name' => $row['first_name'],
        'last_name' => $row['last_name'],
        'user_id' => $row['user_id'],
        'email' => $row['email'],
        'tracking_source' => $row['tracking_source'] ?? 'Unknown',
        'created_at' => !empty($row['created_at']) ? date('M j, Y', strtotime($row['created_at'])) : ''
    ];
}

exit(json_encode(["status" => "success", "data" => $formatted]));
