<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\SubscriptionRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminSubscriptionRequestController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->get('status');

        $query = SubscriptionRequest::with(['user', 'plan', 'paymentMethod'])->latest();

        if ($status && in_array($status, ['pending', 'approved', 'cancelled'])) {
            $query->where('status', $status);
        }

        $subscriptionRequests = $query->paginate(12)->withQueryString();

        $stats = [
            'total'     => SubscriptionRequest::count(),
            'pending'   => SubscriptionRequest::where('status', 'pending')->count(),
            'approved'  => SubscriptionRequest::where('status', 'approved')->count(),
            'cancelled' => SubscriptionRequest::where('status', 'cancelled')->count(),
        ];

        return view('admin.subscription_requests.index', compact('subscriptionRequests', 'stats', 'status'));
    }

    public function show(SubscriptionRequest $subscriptionRequest)
    {
        $subscriptionRequest->load(['user', 'plan', 'paymentMethod']);

        return view('admin.subscription_requests.show', compact('subscriptionRequest'));
    }

    public function approve(SubscriptionRequest $subscriptionRequest)
    {
        if ($subscriptionRequest->status !== 'pending') {
            return redirect()
                ->route('admin.subscription-requests.index')
                ->with('error', 'This request has already been processed.');
        }

        DB::transaction(function () use ($subscriptionRequest) {
            $subscriptionRequest->load(['plan']);

            Subscription::where('user_id', $subscriptionRequest->user_id)
                ->where('status', 'active')
                ->where('is_trial', false)
                ->update([
                    'status'     => 'expired',
                    'updated_at' => now(),
                ]);

            $startDate = now();
            $endDate = Carbon::parse($startDate)->addDays((int) $subscriptionRequest->plan->duration_days);

            Subscription::create([
                'user_id'    => $subscriptionRequest->user_id,
                'plan_id'    => $subscriptionRequest->plan_id,
                'start_date' => $startDate,
                'end_date'   => $endDate,
                'status'     => 'active',
                'is_trial'   => false,
            ]);

            $subscriptionRequest->update([
                'status' => 'approved',
            ]);
        });

        return redirect()
            ->route('admin.subscription-requests.show', $subscriptionRequest->id)
            ->with('success', 'Subscription request approved successfully and paid plan activated.');
    }

    public function cancel(SubscriptionRequest $subscriptionRequest)
    {
        if ($subscriptionRequest->status !== 'pending') {
            return redirect()
                ->route('admin.subscription-requests.index')
                ->with('error', 'This request has already been processed.');
        }

        $subscriptionRequest->update([
            'status' => 'cancelled',
        ]);

        return redirect()
            ->route('admin.subscription-requests.show', $subscriptionRequest->id)
            ->with('success', 'Subscription request cancelled successfully.');
    }
}