/**
  * Check if a knight accomplish with requirements for item
  * @param unknown $equipment_type
  * @param unknown $identificator
  * @param unknown $knight_id
  * @return boolean
  */
 public static function checkAccomplish($equipments_type, $identificator, $knight_id)
 {
     Yii::trace('[APP] Cehck for  ' . "{$equipments_type}, {$identificator}, {$knight_id}");
     // Search all requirements
     $equipmentRequirementsList = self::model()->findAll('identificator=:identificator AND equipments_type=:equipments_type', array(':identificator' => $identificator, ':equipments_type' => $equipments_type));
     if ($equipmentRequirementsList) {
         Yii::trace('[APP] equipment requirement exist');
         // Load knight card
         $knight = Knights::model()->findByPk($knight_id);
         $knightCard = KnightsCard::model()->findByPk($knight_id);
         // Check for each requirement if knight accomplish with it
         // Check if all requirements are accomplish. Load requirements
         foreach ($equipmentRequirementsList as $equipmentRequirements) {
             Yii::trace('[APP] check requirement ' . $equipmentRequirements->requirements_id);
             // Load requirement
             $requirement = Requirements::model()->findByPk($equipmentRequirements->requirements_id);
             Yii::trace('[APP] Load requirement ' . $requirement->id . ': ' . $requirement->level . ' - ' . $requirement->attribute . ' - ' . $requirement->skill);
             // Check level
             if ($requirement->level != null && $requirement->value > $knight->level) {
                 Yii::trace('[APP] No level');
                 return false;
             } else {
                 if ($requirement->attribute != null) {
                     Yii::trace('[APP] Is attribute');
                     // Load name of characteristic
                     $attributeName = Constants::model()->findByPk($requirement->attribute);
                     if ($requirement->value > $knightCard->{$attributeName->name}) {
                         Yii::trace('[APP] NO attribute');
                         return false;
                     }
                 } else {
                     if ($requirement->skill != null) {
                         Yii::trace('[APP] Is skill');
                         $attributeName = Constants::model()->findByPk($requirement->skill);
                         if ($requirement->value > $knightCard->{$attributeName->name}) {
                             Yii::trace('[APP] No skill');
                             return false;
                         }
                     }
                 }
             }
             Yii::trace('[APP] requirement pass');
         }
     }
     Yii::trace('[APP] F**k yeah');
     return true;
 }
 /**
  * Activa una cuenta
  */
 public function actionAccountActivation()
 {
     //Initi
     $template = 'error';
     $data = array('message' => '', 'code' => 'en la activación.');
     //Validation input
     /*
     $user = new Users();
     $user->attributes = array(
     	'email'=>$_GET['email']				
     );
     */
     //Check email
     $validator = new CEmailValidator();
     if ($validator->validateValue($_GET['email'])) {
         //Check if user exist
         $user = Users::model()->find('email=:email', array(':email' => $_GET['email']));
         if ($user) {
             //User found
             if ($user->status == Users::STATUS_PENDING_ACTIVATION) {
                 //Load his knight
                 $knight = Knights::model()->find('users_id=:users_id', array('users_id' => $user->id));
                 //Check if code is the same
                 $codigo_activacion = md5($user->email . $knight->name . $user->password_md5 . $user->suscribe_date);
                 if ($_GET['code'] === $codigo_activacion) {
                     //ACTIVATED ACCOUNT
                     //1.- change status
                     $user->status = Users::STATUS_ENABLE;
                     $user->save();
                     $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT;
                     $knight->save();
                     //2.- create card
                     $knight_card = new KnightsCard();
                     $knight_card->attributes = array('knights_id' => $knight->id);
                     $knight_card->save();
                     //3.- Create general stats
                     $knight_stats = new KnightsStats();
                     $knight_stats->attributes = array('knights_id' => $knight->id);
                     if (!$knight_stats->save()) {
                         Yii::trace('[Site][actionAccountActivation] No se puede salvar las stats del caballero', 'error');
                     }
                     //4.- set stats attack location
                     //load all location
                     /*
                     $locations = Constants::model()->findAll( 
                     	'type=:type',
                     	array( ':type'=> Constants::KNIGHTS_LOCATION)
                     );
                     
                     if( count($locations) > 0 ){
                     	//Foreach location set a value for attack location. Defense is depending of shield
                     	foreach( $locations as $location ){
                     		$knights_stats_attack_location = new KnightsStatsAttackLocation();
                     		$knights_stats_attack_location->attributes = array(
                     			'knights_id'=>$knight->id,
                     			'location'=>$location['id']
                     		);
                     		$knights_stats_attack_location->save();
                     	}
                     	
                     }else{
                     	$data['message'] .= 'No hay datos de localizaciones';
                     }
                     */
                     //Change for points of location. 48 is the maximun position number in the attack and defense points
                     for ($i = 1; $i <= 48; $i++) {
                         $knights_stats_attack_location = new KnightsStatsAttackLocation();
                         $knights_stats_attack_location->attributes = array('knights_id' => $knight->id, 'location' => $i);
                         $knights_stats_attack_location->save();
                     }
                     //6.- Set default equipment
                     //Set armours
                     foreach (Armours::getDefaultEquipment() as $key => $id) {
                         //Find armour
                         $armour = Armours::model()->findByPk($id);
                         if ($armour) {
                             //creamos nuevo objeto de la armadura
                             $armour_object = new ArmoursObjects();
                             $armour_object->attributes = array('armours_id' => $id, 'knights_id' => $knight->id, 'current_pde' => $armour->pde);
                             if (!$armour_object->save()) {
                                 //$data['message'] .= '<p>Armadura '.$id.' ('.$armour_object->attributes['armours_id'].') generada ('.var_dump( $armour_object->getErrors()).') ';
                                 Yii::trace('[SITE][actionAccountActivation] Error al salvar la armadura ' . $armour->name, 'error');
                             }
                             //Lo inventariamos. Como son los primeros objetos la posición que ocupa será empezando desde 1
                             $inventory = new Inventory();
                             //Sabemos que no hay objetos por lo que ocupamos las primeras posiciones, que concuerdan con el id
                             $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_ARMOUR, 'identificator' => $armour_object->id, 'position' => $key + 11);
                             $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                         } else {
                             $data['message'] .= '<p>KAKUNA MATATA!!';
                         }
                     }
                     //Set spears
                     $position = 27;
                     $spear = Spears::model()->findByPk(1);
                     //Lanza de entrenamiento
                     foreach (Spears::getDefaultEquipment() as $key => $id) {
                         //Creamos el bojeto lanza
                         $spear_object = new SpearsObjects();
                         $spear_object->attributes = array('spears_id' => $spear->id, 'knights_id' => $knight->id, 'current_pde' => $spear->pde);
                         $spear_object->save();
                         $data['message'] .= '<p>Lanza ' . $id . ' generada</p>';
                         //La inventariamos
                         $inventory = new Inventory();
                         $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_SPEAR, 'identificator' => $spear_object->id, 'position' => $position++);
                         $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                     }
                     //Creamos las eventos de knights_events_last
                     $sql = '';
                     for ($i = 0; $i < Yii::app()->params['events']['event_last']['maximum']; $i++) {
                         $sql .= 'INSERT INTO knights_events_last (knights_id, type, identificator, date) VALUES (' . $knight->id . ', ' . KnightsEvents::TYPE_VOID . ', 0, \'2012-01-01 00:00:' . ($i < 10 ? '0' . $i : $i) . '\' );';
                         /*
                         $event = new KnightsEventsLast();
                         $event->attributes = array(
                         	'knights_id'=>$knight->id,
                         	'type'=> KnightsEvents::TYPE_VOID,
                         	'identificator'=>0,
                         	'date'=>'2012-01-01 00:00:'.(($i<10)?'0'.$i:$i)//for update
                         );
                         $event->save();
                         */
                     }
                     $command = Yii::app()->db->createCommand($sql);
                     $command->execute();
                     Yii::app()->db->setActive(false);
                     //Create healing row
                     $healing = new Healings();
                     $healing->attributes = array('knights_id' => $knight->id, 'next_healing_date' => null);
                     if (!$healing->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert healing row.', 'error');
                     }
                     //Create settings
                     $knights_settings = new KnightsSettings();
                     $knights_settings->attributes = array('knights_id' => $knight->id);
                     if (!$knights_settings->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert setting row.', 'error');
                     }
                     unset($knights_settings);
                     //UPDATE YELLOW PAGES
                     $initial_character = substr($knight->name, 0, 1);
                     if (is_numeric($initial_character)) {
                         $initial_character = '[0-9]';
                     } else {
                         $initial_character = strtoupper($initial_character);
                     }
                     $yellow_pages_total = YellowPagesTotal::model()->with('letter0')->find('letter0.name = :letter', array(':letter' => $initial_character));
                     $yellow_pages_total->total += 1;
                     if (!$yellow_pages_total->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido actualizar yellow pages total', 'error');
                     }
                     $yellow_pages_total_by_letter = new YellowPagesTotalByLetter();
                     $yellow_pages_total_by_letter->attributes = array('letter' => $yellow_pages_total->letter, 'knights_id' => $knight->id);
                     if (!$yellow_pages_total_by_letter->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido crear yellow pages total by letter', 'error');
                     }
                     //Hacemos el login de alta
                     $model = new LoginForm();
                     $model->attributes = array('username' => $user->email, 'password' => 'nolosabemos');
                     //Check if all is ok
                     if ($model->loginFromValidation()) {
                         $template = 'accountActivation';
                     } else {
                         $data['message'] = 'Se ha producido un error al validar la cuenta. Escribenos un correo a ' . Yii::app()->params['adminEmail'];
                     }
                 } else {
                     $data['message'] = 'El usuario y el código de activación no son correctos.';
                 }
             } else {
                 //Message Error: user is not pending of activation
                 $data['message'] = 'El usuario no está pendiente de activación';
             }
         } else {
             //User not found
             $data['message'] = 'El usuario o código de activación no están relacionados.';
         }
     } else {
         //Input not valid
         $data['message'] = 'Los datos de entrada no son correctos.';
     }
     //Show Output
     $this->render($template, $data);
 }
if ($evolution->type == KnightsEvolution::TYPE_UPGRADE) {
    ?>
			
		<p>Sir <?php 
    echo $this->knight->name;
    ?>
 ha <span class="colorBlue">subido</span> el nivel de <strong class="colorBlue"><?php 
    echo KnightsCard::getNameAttributeLabel($evolution->characteristic0->name);
    ?>
</strong>  a <strong class="colorBlue"><?php 
    echo $evolution->value;
    ?>
</strong></p>
	<?php 
} else {
    ?>
			
		<p>Sir <?php 
    echo $this->knight->name;
    ?>
 ha <span class="colorRed">bajado</span> el nivel de <strong><?php 
    echo KnightsCard::getNameAttributeLabel($evolution->characteristic0->name);
    ?>
</strong>  a <strong><?php 
    echo $evolution->value;
    ?>
</strong> debido a su último combate.</p>
	<?php 
}
?>
</div>
 public function actionShowPostcombat()
 {
     $output = array('errno' => 1, 'html' => '');
     //Valid input
     if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
         //Load combat
         if ($combat = Combats::model()->with('fromKnight', 'toKnight')->findByPk($_GET['id'])) {
             //Check if precombat exit
             $postcombats = CombatsPostcombat::model()->findAll('combats_id = :combats_id', array(':combats_id' => $_GET['id']));
             if (count($postcombats) == 2) {
                 //Set data from knight and to knight
                 if ($combat->from_knight == $postcombats[0]->knights_id) {
                     $data = array('combat' => $combat, 'from_knight_postcombat' => &$postcombats[0], 'from_knight_automatic_object_repairs' => array(), 'from_knight_downgrades' => array(), 'to_knight_postcombat' => &$postcombats[1], 'to_knight_automatic_object_repairs' => array(), 'to_knight_downgrades' => array(), 'injuryLabels' => Constants::getLabelsTypeInjuries(), 'knight_card_labels' => array());
                 } else {
                     $data = array('combat' => $combat, 'from_knight_postcombat' => &$postcombats[1], 'from_knight_automatic_object_repairs' => array(), 'from_knight_downgrades' => array(), 'to_knight_postcombat' => &$postcombats[0], 'to_knight_automatic_object_repairs' => array(), 'to_knight_downgrades' => array(), 'injuryLabels' => Constants::getLabelsTypeInjuries(), 'knight_card_labels' => array());
                 }
                 //Load repairs
                 $result = ObjectRepairs::model()->findAll('combats_id = :combats_id', array(':combats_id' => $combat->id));
                 //sort result by knight
                 if (count($result)) {
                     foreach ($result as $repair) {
                         if ($repair['knights_id'] == $combat->from_knight) {
                             //Add to from knight
                             array_push($data['from_knight_automatic_object_repairs'], $repair);
                         } else {
                             array_push($data['to_knight_automatic_object_repairs'], $repair);
                         }
                     }
                 }
                 //Load downgrades!!
                 $downgrades = KnightsEvolution::model()->findAll('combats_id = :combats_id', array(':combats_id' => $combat->id));
                 //sort result by knight
                 if (count($downgrades)) {
                     foreach ($downgrades as $downgrade) {
                         if ($downgrade->knights_id == $combat->from_knight) {
                             array_push($data['from_knight_downgrades'], $downgrade);
                         } else {
                             array_push($data['to_knight_downgrades'], $downgrade);
                         }
                     }
                     //Load knight card labels
                     $data['knight_card_labels'] = KnightsCard::model()->attributeLabelsById();
                 }
                 //	var_dump($data);die;
                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_post_combat.php', $data, true);
                 $output['errno'] = 0;
             } else {
                 $output['html'] = 'Se ha producido un error al cargar el postcombate ' . count($postcombats);
             }
         } else {
             $output['html'] = 'No se ha encontrado al combate.';
         }
     } else {
         $output['html'] = 'El identificador del combate no es válido.';
     }
     echo CJSON::encode($output);
 }