false, 'error' => 'Not logged in']); exit; } $startup_id = $_POST['startup_id'] ?? null; if (!$startup_id) { echo json_encode(['success' => false, 'error' => 'Startup ID is required']); exit; } try { // Check if already following $stmt = db()->prepare("SELECT 1 FROM startup_followers WHERE startup_id = ? AND user_id = ?"); $stmt->execute([$startup_id, $user_id]); $is_following = (bool)$stmt->fetch(); if (!$is_following) { // Follow $stmt = db()->prepare("INSERT IGNORE INTO startup_followers (startup_id, user_id) VALUES (?, ?)"); $stmt->execute([$startup_id, $user_id]); $action_result = 'followed'; } else { // Unfollow $stmt = db()->prepare("DELETE FROM startup_followers WHERE startup_id = ? AND user_id = ?"); $stmt->execute([$startup_id, $user_id]); $action_result = 'unfollowed'; } // Update denormalized count $stmt = db()->prepare("UPDATE startups SET followers_count = (SELECT COUNT(*) FROM startup_followers WHERE startup_id = ?) WHERE id = ?"); $stmt->execute([$startup_id, $startup_id]); // Get new count $stmt = db()->prepare("SELECT followers_count FROM startups WHERE id = ?"); $stmt->execute([$startup_id]); $new_count = $stmt->fetchColumn(); echo json_encode([ 'success' => true, 'action' => $action_result, 'new_count' => (int)$new_count, 'followers_count' => (int)$new_count // redundancy for both frontend versions ]); } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage()]); }