<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Core\Tenant;
use App\Core\Validator;
use App\Services\StripeService;
use App\Services\SubscriptionService;

/**
 * BillingController
 *
 * The wall TenantMiddleware redirects a company to once its
 * subscription_expires_at (or trial_ends_at) has passed. Reachable
 * even while "expired" — see TenantMiddleware's BILLING_ROUTE_PREFIXES
 * — so a company can actually get back in.
 */
final class BillingController extends BaseController
{
    public function expired(Request $request): Response
    {
        return $this->view('billing/expired', [
            'title' => 'Subscription ended',
            'tenant' => Tenant::current(),
            'stripeConfigured' => StripeService::configured(),
        ], useLayout: false);
    }

    public function checkout(Request $request): Response
    {
        $tenant = Tenant::current();

        try {
            $url = (new StripeService())->createCheckoutSession(
                businessLineId: Tenant::id(),
                customerEmail: (string) ($tenant['billing_email'] ?? ''),
                successUrl: base_url('dashboard?renewed=1'),
                cancelUrl: base_url('billing/expired'),
            );
        } catch (\RuntimeException $e) {
            return $this->withErrors($request, ['stripe' => $e->getMessage()], 'billing/expired');
        }

        return Response::redirect($url);
    }

    public function redeemCode(Request $request): Response
    {
        $validator = Validator::make($request->all(), ['code' => 'required|string|max:40']);
        if ($validator->fails()) {
            return $this->withErrors($request, $validator->errors(), 'billing/expired');
        }

        try {
            (new SubscriptionService())->redeemCode($validator->validated()['code'], (int) Tenant::id(), isNewSignup: false);
        } catch (\RuntimeException $e) {
            return $this->withErrors($request, ['code' => $e->getMessage()], 'billing/expired');
        }

        return $this->redirect('dashboard?renewed=1');
    }
}
