<?php
class Announcement
{
    public static function all(): array
    {
        Database::migrate();
        return Database::pdo()->query("SELECT * FROM student_announcements ORDER BY is_active DESC, id DESC")->fetchAll();
    }

    public static function activeForStudents(): array
    {
        Database::migrate();
        $now = date('Y-m-d H:i:s');
        $stmt = Database::pdo()->prepare("SELECT * FROM student_announcements
            WHERE is_active=1
              AND (starts_at IS NULL OR starts_at='' OR starts_at<=?)
              AND (ends_at IS NULL OR ends_at='' OR ends_at>=?)
            ORDER BY id DESC");
        $stmt->execute([$now, $now]);
        return $stmt->fetchAll();
    }

    public static function find(int $id): ?array
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('SELECT * FROM student_announcements WHERE id=? LIMIT 1');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public static function save(array $data): array
    {
        Database::migrate();
        $id = (int)($data['announcement_id'] ?? 0);
        $title = trim((string)($data['title'] ?? ''));
        $message = trim((string)($data['message'] ?? ''));
        $style = trim((string)($data['style'] ?? 'info'));
        $startsAt = self::normalizeDateTime($data['starts_at'] ?? '');
        $endsAt = self::normalizeDateTime($data['ends_at'] ?? '');
        if ($title === '' || $message === '') {
            return ['ok' => false, 'message' => 'Informe o título e o texto do aviso.'];
        }
        if (!in_array($style, ['info','success','warning','danger','primary'], true)) {
            $style = 'info';
        }
        if ($startsAt && $endsAt && $endsAt < $startsAt) {
            return ['ok' => false, 'message' => 'A data final do aviso precisa ser posterior à data inicial.'];
        }
        $now = date('Y-m-d H:i:s');
        if ($id > 0) {
            $stmt = Database::pdo()->prepare('UPDATE student_announcements SET title=?,message=?,style=?,starts_at=?,ends_at=?,updated_at=? WHERE id=?');
            $stmt->execute([$title,$message,$style,$startsAt,$endsAt,$now,$id]);
            return ['ok' => $stmt->rowCount() > 0 || self::find($id) !== null, 'message' => 'Aviso atualizado.'];
        }
        $stmt = Database::pdo()->prepare('INSERT INTO student_announcements (title,message,style,starts_at,ends_at,is_active,created_at,updated_at) VALUES (?,?,?,?,?,1,?,?)');
        $stmt->execute([$title,$message,$style,$startsAt,$endsAt,$now,$now]);
        return ['ok' => true, 'message' => 'Aviso publicado para os alunos.'];
    }

    public static function toggle(int $id): bool
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('UPDATE student_announcements SET is_active=CASE WHEN is_active=1 THEN 0 ELSE 1 END,updated_at=? WHERE id=?');
        $stmt->execute([date('Y-m-d H:i:s'),$id]);
        return $stmt->rowCount() > 0;
    }

    public static function delete(int $id): bool
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('DELETE FROM student_announcements WHERE id=?');
        $stmt->execute([$id]);
        return $stmt->rowCount() > 0;
    }

    private static function normalizeDateTime(mixed $value): ?string
    {
        $value = trim((string)$value);
        if ($value === '') return null;
        $timestamp = strtotime($value);
        return $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
    }
}
