<?php

namespace App\Models;

use App\Core\Model;

class ForumTopic extends Model
{
    protected $table = 'forum_topics';
    protected $primaryKey = 'id';

    public function getByCategory($categoryId, $page = 1, $perPage = 20)
    {
        $offset = ($page - 1) * $perPage;
        $stmt = $this->db->prepare("SELECT t.*, u.name as user_name, (SELECT COUNT(*) FROM forum_posts WHERE topic_id = t.id AND status = 'active') as post_count FROM {$this->table} t LEFT JOIN users u ON t.user_id = u.id WHERE t.category_id = ? AND t.status = 'active' ORDER BY t.is_pinned DESC, t.last_post_at DESC LIMIT ? OFFSET ?");
        $stmt->execute([$categoryId, $perPage, $offset]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getWithPosts($id)
    {
        $stmt = $this->db->prepare("SELECT t.*, u.name as user_name, u.avatar as user_avatar FROM {$this->table} t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(\PDO::FETCH_OBJ);
    }

    public function incrementViews($id)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET views = views + 1 WHERE id = ?");
        $stmt->execute([$id]);
    }

    public function getRecent($limit = 10)
    {
        $stmt = $this->db->prepare("SELECT t.*, u.name as user_name, c.name as category_name FROM {$this->table} t LEFT JOIN users u ON t.user_id = u.id LEFT JOIN forum_categories c ON t.category_id = c.id WHERE t.status = 'active' ORDER BY t.last_post_at DESC LIMIT ?");
        $stmt->execute([$limit]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function softDelete($id)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET status = 'hidden' WHERE id = ?");
        return $stmt->execute([$id]);
    }

    public function togglePin($id)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET is_pinned = CASE WHEN is_pinned = 1 THEN 0 ELSE 1 END WHERE id = ?");
        return $stmt->execute([$id]);
    }

    public function toggleLock($id)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET is_locked = CASE WHEN is_locked = 1 THEN 0 ELSE 1 END WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
