<?php

namespace Core\App\Models;

use PDO;

class TeamGroupMessageModel
{
    private PDO $db;

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

    /**
     * Get last N messages for a meeting group chat
     */
    public function getMessages(int $meetingId, int $limit = 60): array
    {
        $stmt = $this->db->prepare("
            SELECT m.id, m.meeting_id, m.sender_id, m.content,
                   m.attachment_path, m.attachment_type, m.attachment_kind, m.attachment_name, m.attachment_size,
                   m.is_pinned, m.created_at,
                   a.username AS sender_name, a.avatar AS sender_avatar
            FROM team_group_messages m
            JOIN admins a ON a.id = m.sender_id
            WHERE m.meeting_id = :mid
            ORDER BY m.is_pinned DESC, m.id ASC
            LIMIT :lim
        ");
        $stmt->bindValue(':mid', $meetingId, PDO::PARAM_INT);
        $stmt->bindValue(':lim', $limit,     PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get messages after a given ID (for polling)
     */
    public function getAfter(int $meetingId, int $lastId): array
    {
        $stmt = $this->db->prepare("
            SELECT m.id, m.meeting_id, m.sender_id, m.content,
                   m.attachment_path, m.attachment_type, m.attachment_kind, m.attachment_name, m.attachment_size,
                   m.is_pinned, m.created_at,
                   a.username AS sender_name, a.avatar AS sender_avatar
            FROM team_group_messages m
            JOIN admins a ON a.id = m.sender_id
            WHERE m.meeting_id = :mid AND m.id > :last
            ORDER BY m.created_at ASC
        ");
        $stmt->bindValue(':mid',  $meetingId, PDO::PARAM_INT);
        $stmt->bindValue(':last', $lastId,    PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Send a group message
     */
    public function send(int $meetingId, int $senderId, string $content, ?array $attachment = null): int
    {
        $stmt = $this->db->prepare("
            INSERT INTO team_group_messages
                (meeting_id, sender_id, content, attachment_path, attachment_type, attachment_kind, attachment_name, attachment_size)
            VALUES
                (:mid, :sender, :content, :apath, :atype, :akind, :aname, :asize)
        ");
        $stmt->execute([
            ':mid'    => $meetingId,
            ':sender' => $senderId,
            ':content'=> trim($content),
            ':apath'  => $attachment['path'] ?? null,
            ':atype'  => $attachment['type'] ?? null,
            ':akind'  => $attachment['kind'] ?? null,
            ':aname'  => $attachment['name'] ?? null,
            ':asize'  => $attachment['size'] ?? null,
        ]);
        return (int)$this->db->lastInsertId();
    }

    /**
     * Get a single message by ID
     */
    public function getById(int $id): ?array
    {
        $stmt = $this->db->prepare("
            SELECT m.id, m.meeting_id, m.sender_id, m.content,
                   m.attachment_path, m.attachment_type, m.attachment_kind, m.attachment_name, m.attachment_size,
                   m.is_pinned, m.created_at,
                   a.username AS sender_name, a.avatar AS sender_avatar
            FROM team_group_messages m
            JOIN admins a ON a.id = m.sender_id
            WHERE m.id = :id
        ");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public function togglePin(int $messageId, int $meetingId): bool
    {
        $stmt = $this->db->prepare("
            UPDATE team_group_messages
            SET is_pinned = 1 - is_pinned
            WHERE id = :id AND meeting_id = :mid
        ");
        $stmt->execute([':id' => $messageId, ':mid' => $meetingId]);
        return $stmt->rowCount() > 0;
    }

    private function ensureSchema(): void
    {
        try {
            $this->db->exec("
                ALTER TABLE team_group_messages
                ADD COLUMN IF NOT EXISTS is_pinned tinyint(1) NOT NULL DEFAULT 0 AFTER attachment_size,
                ADD COLUMN IF NOT EXISTS attachment_kind varchar(20) DEFAULT NULL AFTER attachment_type
            ");
        } catch (\Throwable $e) {
        }
    }

    /**
     * Check if an admin is an attendee of a meeting
     */
    public function isAttendee(int $meetingId, int $adminId): bool
    {
        $stmt = $this->db->prepare("
            SELECT COUNT(*) FROM team_meeting_attendees
            WHERE meeting_id = :mid AND admin_id = :aid
        ");
        $stmt->execute([':mid' => $meetingId, ':aid' => $adminId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
