<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SubscriptionController extends Controller
{
    public function index()
    {
        $plans = SubscriptionPlan::withCount('subscriptions')->get();
        $subscriptions = Subscription::with(['client', 'plan'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        $clients = Client::orderBy('name', 'asc')->get();

        return view('admin.subscriptions.index', compact('plans', 'subscriptions', 'clients'));
    }

    public function storePlan(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'billing_cycle' => 'required|in:Monthly,Quarterly,Annual',
            'description' => 'nullable|string',
        ]);

        $validated['slug'] = Str::slug($validated['name']) . '-' . Str::random(4);
        $validated['features'] = ['Full Dashboard Access', 'Automated Invoices', 'Priority Email Support'];
        $validated['is_active'] = true;

        SubscriptionPlan::create($validated);

        return redirect()->route('admin.subscriptions.index')->with('success', 'New plan tier created successfully!');
    }

    public function storeSubscription(Request $request)
    {
        $validated = $request->validate([
            'client_id' => 'required|exists:clients,id',
            'subscription_plan_id' => 'required|exists:subscription_plans,id',
            'starts_at' => 'required|date',
            'renews_at' => 'required|date|after:starts_at',
        ]);

        $validated['status'] = 'Active';
        $validated['auto_renew'] = true;

        Subscription::create($validated);

        return redirect()->route('admin.subscriptions.index')->with('success', 'Subscription assigned to client successfully!');
    }

    public function toggleStatus(Subscription $subscription)
    {
        $newStatus = $subscription->status === 'Active' ? 'Paused' : 'Active';
        $subscription->update(['status' => $newStatus]);

        return redirect()->route('admin.subscriptions.index')->with('success', "Subscription status updated to {$newStatus}.");
    }
}
