<?php
require_once __DIR__ . '/config.php';

// Extrae un entero desde una variable de entorno limpiando caracteres no numéricos.
function envInt($key, $default = 0) {
    $val = getenv($key);
    if ($val === false) return $default;
    $digits = preg_replace('/[^0-9]/', '', (string)$val);
    return $digits === '' ? $default : (int)$digits;
}
 
/**
 * Catálogo de planes disponibles. Las cantidades por defecto se basan
 * en la tabla compartida (mensual/total, firmas incluidas y meses de verificación).
 * Los montos se pueden sobreescribir vía variables de entorno
 * (STRIPE_PRICE_ID_*, MP_PLAN_AMOUNT_* y WOMPI_PLAN_AMOUNT_*_IN_CENTS).
 */ 
function getPlanCatalog() {
    return [
        '1y120' => [
            'code' => '1y120', 
            'name' => '1 Año Completo',
            'badge' => '',
            'months' => 12,
            'monthly_cop' => 4745,
            'total_cop' => 56940,
            'signatures' => 120,
            'unit_cost_cop' => 476,
            'stripe_price_id' => getenv('STRIPE_PRICE_ID_1Y120') ?: getenv('STRIPE_PRICE_ID'),
            'mp_amount' => getenv('MP_PLAN_AMOUNT_1Y120') ?: getenv('MP_PLAN_AMOUNT') ?: 4745,
            'mp_frequency' => getenv('MP_PLAN_FREQUENCY_1Y120') ?: getenv('MP_PLAN_FREQUENCY') ?: 1,
            'mp_frequency_type' => getenv('MP_PLAN_FREQUENCY_TYPE_1Y120') ?: getenv('MP_PLAN_FREQUENCY_TYPE') ?: 'months',
            // Wompi: cobra el total del plan (12 meses).
            'wompi_amount_cents' => envInt('WOMPI_PLAN_AMOUNT_1Y120_IN_CENTS', 56940 * 100),
        ],
        '2y300' => [
            'code' => '2y300',
            'name' => '2 Años Completos',
            'badge' => '30% desc. por firma',
            'months' => 24,
            'monthly_cop' => 8304,
            'total_cop' => 99645,
            'signatures' => 300,
            'unit_cost_cop' => 333,
            'stripe_price_id' => getenv('STRIPE_PRICE_ID_2Y300') ?: getenv('STRIPE_PRICE_ID'),
            'mp_amount' => getenv('MP_PLAN_AMOUNT_2Y300') ?: getenv('MP_PLAN_AMOUNT') ?: 8304,
            'mp_frequency' => getenv('MP_PLAN_FREQUENCY_2Y300') ?: getenv('MP_PLAN_FREQUENCY') ?: 1,
            'mp_frequency_type' => getenv('MP_PLAN_FREQUENCY_TYPE_2Y300') ?: getenv('MP_PLAN_FREQUENCY_TYPE') ?: 'months',
            // Wompi: cobra el total del plan (24 meses).
            'wompi_amount_cents' => envInt('WOMPI_PLAN_AMOUNT_2Y300_IN_CENTS', 99645 * 100),
        ],
        '1y500' => [
            'code' => '1y500',
            'name' => '1 Año Completo',
            'badge' => '52.1% desc. por firma',
            'months' => 12,
            'monthly_cop' => 9490,
            'total_cop' => 113880,
            'signatures' => 500,
            'unit_cost_cop' => 228,
            'stripe_price_id' => getenv('STRIPE_PRICE_ID_1Y500') ?: getenv('STRIPE_PRICE_ID'),
            'mp_amount' => getenv('MP_PLAN_AMOUNT_1Y500') ?: getenv('MP_PLAN_AMOUNT') ?: 9490,
            'mp_frequency' => getenv('MP_PLAN_FREQUENCY_1Y500') ?: getenv('MP_PLAN_FREQUENCY') ?: 1,
            'mp_frequency_type' => getenv('MP_PLAN_FREQUENCY_TYPE_1Y500') ?: getenv('MP_PLAN_FREQUENCY_TYPE') ?: 'months',
            'wompi_amount_cents' => envInt('WOMPI_PLAN_AMOUNT_1Y500_IN_CENTS', 113880 * 100),
        ],
        '2y1000' => [
            'code' => '2y1000',
            'name' => '2 Años Completos',
            'badge' => '64% desc. por firma',
            'months' => 24,
            'monthly_cop' => 14235,
            'total_cop' => 170820,
            'signatures' => 1000,
            'unit_cost_cop' => 171,
            'stripe_price_id' => getenv('STRIPE_PRICE_ID_2Y1000') ?: getenv('STRIPE_PRICE_ID'),
            'mp_amount' => getenv('MP_PLAN_AMOUNT_2Y1000') ?: getenv('MP_PLAN_AMOUNT') ?: 14235,
            'mp_frequency' => getenv('MP_PLAN_FREQUENCY_2Y1000') ?: getenv('MP_PLAN_FREQUENCY') ?: 1,
            'mp_frequency_type' => getenv('MP_PLAN_FREQUENCY_TYPE_2Y1000') ?: getenv('MP_PLAN_FREQUENCY_TYPE') ?: 'months',
            'wompi_amount_cents' => envInt('WOMPI_PLAN_AMOUNT_2Y1000_IN_CENTS', 170820 * 100),
        ],
    ];
}
 
function getPlanByCode($code) {
    $plans = getPlanCatalog();
    if ($code && isset($plans[$code])) {
        return $plans[$code];
    }
    if (isset($plans['1y120'])) {
        return $plans['1y120'];
    }
    return reset($plans);
}

function formatCop($amount) {
    return '$' . number_format((float)$amount, 0, ',', '.');
}

/**
 * Obtiene la suscripción del usuario desde la tabla suscripciones.
 */
function getUserSubscription($db, $userId) {
    $stmt = $db->prepare("
        SELECT id_de_usuario, stripe_customer_id, stripe_subscription_id, status, current_period_end, cancel_at_period_end, creado_el, actualizado_el
        FROM suscripciones
        WHERE id_de_usuario = ?
        ORDER BY actualizado_el DESC
        LIMIT 1
    ");
    if (!$stmt) {
        return null;
    }
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

/**
 * Determina si la suscripción está vigente según estado y fecha.
 */
function isSubscriptionActive($sub) {
    if (!$sub) return false;
    $status = strtolower((string)($sub['status'] ?? ''));
    $activeStatuses = ['active', 'trialing', 'authorized'];
    $statusOk = in_array($status, $activeStatuses, true);
    $periodEnd = isset($sub['current_period_end']) ? strtotime($sub['current_period_end']) : null;
    $dateOk = $periodEnd ? ($periodEnd > time()) : true;
    return $statusOk && $dateOk;
}

/**
 * Enforce an active subscription for web routes.
 * If the user does not have an active subscription, redirect to the subscription page.
 */
function requireSubscription($db, $userId) {
    // Respeta la bandera global de bypass
    $flag = getenv('SUBSCRIPTIONS_ENABLED');
    if ($flag !== false) {
        $flagNorm = strtolower(trim((string)$flag));
        if ($flagNorm === '0' || $flagNorm === 'false' || $flagNorm === 'off' || $flagNorm === 'no') {
            return; // no aplica restricción cuando está desactivada
        }
    }
    $sub = getUserSubscription($db, $userId);
    if (!isSubscriptionActive($sub)) {
        header('Location: subscription?message=' . urlencode('Se requiere una suscripción activa.'));
        exit;
    }
} 
