<?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';

// Helper function to sanitize user input
function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

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

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

// Use prepared statement to prevent SQL injection
$stmt = $con->prepare("SELECT gender, city, state 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) {
    $userRow = $userResult->fetch_assoc();
    $gender = $userRow['gender'];
    $city = $userRow['city'];
    $state = $userRow['state'];

    // Set preferred gender
    $preferredGender = ($gender === "Male") ? "Female" : "Male";

    // Fetch other users with opposite gender, prioritizing those in the same city and state
   $stmt = $con->prepare("
    SELECT * FROM users 
    WHERE gender = ? 
      AND user_id != ? 
      AND user_id NOT IN (SELECT match_id FROM likes WHERE user_id = ?) 
      AND user_id NOT IN (SELECT match_id FROM matches WHERE user_id = ?) 
      AND ( (city = ? AND state = ?) OR (1 = 1) )
    ORDER BY id DESC 
    LIMIT 100
");
$stmt->bind_param("ssssss", $preferredGender, $user_id, $user_id, $user_id, $city, $state);
 $stmt->execute();
    $activityResult = $stmt->get_result();

    $data = $activityResult->fetch_all(MYSQLI_ASSOC);

    $response = [
        'status' => true,
        'success' => !empty($data) ? 'Success' : 'No Match',
        'data' => $data
    ];
} else {
    $response = ['status' => false, 'success' => 'Invalid user ID or authentication token'];
}

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