<?php
session_start();

function checkLogin() {
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'User not logged in. Please login to comment.']);
        exit;
    }
}

function connectDatabase() {
    $host = 'localhost';
    $db = 'digupdog_FEED';
    $user = 'digupdog_FEEDadmin';
    $pass = 'Raimundinho1';
    $charset = 'utf8mb4';
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    try {
        return new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass, $options);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Failed to connect to the database: ' . $e->getMessage()]);
        exit;
    }
}

function insertComment($pdo, $feed_id, $user_id, $comment_text, $link_preview, $title, $description, $thumbnail, $parent_comment_id = null) {
    $stmt = $pdo->prepare("INSERT INTO comments (feed_id, user_id, comment_text, link_preview, title, description, thumbnail, parent_comment_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    return $stmt->execute([$feed_id, $user_id, $comment_text, $link_preview, $title, $description, $thumbnail, $parent_comment_id]);
}

// Verificação de login
checkLogin();
$user_id = $_SESSION['user_id'];
$pdo = connectDatabase();

// Verifica o método da requisição e processa o comentário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $feed_id = intval($_POST['feed_id']);
    $comment_text = trim($_POST['comment_text']);
    $link_preview = trim($_POST['link_preview'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $thumbnail = trim($_POST['thumbnail'] ?? '');
    $parent_comment_id = isset($_POST['parent_comment_id']) ? intval($_POST['parent_comment_id']) : null;

    if (!empty($comment_text)) {
        if (insertComment($pdo, $feed_id, $user_id, $comment_text, $link_preview, $title, $description, $thumbnail, $parent_comment_id)) {
            echo json_encode(['success' => true, 'message' => 'Comment posted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error inserting comment']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Comment cannot be empty']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}

?>