<?php

namespace App\Http\Controllers\SaasAdmin;

use App\Http\Controllers\Controller;
use App\Models\SubscriptionPlan;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

/**
 * Root-admin-only CRUD for the SaaS pricing tiers companies subscribe to.
 * Entirely separate from the student-facing Plan model — this never
 * touches that table, and nothing here is reachable from a company's own
 * admin panel.
 */
class SubscriptionPlanController extends Controller
{
    public function index(): View
    {
        $plans = SubscriptionPlan::withCount('companySubscriptions')->latest('id')->get();

        return view('saas-admin.subscription-plans.index', compact('plans'));
    }

    public function create(): View
    {
        return view('saas-admin.subscription-plans.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validated($request);
        $validated['slug'] = $this->uniqueSlug($validated['name']);

        SubscriptionPlan::create($validated);

        return to_route('saas-admin.subscription-plans.index')->with('success', __(':name created.', ['name' => $validated['name']]));
    }

    public function edit(SubscriptionPlan $plan): View
    {
        return view('saas-admin.subscription-plans.edit', compact('plan'));
    }

    public function update(Request $request, SubscriptionPlan $plan): RedirectResponse
    {
        $validated = $this->validated($request);

        $plan->update($validated);

        return to_route('saas-admin.subscription-plans.index')->with('success', __(':name updated.', ['name' => $plan->name]));
    }

    public function destroy(SubscriptionPlan $plan): RedirectResponse
    {
        if ($plan->companySubscriptions()->exists()) {
            return back()->with(
                'error',
                __(':name is still assigned to at least one company — move them to a different plan first.', ['name' => $plan->name])
            );
        }

        $plan->delete();

        return to_route('saas-admin.subscription-plans.index')->with('success', __(':name deleted.', ['name' => $plan->name]));
    }

    private function validated(Request $request): array
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'price' => ['required', 'numeric', 'min:0'],
            'billing_interval' => ['required', 'in:monthly,yearly'],
            'user_limit' => ['nullable', 'integer', 'min:1'],
            'custom_domain_allowed' => ['nullable', 'boolean'],
            'status' => ['required', 'in:active,archived'],
        ]);

        // A checkbox sends nothing at all when unchecked, so this can't be
        // left to the validated array alone — cast it explicitly.
        $validated['custom_domain_allowed'] = $request->boolean('custom_domain_allowed');

        return $validated;
    }

    private function uniqueSlug(string $name): string
    {
        $base = Str::slug($name, '-') ?: 'plan';
        $slug = $base;
        $suffix = 2;

        while (SubscriptionPlan::where('slug', $slug)->exists()) {
            $slug = $base . '-' . $suffix;
            $suffix++;
        }

        return $slug;
    }
}
