<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePlanRequest;
use App\Models\Plan;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Laravel\Cashier\Subscription;

class PlanController extends Controller
{
    public function index(Request $request): Response
    {
        $query = Plan::query();

        // Filter by service type
        if ($request->filled('service_type') && $request->input('service_type') !== 'all') {
            $query->where('service_type', $request->input('service_type'));
        }

        // Search by name
        if ($request->filled('search')) {
            $query->where('name', 'like', '%'.$request->input('search').'%');
        }

        $plans = $query
            ->withCount(['services as subscribers_count' => function ($q): void {
                $q->where('status', 'active');
            }])
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return Inertia::render('Admin/Plans/Index', [
            'plans' => $plans,
            'filters' => [
                'service_type' => $request->input('service_type', 'all'),
                'search' => $request->input('search', ''),
            ],
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Admin/Plans/Create');
    }

    public function store(StorePlanRequest $request): RedirectResponse
    {
        Plan::query()->create([
            'name' => $request->validated('name'),
            'slug' => $request->validated('slug'),
            'description' => $request->validated('description'),
            'service_type' => $request->validated('service_type'),
            'price' => $request->validated('price'),
            'currency' => 'USD',
            'billing_cycle' => $request->validated('billing_cycle'),
            'features' => $request->featuresForStorage(),
            'provisioning_config' => $request->validated('provisioning_config'),
            'stock_quantity' => $request->validated('stock_quantity'),
            'sort_order' => $request->validated('sort_order', 0),
            'days_to_suspend' => $request->validated('days_to_suspend'),
            'days_to_terminate' => $request->validated('days_to_terminate'),
            'auto_suspend_enabled' => $request->validated('auto_suspend_enabled', true),
            'auto_terminate_enabled' => $request->validated('auto_terminate_enabled', true),
            'status' => 'active',
        ]);

        return redirect()
            ->route('admin.plans.index')
            ->with('success', 'Plan created successfully.');
    }

    public function edit(Plan $plan): Response
    {
        $subscribersCount = Subscription::query()
            ->where('plan_id', $plan->id)
            ->where('stripe_status', 'active')
            ->count();

        return Inertia::render('Admin/Plans/Edit', [
            'plan' => $plan,
            'subscribersCount' => $subscribersCount,
        ]);
    }

    public function update(StorePlanRequest $request, Plan $plan): RedirectResponse
    {
        $plan->update([
            'name' => $request->validated('name'),
            'slug' => $request->validated('slug'),
            'description' => $request->validated('description'),
            'service_type' => $request->validated('service_type'),
            'price' => $request->validated('price'),
            'billing_cycle' => $request->validated('billing_cycle'),
            'features' => $request->featuresForStorage(),
            'provisioning_config' => $request->validated('provisioning_config'),
            'stock_quantity' => $request->validated('stock_quantity'),
            'sort_order' => $request->validated('sort_order', 0),
            'days_to_suspend' => $request->validated('days_to_suspend'),
            'days_to_terminate' => $request->validated('days_to_terminate'),
            'auto_suspend_enabled' => $request->validated('auto_suspend_enabled', true),
            'auto_terminate_enabled' => $request->validated('auto_terminate_enabled', true),
        ]);

        return redirect()
            ->route('admin.plans.index')
            ->with('success', 'Plan updated successfully.');
    }

    public function destroy(Plan $plan): RedirectResponse
    {
        // Soft-delete by setting status to inactive
        $plan->update(['status' => 'inactive']);

        return redirect()
            ->route('admin.plans.index')
            ->with('success', 'Plan archived successfully.');
    }
}
