<?php

declare(strict_types=1);

namespace App\Models;

class Plan extends BaseModel
{
    protected string $table = 'planes';
    protected ?string $tenantColumn = null;

    public function currentForCompany(int $companyId): ?array
    {
        if ($companyId <= 0) {
            return null;
        }

        $stmt = $this->db()->prepare(
            'SELECT
                p.id,
                p.nombre,
                p.slug,
                p.permite_facturacion_electronica,
                s.id AS suscripcion_id,
                s.estado AS suscripcion_estado,
                s.fecha_vencimiento
             FROM suscripciones s
             INNER JOIN planes p ON p.id = s.plan_id
             WHERE s.empresa_id = :empresa_id
             ORDER BY
                CASE s.estado
                    WHEN "activa" THEN 0
                    WHEN "vencida" THEN 1
                    WHEN "morosa" THEN 2
                    ELSE 3
                END,
                s.fecha_vencimiento DESC,
                s.id DESC
             LIMIT 1'
        );
        $stmt->execute([':empresa_id' => $companyId]);
        $row = $stmt->fetch();

        return $row ?: null;
    }
}
