<?php

namespace App\Http\Controllers\Coach;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Plan;
use App\Models\Subscription;
use App\Notifications\InvoiceGenerated;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class SubscriptionController extends Controller
{
    /**
     * Display subscription status and available plans.
     */
    public function index(Request $request): Response
    {
        $user = $request->user();
        $activeSubscription = $user->activeSubscription?->load('plan');
        
        return Inertia::render('Coach/Subscription/Index', [
            'subscription' => $activeSubscription,
            'plans' => Plan::where('is_active', true)->get(),
            'usage' => [
                'clients' => [
                    'used' => $user->clients()->count(),
                    'limit' => $user->currentPlan()?->getLimit('max_clients') ?? 0,
                    'remaining' => $user->remaining('clients'),
                ],
                'diets' => [
                    'used' => $user->clients()->withCount('mealPlans')->get()->sum('meal_plans_count'),
                    'limit' => $user->currentPlan()?->getLimit('max_diets') ?? 0,
                    'remaining' => $user->remaining('diets'),
                ],
                'routines' => [
                    'used' => $user->clients()->withCount('workouts')->get()->sum('workouts_count'),
                    'limit' => $user->currentPlan()?->getLimit('max_routines') ?? 0,
                    'remaining' => $user->remaining('routines'),
                ],
            ],
            'invoices' => $user->invoices()->latest()->take(5)->get(),
        ]);
    }

    /**
     * Show plan details for upgrade/purchase.
     */
    public function show(Request $request, Plan $plan): Response
    {
        return Inertia::render('Coach/Subscription/Checkout', [
            'plan' => $plan,
            'currentPlan' => $request->user()->currentPlan(),
        ]);
    }

    /**
     * Process subscription purchase (Bank Transfer).
     */
    public function purchase(Request $request, Plan $plan): RedirectResponse
    {
        $validated = $request->validate([
            'payment_method' => 'required|in:bank_transfer,paypal,stripe',
        ]);

        $user = $request->user();

        // For bank transfer, create pending subscription and invoice
        if ($validated['payment_method'] === 'bank_transfer') {
            // Expire current subscription
            Subscription::where('user_id', $user->id)
                ->where('status', 'active')
                ->update(['status' => 'expired']);

            // Create new subscription (pending until payment confirmed)
            $subscription = Subscription::create([
                'user_id' => $user->id,
                'plan_id' => $plan->id,
                'start_date' => now(),
                'end_date' => now()->addDays($plan->duration_days),
                'status' => 'pending', // Will be activated by admin after payment confirmation
            ]);

            // Create invoice
            $invoice = Invoice::create([
                'user_id' => $user->id,
                'subscription_id' => $subscription->id,
                'invoice_number' => Invoice::generateNumber(),
                'subtotal' => $plan->price,
                'tax' => $plan->price * 0.18, // 18% ITBIS
                'total' => $plan->price * 1.18,
                'status' => 'pending',
                'payment_method' => 'bank_transfer',
                'items' => json_encode([
                    [
                        'description' => "Plan {$plan->name} - {$plan->duration_days} días",
                        'quantity' => 1,
                        'unit_price' => $plan->price,
                        'total' => $plan->price,
                    ]
                ]),
                'notes' => 'Transferencia bancaria pendiente de confirmación.',
            ]);

            // Notificar al coach sobre la factura generada
            $user->notify(new InvoiceGenerated($invoice));

            return redirect()->route('coach.subscription.payment-pending', $invoice)
                ->with('success', 'Orden creada. Complete el pago para activar su suscripción.');
        }

        // PayPal/Stripe (placeholder for future integration)
        return back()->with('error', 'Método de pago no disponible aún.');
    }

    /**
     * Show payment pending page with bank details.
     */
    public function paymentPending(Request $request, Invoice $invoice): Response
    {
        $this->authorize('view', $invoice);

        return Inertia::render('Coach/Subscription/PaymentPending', [
            'invoice' => $invoice->load('subscription.plan'),
            'bankDetails' => \App\Models\Setting::get('bank_details'),
        ]);
    }

    /**
     * Show invoice history.
     */
    public function invoices(Request $request): Response
    {
        return Inertia::render('Coach/Subscription/Invoices', [
            'invoices' => $request->user()
                ->invoices()
                ->with('subscription.plan')
                ->latest()
                ->paginate(10),
        ]);
    }

    /**
     * Download invoice as PDF (placeholder).
     */
    public function downloadInvoice(Request $request, Invoice $invoice): RedirectResponse
    {
        $this->authorize('view', $invoice);

        // TODO: Generate PDF with DomPDF or similar
        return back()->with('info', 'Descarga de PDF disponible próximamente.');
    }
}
