<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

// Sanitize helper
function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

// Required params
if (empty($_POST['user_id']) || empty($_POST['auth']) || empty($_POST['q'])) {
    echo json_encode(['status' => false, 'success' => 'Missing required parameters']);
    exit;
}

$user_id = check_input($_POST['user_id']);
$auth    = check_input($_POST['auth']);
$q       = check_input($_POST['q']);

// Validate requesting user
$stmt = $con->prepare("SELECT id FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$userResult = $stmt->get_result();

if (!$userResult || $userResult->num_rows !== 1) {
    echo json_encode(['status' => false, 'success' => 'Invalid user ID or authentication token']);
    exit;
}

// ✅ Search across firstname, midname, lastname, state, denomination, hobbies, books, activities
$sql = "SELECT * FROM users 
        WHERE user_id != ? 
        AND (
            firstname LIKE CONCAT('%', ?, '%')
            OR midname LIKE CONCAT('%', ?, '%')
            OR lastname LIKE CONCAT('%', ?, '%')
            OR state LIKE CONCAT('%', ?, '%') 
            OR denomination LIKE CONCAT('%', ?, '%') 
            OR hobbies LIKE CONCAT('%', ?, '%') 
            OR books LIKE CONCAT('%', ?, '%') 
            OR activities LIKE CONCAT('%', ?, '%')
        )
        ORDER BY id DESC 
        LIMIT 100";

$stmt = $con->prepare($sql);
$stmt->bind_param("sssssssss", $user_id, $q, $q, $q, $q, $q, $q, $q, $q);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Remove sensitive fields
    unset($row['password'], $row['auth'], $row['ver_code'], $row['code_expiry']);
    $data[] = $row;
}

if (!empty($data)) {
    $response = ['status' => true, 'success' => 'Success', 'data' => $data];
} else {
    $response = ['status' => true, 'success' => 'No matches found', 'data' => []];
}

$con->close();
echo json_encode($response);
?>
