churchtube/api/react.php

44 lines
1.4 KiB
PHP

<?php
require_once '../includes/db.php';
require_once '../includes/auth.php';
header('Content-Type: application/json');
if (!isLoggedIn()) {
echo json_encode(['success' => false, 'error' => 'Login required']);
exit;
}
$comment_id = (int)($_POST['comment_id'] ?? 0);
$type = $_POST['type'] ?? '';
if (!$comment_id || !in_array($type, ['thumb', 'heart', 'pray', 'insight', 'clap'])) {
echo json_encode(['success' => false, 'error' => 'Invalid data']);
exit;
}
try {
// Check if exists
$stmt = $pdo->prepare("SELECT id FROM reactions WHERE comment_id = ? AND user_id = ? AND reaction_type = ?");
$stmt->execute([$comment_id, $_SESSION['user_id'], $type]);
$exists = $stmt->fetch();
if ($exists) {
$pdo->prepare("DELETE FROM reactions WHERE id = ?")->execute([$exists['id']]);
$action = 'removed';
} else {
$pdo->prepare("INSERT INTO reactions (comment_id, user_id, reaction_type) VALUES (?, ?, ?)")->execute([$comment_id, $_SESSION['user_id'], $type]);
$action = 'added';
}
// Get new count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM reactions WHERE comment_id = ? AND reaction_type = ?");
$stmt->execute([$comment_id, $type]);
$count = $stmt->fetchColumn();
echo json_encode(['success' => true, 'action' => $action, 'count' => $count]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => 'DB error']);
}
?>