<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password as PasswordRule;

class ProfileController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $user = $request->user();

        return response()->json([
            'user' => [
                'id'                  => $user->id,
                'name'                => $user->name,
                'username'            => $user->username,
                'email'               => $user->email,
                'avatar'              => $user->avatar,
                'balance'             => (float) $user->balance,
                'vip_tier'            => $user->vip_tier,
                'vip_points'          => $user->vip_points,
                'roles'               => $user->getRoleNames(),
                'email_notifications' => $user->email_notifications,
                'promotional_offers'  => $user->promotional_offers,
                'security_alerts'     => $user->security_alerts,
                'total_bets'          => $user->bets()->count(),
                'win_rate'            => $user->win_rate,
                'total_staked'        => (float) $user->total_staked,
                'total_won'           => (float) $user->total_won,
                'created_at'          => $user->created_at,
            ],
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $user = $request->user();

        $data = $request->validate([
            'username' => ['sometimes', 'string', 'min:3', 'max:30', Rule::unique('users')->ignore($user->id)],
            'email'    => ['sometimes', 'email', Rule::unique('users')->ignore($user->id)],
            'password' => ['sometimes', 'nullable', 'confirmed', PasswordRule::min(6)],
            'email_notifications' => 'sometimes|boolean',
            'promotional_offers'  => 'sometimes|boolean',
            'security_alerts'     => 'sometimes|boolean',
            'phone'               => 'sometimes|nullable|string|max:20',
            'avatar'              => 'sometimes|nullable|string|url',
        ]);

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

        if (isset($data['username'])) {
            $data['name'] = $data['username'];
        }

        $user->update($data);

        return response()->json([
            'message' => 'Profile updated successfully.',
            'user'    => [
                'id'                  => $user->id,
                'name'                => $user->name,
                'username'            => $user->username,
                'email'               => $user->email,
                'avatar'              => $user->avatar,
                'balance'             => (float) $user->balance,
                'vip_tier'            => $user->vip_tier,
                'vip_points'          => $user->vip_points,
                'email_notifications' => $user->email_notifications,
                'promotional_offers'  => $user->promotional_offers,
                'security_alerts'     => $user->security_alerts,
            ],
        ]);
    }

    public function stats(Request $request): JsonResponse
    {
        $user = $request->user();
        $bets = $user->bets()->with('items')->get();

        return response()->json([
            'stats' => [
                'balance'      => (float) $user->balance,
                'total_bets'   => $bets->count(),
                'won_bets'     => $bets->where('status', 'won')->count(),
                'lost_bets'    => $bets->where('status', 'lost')->count(),
                'win_rate'     => $user->win_rate,
                'total_staked' => (float) $bets->sum('stake'),
                'total_won'    => (float) $bets->where('status', 'won')->sum('actual_payout'),
                'net_profit'   => (float) ($bets->where('status', 'won')->sum('actual_payout') - $bets->sum('stake')),
                'vip_tier'     => $user->vip_tier,
                'vip_points'   => $user->vip_points,
            ],
        ]);
    }
}
