<?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;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $query = User::latest();

        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%');
            });
        }
        if ($request->membership) {
            $query->where('membership', $request->membership);
        }
        if ($request->role) {
            $query->where('role', $request->role);
        }
        if ($request->banned) {
            $query->where('is_banned', true);
        }

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

    public function show(User $user)
    {
        $user->load(['subscriptions.plan', 'comments']);
        $plans = MembershipPlan::where('is_active', true)->get();
        return view('admin.users.show', compact('user', 'plans'));
    }

    public function edit(User $user)
    {
        return view('admin.users.edit', compact('user'));
    }

    public function update(Request $request, User $user)
    {
        if ($user->isAdmin() && !auth()->user()->isAdmin()) {
            return back()->with('error', 'Admin kullanıcı düzenlenemez.');
        }

        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'email'       => 'required|email|unique:users,email,' . $user->id,
            'role'        => 'required|in:user,moderator,admin',
            'password'    => 'nullable|string|min:8',
            'admin_badge' => 'nullable|string|max:32',
        ]);

        if (!empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $user->update($data);
        return redirect()->route('admin.users.show', $user)->with('success', 'Kullanıcı güncellendi.');
    }

    public function destroy(User $user)
    {
        if ($user->id === auth()->id()) {
            return back()->with('error', 'Kendinizi silemezsiniz.');
        }
        if ($user->isAdmin()) {
            return back()->with('error', 'Admin kullanıcı silinemez.');
        }
        $user->delete();
        return redirect()->route('admin.users.index')->with('success', 'Kullanıcı silindi.');
    }

    public function ban(Request $request, User $user)
    {
        $request->validate(['ban_reason' => 'nullable|string|max:500']);

        if ($user->isAdmin()) {
            return back()->with('error', 'Admin kullanıcı banlanamaz.');
        }

        $user->update([
            'is_banned'  => true,
            'ban_reason' => $request->ban_reason,
            'banned_at'  => now(),
        ]);

        return back()->with('success', $user->name . ' banlandı.');
    }

    public function unban(User $user)
    {
        $user->update([
            'is_banned'  => false,
            'ban_reason' => null,
            'banned_at'  => null,
        ]);
        return back()->with('success', $user->name . ' bandan çıkarıldı.');
    }

    public function givePremium(Request $request, User $user)
    {
        $request->validate([
            'plan_id' => 'required|exists:membership_plans,id',
        ]);

        $plan = MembershipPlan::findOrFail($request->plan_id);
        $expiresAt = now()->addDays($plan->duration_days);

        $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',
            'notes'          => 'Admin tarafından verildi: ' . auth()->user()->name,
        ]);

        return back()->with('success', $user->name . "'e {$plan->duration_days} günlük premium verildi.");
    }

    public function removePremium(User $user)
    {
        $user->update([
            'membership'         => 'free',
            'premium_expires_at' => null,
        ]);

        Subscription::where('user_id', $user->id)
            ->where('status', 'active')
            ->update(['status' => 'cancelled']);

        return back()->with('success', $user->name . "'in premiumu kaldırıldı.");
    }
}
