<?php
/**
 * TechStackBase – Subscription Plans
 * Version: v1.0.0
 * Purpose: List available subscription plans (read-only)
 *
 * Access:
 * - Auth required
 * - All authenticated users
 *
 * Security:
 * - Read-only
 * - Server-authoritative pricing
 * - Active plans 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';

requirePermission('users.view');

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

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

/* ============================================================
   INPUT (OPTIONAL)
   ============================================================ */

// Optional: include inactive plans (admin/support only)
$includeInactive = isset($_GET['all']) && $_GET['all'] === '1';
if ($includeInactive && !in_array($user['role'], ['admin', 'support'], true)) {
    forbidden('Insufficient privileges');
}

/* ============================================================
   LOAD PLANS
   ============================================================ */

$sql = "
SELECT
    sp.code,
    sp.name,
    sp.description,
    sp.price,
    sp.currency,
    sp.billing_cycle,
    sp.active
FROM subscription_plans sp
";

$params = [];

if (!$includeInactive) {
    $sql .= " WHERE sp.active = 1";
}

$sql .= " ORDER BY sp.price ASC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$plans = $stmt->fetchAll();

/* ============================================================
   LOAD MODULE ENTITLEMENTS (PER PLAN)
   ============================================================ */

$planCodes = array_column($plans, 'code');

$modulesByPlan = [];

if ($planCodes) {

    $in = implode(',', array_fill(0, count($planCodes), '?'));

    $stmt = $db->prepare(
        "SELECT plan_code, module_code
         FROM plan_modules
         WHERE plan_code IN ($in)"
    );

    $stmt->execute($planCodes);

    foreach ($stmt->fetchAll() as $row) {
        $modulesByPlan[$row['plan_code']][] = $row['module_code'];
    }
}

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

$output = [];

foreach ($plans as $plan) {
    $output[] = [
        'code'          => $plan['code'],
        'name'          => $plan['name'],
        'description'   => $plan['description'],
        'price'         => (float) $plan['price'],
        'currency'      => $plan['currency'],
        'billing_cycle' => $plan['billing_cycle'],
        'active'        => (bool) $plan['active'],
        'modules'       => $modulesByPlan[$plan['code']] ?? []
    ];
}

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

auditLog(
    $user['user_id'],
    $user['company_id'],
    'billing',
    'plans_viewed',
    [
        'include_inactive' => $includeInactive
    ]
);

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

jsonResponse(
    true,
    'Subscription plans loaded',
    $output
);
