<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MembershipPlan;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    public function index(Request $request)
    {
        $query = Subscription::with(['user', 'plan'])->latest();

        if ($request->status) {
            $query->where('status', $request->status);
        }
        if ($request->search) {
            $query->whereHas('user', fn($q) =>
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%')
            );
        }

        $subscriptions = $query->paginate(30)->withQueryString();
        return view('admin.subscriptions.index', compact('subscriptions'));
    }

    public function show(Subscription $subscription)
    {
        $subscription->load(['user', 'plan']);
        return view('admin.subscriptions.show', compact('subscription'));
    }

    public function store(Request $request)
    {
        // Manuel abonelik ekleme (UserController.givePremium ile aynı mantık)
        $request->validate([
            'user_id'  => 'required|exists:users,id',
            'plan_id'  => 'required|exists:membership_plans,id',
        ]);

        $plan = MembershipPlan::findOrFail($request->plan_id);
        $user = User::findOrFail($request->user_id);

        $hasEverSubscribed = Subscription::where('user_id', $user->id)->exists();
        $bonusDays = (!$hasEverSubscribed && ($plan->trial_days ?? 0) > 0) ? $plan->trial_days : 0;
        $expiresAt = now()->addDays($plan->duration_days + $bonusDays);

        $user->update(['membership' => 'premium', 'premium_expires_at' => $expiresAt]);

        Subscription::create([
            'user_id'        => $user->id,
            'plan_id'        => $plan->id,
            'status'         => 'active',
            'starts_at'      => now(),
            'expires_at'     => $expiresAt,
            'payment_method' => 'manual',
        ]);

        return back()->with('success', 'Abonelik eklendi.');
    }

    public function destroy(Subscription $subscription)
    {
        $subscription->update(['status' => 'cancelled']);
        return back()->with('success', 'Abonelik iptal edildi.');
    }
}
