<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePlanRequest;
use App\Http\Requests\UpdatePlanRequest;
use App\Models\Plan;
use App\Services\SuperAdmin\PlatformAdminService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class PlanController extends Controller
{
    public function index(): View
    {
        Gate::authorize('viewAny', Plan::class);

        return view('super-admin.plans.index', [
            'plans' => Plan::query()
                ->withCount('subscriptions')
                ->orderBy('sort_order')
                ->orderBy('monthly_price')
                ->get(),
        ]);
    }

    public function create(): View
    {
        Gate::authorize('create', Plan::class);

        return view('super-admin.plans.form', [
            'plan' => new Plan([
                'status' => Plan::STATUS_ACTIVE,
                'trial_days' => 14,
                'invoice_module_enabled' => true,
                'email_reminder_enabled' => true,
            ]),
            'formAction' => route('super-admin.plans.store'),
            'formMethod' => 'POST',
            'submitLabel' => 'Save Plan',
        ]);
    }

    public function store(StorePlanRequest $request, PlatformAdminService $platform): RedirectResponse
    {
        $plan = Plan::query()->create($request->validated());
        $platform->log($request->user(), 'plan.created', "Created {$plan->name} plan.", $plan, ['plan_id' => $plan->id], $request);

        return redirect()
            ->route('super-admin.plans.edit', $plan)
            ->with('status', 'Plan created successfully.');
    }

    public function edit(Plan $plan): View
    {
        Gate::authorize('view', $plan);

        return view('super-admin.plans.form', [
            'plan' => $plan,
            'formAction' => route('super-admin.plans.update', $plan),
            'formMethod' => 'PUT',
            'submitLabel' => 'Update Plan',
        ]);
    }

    public function update(UpdatePlanRequest $request, Plan $plan, PlatformAdminService $platform): RedirectResponse
    {
        Gate::authorize('update', $plan);
        $before = $plan->only(array_keys($request->validated()));
        $plan->update($request->validated());
        $platform->log($request->user(), 'plan.updated', "Updated {$plan->name} plan.", $plan, [
            'before' => $before,
            'after' => $plan->fresh()->only(array_keys($request->validated())),
        ], $request);

        return redirect()
            ->route('super-admin.plans.edit', $plan)
            ->with('status', 'Plan updated successfully.');
    }
}
