<?php

namespace App\Http\Controllers;

use App\Models\MexcoFeature;
use App\Models\MexcoPlan;
use App\Services\CheckoutService;
use App\Services\CustomerAuthService;
use App\Services\DemoService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoPublicController extends Controller
{
    public function __construct(
        private CustomerAuthService $auth,
        private CheckoutService $checkout,
        private DemoService $demo,
    ) {}

    public function home(): View
    {
        $plans = MexcoPlan::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $commercialPlans = $plans->filter(function ($plan) {
            return ! in_array($plan->code, ['campus', 'enterprise', 'demo'], true)
                && ! $plan->is_custom_pricing
                && $plan->price_cents > 0;
        })->values();

        return view('public.home', [
            'commercialPlans' => $commercialPlans,
            'demoEnabled' => $this->demo->isEnabled(),
            'demoLimits' => $this->demo->isEnabled() ? $this->demo->limitations() : null,
        ]);
    }

    public function features(): View
    {
        $features = MexcoFeature::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get()
            ->groupBy('category');

        return view('public.features', compact('features'));
    }

    public function plans(): View
    {
        $plans = MexcoPlan::query()
            ->where('is_active', true)
            ->with(['features' => fn ($q) => $q->orderBy('sort_order')])
            ->orderBy('sort_order')
            ->get();

        $commercialPlans = $plans->filter(function ($plan) {
            return ! in_array($plan->code, ['campus', 'enterprise', 'demo'], true)
                && ! $plan->is_custom_pricing
                && $plan->price_cents > 0;
        })->values();

        $specialPlans = $plans->filter(function ($plan) {
            return in_array($plan->code, ['campus', 'enterprise'], true)
                || $plan->is_custom_pricing;
        })->values();

        $demoPlan = $plans->firstWhere('code', 'demo');

        $features = MexcoFeature::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $matrix = [];
        foreach ($commercialPlans as $plan) {
            foreach ($plan->features as $feature) {
                $matrix[$plan->id][$feature->id] = (bool) ($feature->pivot->enabled ?? false);
            }
        }

        return view('public.plans', [
            'commercialPlans' => $commercialPlans,
            'specialPlans' => $specialPlans,
            'demoPlan' => $demoPlan,
            'demoEnabled' => $this->demo->isEnabled(),
            'demoLimits' => $this->demo->isEnabled() ? $this->demo->limitations() : null,
            'features' => $features,
            'matrix' => $matrix,
        ]);
    }

    public function demo(): View|RedirectResponse
    {
        if (! $this->demo->isEnabled()) {
            return redirect()->route('mexco.plans')
                ->with('error', 'Free demo is currently unavailable.');
        }

        $event = $this->demo->ensureSharedSandbox();
        $accounts = $this->demo->defaultAccounts();

        return view('public.demo', [
            'plan' => $this->demo->plan(),
            'limits' => $this->demo->limitations(),
            'accounts' => $accounts,
            'visitor' => $this->demo->primaryVisitor(),
            'event' => $event,
        ]);
    }

    public function choosePlan(Request $request, string $planCode): RedirectResponse
    {
        $plan = MexcoPlan::query()->where('code', $planCode)->where('is_active', true)->firstOrFail();

        if ($plan->code === 'campus') {
            return redirect()->route('mexco.campus');
        }

        if ($plan->code === 'demo') {
            return redirect()->route('mexco.demo');
        }

        if ($plan->is_custom_pricing || $plan->code === 'enterprise') {
            return redirect()->route('mexco.enterprise');
        }

        $user = $this->auth->currentUser($request);

        if ($user) {
            $order = $this->checkout->startOrder($plan, $user);
            $request->session()->put('mexco_checkout_order_id', $order->id);
            $request->session()->put('mexco_selected_plan_code', $plan->code);

            return redirect()->route('mexco.checkout.event');
        }

        $request->session()->put('mexco_selected_plan_code', $plan->code);

        return redirect()->route('mexco.register', ['plan' => $plan->code]);
    }

    public function howItWorks(): View
    {
        return view('public.how-it-works');
    }

    public function campus(): View
    {
        return view('public.campus');
    }

    public function campusPending(Request $request): View
    {
        $ref = strtoupper(trim((string) $request->query('ref', '')));
        $application = $ref !== ''
            ? \App\Models\MexcoCampusApplication::query()->where('reference_no', $ref)->first()
            : null;

        return view('public.campus-pending', [
            'application' => $application,
            'reference' => $ref ?: null,
        ]);
    }

    public function enterprise(): View
    {
        return view('public.enterprise');
    }

    public function contact(): View
    {
        return view('public.contact');
    }
}
