<?php

namespace App\Http\Controllers;

use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class SubscriptionController extends Controller
{
    /**
     * Show subscription management page.
     */
    public function index()
    {
        $user = Auth::user();
        $plans = SubscriptionPlan::active()->orderBy('sort_order')->get();
        
        return view('subscription.index', compact('user', 'plans'));
    }

    /**
     * Handle subscription plan selection/upgrade.
     */
    public function selectPlan(Request $request)
    {
        $request->validate([
            'plan_id' => ['required', 'exists:subscription_plans,id'],
        ]);

        $user = Auth::user();
        $plan = SubscriptionPlan::findOrFail($request->plan_id);

        // If selecting free plan
        if ($plan->slug === 'free' || $plan->price == 0) {
            $user->update([
                'subscription_status' => 'free',
                'trial_start_date' => null,
                'trial_expiry_date' => null,
            ]);

            return back()->with('success', 'Switched to Free plan successfully.');
        }

        // If plan has trial days, start trial
        if ($plan->trial_days > 0 && $user->subscription_status !== 'paid') {
            $user->update([
                'subscription_status' => 'trial',
                'trial_start_date' => Carbon::now(),
                'trial_expiry_date' => Carbon::now()->addDays($plan->trial_days),
            ]);

            return back()->with('success', "Started {$plan->trial_days}-day trial for {$plan->name} plan!");
        }

        // For paid plans, this would integrate with payment gateway
        // For now, we'll show a message
        return back()->with('info', "To upgrade to {$plan->name} ({$plan->formatted_price}/month), payment gateway integration is required. Please contact support or admin to upgrade.");
    }

    /**
     * Handle subscription upgrade (legacy method for compatibility).
     */
    public function upgrade(Request $request)
    {
        return $this->selectPlan($request);
    }
}
