<?php

declare(strict_types=1);

class Comment
{
    public static function find(int $id): ?array
    {
        return Database::fetchOne('SELECT * FROM comments WHERE id = ?', [$id]);
    }

    public static function forVideo(int $videoId, int $maxComments = 500): array
    {
        $all = Database::fetchAll(
            'SELECT c.*, COALESCE(u.username, c.guest_name, ?) as username FROM comments c
             LEFT JOIN users u ON c.user_id = u.id
             WHERE c.video_id = ? AND c.status = ?
             ORDER BY c.parent_id ASC, c.created_at DESC
             LIMIT ?',
            ['Anonymous', $videoId, 'approved', $maxComments]
        );

        $parents = [];
        $replies = [];

        foreach ($all as $comment) {
            $comment['replies'] = [];
            if ($comment['parent_id'] === null) {
                $parents[$comment['id']] = $comment;
            } else {
                $replies[] = $comment;
            }
        }

        foreach ($replies as $reply) {
            if (isset($parents[$reply['parent_id']])) {
                $parents[$reply['parent_id']]['replies'][] = $reply;
            }
        }

         
         
        return array_values($parents);
    }

    public static function forAlbum(int $albumId, int $maxComments = 500): array
    {
        $all = Database::fetchAll(
            'SELECT c.*, COALESCE(u.username, c.guest_name, ?) as username FROM comments c
             LEFT JOIN users u ON c.user_id = u.id
             WHERE c.album_id = ? AND c.status = ?
             ORDER BY c.parent_id ASC, c.created_at DESC
             LIMIT ?',
            ['Anonymous', $albumId, 'approved', $maxComments]
        );
        $parents = [];
        $replies = [];
        foreach ($all as $comment) {
            $comment['replies'] = [];
            if ($comment['parent_id'] === null) { $parents[$comment['id']] = $comment; }
            else { $replies[] = $comment; }
        }
        foreach ($replies as $reply) {
            if (isset($parents[$reply['parent_id']])) { $parents[$reply['parent_id']]['replies'][] = $reply; }
        }
        return array_values($parents);
    }

    public static function all(int $limit = 20, int $offset = 0, string $status = ''): array
    {
        $where = '1=1';
        $params = [];

        if ($status !== '') {
            $where = 'c.status = ?';
            $params[] = $status;
        }

        $params[] = $limit;
        $params[] = $offset;

        return Database::fetchAll(
            "SELECT c.*, COALESCE(u.username, c.guest_name, 'Anonymous') as username,
                    v.title as video_title, v.slug as video_slug, a.title as album_title, a.slug as album_slug
             FROM comments c
             LEFT JOIN users u ON c.user_id = u.id
             LEFT JOIN videos v ON c.video_id = v.id
             LEFT JOIN albums a ON c.album_id = a.id
             WHERE {$where}
             ORDER BY c.created_at DESC LIMIT ? OFFSET ?",
            $params
        );
    }

    public static function countForAlbum(int $albumId): int
    {
        return (int) (Database::fetchOne('SELECT COUNT(*) AS c FROM comments WHERE album_id = ? AND status = ?', [$albumId, 'approved'])['c'] ?? 0);
    }

     
    public static function subject(array $c): array
    {
        if (!empty($c['album_id'])) {
            $slug = (string) ($c['album_slug'] ?? '');
            return ['type' => 'album', 'title' => $c['album_title'] ?? 'Deleted gallery', 'url' => $slug !== '' ? '/album/' . $slug : '', 'label' => 'Gallery'];
        }
        $slug = (string) ($c['video_slug'] ?? '');
        return ['type' => 'video', 'title' => $c['video_title'] ?? 'Deleted video', 'url' => $slug !== '' ? '/video/' . $slug : '', 'label' => 'Video'];
    }

    public static function count(string $status = ''): int
    {
        if ($status !== '') {
            return Database::count('comments', 'status = ?', [$status]);
        }
        return Database::count('comments');
    }

    public static function create(array $data): int
    {
        return Database::insert('comments', $data);
    }

    public static function update(int $id, array $data): void
    {
        Database::update('comments', $data, 'id = ?', [$id]);
    }

    public static function delete(int $id): void
    {
        Database::delete('comments', 'id = ?', [$id]);
    }

    public static function approve(int $id): void
    {
        Database::update('comments', ['status' => 'approved'], 'id = ?', [$id]);
    }

    public static function spam(int $id): void
    {
        Database::update('comments', ['status' => 'spam'], 'id = ?', [$id]);
    }
}
