<?php
class NotificacionController {
    public static function index(): void {
        $payload = AuthMiddleware::verificar();
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM notificaciones WHERE usuario_id = ? ORDER BY created_at DESC LIMIT 50");
        $stmt->execute([$payload['sub']]);
        Response::success($stmt->fetchAll());
    }

    public static function marcarLeida(int $id): void {
        $payload = AuthMiddleware::verificar();
        $db = getDB();
        $db->prepare("UPDATE notificaciones SET leida = 1 WHERE id = ? AND usuario_id = ?")->execute([$id, $payload['sub']]);
        Response::success(null, 'Marcada como leída');
    }

    public static function marcarTodasLeidas(): void {
        $payload = AuthMiddleware::verificar();
        $db = getDB();
        $db->prepare("UPDATE notificaciones SET leida = 1 WHERE usuario_id = ? AND leida = 0")->execute([$payload['sub']]);
        Response::success(null, 'Todas marcadas como leídas');
    }

    public static function noLeidas(): void {
        $payload = AuthMiddleware::verificar();
        $db = getDB();
        $count = (int)$db->prepare("SELECT COUNT(*) FROM notificaciones WHERE usuario_id = ? AND leida = 0")->execute([$payload['sub']]) ? 
            $db->query("SELECT FOUND_ROWS()")->fetchColumn() : 0;
        $stmt = $db->prepare("SELECT COUNT(*) FROM notificaciones WHERE usuario_id = ? AND leida = 0");
        $stmt->execute([$payload['sub']]);
        Response::success(['count' => (int)$stmt->fetchColumn()]);
    }
}
