false, 'match' => false, 'error' => null]; if (!isset($_SESSION['user_id'])) { $response['error'] = 'User not authenticated.'; echo json_encode($response); exit; } $current_user_id = $_SESSION['user_id']; $data = json_decode(file_get_contents('php://input'), true); $swiped_user_id = $data['swiped_user_id'] ?? null; $action = $data['action'] ?? null; // 'like' or 'dislike' if (!$swiped_user_id || !in_array($action, ['like', 'dislike'])) { $response['error'] = 'Invalid input.'; echo json_encode($response); exit; } try { $pdo = db(); // 1. Record the swipe action $stmt = $pdo->prepare( "INSERT INTO swipes (swiper_user_id, swiped_user_id, swipe_type) VALUES (:swiper_user_id, :swiped_user_id, :swipe_type)" ); $stmt->execute([ ':swiper_user_id' => $current_user_id, ':swiped_user_id' => $swiped_user_id, ':swipe_type' => $action ]); // 2. If it was a 'like', check for a mutual match if ($action === 'like') { $stmt = $pdo->prepare( "SELECT COUNT(*) FROM swipes WHERE swiper_user_id = :swiped_user_id AND swiped_user_id = :current_user_id AND swipe_type = 'like'" ); $stmt->execute([ ':swiped_user_id' => $swiped_user_id, ':current_user_id' => $current_user_id ]); $is_mutual = (int)$stmt->fetchColumn() > 0; if ($is_mutual) { // 3. It's a match! Insert into matches table. $user1 = min($current_user_id, $swiped_user_id); $user2 = max($current_user_id, $swiped_user_id); $stmt = $pdo->prepare( "INSERT INTO matches (user1_id, user2_id) SELECT :user1_id, :user2_id WHERE NOT EXISTS ( SELECT 1 FROM matches WHERE (user1_id = :user1_id AND user2_id = :user2_id) OR (user1_id = :user2_id AND user2_id = :user1_id) )" ); $stmt->execute([ ':user1_id' => $user1, ':user2_id' => $user2 ]); $response['match'] = true; // Fetch the matched user's name for the notification $stmt = $pdo->prepare("SELECT name FROM user_profiles WHERE user_id = :swiped_user_id"); $stmt->execute(['swiped_user_id' => $swiped_user_id]); $matched_user = $stmt->fetch(PDO::FETCH_ASSOC); $response['matched_user_name'] = $matched_user['name'] ?? 'Someone'; } } $response['success'] = true; } catch (PDOException $e) { $response['error'] = "Database error: " . $e->getMessage(); } // Finally, get the next companion to show $stmt = $pdo->prepare( "SELECT p.* FROM user_profiles p JOIN users u ON p.user_id = u.id WHERE u.role = 'companion' AND p.user_id != :current_user_id AND p.user_id NOT IN ( SELECT swiped_user_id FROM swipes WHERE swiper_user_id = :current_user_id ) ORDER BY RAND() LIMIT 1" ); $stmt->execute(['current_user_id' => $current_user_id]); $next_companion = $stmt->fetch(PDO::FETCH_ASSOC); $response['next_companion_html'] = render_companion_card($next_companion); echo json_encode($response);