<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\PlatformProduct;
use App\Services\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class PlatformProductController extends Controller
{
    public function index(): View
    {
        $products = PlatformProduct::query()
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        return view('super.platform-products.index', [
            'products' => $products,
            'categories' => PlatformProduct::CATEGORIES,
            'stats' => [
                'total' => $products->count(),
                'active' => $products->where('is_active', true)->count(),
                'featured' => $products->where('is_featured', true)->count(),
                'merchant_count' => Agent::query()->where('status', Agent::STATUS_ACTIVE)->count(),
            ],
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validatedProduct($request);
        $validated['slug'] = $this->uniqueSlug($validated['name']);
        $validated['is_active'] = $request->boolean('is_active', true);
        $validated['is_featured'] = $request->boolean('is_featured');
        $validated['sort_order'] = $validated['sort_order'] ?? 0;

        $product = PlatformProduct::create($validated);
        ActivityLogger::log('platform_product_created', $product->name.' was added to merchant software products.', $product);

        return back()->with('status', 'Software product added.');
    }

    public function update(Request $request, PlatformProduct $softwareProduct): RedirectResponse
    {
        $validated = $this->validatedProduct($request);
        $validated['is_active'] = $request->boolean('is_active');
        $validated['is_featured'] = $request->boolean('is_featured');
        $validated['sort_order'] = $validated['sort_order'] ?? 0;

        $softwareProduct->update($validated);
        ActivityLogger::log('platform_product_updated', $softwareProduct->name.' software product was updated.', $softwareProduct);

        return back()->with('status', 'Software product updated.');
    }

    public function destroy(PlatformProduct $softwareProduct): RedirectResponse
    {
        $name = $softwareProduct->name;
        $softwareProduct->delete();
        ActivityLogger::log('platform_product_deleted', $name.' software product was deleted.');

        return back()->with('status', 'Software product deleted.');
    }

    private function validatedProduct(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'category' => ['required', Rule::in(array_keys(PlatformProduct::CATEGORIES))],
            'short_description' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:5000'],
            'website_url' => ['nullable', 'string', 'max:255'],
            'signup_url' => ['nullable', 'string', 'max:255'],
            'support_url' => ['nullable', 'string', 'max:255'],
            'monthly_price' => ['nullable', 'numeric', 'min:0'],
            'yearly_price' => ['nullable', 'numeric', 'min:0'],
            'onboarding_commission_rate' => ['required', 'numeric', 'min:0', 'max:'.Agent::MAX_COMMISSION_RATE],
            'referral_commission_rate' => ['required', 'numeric', 'min:0', 'max:'.Agent::MAX_COMMISSION_RATE],
            'color' => ['required', 'string', 'max:20'],
            'icon' => ['nullable', 'string', 'max:60'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);
    }

    private function uniqueSlug(string $name): string
    {
        $base = Str::slug($name) ?: 'software';
        $slug = $base;
        $counter = 2;

        while (PlatformProduct::query()->where('slug', $slug)->exists()) {
            $slug = $base.'-'.$counter++;
        }

        return $slug;
    }
}
