/**
  * Set combats points
  */
 public function actionSetCombatPoints()
 {
     Yii::trace('[CHARACTER][actionSetCombatPoints] Start');
     $output = array('errno' => 1, 'html' => '', 'isFinishedRound' => false, 'isCombatFinished' => false, 'round_id' => null);
     //Check session is enable
     if (!Yii::app()->user->isGuest) {
         //Check if user is in his page
         if (Yii::app()->user->knights_id == $this->knight->id) {
             //Check if input is valid
             if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0 && isset($_GET['attack_position']) && is_numeric($_GET['attack_position']) && $_GET['attack_position'] > 0 && isset($_GET['defense_position']) && is_numeric($_GET['defense_position']) && $_GET['defense_position'] > 0) {
                 //Check if combat exist
                 $combat = Combats::model()->with('rounds')->findByPk($_GET['combat']);
                 if ($combat) {
                     //Check status of combat
                     if ($combat->status == Combats::STATUS_ENABLE) {
                         //Check if user is in combat
                         if (Yii::app()->user->knights_id == $combat->from_knight || Yii::app()->user->knights_id == $combat->to_knight) {
                             //Check if last round is pending
                             $output['round_id'] = count($combat->rounds);
                             if ($combat->rounds[$output['round_id'] - 1]->status == Rounds::STATUS_PENDING) {
                                 //Check if user has data for this round
                                 $roundData = RoundsData::model()->find('rounds_combats_id=:rounds_combats_id AND rounds_number=:rounds_number AND knights_id=:knights_id', array(':rounds_combats_id' => $combat->id, ':rounds_number' => $combat->rounds[count($combat->rounds) - 1]->number, ':knights_id' => Yii::app()->user->knights_id));
                                 if (!$roundData) {
                                     //Check if rival set attack and defense
                                     if ($combat->from_knight == Yii::app()->user->knights_id) {
                                         $rival_id = $combat->to_knight;
                                     } else {
                                         $rival_id = $combat->from_knight;
                                     }
                                     $roundDataRival = RoundsData::model()->find('rounds_combats_id=:rounds_combats_id AND rounds_number=:rounds_number AND knights_id=:knights_id', array(':rounds_combats_id' => $combat->id, ':rounds_number' => $combat->rounds[count($combat->rounds) - 1]->number, ':knights_id' => $rival_id));
                                     //Load knight card
                                     $knights_card = $this->knight->knightsCard;
                                     /*
                                      * LOAD EQUIPMENT IN USE (spear, shield and armour) for this knight user
                                      */
                                     if ($roundDataRival) {
                                         //Load spear, shield and armour. We have armour position of impact
                                         $from_knight_received_impact_inventory_position = Inventory::getPositionFromAttackPosition($roundDataRival->attack_point);
                                         Yii::trace('[CHARACTER][actionSetCombatPoints] Load equipment in use with attack position (' . $roundDataRival->attack_point . ') and position in inventory (' . $from_knight_received_impact_inventory_position . ')');
                                         $user_knight_equipment = Inventory::getCurrentEquipment4Round(Yii::app()->user->knights_id, $from_knight_received_impact_inventory_position);
                                     } else {
                                         //Load only spear and shield.
                                         $from_knight_received_impact_inventory_position = null;
                                         Yii::trace('[CHARACTER][actionSetCombatPoints] Load equipment in use without attack position.');
                                         $user_knight_equipment = Inventory::getCurrentEquipment4Round(Yii::app()->user->knights_id);
                                     }
                                     //Check if user has all equipment
                                     if ($user_knight_equipment['spear_object'] != null && $user_knight_equipment['shield_object'] != null && (!$roundDataRival || $roundDataRival && $user_knight_equipment['armour_object'] != null)) {
                                         //Insert round data for user
                                         srand();
                                         $roundData = new RoundsData();
                                         $roundData->attributes = array('rounds_combats_id' => $combat->id, 'rounds_number' => count($combat->rounds), 'knights_id' => Yii::app()->user->knights_id, 'date' => date('Y-m-d H:i:s'), 'knights_endurance' => $this->knight->endurance, 'knights_life' => $this->knight->life, 'knights_pain' => $this->knight->pain, 'attack_point' => $_GET['attack_position'], 'defense_point' => $_GET['defense_position'], 'pain_throw' => $this->knight->pain ? rand(1, 10) : null, 'knights_will' => $knights_card->will, 'knights_concentration' => $knights_card->concentration, 'knights_skill' => $knights_card->skill, 'knights_dexterity' => $knights_card->dexterity, 'knights_spear' => $knights_card->spear, 'knights_shield' => $knights_card->shield, 'knights_constitution' => $knights_card->constitution, 'armour_id' => $user_knight_equipment['armour'] != null ? $user_knight_equipment['armour']->id : null, 'armour_object_pde_initial' => $user_knight_equipment['armour_object'] != null ? $user_knight_equipment['armour_object']->current_pde : null, 'shield_id' => $user_knight_equipment['shield']->id, 'shield_object_pde_initial' => $user_knight_equipment['shield_object']->current_pde, 'spears_id' => $user_knight_equipment['spear']->id, 'spears_object_pde_initial' => $user_knight_equipment['spear_object']->current_pde, 'attack_throw' => rand(1, 10), 'defense_throw' => rand(1, 10));
                                         /*
                                          * STATS ATTACK AND DEFENSE POINTS
                                          */
                                         $sql = "UPDATE knights_stats_attack_location\n\t\t\t\t\t\t\t\t\t\t\t\t\tSET amount = amount +1\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE knights_id = :knights_id1 AND location = :location1;";
                                         $command = Yii::app()->db->createCommand($sql);
                                         $command->bindValue(':knights_id1', Yii::app()->user->knights_id);
                                         $command->bindValue(':location1', $_GET['attack_position']);
                                         if ($command->execute() == 0) {
                                             Yii::trace('[CHARACTER][actionSetCombatPoints] No se ha podido actualizar las estadisticas de el punto de ataque', 'error');
                                         }
                                         $command->text = "INSERT INTO knights_stats_defense_location (knights_id, location, armours_type, amount)\n\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES ( :knights_id2, :location2, :armours_type2, 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\tON DUPLICATE KEY UPDATE amount = amount + 1;";
                                         $command->bindValue(':knights_id2', Yii::app()->user->knights_id);
                                         $command->bindValue(':location2', $_GET['defense_position']);
                                         $command->bindValue(':armours_type2', $user_knight_equipment['shield']->type);
                                         if ($command->execute() == 0) {
                                             Yii::trace('[CHARACTER][actionSetCombatPoints] No se ha podido actualizar las estadisticas de el punto de defensa', 'error');
                                         }
                                         /*
                                          $knight_statsAttackLocation = KnightsStatsAttackLocation::model()->find( 'knights_id = :knights_id AND location = :location', array(':knights_id'=>Yii::app()->user->knights_id, ':location'=>$_GET['attack_position'] ) );
                                         $knight_statsAttackLocation->amount += 1;
                                         if( !$knight_statsAttackLocation->save() ) Yii::trace( '[CHARACTER][actionSetCombatPoints] Las estadisticas de locaclizacion de punto de ataque no se ha podido salvar', 'error' );
                                         unset( $knight_statsAttackLocation );
                                         	
                                         $knight_statsDefenseLocation = KnightsStatsDefenseLocation::model()->find( 'knights_id = :knights_id AND location = :location', array(':knights_id'=>Yii::app()->user->knights_id, ':location'=>$_GET['attack_position'] ) );
                                         if( ! $knight_statsDefenseLocation ){
                                         $knight_statsDefenseLocation = new KnightsStatsDefenseLocation();
                                         $knight_statsDefenseLocation = 0;
                                         $knight_statsDefenseLocation->armours_type = $user_knight_equipment['shield']->type;
                                         }
                                         $knight_statsDefenseLocation->amount += 1;
                                         if( !$knight_statsDefenseLocation->save() ) Yii::trace( '[CHARACTER][actionSetCombatPoints] Las estadisticas de locaclizacion de punto de defensa no se ha podido salvar', 'error' );
                                         unset( $knight_statsDefenseLocation );
                                         */
                                         //Resolve combat if all data is insert
                                         if ($roundDataRival) {
                                             Yii::trace('[CHARACTER][actionSetCombatPoints] RESOLVIENDO COMBATE');
                                             $roundData->received_impact_inventory_position = $from_knight_received_impact_inventory_position;
                                             //Load inventory attack position
                                             $roundDataRival->received_impact_inventory_position = Inventory::getPositionFromAttackPosition($roundData->attack_point);
                                             /*
                                              * LOAD EQUIPMENT IN USE (spear, shield and armour) for this knight user
                                              */
                                             $rival_knight_equipment = Inventory::getCurrentEquipment4Round($roundDataRival->knights_id, $roundDataRival->received_impact_inventory_position);
                                             //Load de armour by the attack point of user
                                             //$inventoryRival = Inventory::model()->find( 'knights_id=:knights_id AND position=:position', array( ':knights_id'=>$roundDataRival->knights_id,':position'=>$roundDataRival->received_impact_inventory_position ) );
                                             //echo "idetificaor:".$inventoryRival->identificator;
                                             //$armour_rival = ArmoursObjects::model()->findByPk( $inventoryRival->identificator );
                                             $roundDataRival->armour_id = $rival_knight_equipment['armour_object']->armours_id;
                                             $roundDataRival->armour_object_pde_initial = $rival_knight_equipment['armour_object']->current_pde;
                                             /*
                                              * Save data rival knight and resolve round
                                              */
                                             if ($roundDataRival->save()) {
                                                 //Check who is the from_knight and to_knight
                                                 if ($combat->from_knight == Yii::app()->user->knights_id) {
                                                     $from_knight = $this->knight;
                                                     //Knight object
                                                     $from_knight_card =& $knights_card;
                                                     //Knights_card object
                                                     $from_knight_round_data =& $roundData;
                                                     //Round data
                                                     $from_knight_equipment =& $user_knight_equipment;
                                                     //Equipment
                                                     $to_knight = Knights::model()->with('knightsCard')->findByPk($combat->to_knight);
                                                     $to_knight_card = $to_knight->knightsCard;
                                                     $to_knight_round_data =& $roundDataRival;
                                                     $to_knight_equipment =& $rival_knight_equipment;
                                                 } else {
                                                     $from_knight = Knights::model()->with('knightsCard')->findByPk($combat->from_knight);
                                                     $from_knight_card = $from_knight->knightsCard;
                                                     $from_knight_round_data =& $roundDataRival;
                                                     $from_knight_equipment =& $rival_knight_equipment;
                                                     $to_knight =& $this->knight;
                                                     $to_knight_card =& $knights_card;
                                                     $to_knight_round_data =& $roundData;
                                                     $to_knight_equipment =& $user_knight_equipment;
                                                 }
                                                 /*
                                                  * RESOLVE ROUND
                                                  */
                                                 $output['isFinishedRound'] = true;
                                                 //Init default status rounds
                                                 $from_knight_round_data->status = RoundsData::STATUS_RESISTED;
                                                 $to_knight_round_data->status = RoundsData::STATUS_RESISTED;
                                                 //Check pain value.
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] CHECKEANDO TIRADAS DE DOLOR');
                                                 $from_knight_pain = $from_knight_round_data->knights_pain;
                                                 if ($from_knight_pain > 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] Tirada dolor from knight: voluntad(' . $from_knight_round_data->knights_will . ')+concentracion(' . $from_knight_round_data->knights_concentration . ')+tirada(' . $from_knight_round_data->pain_throw . ') > 18');
                                                     if ($from_knight_round_data->knights_will + $from_knight_round_data->knights_concentration + $from_knight_round_data->pain_throw > 18) {
                                                         $from_knight_round_data->is_pain_throw_pass = 1;
                                                         $from_knight_pain = 0;
                                                     } else {
                                                         $from_knight_round_data->is_pain_throw_pass = 0;
                                                     }
                                                 }
                                                 $to_knight_pain = $to_knight_round_data->knights_pain;
                                                 if ($to_knight_pain > 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] Tirada dolor to knight: voluntad(' . $to_knight_round_data->knights_will . ')+concentracion(' . $to_knight_round_data->knights_concentration . ')+tirada(' . $to_knight_round_data->pain_throw . ') > 18');
                                                     if ($to_knight_round_data->knights_will + $to_knight_round_data->knights_concentration + $to_knight_round_data->pain_throw > 18) {
                                                         $to_knight_round_data->is_pain_throw_pass = 1;
                                                         $to_knight_pain = 0;
                                                     } else {
                                                         $to_knight_round_data->is_pain_throw_pass = 0;
                                                     }
                                                 }
                                                 //Calculate if impact is defended and add shield endurance
                                                 Yii::trace('[actionSetCombatPoints] CRUZANDO ATAQUE Y DEFENSAS');
                                                 $from_knight_shield_endurance = 0;
                                                 $to_knight_shield_endurance = 0;
                                                 if (Rounds::isImpactDefended($to_knight_round_data->attack_point, $from_knight_round_data->defense_point, Armours::getWidthShield($from_knight_equipment['shield']->type), Armours::getHeightShield($from_knight_equipment['shield']->type))) {
                                                     Yii::trace('[actionSetCombatPoints] from knight defiende el impacto');
                                                     $from_knight_shield_endurance = $from_knight_equipment['shield']->endurance;
                                                     $from_knight_round_data->is_received_impact_defended = 1;
                                                 }
                                                 if (Rounds::isImpactDefended($from_knight_round_data->attack_point, $to_knight_round_data->defense_point, Armours::getWidthShield($to_knight_equipment['shield']->type), Armours::getHeightShield($to_knight_equipment['shield']->type))) {
                                                     Yii::trace('[actionSetCombatPoints] to knight defiende el impacto');
                                                     $to_knight_shield_endurance = $to_knight_equipment['shield']->endurance;
                                                     $to_knight_round_data->is_received_impact_defended = 1;
                                                 }
                                                 /*
                                                  * CALCULATE DAMAGE
                                                  */
                                                 Yii::trace('[actionSetCombatPoints] CALCULO DE DAÑO');
                                                 $from_knight_damage = Rounds::calculateDamage($to_knight_round_data, $from_knight_round_data, $to_knight_equipment['spear']->damage, $to_knight_pain, $from_knight_equipment['armour']->endurance, $from_knight_shield_endurance, $from_knight_pain);
                                                 $from_knight_round_data->received_damage = $from_knight_damage['received_damage'];
                                                 $from_knight_round_data->defended_damage = $from_knight_damage['defended_damage'];
                                                 $from_knight_total_damage = $from_knight_round_data->received_damage - $from_knight_round_data->defended_damage < 0 ? 0 : $from_knight_round_data->received_damage - $from_knight_round_data->defended_damage;
                                                 Yii::trace('[actionSetCombatPoints] from knight daño recibido (' . $from_knight_round_data->received_damage . ') daño defendido (' . $from_knight_round_data->defended_damage . ')');
                                                 $to_knight_damage = Rounds::calculateDamage($from_knight_round_data, $to_knight_round_data, $from_knight_equipment['spear']->damage, $from_knight_pain, $to_knight_equipment['armour']->endurance, $to_knight_shield_endurance, $to_knight_pain);
                                                 $to_knight_round_data->received_damage = $to_knight_damage['received_damage'];
                                                 $to_knight_round_data->defended_damage = $to_knight_damage['defended_damage'];
                                                 $to_knight_total_damage = $to_knight_round_data->received_damage - $to_knight_round_data->defended_damage < 0 ? 0 : $to_knight_round_data->received_damage - $to_knight_round_data->defended_damage;
                                                 Yii::trace('[actionSetCombatPoints] to knight daño recibido (' . $to_knight_round_data->received_damage . ') daño defendido (' . $to_knight_round_data->defended_damage . ')');
                                                 /*
                                                  * UPDATE PDE OF OBJECTS AND CALCULATE EXTRA DAMAGE
                                                  */
                                                 $from_knight_round_data->pde_shield_loosed = 0;
                                                 $from_knight_round_data->pde_armour_loosed = 0;
                                                 Yii::trace('[actionSetCombatPoints] CALCULANDO PDEs Y DAÑO EXTRA)');
                                                 if ($from_knight_total_damage > 0) {
                                                     //Check if impact is defend
                                                     if ($from_knight_round_data->is_received_impact_defended) {
                                                         //Check if shield can to get all damage
                                                         if ($from_knight_round_data->shield_object_pde_initial - $from_knight_total_damage >= 0) {
                                                             //shield received all damage
                                                             $from_knight_round_data->pde_shield_loosed = $from_knight_total_damage;
                                                             $from_knight_equipment['shield_object']->current_pde -= $from_knight_total_damage;
                                                             //Check if shield is destroy
                                                             if ($from_knight_equipment['shield_object']->current_pde == 0) {
                                                                 $from_knight_round_data->is_shield_destroyed = true;
                                                             }
                                                         } else {
                                                             //Shield is destroyed and armour is damage too
                                                             $from_knight_round_data->is_shield_destroyed = 1;
                                                             $from_knight_round_data->pde_shield_loosed = $from_knight_round_data->shield_object_pde_initial;
                                                             $from_knight_equipment['shield_object']->current_pde = 0;
                                                             $from_knight_round_data->pde_armour_loosed = $from_knight_total_damage - $from_knight_round_data->pde_shield_loosed;
                                                             //Check if Armour is destroyed and knight gets an extra damage
                                                             if ($from_knight_round_data->pde_armour_loosed >= $from_knight_round_data->armour_object_pde_initial) {
                                                                 $from_knight_round_data->pde_armour_loosed = $from_knight_round_data->armour_object_pde_initial;
                                                                 $from_knight_round_data->is_armour_destroyed = 1;
                                                                 $from_knight_equipment['armour_object']->pde = 0;
                                                                 //check if there is extra damage
                                                                 if ($from_knight_total_damage > $from_knight_round_data->pde_shield_loosed + $from_knight_round_data->pde_armour_loosed) {
                                                                     $from_knight_round_data->extra_damage = $from_knight_total_damage - $from_knight_round_data->pde_shield_loosed - $from_knight_round_data->pde_armour_loosed;
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         //Check if armour can to get all damage
                                                         if ($from_knight_total_damage >= $from_knight_round_data->armour_object_pde_initial) {
                                                             //Armour crash and knight gets extra damage
                                                             $from_knight_round_data->pde_armour_loosed = $from_knight_round_data->armour_object_pde_initial;
                                                             $from_knight_round_data->is_armour_destroyed = 1;
                                                             $from_knight_equipment['armour_object']->current_pde = 0;
                                                             //calculate extra damage
                                                             $from_knight_round_data->extra_damage = $from_knight_total_damage - $from_knight_round_data->pde_armour_loosed;
                                                         } else {
                                                             //armour receive all damage
                                                             $from_knight_round_data->pde_armour_loosed = $from_knight_total_damage;
                                                             $from_knight_equipment['armour_object']->current_pde -= $from_knight_total_damage;
                                                         }
                                                     }
                                                 }
                                                 $to_knight_round_data->pde_shield_loosed = 0;
                                                 $to_knight_round_data->pde_armour_loosed = 0;
                                                 if ($to_knight_total_damage > 0) {
                                                     //Check if impact is defended
                                                     if ($to_knight_round_data->is_received_impact_defended) {
                                                         //Check if shield can to get all damage
                                                         if ($to_knight_round_data->shield_object_pde_initial >= $to_knight_total_damage) {
                                                             //shield received all damage
                                                             $to_knight_round_data->pde_shield_loosed = $to_knight_total_damage;
                                                             $to_knight_equipment['shield_object']->current_pde -= $to_knight_total_damage;
                                                             //Check if shield is destroy
                                                             if ($to_knight_equipment['shield_object']->current_pde == 0) {
                                                                 $to_knight_round_data->is_shield_destroyed = true;
                                                             }
                                                         } else {
                                                             //Shield is destroyed and armour is damage too
                                                             $to_knight_round_data->is_shield_destroyed = 1;
                                                             $to_knight_round_data->pde_shield_loosed = $to_knight_round_data->shield_object_pde_initial;
                                                             $to_knight_equipment['shield_object']->current_pde = 0;
                                                             $to_knight_round_data->pde_armour_loosed = $to_knight_total_damage - $to_knight_round_data->pde_shield_loosed;
                                                             //Check if Armour is destroyed and knight gets an extra damage
                                                             if ($to_knight_round_data->pde_armour_loosed >= $to_knight_round_data->armour_object_pde_initial) {
                                                                 $to_knight_round_data->pde_armour_loosed = $to_knight_round_data->armour_object_pde_initial;
                                                                 $to_knight_round_data->is_armour_destroyed = 1;
                                                                 $to_knight_equipment['armour_object']->current_pde = 0;
                                                                 //check if there is extra damage
                                                                 if ($to_knight_total_damage > $to_knight_round_data->pde_shield_loosed + $to_knight_round_data->pde_armour_loosed) {
                                                                     $to_knight_round_data->extra_damage = $to_knight_total_damage - $to_knight_round_data->pde_shield_loosed - $to_knight_round_data->pde_armour_loosed;
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         //Check if armour get all damage
                                                         if ($to_knight_total_damage >= $to_knight_round_data->armour_object_pde_initial) {
                                                             //Armour crash and knight gets extra damage
                                                             $to_knight_round_data->pde_armour_loosed = $to_knight_round_data->armour_object_pde_initial;
                                                             $to_knight_round_data->is_armour_destroyed = 1;
                                                             $to_knight_equipment['armour_object']->current_pde = 0;
                                                             //calculate extra damage
                                                             $to_knight_round_data->extra_damage = $to_knight_total_damage - $to_knight_round_data->pde_armour_loosed;
                                                         } else {
                                                             //armour received all damage
                                                             $to_knight_round_data->pde_armour_loosed = $to_knight_total_damage;
                                                             $to_knight_equipment['armour_object']->current_pde -= $to_knight_round_data->pde_armour_loosed;
                                                         }
                                                     }
                                                 }
                                                 //calculate pde of spear
                                                 $pde_damage_spear = $from_knight_equipment['spear']->damage <= $to_knight_total_damage ? 0 : $from_knight_equipment['spear']->damage - $to_knight_total_damage;
                                                 if ($from_knight_round_data->spears_object_pde_initial - $pde_damage_spear > 0) {
                                                     //Spear is not destroyed
                                                     $from_knight_round_data->pde_spear_loosed = $pde_damage_spear;
                                                     $from_knight_round_data->spears_object_pde_final = $from_knight_equipment['spear_object']->current_pde - $pde_damage_spear;
                                                     $from_knight_equipment['spear_object']->current_pde = $from_knight_round_data->spears_object_pde_final;
                                                 } else {
                                                     //Spears is broken!
                                                     $from_knight_round_data->pde_spear_loosed = $from_knight_round_data->spears_object_pde_initial;
                                                     $from_knight_round_data->spears_object_pde_final = 0;
                                                     $from_knight_round_data->is_spear_destroyed = 1;
                                                     $from_knight_equipment['spear_object']->current_pde = 0;
                                                 }
                                                 $pde_damage_spear = $to_knight_equipment['spear']->damage <= $from_knight_total_damage ? 0 : $to_knight_equipment['spear']->damage - $from_knight_total_damage;
                                                 if ($to_knight_round_data->spears_object_pde_initial - $pde_damage_spear > 0) {
                                                     //Spear is not destroyed
                                                     $to_knight_round_data->pde_spear_loosed = $pde_damage_spear;
                                                     $to_knight_round_data->spears_object_pde_final = $to_knight_equipment['spear_object']->current_pde - $pde_damage_spear;
                                                     $to_knight_equipment['spear_object']->current_pde = $to_knight_round_data->spears_object_pde_final;
                                                 } else {
                                                     //Spears is broken!
                                                     $to_knight_round_data->pde_spear_loosed = $to_knight_round_data->spears_object_pde_initial;
                                                     $to_knight_round_data->spears_object_pde_final = 0;
                                                     $to_knight_round_data->is_spear_destroyed = 1;
                                                     $to_knight_equipment['spear_object']->current_pde = 0;
                                                 }
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] from knight pde perdidos escudo (' . $from_knight_round_data->pde_shield_loosed . '), armadura(' . $from_knight_round_data->pde_armour_loosed . '), lanza (' . $from_knight_round_data->pde_spear_loosed . '), daño extra (' . $from_knight_round_data->extra_damage . ') ');
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] to knight pde perdidos escudo (' . $to_knight_round_data->pde_shield_loosed . '), armadura(' . $to_knight_round_data->pde_armour_loosed . '), lanza (' . $to_knight_round_data->pde_spear_loosed . '), daño extra (' . $to_knight_round_data->extra_damage . ') ');
                                                 //Update pde equipment
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EQUIPMENT');
                                                 $from_knight_round_data->armour_object_pde_final = $from_knight_equipment['armour_object']->current_pde;
                                                 $from_knight_round_data->shield_object_pde_final = $from_knight_equipment['shield_object']->current_pde;
                                                 $from_knight_round_data->spears_object_pde_final = $from_knight_equipment['spear_object']->current_pde;
                                                 $to_knight_round_data->armour_object_pde_final = $to_knight_equipment['armour_object']->current_pde;
                                                 $to_knight_round_data->shield_object_pde_final = $to_knight_equipment['shield_object']->current_pde;
                                                 $to_knight_round_data->spears_object_pde_final = $to_knight_equipment['spear_object']->current_pde;
                                                 //Calculate new endurance of knights
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE ENDURANCE OF KNIGHTS');
                                                 $from_knight->endurance = $from_knight_round_data->knights_endurance - $from_knight_total_damage - $from_knight_round_data->extra_damage;
                                                 $to_knight->endurance = $to_knight_round_data->knights_endurance - $to_knight_total_damage - $to_knight_round_data->extra_damage;
                                                 //Calcula if knight fall. Fall is produced if pass one o more limits.
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] CHECK IF KNIGHTS  FALL');
                                                 if ($from_knight_round_data->is_falled = Rounds::checkFall(($from_knight_round_data->knights_will + $from_knight_round_data->knights_constitution) * 3, $from_knight_round_data->knights_endurance, $from_knight->endurance)) {
                                                     $from_knight_round_data->status = RoundsData::STATUS_KNOCK_DOWN;
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] from knight fall');
                                                 }
                                                 if ($to_knight_round_data->is_falled = Rounds::checkFall(($to_knight_round_data->knights_will + $to_knight_round_data->knights_constitution) * 3, $to_knight_round_data->knights_endurance, $to_knight->endurance)) {
                                                     $to_knight_round_data->status = RoundsData::STATUS_KNOCK_DOWN;
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] to knight fall');
                                                 }
                                                 //Check if knights are knock out
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] CHECK IF KNIGHTS ARE KNOCK OUT');
                                                 if ($from_knight->endurance == 0) {
                                                     $from_knight_round_data->is_falled = 1;
                                                     $from_knight_round_data->status = RoundsData::STATUS_KNOCK_OUT;
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] from knight is knock out');
                                                 }
                                                 if ($to_knight->endurance == 0) {
                                                     $to_knight_round_data->is_falled = 1;
                                                     $to_knight_round_data->status = RoundsData::STATUS_KNOCK_OUT;
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] to knight is knock out');
                                                 }
                                                 //Check injuries
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] CHECK INJURIES');
                                                 if ($from_knight->endurance < 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] from knight is injuried');
                                                     //Fall is obligatory
                                                     $from_knight_round_data->is_falled = 1;
                                                     //Load pain from new injury
                                                     $from_knight_round_data->injury_type = Rounds::getInjuryType($from_knight->life, $from_knight_total_damage - $from_knight_round_data->knights_endurance);
                                                     $from_knight_round_data->status = RoundsData::STATUS_INJURIED;
                                                     $from_knight->pain = Rounds::getPainByInjuryType($from_knight_round_data->injury_type);
                                                 }
                                                 if ($to_knight->endurance < 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] to knight is injuried');
                                                     //Fall is obligatory
                                                     $to_knight_round_data->is_falled = 1;
                                                     //Load pain from new injury
                                                     $to_knight_round_data->injury_type = Rounds::getInjuryType($to_knight->life, $to_knight_total_damage - $to_knight_round_data->knights_endurance);
                                                     $to_knight_round_data->status = RoundsData::STATUS_INJURIED;
                                                     $to_knight->pain = Rounds::getPainByInjuryType($to_knight_round_data->injury_type);
                                                 }
                                                 //Check final status of this round
                                                 $round = Rounds::model()->find('combats_id = :combats_id AND number = :number', array(':combats_id' => $combat->id, ':number' => count($combat->rounds)));
                                                 if ($from_knight_round_data->is_falled == $to_knight_round_data->is_falled) {
                                                     //Both are falled or not
                                                     $round->status = Rounds::STATUS_DRAW;
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FINAL STATUS ROUND: DRAW');
                                                 } else {
                                                     //One is falled and other is standing
                                                     if ($from_knight_round_data->is_falled) {
                                                         $round->status = Rounds::STATUS_TO_KNIGHT_WIN;
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] FINAL STATUS ROUND: TO KNIGHT WIN');
                                                     } else {
                                                         $round->status = Rounds::STATUS_FROM_KNIGHT_WIN;
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] FINAL STATUS ROUND: FROM KNGHT WIN');
                                                     }
                                                 }
                                                 /*
                                                  * UPDATE ROUND
                                                  */
                                                 //Update equipment
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EQUIPMENT');
                                                 Inventory::updateOrDeleteEquipment($from_knight_equipment['armour_object']);
                                                 Inventory::updateOrDeleteEquipment($from_knight_equipment['shield_object']);
                                                 Inventory::updateOrDeleteEquipment($from_knight_equipment['spear_object']);
                                                 Inventory::updateOrDeleteEquipment($to_knight_equipment['armour_object']);
                                                 Inventory::updateOrDeleteEquipment($to_knight_equipment['shield_object']);
                                                 Inventory::updateOrDeleteEquipment($to_knight_equipment['spear_object']);
                                                 //Update round_data
                                                 if (!$from_knight_round_data->save()) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] ERROR TO SAVE FROM KNIGHT ROUND DATA', 'error');
                                                 }
                                                 if (!$to_knight_round_data->save()) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] ERROR TO SAVE TO KNIGHT ROUND DATA', 'error');
                                                 }
                                                 //Round
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE ROUND');
                                                 if (!$round->save()) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] ERROR TO UPDATE ROUND', 'warning');
                                                 }
                                                 /*
                                                  * STATS
                                                  */
                                                 $from_knight_stats = KnightsStats::model()->findByPk($from_knight->id);
                                                 $to_knight_stats = KnightsStats::model()->findByPk($to_knight->id);
                                                 $from_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $from_knight->id, ':opponent' => $to_knight->id));
                                                 $to_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $to_knight->id, ':opponent' => $from_knight->id));
                                                 $from_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $from_knight->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' => $to_knight->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'));
                                                 }
                                                 //Update stats
                                                 $from_knight_stats->hits_total_produced += 1;
                                                 $from_knight_stats_vs->hits_total_produced += 1;
                                                 $from_knight_stats_by_date->hits_total_produced += 1;
                                                 $to_knight_stats->hits_total_produced += 1;
                                                 $to_knight_stats_vs->hits_total_produced += 1;
                                                 $to_knight_stats_by_date->hits_total_produced += 1;
                                                 $from_knight_stats->hits_total_received += 1;
                                                 $from_knight_stats_vs->hits_total_received += 1;
                                                 $from_knight_stats_by_date->hits_total_received += 1;
                                                 $to_knight_stats->hits_total_received += 1;
                                                 $to_knight_stats_vs->hits_total_received += 1;
                                                 $to_knight_stats_by_date->hits_total_received += 1;
                                                 $from_knight_stats->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 $from_knight_stats_vs->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 $from_knight_stats_by_date->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 $to_knight_stats->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $to_knight_stats_vs->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $to_knight_stats_by_date->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $from_knight_stats->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $from_knight_stats_vs->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $from_knight_stats_by_date->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;
                                                 //sum 0 or 1
                                                 $to_knight_stats->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 $to_knight_stats_vs->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 $to_knight_stats_by_date->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                 if ($to_knight_total_damage > 0) {
                                                     $from_knight_stats->damage_total_produced += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                     $from_knight_stats_vs->damage_total_produced += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                     $from_knight_stats_by_date->damage_total_produced += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                     $to_knight_stats->damage_total_received += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                     $to_knight_stats_vs->damage_total_received += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                     $to_knight_stats_by_date->damage_total_received += $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage > 0) {
                                                     $to_knight_stats->damage_total_produced += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                     $to_knight_stats_vs->damage_total_produced += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                     $to_knight_stats_by_date->damage_total_produced += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                     $from_knight_stats->damage_total_received += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                     $from_knight_stats_vs->damage_total_received += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                     $from_knight_stats_by_date->damage_total_received += $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $from_knight_stats->damage_maximum_produced) {
                                                     $from_knight_stats->damage_maximum_produced = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $from_knight_stats_vs->damage_maximum_produced) {
                                                     $from_knight_stats_vs->damage_maximum_produced = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $from_knight_stats_by_date->damage_maximum_produced) {
                                                     $from_knight_stats_by_date->damage_maximum_produced = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $to_knight_stats->damage_maximum_produced) {
                                                     $to_knight_stats->damage_maximum_produced = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $to_knight_stats_vs->damage_maximum_produced) {
                                                     $to_knight_stats_vs->damage_maximum_produced = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $to_knight_stats_by_date->damage_maximum_produced) {
                                                     $to_knight_stats_by_date->damage_maximum_produced = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $from_knight_stats->damage_maximum_received) {
                                                     $from_knight_stats->damage_maximum_received = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $from_knight_stats_vs->damage_maximum_received) {
                                                     $from_knight_stats_vs->damage_maximum_received = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($from_knight_total_damage + $from_knight_round_data->extra_damage > $from_knight_stats_by_date->damage_maximum_received) {
                                                     $from_knight_stats_by_date->damage_maximum_received = $from_knight_total_damage + $from_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $to_knight_stats->damage_maximum_received) {
                                                     $to_knight_stats->damage_maximum_received = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $to_knight_stats_vs->damage_maximum_received) {
                                                     $to_knight_stats_vs->damage_maximum_received = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 if ($to_knight_total_damage + $to_knight_round_data->extra_damage > $to_knight_stats_by_date->damage_maximum_received) {
                                                     $to_knight_stats_by_date->damage_maximum_received = $to_knight_total_damage + $to_knight_round_data->extra_damage;
                                                 }
                                                 /*
                                                  * CHECK IF COMBAT IS FINISHED
                                                  * A combat is finished when knights is knock down 3 times, injuried or KO (endurance is 0 but not injuried)
                                                  */
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] CHECK IF COMBAT IS FINISHED');
                                                 //First, check if some knight is injuried
                                                 if ($from_knight_round_data->status == RoundsData::STATUS_INJURIED || $to_knight_round_data->status == RoundsData::STATUS_INJURIED) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FINISH BY INJURIED');
                                                     //Combat is finished
                                                     $combat->status = Combats::STATUS_FINISHED;
                                                     //Combat result is by injury
                                                     $combat->result_by = Combats::RESULT_BY_INJURY;
                                                     if ($from_knight_round_data->status == $to_knight_round_data->status) {
                                                         //Both knights are injuried
                                                         $combat->result = Combats::RESULT_DRAW;
                                                         $combat->from_knight_injury_type = $from_knight_round_data->injury_type;
                                                         $combat->to_knight_injury_type = $to_knight_round_data->injury_type;
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] draw combat by injury');
                                                     } else {
                                                         //Check who is injuried knight
                                                         if ($from_knight_round_data->status == RoundsData::STATUS_INJURIED) {
                                                             //Win to_knight
                                                             $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                                             $combat->from_knight_injury_type = $from_knight_round_data->injury_type;
                                                             Yii::trace('[CHARACTER][actionSetCombatPoints] to knight win combat by injury');
                                                         } else {
                                                             //Win from_knight
                                                             $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                                             $combat->to_knight_injury_type = $to_knight_round_data->injury_type;
                                                             Yii::trace('[CHARACTER][actionSetCombatPoints] from knight win combat by injury');
                                                         }
                                                     }
                                                     //Check if combat is finished by 3 fall
                                                 } elseif (count($combat->rounds) > 2 && ($from_knight_round_data->is_falled || $to_knight_round_data->is_falled)) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FINISH BY 3 FALL');
                                                     //Check how many fall have knights
                                                     $from_knight_total_fall = $to_knight_total_fall = 0;
                                                     if ($from_knight_round_data->is_falled) {
                                                         $from_knight_total_fall++;
                                                     }
                                                     //Add last fall
                                                     if ($to_knight_round_data->is_falled) {
                                                         $to_knight_total_fall++;
                                                     }
                                                     //Add last fall
                                                     foreach ($combat->rounds as $round) {
                                                         switch ($round->status) {
                                                             case Rounds::STATUS_FROM_KNIGHT_WIN:
                                                                 $to_knight_total_fall++;
                                                                 break;
                                                             case Rounds::STATUS_TO_KNIGHT_WIN:
                                                                 $from_knight_total_fall++;
                                                                 break;
                                                             default:
                                                                 //Nothing to do here
                                                         }
                                                     }
                                                     //Check total combats
                                                     if ($from_knight_total_fall == 3 || $to_knight_total_fall == 3) {
                                                         //Combat is finished by three fall
                                                         $combat->status = Combats::STATUS_FINISHED;
                                                         $combat->result_by = Combats::RESULT_BY_THREE_FALL;
                                                         //Check result of combat
                                                         if ($from_knight_total_fall == $to_knight_total_fall) {
                                                             $combat->result = Combats::RESULT_DRAW;
                                                             Yii::trace('[CHARACTER][actionSetCombatPoints] draw combat by three falls');
                                                         } else {
                                                             if ($from_knight_total_fall == 3) {
                                                                 $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] to knight win combat by three falls');
                                                             } else {
                                                                 $combat->result = Combats::RESULT_FROM_KNIGHT_WIN_;
                                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] from knight win combat by three falls');
                                                             }
                                                         }
                                                     }
                                                     //Check if somebody is KO.
                                                 } elseif ($from_knight->endurance == 0 || $to_knight->endurance == 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FINISH BY KO');
                                                     $combat->status = Combats::STATUS_FINISHED;
                                                     $combat->result_by = Combats::RESULT_BY_KO;
                                                     //Check result of combat
                                                     if ($from_knight->endurance == $to_knight->endurance) {
                                                         $combat->result = Combats::RESULT_DRAW;
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] draw combat by ko');
                                                     } else {
                                                         if ($from_knight->endurance == 0) {
                                                             $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                                             Yii::trace('[CHARACTER][actionSetCombatPoints] to knight win combat ko');
                                                         } else {
                                                             $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                                             Yii::trace('[CHARACTER][actionSetCombatPoints] from knight win combat by ko');
                                                         }
                                                     }
                                                     //Check if somebody has not enough equipment
                                                 } elseif ($from_knight_equipment['armour_object']->current_pde == 0 || $from_knight_equipment['shield_object']->current_pde == 0 || $from_knight_equipment['spear_object']->current_pde == 0 || $to_knight_equipment['armour_object']->current_pde == 0 || $to_knight_equipment['shield_object']->current_pde == 0 || $to_knight_equipment['spear_object']->current_pde == 0) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] NOT ENOUGH EQUIPMENT');
                                                     //Check if from knight armour, shield or spear are broken
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] CHECK SOMEBODY HAS NOT ENOGH EQUIPMENT');
                                                     if ($from_knight_equipment['spear_object']->current_pde == 0 && !Inventory::checkHasReplacement($from_knight->id, Inventory::EQUIPMENT_TYPE_SPEAR, $from_knight_equipment['spear_object']->id) || $from_knight_equipment['armour_object']->current_pde == 0 && !Inventory::checkHasReplacement($from_knight->id, $from_knight_equipment['armour']->type, $from_knight_equipment['arnmour_object']->id) || $from_knight_equipment['shield_object']->current_pde == 0 && !Inventory::checkHasReplacement($from_knight->id, $from_knight_equipment['shield']->type, $from_knight_equipment['shield_object']->id)) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] from knight has not replacement equipment');
                                                         $combat->status = Combats::STATUS_FINISHED;
                                                         $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                                         $combat->result_by = Combats::RESULT_BY_NOT_EQUIPMENT_REPLACE;
                                                     }
                                                     if ($to_knight_equipment['spear_object']->current_pde == 0 && !Inventory::checkHasReplacement($to_knight->id, Inventory::EQUIPMENT_TYPE_SPEAR, $to_knight_equipment['spear_object']->id) || $to_knight_equipment['armour_object']->current_pde == 0 && !Inventory::checkHasReplacement($to_knight->id, $to_knight_equipment['armour']->type, $to_knight_equipment['armour_object']->id) || $to_knight_equipment['shield_object']->current_pde == 0 && !Inventory::checkHasReplacement($to_knight->id, $to_knight_equipment['shield']->type, $to_knight_equipment['shield_object']->id)) {
                                                         $combat->status = Combats::STATUS_FINISHED;
                                                         $combat->result_by = Combats::RESULT_BY_NOT_EQUIPMENT_REPLACE;
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] to knight has not replacement equipment');
                                                         //Check if previously from knight has not enogh equipment too.
                                                         if ($combat->result == Combats::RESULT_TO_KNIGHT_WIN) {
                                                             $combat->result = Combats::RESULT_DRAW;
                                                         } else {
                                                             $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                                         }
                                                     }
                                                 }
                                                 //if combat is finished then we save it and reset endurance and life of knight
                                                 if ($combat->status == Combats::STATUS_FINISHED) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FINISHED COMBAT -> SAVE COMBAT');
                                                     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][actionSetCombatPoints]', 'error');
                                                     }
                                                     $output['isCombatFinished'] = true;
                                                     //Reset Knights
                                                     Yii::trace('[actionSetCombatPoints] RESET KNIGHTS');
                                                     $from_knight->endurance = ($from_knight_card->will + $from_knight_card->constitution) * 3;
                                                     $from_knight->life = $from_knight_card->constitution * 2;
                                                     $from_knight->status = Knights::STATUS_ENABLE;
                                                     $to_knight->endurance = ($to_knight_card->will + $to_knight_card->constitution) * 3;
                                                     $to_knight->life = $to_knight_card->constitution * 2;
                                                     $to_knight->status = Knights::STATUS_ENABLE;
                                                     /*
                                                      * CALCULATE POSTCOMBAT
                                                      */
                                                     //Calculate experience
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] CALCULATE EXPERIENCE');
                                                     $precombat = $combat->combatsPrecombat;
                                                     $postcombatData = CombatsPostcombat::calculateEarnedExperience($combat, $from_knight->level, $to_knight->level);
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] SAVE POSTCOMBATS');
                                                     $from_knight_post_combat = new CombatsPostcombat();
                                                     $from_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $from_knight->id, 'knight_rival_level' => $from_knight->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' => $from_knight->experiencie_earned + $postcombatData['from_knight_earned_experience'], 'total_coins' => $precombat->from_knight_gate + $from_knight->coins, 'earned_coins' => $precombat->from_knight_gate, 'injury_type' => $from_knight_round_data->injury_type);
                                                     if (!$from_knight_post_combat->save()) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] 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' => $to_knight->id, 'knight_rival_level' => $to_knight->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' => $to_knight->experiencie_earned + $postcombatData['to_knight_earned_experience'], 'total_coins' => $precombat->to_knight_gate + $to_knight->coins, 'earned_coins' => $precombat->to_knight_gate, 'injury_type' => $to_knight_round_data->injury_type);
                                                     if (!$to_knight_post_combat->save()) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] se ha producido un error al salvar postcombate para to knight', 'error');
                                                     }
                                                     //Update experience of knights
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EXPERIECE');
                                                     $from_knight->experiencie_earned = $from_knight_post_combat->total_experience;
                                                     $to_knight->experiencie_earned = $to_knight_post_combat->total_experience;
                                                     /*
                                                      * Check if enable experience is less than 0 then downgrade last upgrade.
                                                      */
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FROM KNIGHT DOWNGRADE earned experience (' . $from_knight->experiencie_earned . ') < used experience (' . $from_knight->experiencie_used . ') ');
                                                     if ($from_knight->experiencie_earned < $from_knight->experiencie_used) {
                                                         //Select all evolution
                                                         $knight_evolutions = KnightsEvolution::model()->findAll('knights_id = :knights_id ORDER BY date DESC', array(':knights_id' => $from_knight->id));
                                                         if ($knight_evolutions) {
                                                             //Downgrade up to earned experience more than used experience
                                                             $jump = 0;
                                                             //Store jumps over rows with associate downgrade. Serveral downgrades would be consecutive
                                                             foreach ($knight_evolutions as $evolution) {
                                                                 //Check if is a upgrade
                                                                 if ($evolution->type == KnightsEvolution::TYPE_UPGRADE) {
                                                                     if ($jump > 0) {
                                                                         $jump--;
                                                                         continue;
                                                                     }
                                                                     //Add a downgrade
                                                                     $downgrade = new KnightsEvolution();
                                                                     $downgrade->attributes = array('knights_id' => $from_knight->id, 'type' => KnightsEvolution::TYPE_DOWNGRADE, 'characteristic' => $evolution->characteristic, 'value' => $evolution->value - 1, 'experiencie_used' => $evolution->experiencie_used, 'date' => date('Y-m-d H:i:s'), 'combats_id' => $combat->id);
                                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] Evolution value (' . $evolution->value . ') downgrade (' . $downgrade->value . ')');
                                                                     if (!$downgrade->save()) {
                                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] From knight downgrade not save', 'error');
                                                                     }
                                                                     //Add to time line downgrade
                                                                     //Load events tables
                                                                     $knights_events = new KnightsEvents();
                                                                     $knights_events->attributes = array('knights_id' => $from_knight->id, 'type' => KnightsEvents::TYPE_KNIGHTS_EVOLUTION, 'identificator' => $downgrade->id);
                                                                     if (!$knights_events->save()) {
                                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] From knight events downgrade not save', 'error');
                                                                     }
                                                                     $knights_events_last = new KnightsEventsLast();
                                                                     $knights_events_last->attributes = array('knights_id' => $from_knight->id, 'type' => KnightsEvents::TYPE_KNIGHTS_EVOLUTION, 'identificator' => $downgrade->id, 'date' => date("Y-m-d H:i:s"));
                                                                     if (!$knights_events_last->save()) {
                                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] From knightevents last  downgrade not save', 'error');
                                                                     }
                                                                     //Update experience of knight
                                                                     $from_knight->experiencie_used -= $evolution->experiencie_used;
                                                                     //Update characteristic
                                                                     $characteristic = Constants::model()->findByPk($evolution->characteristic);
                                                                     $from_knight_card->{$characteristic->name}--;
                                                                     if ($from_knight_card->save()) {
                                                                         Yii::trace('[actionSetCombatPoints] No se ha podido guardar la caracteristica de from knight', 'error');
                                                                     }
                                                                     //Check if user has a positive experience then break loop.
                                                                     if ($from_knight->experiencie_earned >= $from_knight->experiencie_used) {
                                                                         break;
                                                                     }
                                                                 } else {
                                                                     //This downgrade has associated the next upgrade
                                                                     $jump++;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] TO KNIGHT DOWNGRADE earned experience (' . $to_knight->experiencie_earned . ') < used experience (' . $to_knight->experiencie_used . ') ');
                                                     if ($to_knight->experiencie_earned < $to_knight->experiencie_used) {
                                                         //Select all evolution
                                                         $knight_evolutions = KnightsEvolution::model()->findAll('knights_id = :knights_id ORDER BY date DESC', array(':knights_id' => $to_knight->id));
                                                         if ($knight_evolutions) {
                                                             //Downgrade up to earned experience more than used experience
                                                             $jump = 0;
                                                             foreach ($knight_evolutions as $evolution) {
                                                                 //Check if is a upgrade
                                                                 if ($evolution->type == KnightsEvolution::TYPE_UPGRADE) {
                                                                     if ($jump > 0) {
                                                                         $jump--;
                                                                         continue;
                                                                     }
                                                                     //Add a downgrade
                                                                     $downgrade = new KnightsEvolution();
                                                                     $downgrade->attributes = array('knights_id' => $to_knight->id, 'type' => KnightsEvolution::TYPE_DOWNGRADE, 'characteristic' => $evolution->characteristic, 'value' => $evolution->value - 1, 'experiencie_used' => $evolution->experiencie_used, 'date' => date('Y-m-d H:i:s'), 'combats_id' => $combat->id);
                                                                     Yii::trace('Evolution value (' . $evolution->value . ') downgrade (' . $downgrade->value . ')');
                                                                     if (!$downgrade->save()) {
                                                                         Yii::trace('to knight downgrade not save', 'error');
                                                                     }
                                                                     $knights_events = new KnightsEvents();
                                                                     $knights_events->attributes = array('knights_id' => $to_knight->id, 'type' => KnightsEvents::TYPE_KNIGHTS_EVOLUTION, 'identificator' => $downgrade->id);
                                                                     if (!$knights_events->save()) {
                                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] to knight events downgrade not save', 'error');
                                                                     }
                                                                     $knights_events_last = new KnightsEventsLast();
                                                                     $knights_events_last->attributes = array('knights_id' => $to_knight->id, 'type' => KnightsEvents::TYPE_KNIGHTS_EVOLUTION, 'identificator' => $downgrade->id, 'date' => date("Y-m-d H:i:s"));
                                                                     if (!$knights_events_last->save()) {
                                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] From knightevents last  downgrade not save', 'error');
                                                                     }
                                                                     //Update experience of knight
                                                                     $to_knight->experiencie_used -= $evolution->experiencie_used;
                                                                     //Update characteristic
                                                                     $characteristic = Constants::model()->findByPk($evolution->characteristic);
                                                                     $to_knight_card->{$characteristic->name}--;
                                                                     if (!$to_knight_card->save()) {
                                                                         Yii::trace('[actionSetCombatPoints] No se ha podido guardar la caracteristica de to knight', 'error');
                                                                     }
                                                                     //Check if user has a positive experience then break loop.
                                                                     if ($to_knight->experiencie_earned >= $to_knight->experiencie_used) {
                                                                         break;
                                                                     }
                                                                 } else {
                                                                     //This downgrade has associated the next upgrade
                                                                     $jump++;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     /*
                                                      * Calculate repair prize equipment
                                                      */
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints]CALCULATE REPAIR PRIZE');
                                                     $from_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $from_knight);
                                                     if ($from_knight_autorepair['errno'] > 0) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] FROM KNIGHT AUTOREPAIR FAIL', 'error');
                                                     }
                                                     $to_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $to_knight);
                                                     if ($to_knight_autorepair['errno'] > 0) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] TO KNIGHT AUTOREPAIR FAIL', 'error');
                                                     }
                                                     /*
                                                      * Update coins of knights
                                                      */
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE COINS OF KNIGHTS');
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FROM_KNIGHT earned coins: current coinds(' . $from_knight->coins . ') + gate coins (' . $precombat->from_knight_gate . ') - autorrepair coins (' . $from_knight_autorepair['repair_cost'] . ') ');
                                                     $from_knight->coins += $precombat->from_knight_gate - $from_knight_autorepair['repair_cost'];
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] TO_KNIGHT earned coins: current coinds(' . $to_knight->coins . ') + gate coins (' . $precombat->to_knight_gate . ') - autorrepair coins (' . $to_knight_autorepair['repair_cost'] . ') ');
                                                     $to_knight->coins += $precombat->to_knight_gate - $to_knight_autorepair['repair_cost'];
                                                     /*
                                                      * Update healings of knights
                                                      */
                                                     if ($from_knight->pain > 0) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] Healing schule for from knigth');
                                                         $healing = Healings::model()->findByPk($from_knight->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][actionSetCombatPoints] Error to update from knight next healing date', 'error');
                                                         }
                                                     }
                                                     if ($to_knight->pain > 0) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints] Healing schule for to knigth');
                                                         $healing = Healings::model()->findByPk($to_knight->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][actionSetCombatPoints] Error to update to knight next healing date', 'error');
                                                         }
                                                     }
                                                     /*
                                                      * STATS
                                                      * Update stats of knights and platform
                                                      */
                                                     /*
                                                      $from_knight_stats = KnightsStats::model()->findByPk($from_knight->id );
                                                     $to_knight_stats = KnightsStats::model()->findByPk($to_knight->id );
                                                     $from_knight_stats_vs = KnightsStatsVs::model()->find( 'knights_id = :knights_id AND opponent = :opponent',array(':knights_id'=>$from_knight->id, ':opponent'=>$to_knight->id) );
                                                     $to_knight_stats_vs = KnightsStatsVs::model()->find( 'knights_id = :knights_id AND opponent = :opponent',array(':knights_id'=>$to_knight->id, ':opponent'=>$from_knight->id) );
                                                     $from_knight_stats_by_date = KnightsStatsByDate::model()->find( 'knights_id = :knights_id AND date = :date', array(':knights_id'=>$from_knight->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'=>$to_knight->id, ':date'=>substr($combat->date, 0,10) ) );
                                                     */
                                                     //who win combat
                                                     if ($combat->result == Combats::RESULT_FROM_KNIGHT_WIN) {
                                                         if ($combat->result_by == Combats::RESULT_BY_INJURY) {
                                                             $from_knight_stats->combats_wins_injury += 1;
                                                             $from_knight_stats_vs->combats_wins_injury += 1;
                                                             $from_knight_stats_by_date->combats_wins_injury += 1;
                                                             $to_knight_stats->combats_loose_injury += 1;
                                                             $to_knight_stats_vs->combats_loose_injury += 1;
                                                             $to_knight_stats_by_date->combats_loose_injury += 1;
                                                             switch ($to_knight_round_data->injury_type) {
                                                                 case Knights::TYPE_INJURY_LIGHT:
                                                                     $from_knight_stats->injury_total_light_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_light_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_light_produced += 1;
                                                                     $to_knight_stats->injury_total_light_received += 1;
                                                                     $to_knight_stats_vs->injury_total_light_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_light_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_SERIOUSLY:
                                                                     $from_knight_stats->injury_total_serious_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_serious_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_serious_produced += 1;
                                                                     $to_knight_stats->injury_total_serious_received += 1;
                                                                     $to_knight_stats_vs->injury_total_serious_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_VERY_SERIOUSLY:
                                                                     $from_knight_stats->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats->injury_total_very_serious_received += 1;
                                                                     $to_knight_stats_vs->injury_total_very_serious_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_very_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_FATALITY:
                                                                     $from_knight_stats->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats->injury_total_fatality_received += 1;
                                                                     $to_knight_stats_vs->injury_total_fatality_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_fatality_received += 1;
                                                                     break;
                                                                 default:
                                                                     Yii::trace('[][] El tipo de herida no existe', 'error');
                                                             }
                                                         } else {
                                                             $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;
                                                         }
                                                     } elseif ($combat->result == Combats::RESULT_TO_KNIGHT_WIN) {
                                                         if ($combat->result_by == Combats::RESULT_BY_INJURY) {
                                                             $from_knight_stats->combats_loose_injury += 1;
                                                             $from_knight_stats_vs->combats_loose_injury += 1;
                                                             $from_knight_stats_by_date->combats_loose_injury += 1;
                                                             $to_knight_stats->combats_wins_injury += 1;
                                                             $to_knight_stats_vs->combats_wins_injury += 1;
                                                             $to_knight_stats_by_date->combats_wins_injury += 1;
                                                             switch ($from_knight_round_data->injury_type) {
                                                                 case Knights::TYPE_INJURY_LIGHT:
                                                                     $to_knight_stats->injury_total_light_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_light_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_light_produced += 1;
                                                                     $from_knight_stats->injury_total_light_received += 1;
                                                                     $from_knight_stats_vs->injury_total_light_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_light_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_SERIOUSLY:
                                                                     $to_knight_stats->injury_total_serious_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_serious_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_serious_produced += 1;
                                                                     $from_knight_stats->injury_total_serious_received += 1;
                                                                     $from_knight_stats_vs->injury_total_serious_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_VERY_SERIOUSLY:
                                                                     $to_knight_stats->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats->injury_total_very_serious_received += 1;
                                                                     $from_knight_stats_vs->injury_total_very_serious_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_very_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_FATALITY:
                                                                     $to_knight_stats->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats->injury_total_fatality_received += 1;
                                                                     $from_knight_stats_vs->injury_total_fatality_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_fatality_received += 1;
                                                                     break;
                                                                 default:
                                                                     Yii::trace('[][] El tipo de herida no existe', 'error');
                                                             }
                                                         } else {
                                                             $from_knight_stats->combats_loose += 1;
                                                             $from_knight_stats_vs->combats_loose += 1;
                                                             $from_knight_stats_by_date->combats_loose += 1;
                                                             $to_knight_stats->combats_wins += 1;
                                                             $to_knight_stats_vs->combats_wins += 1;
                                                             $to_knight_stats_by_date->combats_wins += 1;
                                                         }
                                                     } else {
                                                         if ($combat->result_by == Combats::RESULT_BY_INJURY) {
                                                             $from_knight_stats->combats_draw_injury += 1;
                                                             $from_knight_stats_vs->combats_draw_injury += 1;
                                                             $from_knight_stats_by_date->combats_draw_injury += 1;
                                                             $to_knight_stats->combats_draw_injury += 1;
                                                             $to_knight_stats_vs->combats_draw_injury += 1;
                                                             $to_knight_stats_by_date->combats_draw_injury += 1;
                                                             //Check knight
                                                             switch ($from_knight_round_data->injury_type) {
                                                                 case Knights::TYPE_INJURY_LIGHT:
                                                                     $to_knight_stats->injury_total_light_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_light_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_light_produced += 1;
                                                                     $from_knight_stats->injury_total_light_received += 1;
                                                                     $from_knight_stats_vs->injury_total_light_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_light_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_SERIOUSLY:
                                                                     $to_knight_stats->injury_total_serious_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_serious_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_serious_produced += 1;
                                                                     $from_knight_stats->injury_total_serious_received += 1;
                                                                     $from_knight_stats_vs->injury_total_serious_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_VERY_SERIOUSLY:
                                                                     $to_knight_stats->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats->injury_total_very_serious_received += 1;
                                                                     $from_knight_stats_vs->injury_total_very_serious_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_very_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_FATALITY:
                                                                     $to_knight_stats->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats_vs->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats_by_date->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats->injury_total_fatality_received += 1;
                                                                     $from_knight_stats_vs->injury_total_fatality_received += 1;
                                                                     $from_knight_stats_by_date->injury_total_fatality_received += 1;
                                                                     break;
                                                                 default:
                                                                     Yii::trace('[][] El tipo de herida no existe', 'error');
                                                             }
                                                             switch ($to_knight_round_data->injury_type) {
                                                                 case Knights::TYPE_INJURY_LIGHT:
                                                                     $from_knight_stats->injury_total_light_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_light_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_light_produced += 1;
                                                                     $to_knight_stats->injury_total_light_received += 1;
                                                                     $to_knight_stats_vs->injury_total_light_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_light_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_SERIOUSLY:
                                                                     $from_knight_stats->injury_total_serious_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_serious_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_serious_produced += 1;
                                                                     $to_knight_stats->injury_total_serious_received += 1;
                                                                     $to_knight_stats_vs->injury_total_serious_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_VERY_SERIOUSLY:
                                                                     $from_knight_stats->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_very_serious_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_very_serious_produced += 1;
                                                                     $to_knight_stats->injury_total_very_serious_received += 1;
                                                                     $to_knight_stats_vs->injury_total_very_serious_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_very_serious_received += 1;
                                                                     break;
                                                                 case Knights::TYPE_INJURY_FATALITY:
                                                                     $from_knight_stats->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats_vs->injury_total_fatality_produced += 1;
                                                                     $from_knight_stats_by_date->injury_total_fatality_produced += 1;
                                                                     $to_knight_stats->injury_total_fatality_received += 1;
                                                                     $to_knight_stats_vs->injury_total_fatality_received += 1;
                                                                     $to_knight_stats_by_date->injury_total_fatality_received += 1;
                                                                     break;
                                                                 default:
                                                                     Yii::trace('[][] El tipo de herida no existe', 'error');
                                                             }
                                                         } else {
                                                             $from_knight_stats->combats_draw += 1;
                                                             $from_knight_stats_vs->combats_draw += 1;
                                                             $from_knight_stats_by_date->combats_draw += 1;
                                                             $to_knight_stats->combats_draw += 1;
                                                             $to_knight_stats_vs->combats_draw += 1;
                                                             $to_knight_stats_by_date->combats_draw += 1;
                                                         }
                                                     }
                                                     /*
                                                      * UPDATE STATS
                                                      */
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE STATS ');
                                                     if (!$from_knight_stats->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística de from knight', 'error');
                                                     }
                                                     if (!$from_knight_stats_vs->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística vs de from knight stats', 'error');
                                                     }
                                                     if (!$from_knight_stats_by_date->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística por dia de from knight stats', 'error');
                                                     }
                                                     if (!$to_knight_stats->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística de to knight', 'error');
                                                     }
                                                     if (!$to_knight_stats_vs->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística vs de to knight', 'error');
                                                     }
                                                     if (!$to_knight_stats_by_date->save()) {
                                                         trace('[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística diarias de to knight', 'error');
                                                     }
                                                     unset($from_knight_stats);
                                                     unset($to_knight_stats);
                                                     unset($from_knight_stats_vs);
                                                     unset($to_knight_stats_vs);
                                                     unset($from_knight_stats_by_date);
                                                     unset($to_knight_stats_by_date);
                                                     /*
                                                      //Update stats
                                                     $from_knight_stats->hits_total_produced += 1;
                                                     $from_knight_stats_vs->hits_total_produced += 1;
                                                     $from_knight_stats_by_date->hits_total_produced += 1;
                                                     $to_knight_stats->hits_total_produced += 1;
                                                     $to_knight_stats_vs->hits_total_produced += 1;
                                                     $to_knight_stats_by_date->hits_total_produced += 1;
                                                     $from_knight_stats->hits_total_received += 1;
                                                     $from_knight_stats_vs->hits_total_received += 1;
                                                     $from_knight_stats_by_date->hits_total_received += 1;
                                                     $to_knight_stats->hits_total_received += 1;
                                                     $to_knight_stats_vs->hits_total_received += 1;
                                                     $to_knight_stats_by_date->hits_total_received += 1;
                                                     $from_knight_stats->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $from_knight_stats_vs->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $from_knight_stats_by_date->hits_total_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $to_knight_stats->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $to_knight_stats_vs->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $to_knight_stats_by_date->hits_total_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $from_knight_stats->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $from_knight_stats_vs->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $from_knight_stats_by_date->hits_total_received_blocked += $from_knight_round_data->is_received_impact_defended;//sum 0 or 1
                                                     $to_knight_stats->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $to_knight_stats_vs->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $to_knight_stats_by_date->hits_total_received_blocked += $to_knight_round_data->is_received_impact_defended;
                                                     $from_knight_stats->damage_total_produced += $to_knight_round_data->received_damage;
                                                     $from_knight_stats_vs->damage_total_produced += $to_knight_round_data->received_damage;
                                                     $from_knight_stats_by_date->damage_total_produced += $to_knight_round_data->received_damage;
                                                     $to_knight_stats->damage_total_produced += $from_knight_round_data->received_damage;
                                                     $to_knight_stats_vs->damage_total_produced += $from_knight_round_data->received_damage;
                                                     $to_knight_stats_by_date->damage_total_produced += $from_knight_round_data->received_damage;
                                                     $from_knight_stats->damage_total_received += $from_knight_round_data->received_damage;
                                                     $from_knight_stats_vs->damage_total_received += $from_knight_round_data->received_damage;
                                                     $from_knight_stats_by_date->damage_total_received += $from_knight_round_data->received_damage;
                                                     $to_knight_stats->damage_total_received += $to_knight_round_data->received_damage;
                                                     $to_knight_stats_vs->damage_total_received += $to_knight_round_data->received_damage;
                                                     $to_knight_stats_by_date->damage_total_received += $to_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $from_knight_stats->damage_maximum_produced ) $from_knight_stats->damage_maximum_produced = $to_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $from_knight_stats_vs->damage_maximum_produced ) $from_knight_stats_vs->damage_maximum_produced = $to_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $from_knight_stats_by_date->damage_maximum_produced ) $from_knight_stats_by_date->damage_maximum_produced = $to_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $to_knight_stats->damage_maximum_produced ) $to_knight_stats->damage_maximum_produced = $from_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $to_knight_stats_vs->damage_maximum_produced ) $to_knight_stats_vs->damage_maximum_produced = $from_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $to_knight_stats_by_date->damage_maximum_produced ) $to_knight_stats_by_date->damage_maximum_produced = $from_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $from_knight_stats->damage_maximum_received ) $from_knight_stats->damage_maximum_received = $from_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $from_knight_stats_vs->damage_maximum_received ) $from_knight_stats_vs->damage_maximum_received = $from_knight_round_data->received_damage;
                                                     if( $from_knight_round_data->received_damage > $from_knight_stats_by_date->damage_maximum_received ) $from_knight_stats_by_date->damage_maximum_received = $from_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $to_knight_stats->damage_maximum_received ) $to_knight_stats->damage_maximum_received = $to_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $to_knight_stats_vs->damage_maximum_received ) $to_knight_stats_vs->damage_maximum_received = $to_knight_round_data->received_damage;
                                                     if( $to_knight_round_data->received_damage > $to_knight_stats_by_date->damage_maximum_received ) $to_knight_stats_by_date->damage_maximum_received = $to_knight_round_data->received_damage;
                                                     
                                                     //Update all stats
                                                     if( !$from_knight_stats->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística de from knight', 'error');
                                                     if( !$from_knight_stats_vs->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística vs de from knight stats', 'error');
                                                     if( !$from_knight_stats_by_date->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística por dia de from knight stats', 'error');
                                                     if( !$to_knight_stats->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística de to knight', 'error');
                                                     if( !$to_knight_stats_vs->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística vs de to knight', 'error');
                                                     if( !$to_knight_stats_by_date->save() ) trace( '[CHARACTER][actionSetCombatPoints] No se puede salvar las estadística diarias de to knight', 'error');
                                                     
                                                     unset($from_knight_stats);
                                                     unset($to_knight_stats);
                                                     unset($from_knight_stats_vs);
                                                     unset($to_knight_stats_vs);
                                                     unset($from_knight_stats_by_date);
                                                     unset($to_knight_stats_by_date);
                                                     */
                                                     /*
                                                      * SEND EMAIL TO RIVAL
                                                      */
                                                     /*
                                                     Yii::trace( '[CHARACTER][actionSetCombatPoints] CHECK if send email to rival' );
                                                     //Check email of challenge
                                                     if( $knight_setting = KnightsSettings::model()->findByPk( $rival_id ) ){
                                                     	if( $knight_setting->emailToFinishedCombat ){
                                                     		
                                                     
                                                     		//Check email
                                                     		if( $rival_id == $combat->fromKnight->id ){
                                                     			$knight_user = Users::model()->findByPk( $combat->fromKnight->users_id );
                                                     		}else{
                                                     			$knight_user = Users::model()->findByPk( $combat->toKnight->users_id );
                                                     		}
                                                     
                                                     		if( $knight_user ){
                                                     			Yii::trace( '[CHARACTER][actionSetCombatPoints] Yes, we send email to: '.$knight_user->email );
                                                     
                                                     			//cargamos la plantilla
                                                     			$message = Yii::app()->controller->renderFile(
                                                     					Yii::app()->basePath.Yii::app()->params['email_templates_path'] . 'finishedCombat.tpl',
                                                     					array(),
                                                     					true
                                                     			);
                                                     
                                                     			// To send HTML mail, the Content-type header must be set
                                                     			$headers  = 'MIME-Version: 1.0' . "\r\n";
                                                     			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                                                     
                                                     			// Additional headers
                                                     			$headers .= 'To: '.$knight_user->email. "\r\n";
                                                     			$headers .= 'From: <'.Yii::app()->params['adminEmail'].'>' . "\r\n";
                                                     				
                                                     
                                                     			$email = new Emails();
                                                     			$email->attributes = array(
                                                     					'destination'=> $knight_user->email,
                                                     					'headers'=>$headers,
                                                     					'title'=> Yii::app()->name.': combate terminado.',
                                                     					'body'=> $message,
                                                     					'status'=>Emails::STATUS_PENDING,
                                                     					'date'=>date('Y-m-d H:i:s')
                                                     			);
                                                     			if( !$email->save() ){
                                                     				Yii::trace( '[CHARACTER][actionSetCombatPoints] No se ha podido guardar el email', 'error');
                                                     			}
                                                     		}else{
                                                     			Yii::trace( '[CHARACTER][actionSetCombatPoints] No se ha encontrado usuario del caballero '.$this->knight->id, 'error');
                                                     		}
                                                     	}
                                                     }else{
                                                     	Yii::trace( '[CHARACTER][actionSetCombatPoints]No se ha encontrado setting del caballero '.$this->knight->id, 'error');
                                                     }
                                                     */
                                                 } else {
                                                     //Combat is not finished. Create a new round.
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] CREATE NEXT ROUND');
                                                     $nextRound = new Rounds();
                                                     $nextRound->attributes = array('combats_id' => $combat->id, 'number' => count($combat->rounds) + 1, 'status' => Rounds::STATUS_PENDING);
                                                     if (!$nextRound->save()) {
                                                         Yii::trace('[CHARACTER][actionSetCombatPoints]actionSetCombatPoints', 'error');
                                                     }
                                                 }
                                                 /*
                                                  * UPDATE KNIGHTS
                                                  */
                                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE KNIGHTS');
                                                 if (!$from_knight->save()) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FROM KNIGHT SAVE FAIL', 'error');
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] FROM KNIGHT SAVE FAIL');
                                                 } else {
                                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $from_knight->id, $from_knight, Yii::app()->params['cachetime']['knight']);
                                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $from_knight->name, $from_knight, Yii::app()->params['cachetime']['knight']);
                                                 }
                                                 if (!$to_knight->save()) {
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] TO KNIGHT SAVE FAIL', 'error');
                                                     Yii::trace('[CHARACTER][actionSetCombatPoints] TO KNIGHT SAVE FAIL');
                                                 } else {
                                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $to_knight->id, $to_knight, Yii::app()->params['cachetime']['knight']);
                                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $to_knight->name, $to_knight, Yii::app()->params['cachetime']['knight']);
                                                 }
                                                 /*
                                                  * SHOW DIALOG FOR USER
                                                  */
                                                 /*
                                                 													 $data = array(
                                                 													 		'from_knight_round_data'=>$from_knight_round_data,
                                                 													 		'from_knight'=>$from_knight,
                                                 													 		'from_knight_total_damage'=>$from_knight_total_damage,
                                                 													 		'to_knight_round_data'=>$to_knight_round_data,
                                                 													 		'to_knight'=>$to_knight,
                                                 													 		'to_knight_total_damage'=>$to_knight_total_damage,
                                                 													 		'injuryType'=> Constants::getLabelsTypeInjuries(),
                                                 													 		'modifiers'=>''//under development
                                                 													 );*/
                                                 $data = array('from_knight_round_data' => $from_knight_round_data, 'from_knight' => $combat->fromKnight, 'from_knight_total_damage' => $from_knight_round_data['defended_damage'] >= $from_knight_round_data['received_damage'] ? 0 : $from_knight_round_data['received_damage'] - $from_knight_round_data['defended_damage'], 'from_knight_equipment' => array('spear' => Spears::model()->findByPk($from_knight_round_data->spears_id), 'shield' => Armours::model()->findByPk($from_knight_round_data->shield_id), 'armour' => Armours::model()->findByPk($from_knight_round_data->armour_id)), 'from_knight_pain_value' => $from_knight_round_data->is_pain_throw_pass ? 0 : $from_knight_round_data->knights_pain, 'to_knight_round_data' => $to_knight_round_data, 'to_knight' => $combat->toKnight, 'to_knight_total_damage' => $to_knight_round_data['defended_damage'] >= $to_knight_round_data['received_damage'] ? 0 : $to_knight_round_data['received_damage'] - $to_knight_round_data['defended_damage'], 'to_knight_equipment' => array('spear' => Spears::model()->findByPk($to_knight_round_data->spears_id), 'shield' => Armours::model()->findByPk($to_knight_round_data->shield_id), 'armour' => Armours::model()->findByPk($to_knight_round_data->armour_id)), 'to_knight_pain_value' => $to_knight_round_data->is_pain_throw_pass ? 0 : $to_knight_round_data->knights_pain, 'injuryType' => Constants::getLabelsTypeInjuries(), 'modifiers' => '');
                                                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_result.php', $data, true);
                                                 $output['errno'] = 0;
                                             } else {
                                                 $output['html'] = '<p>Se ha producido un error al calcular el punto de ataque del adversario.</p>';
                                             }
                                         } else {
                                             //Salvamos el round data
                                             if ($roundData->save()) {
                                                 $output['errno'] = 0;
                                                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_waiting_for_rival.php', array('desqualifyTime' => Yii::app()->params['desqualifyTime']), true);
                                             } else {
                                                 $output['html'] = '<p>Se ha producido un error al guardar tu ataque y defensa.</p>';
                                             }
                                         }
                                     } else {
                                         $output['html'] = '';
                                         if ($user_knight_equipment['spear_object'] == null) {
                                             $output['html'] .= '<p>Debes llevar la lanza al combate.</p>';
                                         }
                                         if ($user_knight_equipment['shield_object'] == null) {
                                             $output['html'] .= '<p>Debes llevar el escudo al combate.</p>';
                                         }
                                         if ($user_knight_equipment['armour_object'] == null) {
                                             $output['html'] .= '<p>Debes llevar la armadura completa al combate.</p>';
                                         }
                                     }
                                 } else {
                                     $output['html'] = '<p>Ya has seleccionado los puntos de ataque y defensa para esta ronda. Falta tu adversario.</p>';
                                 }
                             } else {
                                 $output['html'] = '<p>El round no está pendiente.</p>';
                             }
                         } else {
                             $output['html'] = '<p>No puedes toquetear cositas de otros caballeros.</p>';
                         }
                     } else {
                         $output['html'] = '<p>El combate no está en curso.</p>';
                     }
                 } else {
                     $output['html'] = '<p>No se ha encontrado el combate.</p>';
                 }
             } else {
                 $output['html'] = '<p>Los datos de entrada no son válidos.</p>';
             }
         } else {
             $output['html'] = '<p>Sólo puedes toquetear tu caballero.</p>';
         }
     } else {
         $output['html'] = '<p>Tu sesión ha expirado. Tienes que volver a hacer login.</p>';
     }
     echo CJSON::encode($output);
 }