<?php

use Morpheus\Ranking\Ranking;

$rewards = config('rewards.rankings');

if ($rewards) {
    foreach ($rewards as $id => $reward) {
        if (isset($reward['normal'])) {
            $reward = $reward['normal'];
            $ranking = config('rankings.' . $id);

            if ($ranking && $ranking['active']) {

                $r = Ranking::factory($id, [
                    'name' => $id
                ]);

                if ($r->isValid()) {
                    $qb = $r->getQuery();
                    $qb->setMaxResults(3);

                    foreach ($qb->execute()->fetchAll() as $index => $data) {
                        $coin = trim($reward['reward'][$index]['coin']);
                        $amount = trim($reward['reward'][$index]['amount']);
                        if (!empty($coin) && !empty($amount)) {
                            $account = account($data['account']);
                            if ($account->exists()) {
                                $account->addCoin($coin, $amount);
                                $account->updateCoins();

                                $account->log(_e('Was rewarded with %s for staying in %s in the general %s ranking', [$amount . ' ' . util('Coin')->name($coin), ($index + 1) . '&deg;', $ranking['name']]), 'reward');

                                user_message(
                                    _e('Congratulations'),
                                    _e('You was rewarded with %s for staying in %s in the general %s ranking', [$amount . ' ' . util('Coin')->name($coin), ($index + 1) . '&deg;', $ranking['name']]),
                                    $account->getUsername()
                                );
                            }
                        }
                    }

                    if ($reward['reset']) {
                        $r->reset();
                    }
                }
            }
        }
    }
}