<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\DB;

class PlanMiddleware
{
    public function handle(): bool
    {
        $tenantId = $_SESSION['tenant_id'] ?? null;
        if (!$tenantId) {
            header('Location: /login');
            return false;
        }
        $stmt = DB::pdo()->prepare("SELECT t.status, p.limit_notas FROM tenants t LEFT JOIN plans p ON t.plan_id = p.id WHERE t.id = ?");
        $stmt->execute([$tenantId]);
        $row = $stmt->fetch();
        if (!$row || $row['status'] !== 'ativo') {
            http_response_code(402);
            echo 'Plano inativo';
            return false;
        }
        $limit = (int)($row['limit_notas'] ?? 0);
        if ($limit > 0) {
            $nowMonth = date('Y-m');
            $countStmt = DB::pdo()->prepare("SELECT COUNT(*) AS c FROM invoices WHERE tenant_id = ? AND DATE_FORMAT(data_emissao, '%Y-%m') = ?");
            try {
                $countStmt->execute([$tenantId, $nowMonth]);
            } catch (\Throwable $e) {
                $countStmt = DB::pdo()->prepare("SELECT COUNT(*) AS c FROM invoices WHERE tenant_id = ? AND strftime('%Y-%m', data_emissao) = ?");
                $countStmt->execute([$tenantId, $nowMonth]);
            }
            $c = (int)($countStmt->fetch()['c'] ?? 0);
            if ($c >= $limit) {
                http_response_code(429);
                echo 'Limite de notas do plano atingido';
                return false;
            }
        }
        return true;
    }
}
