63 lines
2.2 KiB
PHP
63 lines
2.2 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
echo json_encode(['success' => false, 'error' => 'User not logged in.']);
|
|
exit();
|
|
}
|
|
|
|
if (!isset($_GET['post_id']) || !isset($_GET['action'])) {
|
|
echo json_encode(['success' => false, 'error' => 'Invalid request.']);
|
|
exit();
|
|
}
|
|
|
|
$postId = (int)$_GET['post_id'];
|
|
$action = $_GET['action'];
|
|
$userId = $_SESSION['user_id'];
|
|
$vote = ($action === 'like') ? 1 : -1;
|
|
|
|
$pdo = db();
|
|
|
|
try {
|
|
$pdo->beginTransaction();
|
|
|
|
// Check for existing vote
|
|
$stmt = $pdo->prepare('SELECT vote FROM post_votes WHERE user_id = :user_id AND post_id = :post_id');
|
|
$stmt->execute(['user_id' => $userId, 'post_id' => $postId]);
|
|
$existingVote = $stmt->fetchColumn();
|
|
|
|
if ($existingVote) {
|
|
if ($existingVote == $vote) {
|
|
// User is undoing their vote
|
|
$stmt = $pdo->prepare('DELETE FROM post_votes WHERE user_id = :user_id AND post_id = :post_id');
|
|
$stmt->execute(['user_id' => $userId, 'post_id' => $postId]);
|
|
} else {
|
|
// User is changing their vote
|
|
$stmt = $pdo->prepare('UPDATE post_votes SET vote = :vote WHERE user_id = :user_id AND post_id = :post_id');
|
|
$stmt->execute(['vote' => $vote, 'user_id' => $userId, 'post_id' => $postId]);
|
|
}
|
|
} else {
|
|
// New vote
|
|
$stmt = $pdo->prepare('INSERT INTO post_votes (user_id, post_id, vote) VALUES (:user_id, :post_id, :vote)');
|
|
$stmt->execute(['user_id' => $userId, 'post_id' => $postId, 'vote' => $vote]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
|
|
// Fetch new like/dislike counts
|
|
$stmt = $pdo->prepare('SELECT
|
|
(SELECT COUNT(*) FROM post_votes WHERE post_id = :post_id AND vote = 1) as likes,
|
|
(SELECT COUNT(*) FROM post_votes WHERE post_id = :post_id AND vote = -1) as dislikes
|
|
');
|
|
$stmt->execute(['post_id' => $postId]);
|
|
$counts = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
echo json_encode(['success' => true, 'likes' => $counts['likes'], 'dislikes' => $counts['dislikes']]);
|
|
|
|
} catch (Exception $e) {
|
|
$pdo->rollBack();
|
|
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
|
|
} |