<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Administration;
use App\Services\User\Contracts\UserServiceInterface;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function __construct(
        private UserServiceInterface $userService
    ) {}

    public function index(Request $request)
    {
        $selectedMonth = $request->input('month', Carbon::now()->format('Y-m'));
        $user          = Auth::user();

        $administrations = $this->userService->getDashboard($user, $selectedMonth);
        $stats = $this->userService->getPersonalStats($user, $selectedMonth);

        $receivedRanking = $this->userService->getRankingList('received', $selectedMonth, $user);
        $sentRanking = $this->userService->getRankingList('sent', $selectedMonth, $user);

        return view('user.dashboard', array_merge([
            'administrations' => $administrations,
            'selectedMonth' => $selectedMonth,
            'user' => $user,
            'receivedRankers' => $receivedRanking['rankers'],
            'receivedCurrentUserRankItem' => $receivedRanking['currentUserRankItem'],
            'sentRankers' => $sentRanking['rankers'],
            'sentCurrentUserRankItem' => $sentRanking['currentUserRankItem']
        ], $stats));
    }

    public function sendThankcards()
    {
        $users = $this->userService->getOtherActiveUsers(Auth::user());
        return view('user.send', compact('users'));
    }

    public function storeThankcards(Request $request)
    {
        $request->validate([
            'receiver' => [
                'required',
                \Illuminate\Validation\Rule::exists('user', 'msnv')->where('status', \App\Models\User::STATUS_ACTIVE)
            ],
            'amount'   => 'required|integer|min:1|max:' . Administration::MAX_SEND_CARD_PER_MONTH,
        ]);

        try {
            $this->userService->sendThankcards(
                Auth::user(),
                $request->receiver,
                (int) $request->amount
            );
        } catch (\RuntimeException $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
        }

        return response()->json(['success' => true, 'message' => __('messages.thank_card_send_success')]);
    }

    public function changePasswordForm()
    {
        return view('user.change_password');
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'password' => 'required|min:6|confirmed',
        ]);

        $user = Auth::user();
        $this->userService->updatePassword($user, $request->password);

        $route = $user->role == \App\Models\User::ROLE_ADMIN ? 'admin.dashboard' : 'user.dashboard';
        return redirect()->route($route)->with('success', __('messages.password_change_success'));
    }
}
