<?php

namespace App\Models;

use App\Core\Model;

class Comment extends Model
{
    protected string $table = 'comments';

    public function getByPost(int $postId): array
    {
        $stmt = $this->db->prepare(
            "SELECT c.*, u.username, u.avatar,
             (SELECT COALESCE(SUM(vote_type), 0) FROM votes WHERE comment_id = c.id) as score
             FROM comments c
             JOIN users u ON c.user_id = u.id
             WHERE c.post_id = ?
             ORDER BY c.is_accepted DESC, score DESC, c.created_at ASC"
        );
        $stmt->execute([$postId]);
        $flat = $stmt->fetchAll();

        // Build tree
        $tree = [];
        $map = [];
        foreach ($flat as $row) {
            $row['children'] = [];
            $map[$row['id']] = $row;
        }
        foreach ($map as $id => &$row) {
            if ($row['parent_id'] && isset($map[$row['parent_id']])) {
                $map[$row['parent_id']]['children'][] = &$row;
            } else {
                $tree[] = &$row;
            }
        }
        return $tree;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO comments (post_id, user_id, parent_id, content) VALUES (?, ?, ?, ?)"
        );
        $stmt->execute([
            $data['post_id'],
            $data['user_id'],
            $data['parent_id'] ?? null,
            $data['content']
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function accept(int $commentId, int $postId): void
    {
        $this->db->prepare("UPDATE comments SET is_accepted = 0 WHERE post_id = ?")->execute([$postId]);
        $this->db->prepare("UPDATE comments SET is_accepted = 1 WHERE id = ?")->execute([$commentId]);
        $this->db->prepare("UPDATE posts SET is_best_answer_selected = 1 WHERE id = ?")->execute([$postId]);
    }

    public function countByUser(int $userId): int
    {
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM comments WHERE user_id = ?");
        $stmt->execute([$userId]);
        return (int)$stmt->fetchColumn();
    }

    public function countBestAnswersByUser(int $userId): int
    {
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM comments WHERE user_id = ? AND is_accepted = 1");
        $stmt->execute([$userId]);
        return (int)$stmt->fetchColumn();
    }
}
