<?php

class ArenaController extends Controller {

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'attack', 'log'),
                'users' => array('@'),
            ),
            array('deny',
                'users' => array('*'),
                'deniedCallback' => array(Yii::app()->controller, 'redirectToHome'),
            )
        );
    }

    public function actions() {
        return array(
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function actionIndex() {

        /*
          $a = 0;
          while ($a < 70)
          {
          $user = new Users;
          $user->login = 'Боец '.rand(100,10000);
          $user->password = rand(1000000000,2000000000);
          $user->role = 'user';
          $user->side = rand(1,2);
          $user->sex = rand(1,2);
          $user->timereg = time();
          $user->level = rand(15,17);
          $user->health = rand(150,200);
          $user->attack = rand(25,32);
          $user->deff = rand(25,32);
          $user->accuracy = rand(25,31);
          $user->dodge = rand(15,40);
          $user->save();
          $a++;
          }
         */


        $my_stats = Users::stats();
        $user = Users::findUser();

        $max_level = $user->level + 1;
        $min_level = $user->level;
        $random_adversary = Users::model()->findByAttributes(array(), 'level >= :min_level AND level <= :max_level AND side != :side ORDER BY RAND()', array(':min_level' => $min_level, ':max_level' => $max_level, ':side' => $user->side)
        );
        $adversary_stats = Users::stats($random_adversary->id);

        if (empty($random_adversary)) {
            $this->render('no_adv');
        } else {
            $this->render('index', array(
                'health_my' => $my_stats['sum(`health`)'],
                'attack_my' => $my_stats['sum(`attack`)'],
                'deff_my' => $my_stats['sum(`deff`)'],
                'accuracy_my' => $my_stats['sum(`accuracy`)'],
                'dodge_my' => $my_stats['sum(`dodge`)'],
                'side_my' => $user->side,
                //противник
                'health_a' => $adversary_stats['sum(`health`)'],
                'attack_a' => $adversary_stats['sum(`attack`)'],
                'deff_a' => $adversary_stats['sum(`deff`)'],
                'accuracy_a' => $adversary_stats['sum(`accuracy`)'],
                'dodge_a' => $adversary_stats['sum(`dodge`)'],
                'adversary_id' => $random_adversary->id,
                'side_a' => $random_adversary->side,
                'adversary' => $random_adversary,
            ));
        }
    }

    public function actionAttack($id) {
        $adversary = Users::findAdversary($id);
        if ($adversary == 1) {
            Yii::app()->user->setFlash('error', 'Такого пользователя не существует');
            $this->redirect(array('arena/index'));
        }
        if ($adversary == 2) {
            Yii::app()->user->setFlash('error', 'Вы не можете сражаться с этим противником');
            $this->redirect(array('arena/index'));
        }
        if ($adversary == 3) {
            $u = Users::findUser();
            if ($u['energy'] < 10) {
                $isset_energy_bottle = Inventory::model()->findByAttributes(array('user' => Yii::app()->user->id, 'type' => 10));
                if ($isset_energy_bottle) {
                    Yii::app()->user->setFlash('error', 'Недостаточно энергии'
                            . '<br />'
                            . '<table>'
                            . '<tr>'
                            . '<td class="col-xs-6 col-sm-4"><img src="/images/shop/cat_10/' . $isset_energy_bottle->item . '.png">'
                            . '</td>'
                            . '<td>' . $isset_energy_bottle->title
                            . '<br />' . CHtml::link('Использовать', array("hero/useEnergy", 'id' => $isset_energy_bottle->id, 'fight' => '1')) . ''
                            . '</td>'
                            . '</tr>'
                            . '</table>');
                } else {
                    Yii::app()->user->setFlash('error', 'Недостаточно энергии'
                            . '<br />'
                            . '<table>'
                            . '<tr>'
                            . '<td class="col-xs-6 col-sm-4"><img src="/images/shop/cat_10/218.png">'
                            . '</td>'
                            . '<td>Энергетик 30'
                            . '<br />' . CHtml::link('Купить за 1<img src="/images/diamond.png">', array("shop/buy", 'id' => '218', 'fight' => '1')) . ''
                            . '</td>'
                            . '</tr>'
                            . '</table>');
                }
                $this->redirect(array('arena/index'));
                exit();
            }
            Users::energySub();
            $a = Users::findUser($id);
            $my_stats = Users::stats();
            $adversary_stats = Users::stats($a->id);

            $my_health = $my_stats['sum(`health`)'];
            $my_attack = $my_stats['sum(`attack`)'];
            $my_deff = $my_stats['sum(`deff`)'];
            $my_accuracy = $my_stats['sum(`accuracy`)'];
            $my_dodge = $my_stats['sum(`dodge`)'];
            $my_crit = $my_stats['sum(`crit`)'];
            $my_acrit = $my_stats['sum(`acrit`)'];
            $my_pet = Pets_user::ownedmeornot(NULL);

            $adversary_health = $adversary_stats['sum(`health`)'];
            $adversary_attack = $adversary_stats['sum(`attack`)'];
            $adversary_deff = $adversary_stats['sum(`deff`)'];
            $adversary_accuracy = $adversary_stats['sum(`accuracy`)'];
            $adversary_dodge = $adversary_stats['sum(`dodge`)'];
            $adversary_crit = $adversary_stats['sum(`crit`)'];
            $adversary_acrit = $adversary_stats['sum(`acrit`)'];
            $adversary_pet = Pets_user::model()->findByAttributes(array('user' => $a->id));

            $fights = new Fights;
            $fights->user_my = Yii::app()->user->id;
            $fights->user_a = $a->id;
            $fights->health_my = $my_health;
            $fights->health_a = $adversary_health;
            $fights->save();

            $id_fight = Yii::app()->db->getLastInsertId();
            $log = new Log_fight;
            $log->id_fight = $id_fight;
            $log->text = 'Бой между <b>' . $u->login . '</b> и <b>' . $a->login . '</b> начался';
            $log->save();

            $fight = Fights::findFight($id_fight);

            $my_pet_damage = 0;
            //Цикл боя, пока кто то из противников не умрет
            while ($fight->health_my > 0 AND $fight->health_a > 0) {
                $m_attack = intval($my_attack * 3.7);
                $m_deff = intval($my_deff * 2.5);
                $a_attack = intval($adversary_attack * 3.7);
                $a_deff = intval($adversary_deff * 2.5);

                //Уворот
                if ($my_dodge > $adversary_dodge) {
                    $dodge_proc = $my_dodge - $adversary_dodge;
                    $dodge_rand = rand(1, 100);
                    if ($dodge_proc >= $dodge_rand)
                        $dodge_me = 1;
                }
                if ($adversary_dodge > $my_dodge) {
                    $dodge_proc = $adversary_dodge - $my_dodge;
                    $dodge_rand = rand(1, 100);
                    if ($dodge_proc >= $dodge_rand)
                        $dodge_his = 1;
                }

                //Точность
                if ($my_accuracy < $adversary_accuracy) {
                    $accuracy_proc = 2 * ($adversary_accuracy - $my_accuracy);
                    $accuracy_rand = rand(1, 100);
                    if ($accuracy_proc >= $accuracy_rand)
                        $accuracy_me = 1;
                }
                if ($my_accuracy > $adversary_accuracy) {
                    $accuracy_proc = 2 * ($my_accuracy - $adversary_accuracy);
                    $accuracy_rand = rand(1, 100);
                    if ($accuracy_proc >= $accuracy_rand)
                        $accuracy_his = 1;
                }

                //Критический
                if ($my_crit > $adversary_acrit) {
                    $my_crit_proc = $my_crit - $adversary_acrit;
                    $crit_rand = rand(1, 100);
                    if ($my_crit_proc >= $crit_rand)
                        $crit_me = 1;
                }
                if ($adversary_acrit > $my_crit) {
                    $his_crit_proc = $adversary_crit - $my_acrit;
                    $crit_rand = rand(1, 100);
                    if ($his_crit_proc >= $crit_rand)
                        $crit_his = 1;
                }

                $a_strike = intval($a_attack - $m_deff);
                if ($adversary_pet) {
                    $a_strike = intval(($a_attack - $m_deff) * (rand(1, $adversary_pet->procent) / 100)) + intval($m_attack - $a_deff);
                }

                $my_strike = intval($m_attack - $a_deff);
                if ($my_pet) {
                    $my_strike = intval(($m_attack - $a_deff) * (rand(1, $my_pet->procent) / 100)) + intval($m_attack - $a_deff);
                    $my_pet_damage = $my_pet_damage + intval(($m_attack - $a_deff) * ($my_pet->procent / 100));
                }

                $log = new Log_fight;
                $log->id_fight = $id_fight;
                $log->text = '';


                if ($a_strike <= 0)
                    $a_strike = rand(1, 3);
                if ($my_strike <= 0)
                    $my_strike = rand(1, 3);

                if ($crit_me == 1) {
                    $my_strike = intval($my_strike * (rand(1, 9) / 5));
                    $log->text .= '<b>' . $u->login . '</b> нанес критический удар!!!<br />';
                }

                if ($crit_his == 1) {
                    $a_strike = intval($a_strike * (rand(1, 9) / 5));
                    $log->text .= '<b>' . $a->login . '</b> нанес критический удар!!!<br />';
                }


                $health_my = intval($fight->health_my - $a_strike);
                $health_a = intval($fight->health_a - $my_strike);


                if ($dodge_me == 1) {
                    $a_strike = 0;
                    $health_my = $fight->health_my;
                    $log->text .= '<b>' . $u->login . '</b> сумел увернуться от удара!<br />';
                }

                if ($dodge_his == 1) {
                    $my_strike = 0;
                    $health_a = $fight->health_a;
                    $log->text .= '<b>' . $a->login . '</b> сумел увернуться от удара!<br />';
                }

                if ($accuracy_me == 1) {
                    $my_strike = 0;
                    $health_a = $fight->health_a;
                    $log->text .= '<b>' . $u->login . '</b> промахнулся!!!<br />';
                }

                if ($accuracy_his == 1) {
                    $a_strike = 0;
                    $health_my = $fight->health_my;
                    $log->text .= '<b>' . $a->login . '</b> промахнулся!!!<br />';
                }



                Fights::model()->updateByPk($id_fight, array('health_my' => $health_my, 'health_a' => $health_a));
                $fight = Fights::findFight($id_fight);

                if ($fight->health_my > 0 AND $fight->health_a > 0) {
                    $log->text .= '<b>' . $u->login . '</b> наносит удар <b>' . $a->login . ' [' . $fight->health_a . '] </b> на ' . $my_strike . '<br /><b>' . $a->login . ' </b> наносит удар <b>' . $u->login . ' [' . $fight->health_my . ']</b> на ' . $a_strike;
                }
                if ($fight->health_my <= 0 AND $fight->health_a <= 0) {
                    $log->text .= '<br /><b>НИЧЬЯ</b>';
                } else {
                    if ($fight->health_my <= 0) {
                        $log->text .= '<br />' . $u->login . '</b> <b>ПРОИГРАЛ</b>';
                        Fights::model()->updateByPk($id_fight, array('win' => $a->id));
                    }
                    if ($fight->health_a <= 0) {
                        Fights::model()->updateByPk($id_fight, array('win' => $u->id));
                        $log->text .= '<br />' . $a->login . '</b> <b>ПРОИГРАЛ</b>';
                    }
                }
                $log->save();
            }
            if ($my_pet) {
                $log = new Log_fight();
                $log->id_fight = $id_fight;
                $log->text = '<b>Сумарный урон питомца за бой: ' . $my_pet_damage . '</b>';
                $log->save(false);
            }
        }
        $this->redirect(array('arena/log', 'id' => $id_fight));
    }

    public function actionLog($id) {
        $user = Users::findUser();
        $models = Log_fight::model()->findAllByAttributes(array('id_fight' => $id));
        if (empty($models)) {
            $this->redirect(array('arena/index'));
        }
        $fight = Fights::model()->findFight($id);
        if ($fight->win == Yii::app()->user->id) {
            //не забываем дать опыт и бабки если победа
            Users::getexp($user->level);
            $win = 1;
        }
        if ($fight->win == 0)
            $win = 0;
        $user = Users::findUser();
        //проверяем по таблице, не повысился ли уровень
        $level = new Helper();
        if ($user->exp >= $level->level[$user->level]) {
            Users::level_up();
        }
        //Избавляемся от допинга если он был
        Inventory::DopingThrow();
        $this->render('log', array(
            'models' => $models,
            'win' => $win,
        ));
        Log_fight::model()->deleteAllByAttributes(array('id_fight' => $id));
    }

}
