<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'includes/db.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401); // Unauthorized
    echo json_encode(['success' => false, 'message' => 'You must be logged in to like an article.']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);
$item_id = intval($data['item_id'] ?? 0);
$item_type = 'article';
$user_id = $_SESSION['user_id'];

if ($item_id <= 0) {
    http_response_code(400); // Bad Request
    echo json_encode(['success' => false, 'message' => 'Invalid item ID.']);
    exit();
}

$stmt_check = $conn->prepare("SELECT id FROM likes WHERE user_id = ? AND item_id = ? AND item_type = ?");
$stmt_check->bind_param("iis", $user_id, $item_id, $item_type);
$stmt_check->execute();
$result_check = $stmt_check->get_result();

$conn->begin_transaction();
try {
    if ($result_check->num_rows > 0) {
        $like_id = $result_check->fetch_assoc()['id'];
        $conn->prepare("DELETE FROM likes WHERE id = ?")->execute([$like_id]);
        $conn->prepare("UPDATE articles SET like_count = GREATEST(0, like_count - 1) WHERE id = ?")->execute([$item_id]);
        $liked = false;
    } else {
        $conn->prepare("INSERT INTO likes (user_id, item_id, item_type) VALUES (?, ?, ?)")->execute([$user_id, $item_id, $item_type]);
        $conn->prepare("UPDATE articles SET like_count = like_count + 1 WHERE id = ?")->execute([$item_id]);
        $liked = true;
    }
    $conn->commit();

    $new_like_count = $conn->query("SELECT like_count FROM articles WHERE id = $item_id")->fetch_assoc()['like_count'];
    echo json_encode(['success' => true, 'liked' => $liked, 'like_count' => $new_like_count]);
} catch (mysqli_sql_exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
