<?php

class Comment {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function getAll($postId) {
         $stmt = $this->pdo->prepare("
            SELECT c.*, u.username 
            FROM comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.post_id = ?
            ORDER BY c.created_at ASC
        ");
        $stmt->execute([$postId]);
        $rows = $stmt->fetchAll();
        return array_map([$this, 'formatComment'], $rows);
    }

    public function add($userId, $postId, $data) {
        $text = $data['enc_text'] ?? '';
        if (empty($text)) throw new Exception("Text required", 400);

        $stmtP = $this->pdo->prepare("SELECT id FROM posts WHERE id = ?");
        $stmtP->execute([$postId]);
        if (!$stmtP->fetch()) throw new Exception("Post not found", 404);

        $stmt = $this->pdo->prepare("INSERT INTO comments (post_id, user_id, text) VALUES (?, ?, ?)");
        $stmt->execute([$postId, $userId, $text]);
        $commentId = $this->pdo->lastInsertId();

        return $this->getById($commentId);
    }

    private function getById($id) {
         $stmt = $this->pdo->prepare("
            SELECT c.*, u.username 
            FROM comments c
            JOIN users u ON c.user_id = u.id
            WHERE c.id = ?
        ");
        $stmt->execute([$id]);
        return $this->formatComment($stmt->fetch());
    }

    private function formatComment($row) {
        return [
            '_id' => (string)$row['id'],
            'post' => (string)$row['post_id'],
            'user' => [
                '_id' => (string)$row['user_id'],
                'username' => $row['username']
            ],
            'text' => $row['text'],
            'createdAt' => $row['created_at']
        ];
    }
}
