38873-vm/api/follow_startup.php
Flatlogic Bot d2d6703960 v73
2026-02-28 23:48:52 +00:00

55 lines
1.8 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
session_start();
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
echo json_encode(['success' => 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()]);
}