<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;

class SubscriptionManagementController extends Controller
{
    /**
     * Show all users with subscription management.
     */
    public function index()
    {
        $users = User::with('preferences')
            ->latest()
            ->paginate(20);

        return view('admin.subscriptions', compact('users'));
    }

    /**
     * Show user subscription details.
     */
    public function show(User $user)
    {
        $user->load(['preferences', 'assignments']);
        return view('admin.subscription-details', compact('user'));
    }

    /**
     * Update user subscription status.
     */
    public function updateStatus(Request $request, User $user)
    {
        $request->validate([
            'subscription_status' => ['required', 'in:trial,free,paid'],
            'trial_expiry_date' => ['nullable', 'date'],
        ]);

        $updates = [
            'subscription_status' => $request->subscription_status,
        ];

        // Handle trial dates
        if ($request->subscription_status === 'trial') {
            $trialDays = \App\Models\SystemSetting::get('trial_duration_days', 14);
            $updates['trial_start_date'] = Carbon::now();
            $updates['trial_expiry_date'] = $request->trial_expiry_date 
                ? Carbon::parse($request->trial_expiry_date)
                : Carbon::now()->addDays($trialDays);
        } elseif ($request->subscription_status === 'paid') {
            // Keep existing trial dates but mark as paid
            // Optionally clear trial dates for paid users
        } else {
            // Free users - clear trial dates
            $updates['trial_start_date'] = null;
            $updates['trial_expiry_date'] = null;
        }

        $user->update($updates);

        return redirect()
            ->route('admin.subscriptions.show', $user)
            ->with('success', 'Subscription status updated successfully!');
    }

    /**
     * Extend trial period.
     */
    public function extendTrial(Request $request, User $user)
    {
        $request->validate([
            'additional_days' => ['required', 'integer', 'min:1', 'max:365'],
        ]);

        if ($user->subscription_status !== 'trial') {
            return back()->withErrors(['error' => 'User is not on trial.']);
        }

        $newExpiry = $user->trial_expiry_date 
            ? $user->trial_expiry_date->addDays($request->additional_days)
            : Carbon::now()->addDays($request->additional_days);

        $user->update([
            'trial_expiry_date' => $newExpiry,
        ]);

        return back()->with('success', "Trial extended by {$request->additional_days} days. New expiry: {$newExpiry->format('M d, Y')}");
    }

    /**
     * Grant paid subscription.
     */
    public function grantPaid(User $user)
    {
        $user->update([
            'subscription_status' => 'paid',
            'trial_start_date' => null,
            'trial_expiry_date' => null,
        ]);

        return back()->with('success', 'User granted paid subscription!');
    }

    /**
     * Revoke subscription (set to free).
     */
    public function revokeSubscription(User $user)
    {
        $user->update([
            'subscription_status' => 'free',
            'trial_start_date' => null,
            'trial_expiry_date' => null,
        ]);

        return back()->with('success', 'Subscription revoked. User set to free tier.');
    }
}
