/**
  * Desqualify a rival. Knight win combat by desqualify
  */
 public function actionDesqualifyRival()
 {
     $output = array('errno' => 1, 'html' => '', 'isDesqualify' => false);
     //Check session is enable
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0) {
             //Check combat
             if ($combat = Combats::model()->with(array('combatsPrecombat', 'rounds', array('fromKnight' => array('with' => array('knightsCard'))), array('toKnight' => array('with' => 'knightsCard'))))->findByPk($_GET['combat'])) {
                 //Check if user is in combat
                 if ($combat->fromKnight->id == Yii::app()->user->knights_id || $combat->toKnight->id == Yii::app()->user->knights_id) {
                     //Check if combat is enable
                     if ($combat->status == Combats::STATUS_ENABLE) {
                         //Check last round
                         if ($round_data = RoundsData::model()->find('rounds_combats_id = :combats_id AND rounds_number = :rounds_id AND knights_id = :knights_id', array(':combats_id' => $combat->id, ':rounds_id' => count($combat->rounds), ':knights_id' => Yii::app()->user->knights_id))) {
                             //Check time of desqualify
                             $timeLimit = strtotime($round_data->date) + Yii::app()->params['desqualifyTime'];
                             $requestTime = strtotime('now');
                             Yii::trace('[CHARACTER][actionDesqualifyRival] Check limit time of desqualify request (' . $requestTime . ') > $timelimit (' . $timeLimit . ') ');
                             if ($requestTime >= $timeLimit) {
                                 //Finish combat
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FINISH COMBAT  ');
                                 $output['isDesqualified'] = true;
                                 $combat->status = Combats::STATUS_FINISHED;
                                 $combat->result_by = Combats::RESULT_BY_DESQUALIFY;
                                 //Load round and knights
                                 $round = Rounds::model()->find('combats_id=:combats_id AND number=:number', array(':combats_id' => $combat->id, ':number' => count($combat->rounds)));
                                 if (Yii::app()->user->knights_id == $combat->from_knight) {
                                     $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_FROM_KNIGHT_WIN;
                                     $fromKnight =& $this->user_data['knights'];
                                     $toKnight = Knights::model()->findByPk($combat->toKnight->id);
                                 } else {
                                     $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_TO_KNIGHT_WIN;
                                     $fromKnight = Knights::model()->findByPk($combat->fromKnight->id);
                                     $toKnight =& $this->user_data['knights'];
                                 }
                                 /*
                                  * Update round and combat
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update round and combat  ');
                                 if (!$round->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el round');
                                 }
                                 if ($combat->save()) {
                                     //Update combat cache
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['combat'] . $combat->id, $combat, Yii::app()->params['cachetime']['combat']);
                                 } else {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el combate');
                                 }
                                 /*
                                  * Update knights to ready to challenge 
                                  */
                                 $fromKnight->endurance = ($combat->fromKnight->knightsCard->will + $combat->fromKnight->knightsCard->constitution) * 3;
                                 $fromKnight->life = $combat->fromKnight->knightsCard->constitution * 2;
                                 $fromKnight->status = Knights::STATUS_ENABLE;
                                 $toKnight->endurance = ($combat->toKnight->knightsCard->will + $combat->toKnight->knightsCard->constitution) * 3;
                                 $toKnight->life = $combat->toKnight->knightsCard->constitution * 2;
                                 $toKnight->status = Knights::STATUS_ENABLE;
                                 /*
                                  *Calcula postcombat 
                                  */
                                 //Calculate experience
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] CALCULATE EXPERIENCE');
                                 $precombat = $combat->combatsPrecombat;
                                 $postcombatData = CombatsPostcombat::calculateEarnedExperience($combat, $combat->fromKnight->level, $combat->toKnight->level);
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] SAVE POSTCOMBATS');
                                 $from_knight_post_combat = new CombatsPostcombat();
                                 $from_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->fromKnight->id, 'knight_rival_level' => $combat->fromKnight->level, 'experience_generate' => $postcombatData['from_knight_experience_generate'], 'percent_by_result' => $postcombatData['from_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['from_knight_percent_by_injury'], 'earned_experience' => $postcombatData['from_knight_earned_experience'], 'total_experience' => $combat->fromKnight->experiencie_earned + $postcombatData['from_knight_earned_experience'], 'total_coins' => $precombat->from_knight_gate + $combat->fromKnight->coins, 'earned_coins' => $precombat->from_knight_gate, 'injury_type' => null);
                                 if (!$from_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para from knight', 'error');
                                 }
                                 $to_knight_post_combat = new CombatsPostcombat();
                                 $to_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->toKnight->id, 'knight_rival_level' => $combat->toKnight->level, 'experience_generate' => $postcombatData['to_knight_experience_generate'], 'percent_by_result' => $postcombatData['to_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['to_knight_percent_by_injury'], 'earned_experience' => $postcombatData['to_knight_earned_experience'], 'total_experience' => $combat->toKnight->experiencie_earned + $postcombatData['to_knight_earned_experience'], 'total_coins' => $precombat->to_knight_gate + $combat->toKnight->coins, 'earned_coins' => $precombat->to_knight_gate, 'injury_type' => null);
                                 if (!$to_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para to knight', 'error');
                                 }
                                 //Update experience of knights
                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EXPERIECE');
                                 $fromKknight->experiencie_earned = $from_knight_post_combat->total_experience;
                                 $toKnight->experiencie_earned = $to_knight_post_combat->total_experience;
                                 /*
                                  * Calculate repair prize equipment
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival]CALCULATE REPAIR PRIZE');
                                 $from_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->fromKnight);
                                 if ($from_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] FROM KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 $to_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->toKnight);
                                 if ($to_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] TO KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 /*
                                  * Update coins of knights
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE COINS OF KNIGHTS');
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FROM_KNIGHT earned coins: current coinds(' . $combat->fromKnight->coins . ') + gate coins (' . $precombat->from_knight_gate . ') - autorrepair coins (' . $from_knight_autorepair['repair_cost'] . ') ');
                                 $fromKnight->coins += $precombat->from_knight_gate - $from_knight_autorepair['repair_cost'];
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] TO_KNIGHT earned coins: current coinds(' . $toKnight->coins . ') + gate coins (' . $precombat->to_knight_gate . ') - autorrepair coins (' . $to_knight_autorepair['repair_cost'] . ') ');
                                 $toKnight->coins += $precombat->to_knight_gate - $to_knight_autorepair['repair_cost'];
                                 /*
                                  * Update healings of knights
                                  */
                                 if ($combat->fromKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for from knigth');
                                     $healing = Healings::model()->findByPk($combat->fromKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update from knight next healing date', 'error');
                                     }
                                 }
                                 if ($combat->toKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for to knigth');
                                     $healing = Healings::model()->findByPk($combat->toKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update to knight next healing date', 'error');
                                     }
                                 }
                                 /*
                                  * STATS
                                  * Update stats of knights and platform
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update stats');
                                 $from_knight_stats = KnightsStats::model()->findByPk($combat->fromKnight->id);
                                 $to_knight_stats = KnightsStats::model()->findByPk($combat->toKnight->id);
                                 $from_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $fromKnight->id, ':opponent' => $toKnight->id));
                                 $to_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $toKnight->id, ':opponent' => $fromKnight->id));
                                 if (!$from_knight_stats_vs) {
                                     $from_knight_stats_vs = new KnightsStatsVs();
                                     $from_knight_stats_vs->attributes = array('knights_id' => $combat->fromKnight->id, 'opponent' => $combat->toKnight->id, 'money_total_earned' => 0);
                                 }
                                 if (!$to_knight_stats_vs) {
                                     $to_knight_stats_vs = new KnightsStatsVs();
                                     $to_knight_stats_vs->attributes = array('knights_id' => $combat->toKnight->id, 'opponent' => $combat->fromKnight->id, 'money_total_earned' => 0);
                                 }
                                 $from_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $fromKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 $to_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $toKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 if (!$from_knight_stats_by_date) {
                                     $from_knight_stats_by_date = new KnightsStatsByDate();
                                     $from_knight_stats_by_date = array('knights_id' => $combat->fromKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if (!$to_knight_stats_by_date) {
                                     $to_knight_stats_by_date = new KnightsStatsByDate();
                                     $to_knight_stats_by_date = array('knights_id' => $combat->toKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if ($combat->result == Combats::RESULT_FROM_KNIGHT_WIN) {
                                     $from_knight_stats->combats_wins += 1;
                                     $from_knight_stats_vs->combats_wins += 1;
                                     $from_knight_stats_by_date->combats_wins += 1;
                                     $to_knight_stats->combats_loose += 1;
                                     $to_knight_stats_vs->combats_loose += 1;
                                     $to_knight_stats_by_date->combats_loose += 1;
                                 } else {
                                     if ($combat->result == Combats::RESULT_TO_KNIGHT_WIN) {
                                         $to_knight_stats->combats_wins += 1;
                                         $to_knight_stats_vs->combats_wins += 1;
                                         $to_knight_stats_by_date->combats_wins += 1;
                                         $from_knight_stats->combats_loose += 1;
                                         $from_knight_stats_vs->combats_loose += 1;
                                         $from_knight_stats_by_date->combats_loose += 1;
                                     } else {
                                         $to_knight_stats->combats_draw += 1;
                                         $to_knight_stats_vs->combats_draw += 1;
                                         $to_knight_stats_by_date->combats_draw += 1;
                                         $from_knight_stats->combats_draw += 1;
                                         $from_knight_stats_vs->combats_draw += 1;
                                         $from_knight_stats_by_date->combats_draw += 1;
                                     }
                                 }
                                 //stats desquality
                                 if (Yii::app()->user->knights_id == $combat->fromKnight->id) {
                                     $from_knight_stats->desquality_produced += 1;
                                     $to_knight_stats->desquality_received += 1;
                                 } else {
                                     $from_knight_stats->desquality_received += 1;
                                     $to_knight_stats->desquality_produced += 1;
                                 }
                                 //stats money
                                 $from_knight_stats->money_total_earned += $precombat->from_knight_gate;
                                 $to_knight_stats->money_total_earned += $precombat->to_knight_gate;
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE STATS ');
                                 if (!$from_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de from knight', 'error');
                                 }
                                 if (!$from_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de from knight stats', 'error');
                                 }
                                 if (!$from_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística por dia de from knight stats', 'error');
                                 }
                                 if (!$to_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística diarias de to knight', 'error');
                                 }
                                 //UPDATE knights
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update knights ');
                                 if (!$fromKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero from knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight->name, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 if (!$toKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero to knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 //Show desqualify
                                 $desqualifyKnight = Yii::app()->user->knights_id == $combat->fromKnight->id ? $combat->fromKnight->name : $combat->toKnight->name;
                                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_desqualified_by.php', array('desqualifiedKnight' => $desqualifyKnight), true);
                                 $output['errno'] = 0;
                             } else {
                                 $output['html'] = 'Todavía no ha pasado el tiempo para que le puedas descalificar. Faltan ' . ($timeLimit - $requestTime) . ' segundos.';
                             }
                         } else {
                             $output['html'] = 'No puedes descalificar a tu adversario si no has enviado los datos para la última ronda.';
                         }
                     } else {
                         $output['html'] = 'Este combate no está en curso.';
                     }
                 } else {
                     $output['html'] = 'No puedes toquetear combates que no son tuyos.';
                 }
             } else {
                 $output['html'] = 'No se ha encontrado el combate.';
             }
         } else {
             $output['html'] = 'El identificador del combate no es válido.';
         }
     } else {
         $output['html'] = 'La sesión ha expirado. Necesitas volver a hacer login.';
     }
     //Show output
     echo CJSON::encode($output);
 }
 /**
  * Health knights. 
  * Search in healths table all knights with a expired date of healing. Knights recovery 'constitution / 2' points of pain. If pain is greather than 0 then update
  * the next healing date to next hour. If pain is 0 or less then next healing date is set null. 
  * TIME: every minute of all days.
  * identificator 3
  */
 public function actionHealings()
 {
     $controlCronJobId = 3;
     //Search all next healings
     $result = Healings::model()->with(array('knights' => array('knightsCard')))->findAll('next_healing_date IS NOT NULL AND next_healing_date < :date', array(':date' => date('Y:m:d H:i:s')));
     if (count($result) > 0) {
         foreach ($result as $healing) {
             //Calculate new pain
             $healing_points = floor($healing->knights->knightsCard->constitution / 2);
             $healing->knights->pain -= $healing_points > 0 ? $healing_points : 1;
             //All healings recovery one point of pain at least
             //Check next healing
             if ($healing->knights->pain > 0) {
                 $healing->next_healing_date = date("Y-m-d H:i:s", strtotime($healing->next_healing_date . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
             } else {
                 $healing->knights->pain = 0;
                 $healing->next_healing_date = null;
             }
             //Update knights and healings
             if (!$healing->knights->save()) {
                 Yii::trace('[CRONJOB][actionHealings] No se puede actualizar el caballero.', 'error');
             }
             if (!$healing->save()) {
                 Yii::trace('[CRONJOB][actionHealings] No se puede actualizar la curación.', 'error');
             }
         }
     }
 }