<?php

require_once __DIR__ . '/common.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$pdo = db();


if (!csrf_check($_POST['csrf_token'] ?? null)) {
    header('Location: index.php');
    exit;
}


if (is_ip_blacklisted()) {
    header('Location: index.php');
    exit;
}

$articleId = isset($_POST['article_id']) ? (int)$_POST['article_id'] : 0;
$from      = isset($_POST['from']) ? (string)$_POST['from'] : '';

if ($articleId <= 0) {
    header('Location: index.php');
    exit;
}


if (!rate_limit_cooldown('like_' . $articleId, 2)) {
    if ($from === 'home') {
        header('Location: index.php');
    } else {
        header('Location: post.php?id=' . $articleId);
    }
    exit;
}


try {
    $stmt = $pdo->prepare("
        SELECT id, status
        FROM articles
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $articleId]);
    $article = $stmt->fetch();
    if (!$article || $article['status'] !== 'published') {
        header('Location: index.php');
        exit;
    }
} catch (Throwable $e) {
    header('Location: index.php');
    exit;
}


$ip = client_ip();
if ($ip === '') {
    
    if ($from === 'home') {
        header('Location: index.php');
    } else {
        header('Location: post.php?id=' . $articleId);
    }
    exit;
}

$now   = time();
$liked = false;

try {
    
    $stmt = $pdo->prepare("
        INSERT INTO article_likes (article_id, ip, created_at)
        VALUES (:article_id, :ip, :created_at)
    ");
    $stmt->execute([
        ':article_id' => $articleId,
        ':ip'         => $ip,
        ':created_at' => $now,
    ]);

    
    $stmt2 = $pdo->prepare("
        UPDATE articles
        SET like_count = like_count + 1
        WHERE id = :id
    ");
    $stmt2->execute([':id' => $articleId]);
    $liked = true;
} catch (Throwable $e) {
    
    $liked = false;
}


$flag = $liked ? 'ok' : 'exists';

if ($from === 'home') {
    header('Location: index.php?home_like=' . $flag . '#home-article');
} else {
    header('Location: post.php?id=' . $articleId . '&like=' . $flag);
}
exit;
