<?php
/**
 * TechStackBase – Billing Status
 * Version: v1.0.0
 * Purpose: Return current subscription & billing status for a company
 *
 * Access:
 * - Auth required
 * - Any authenticated company user
 *
 * Security:
 * - Server-authoritative
 * - Read-only
 * - Audit logged
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/response.php';
require_once __DIR__ . '/../../core/AuthMiddleware.php';
require_once __DIR__ . '/../../core/AuditLogger.php';
require_once __DIR__ . '/../system/permissions.php';
require_once __DIR__ . '/../system/company_guard.php';

$companyId = (int)($_POST['company_id'] ?? 0);

requireCompanyContext($companyId);

requirePermission('users.view');

/* ============================================================
   AUTHENTICATION
   ============================================================ */

$user = requireAuth();
$db   = Database::connect();

/* ============================================================
   LOAD CURRENT SUBSCRIPTION
   ============================================================ */

$stmt = $db->prepare(
    "SELECT
        cs.id,
        cs.plan_code,
        cs.status,
        cs.started_at,
        cs.expires_at,
        sp.name AS plan_name,
        sp.price,
        sp.currency,
        sp.billing_cycle
     FROM company_subscriptions cs
     JOIN subscription_plans sp ON sp.code = cs.plan_code
     WHERE cs.company_id = ?
     ORDER BY cs.id DESC
     LIMIT 1"
);

$stmt->execute([$user['company_id']]);
$subscription = $stmt->fetch();

/* ============================================================
   NO SUBSCRIPTION
   ============================================================ */

if (!$subscription) {

    auditLog(
        $user['user_id'],
        $user['company_id'],
        'billing',
        'subscription_status_none'
    );

    jsonResponse(
        true,
        'No subscription',
        [
            'has_subscription' => false
        ]
    );
}

/* ============================================================
   COMPUTE STATUS FLAGS
   ============================================================ */

$now = time();
$expiresAt = strtotime($subscription['expires_at']);

$isExpired = $expiresAt < $now;
$isActive  = $subscription['status'] === 'active' && !$isExpired;

/* ============================================================
   LOAD MODULE ENTITLEMENTS
   ============================================================ */

$stmt = $db->prepare(
    "SELECT module_code
     FROM plan_modules
     WHERE plan_code = ?"
);
$stmt->execute([$subscription['plan_code']]);

$modules = $stmt->fetchAll(PDO::FETCH_COLUMN);

/* ============================================================
   AUDIT LOG
   ============================================================ */

auditLog(
    $user['user_id'],
    $user['company_id'],
    'billing',
    'subscription_status_viewed'
);

/* ============================================================
   RESPONSE
   ============================================================ */

jsonResponse(
    true,
    'Subscription status loaded',
    [
        'has_subscription' => true,
        'subscription' => [
            'plan_code'     => $subscription['plan_code'],
            'plan_name'     => $subscription['plan_name'],
            'status'        => $subscription['status'],
            'is_active'     => $isActive,
            'is_expired'    => $isExpired,
            'started_at'    => $subscription['started_at'],
            'expires_at'    => $subscription['expires_at'],
            'price'         => (float) $subscription['price'],
            'currency'      => $subscription['currency'],
            'billing_cycle' => $subscription['billing_cycle'],
            'modules'       => $modules
        ]
    ]
);
