<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Lead;
use App\Models\Withdrawal;
use Illuminate\Http\Request;

class UsersViewController extends Controller
{
    public function index($id)
    {
        $user = User::with(['faceVerifications' => fn ($query) => $query->latest()->take(5)])->findOrFail($id);
        $stats = [
            'completed_offers' => Lead::where('user_id', $user->id)->where('status', 'approved')->count(),
            'total_cashout' => Withdrawal::where('user_id', $user->id)->where('status', 'approved')->sum('amount'),
            'lifetime_income' => Lead::where('user_id', $user->id)->sum('credited_points'),
            'rank' => User::where('is_admin', false)->where('total_points', '>', $user->total_points)->count() + 1,
        ];
        return view('admin.users-view', compact('user', 'stats'));
    }

    public function update($id, Request $request)
    {
        $user = User::findOrFail($id);
        switch ($request->input('action')) {
            case 'save':
                return $this->save($user, $request);
            case 'ban':
                return $this->ban($user);
            case 'role':
                return $this->role($user, $request);
        }

        return redirect()->back()->with('error', 'Unknown action.');
    }

    /**
     * Promote/demote a user. Only full admins may change roles, nobody can
     * change their own, and staff roles carry per-section permissions.
     */
    private function role(User $user, Request $request)
    {
        if (!auth()->user()->is_admin) {
            return redirect()->back()->with('error', 'Only full admins can change roles.');
        }

        if ($user->id === auth()->id()) {
            return redirect()->back()->with('error', 'You cannot change your own role.');
        }

        $data = $request->validate([
            'role' => ['required', 'in:user,support,moderator,admin'],
            'permissions' => ['nullable', 'array'],
            'permissions.*' => ['in:'.implode(',', array_keys(User::ADMIN_SECTIONS))],
        ]);

        $isStaff = in_array($data['role'], ['support', 'moderator'], true);

        $user->update([
            'role' => $data['role'],
            'is_admin' => $data['role'] === 'admin',
            'admin_permissions' => $isStaff ? array_values($data['permissions'] ?? []) : null,
        ]);

        return redirect()->back()->with('success', 'Role updated to '.$data['role'].'.');
    }

    public function save($user, Request $request)
    {
        $request->validate([
            'balance_usd' => ['nullable', 'required_without:points', 'numeric', 'min:0', 'max:100000'],
            'points' => ['nullable', 'required_without:balance_usd', 'numeric', 'min:0', 'max:100000000'],
            'password' => ['nullable', 'string', 'min:8', 'max:255'],
        ]);

        $user->current_points = $request->filled('balance_usd')
            ? round((float) $request->balance_usd * coins_per_usd(), 2)
            : round((float) $request->points, 2);
        if ($request->password) {
            $user->password = bcrypt($request->password);
        }
        $user->save();
        return redirect()->back()->with('success', 'Info has been updated');
    }

    public function ban($user)
    {
        if ($user->is_banned) {
            $user->is_banned = 0;
            $user->save();
            return redirect()->back()->with('success', 'User has been unbanned');
        } else {
            $user->is_banned = 1;
            $user->save();
            return redirect()->back()->with('success', 'User has been banned');
        }
    }
}
