<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AddonProduct;
use App\Models\AddonPurchase;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AddonProductsController extends Controller
{
    public function index(): View
    {
        $products = AddonProduct::withCount('purchases')
            ->latest()
            ->paginate(25);

        $stats = [
            'total_products' => AddonProduct::count(),
            'active_products' => AddonProduct::where('is_active', true)->count(),
            'total_revenue' => AddonPurchase::where('status', 'completed')->sum('amount_paid'),
            'total_purchases' => AddonPurchase::where('status', 'completed')->count(),
        ];

        return view('admin.addons.index', compact('products', 'stats'));
    }

    public function create(): View
    {
        return view('admin.addons.form', ['product' => null]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name'           => 'required|string|max:255',
            'description'    => 'nullable|string|max:1000',
            'price'          => 'required|numeric|min:0',
            'currency'       => 'required|string|size:3',
            'type'           => 'required|string|in:one_time,credit_pack,feature_unlock',
            'is_active'      => 'boolean',
            'stripe_price_id' => 'nullable|string|max:255',
            'paypal_item_id' => 'nullable|string|max:255',
        ]);

        $validated['is_active'] = $request->boolean('is_active', true);

        AddonProduct::create($validated);

        return redirect()->route('admin.addons.index')
            ->with('success', 'Add-on product created successfully.');
    }

    public function edit(AddonProduct $addon): View
    {
        return view('admin.addons.form', ['product' => $addon]);
    }

    public function update(Request $request, AddonProduct $addon): RedirectResponse
    {
        $validated = $request->validate([
            'name'           => 'required|string|max:255',
            'description'    => 'nullable|string|max:1000',
            'price'          => 'required|numeric|min:0',
            'currency'       => 'required|string|size:3',
            'type'           => 'required|string|in:one_time,credit_pack,feature_unlock',
            'is_active'      => 'boolean',
            'stripe_price_id' => 'nullable|string|max:255',
            'paypal_item_id' => 'nullable|string|max:255',
        ]);

        $validated['is_active'] = $request->boolean('is_active');

        $addon->update($validated);

        return redirect()->route('admin.addons.index')
            ->with('success', "Add-on \"{$addon->name}\" updated.");
    }

    public function toggle(AddonProduct $addon): RedirectResponse
    {
        $addon->update(['is_active' => !$addon->is_active]);
        $status = $addon->is_active ? 'activated' : 'deactivated';
        return back()->with('success', "Add-on \"{$addon->name}\" {$status}.");
    }

    public function destroy(AddonProduct $addon): RedirectResponse
    {
        $addon->delete();
        return redirect()->route('admin.addons.index')
            ->with('success', 'Add-on product deleted.');
    }

    public function purchases(Request $request): View
    {
        $purchases = AddonPurchase::with(['user:id,name,email', 'product:id,name,price,currency'])
            ->when($request->filled('product'), fn (Builder $q) => $q->where('addon_product_id', $request->integer('product')))
            ->when($request->filled('status'), fn (Builder $q) => $q->where('status', $request->string('status')))
            ->when($request->filled('q'), function (Builder $q) use ($request) {
                $term = $request->string('q')->value();
                $q->where(function (Builder $inner) use ($term) {
                    $inner->where('provider_reference', 'like', "%{$term}%")
                        ->orWhereHas('user', fn (Builder $uq) => $uq
                            ->where('email', 'like', "%{$term}%")
                            ->orWhere('name', 'like', "%{$term}%"));
                });
            })
            ->latest()
            ->paginate(30)
            ->withQueryString();

        $products = AddonProduct::orderBy('name')->get(['id', 'name']);

        return view('admin.addons.purchases', compact('purchases', 'products'));
    }
}
