<?php
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/../system/csrf.php';
csrf_validate();
/**
 * Update subscription status if expired or in grace
 */
function refresh_module_subscription(int $companyId, int $moduleId): void
{
    global $pdo;

    $stmt = $pdo->prepare(
        'SELECT id, status, expires_at
         FROM company_module_subscriptions
         WHERE company_id = :company_id
           AND module_id = :module_id
         LIMIT 1'
    );

    $stmt->execute([
        'company_id' => $companyId,
        'module_id'  => $moduleId
    ]);

    $sub = $stmt->fetch();

    if (!$sub || !$sub['expires_at']) {
        return;
    }

    $now = new DateTime();
    $expiresAt = new DateTime($sub['expires_at']);
    $graceUntil = (clone $expiresAt)->modify('+' . SUBSCRIPTION_GRACE_DAYS . ' days');

    // Still valid
    if ($now <= $expiresAt) {
        return;
    }

    // Move to grace
    if ($now > $expiresAt && $now <= $graceUntil && $sub['status'] !== 'grace') {
        $pdo->prepare(
            'UPDATE company_module_subscriptions
             SET status = "grace"
             WHERE id = :id'
        )->execute(['id' => $sub['id']]);
        return;
    }

    // Fully expired
    if ($now > $graceUntil && $sub['status'] !== 'expired') {
        $pdo->prepare(
            'UPDATE company_module_subscriptions
             SET status = "expired"
             WHERE id = :id'
        )->execute(['id' => $sub['id']]);
    }
}
