<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

require_once dirname(__DIR__) . '/services/billing.php';
require_once dirname(__DIR__) . '/services/plan_guard.php';
require_once dirname(__DIR__) . '/middleware/roles.php';

$db  = DB::connect();
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

RoleMiddleware::requireAuth();
$ctx = RoleMiddleware::context();

// ── GET /billing?plan=pro — acceso directo al checkout desde onboarding ────────
if ($uri === '/billing' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    RoleMiddleware::requireRole(['owner']);
    $validPlans = ['growth', 'pro'];
    $plan = $_GET['plan'] ?? '';
    if (in_array($plan, $validPlans, true)) {
        $tid = (int)$ctx['tenant_id'];
        try {
            $tenant = PlanGuard::load($db, $tid);
            $url = BillingService::stripeCheckoutUrl($db, $tenant, $plan);
            header('Location: ' . $url);
        } catch (Throwable $e) {
            error_log('[Billing/GET] checkout error: ' . $e->getMessage());
            $_SESSION['billing_error'] = $e->getMessage();
            header('Location: /ajustes');
        }
        exit;
    }
    // Sin plan válido → ajustes
    header('Location: /ajustes');
    exit;
}

// ── POST /billing/checkout — redirige a Stripe Checkout ──────────────────────
if ($uri === '/billing/checkout' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    RoleMiddleware::requireRole(['owner']);
    $plan = $_POST['plan'] ?? '';
    if (!in_array($plan, ['growth', 'pro'], true)) {
        $_SESSION['billing_error'] = 'Plan no válido.';
        header('Location: /ajustes');
        exit;
    }
    $tid  = (int)$ctx['tenant_id'];

    try {
        $tenant = PlanGuard::load($db, $tid);
        $url    = BillingService::stripeCheckoutUrl($db, $tenant, $plan);
        header('Location: ' . $url);
    } catch (Throwable $e) {
        error_log('[Billing/POST] checkout error: ' . $e->getMessage());
        $_SESSION['billing_error'] = $e->getMessage();
        header('Location: /ajustes');
    }
    exit;
}

// ── GET /billing/success — Stripe redirige aquí tras pago exitoso ─────────────
if ($uri === '/billing/success') {
    RoleMiddleware::requireRole(['owner']);
    // El webhook de Stripe ya actualizó el status. Solo mostrar confirmación.
    $_SESSION['billing_success'] = true;
    header('Location: /ajustes');
    exit;
}

// ── POST /billing/cash — activación manual (admin o seller) ───────────────────
if ($uri === '/billing/cash' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    RoleMiddleware::requireRole(['super_admin', 'seller']);

    $tenantId = (int)($_POST['tenant_id'] ?? 0);
    $plan     = $_POST['plan']   ?? 'basic';
    $meses    = (int)($_POST['meses'] ?? 1);

    if (!$tenantId) {
        http_response_code(400);
        echo json_encode(['error' => 'tenant_id requerido']);
        exit;
    }

    // Seller solo puede activar sus propios tenants
    if ($ctx['role'] === 'seller') {
        RoleMiddleware::requireTenantAccess($db, $tenantId, true);
        $sellerId = (int)$ctx['seller_profile_id'];
    } else {
        $sellerId = null;
        // Super admin puede pasar seller_id explícito
        if (!empty($_POST['seller_id'])) {
            $sellerId = (int)$_POST['seller_id'];
        } else {
            $row = $db->prepare("SELECT seller_id FROM tenants WHERE id = :id AND deleted_at IS NULL LIMIT 1");
            $row->execute([':id' => $tenantId]);
            $t = $row->fetch();
            $sellerId = $t ? (int)$t['seller_id'] : null;
        }
    }

    try {
        BillingService::activarCash($db, $tenantId, $plan, $meses, $sellerId ?: null);
        echo json_encode(['ok' => true]);
    } catch (RuntimeException $e) {
        http_response_code(400);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

http_response_code(404);
echo '404 Not Found';
