<?php

namespace Core\App\Models;

use PDO;

class TeamAnnouncementModel
{
    private PDO $db;

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

    /**
     * Get all announcements (pinned first)
     */
    public function getAll(int $limit = 20): array
    {
        $stmt = $this->db->prepare("
            SELECT n.*, a.username AS author_name, a.avatar AS author_avatar, a.role AS author_role
            FROM team_announcements n
            JOIN admins a ON a.id = n.admin_id
            ORDER BY n.is_pinned DESC, n.created_at DESC
            LIMIT :lim
        ");
        $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get recent announcements (for sidebar/dashboard widget)
     */
    public function getRecent(int $limit = 3): array
    {
        $stmt = $this->db->prepare("
            SELECT n.id, n.title, n.is_pinned, n.created_at, a.username AS author_name
            FROM team_announcements n
            JOIN admins a ON a.id = n.admin_id
            ORDER BY n.is_pinned DESC, n.created_at DESC
            LIMIT :lim
        ");
        $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Create an announcement
     */
    public function create(int $adminId, string $title, string $content, bool $pinned = false): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO team_announcements (admin_id, title, content, is_pinned)
            VALUES (:admin_id, :title, :content, :pinned)
        ");
        $stmt->execute([
            ':admin_id' => $adminId,
            ':title'    => trim($title),
            ':content'  => trim($content),
            ':pinned'   => $pinned ? 1 : 0,
        ]);
        return (int)$this->db->lastInsertId();
    }

    /**
     * Delete an announcement
     */
    public function delete(int $id): void
    {
        $stmt = $this->db->prepare("DELETE FROM team_announcements WHERE id = :id");
        $stmt->execute([':id' => $id]);
    }

    /**
     * Toggle pin status
     */
    public function togglePin(int $id): void
    {
        $stmt = $this->db->prepare("
            UPDATE team_announcements SET is_pinned = 1 - is_pinned WHERE id = :id
        ");
        $stmt->execute([':id' => $id]);
    }

    /**
     * Get by ID
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("SELECT * FROM team_announcements WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}
