<div class="form">

<?php 
$form = $this->beginWidget('CActiveForm', array('id' => 'equipment-requirements-form', 'enableAjaxValidation' => false));
?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

<?php 
// Load equipment view
if ($model->equipments_type == Inventory::EQUIPMENT_TYPE_ARMOUR) {
    // Load view for armour
    echo $this->renderPartial('/armours/_view', array('data' => Armours::model()->findByPk($model->identificator)));
} else {
    // Load view for spear
    echo $this->renderPartial('/spears/_view', array('data' => Spears::model()->findByPk($model->identificator)));
}
?>
	<?php 
echo $form->errorSummary($model);
/* by default
	<div class="row">
		<?php echo $form->labelEx($model,'identificator'); ?>
		<?php echo $form->textField($model,'identificator',array('size'=>10,'maxlength'=>10)); ?>
		<?php echo $form->error($model,'identificator'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'equipments_type'); ?>
		<?php echo $form->textField($model,'equipments_type',array('size'=>10,'maxlength'=>10)); ?>
		<?php echo $form->error($model,'equipments_type'); ?>
 public function actionBuy()
 {
     $output = array('errno' => 1, 'html' => '');
     //Check session
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['equipments_type']) && is_numeric($_GET['equipments_type']) && $_GET['equipments_type'] > 0 && isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
             //Search object
             switch ($_GET['equipments_type']) {
                 case Inventory::EQUIPMENT_TYPE_ARMOUR:
                     $item = Armours::model()->findByPk($_GET['id']);
                     $itemObject = new ArmoursObjects();
                     $itemObject->attributes = array('armours_id' => $item->id, 'knights_id' => $this->user_data['knights']->id, 'current_pde' => $item->pde);
                     break;
                 case Inventory::EQUIPMENT_TYPE_SPEAR:
                     $item = Spears::model()->findByPk($_GET['id']);
                     $itemObject = new SpearsObjects();
                     $itemObject->attributes = array('spears_id' => $item->id, 'knights_id' => $this->user_data['knights']->id, 'current_pde' => $item->pde);
                     break;
                 case Inventory::EQUIPMENT_TYPE_TRICK:
                     $item = null;
                     break;
                 default:
                     $item = null;
             }
             //Check item
             if ($item) {
                 //Check requeriments
                 if (EquipmentRequirements::checkAccomplish($_GET['equipments_type'], $_GET['id'], $this->user_data['knights']->id)) {
                     //Check coins
                     if ($item->prize <= $this->user_data['knights']->coins) {
                         //add item to inventory of knight
                         if ($emptyPosition = Inventory::getFirstEmptySocket($this->user_data['knights']->id)) {
                             //Save item object
                             $itemObject->save();
                             //Add item to knight's inventory
                             $inventoryObject = new Inventory();
                             $inventoryObject->attributes = array('knights_id' => $this->user_data['knights']->id, 'type' => $_GET['equipments_type'], 'identificator' => $itemObject->id, 'position' => $emptyPosition, 'amount' => 1);
                             $inventoryObject->save();
                             //sustract coins
                             $this->user_data['knights']->coins -= $item->prize;
                             $this->user_data['knights']->save();
                             //Set purchase history
                             $purchase = new KnightsPurchases();
                             $purchase->attributes = array('knights_id' => $this->user_data['knights']->id, 'equipments_type_id' => $_GET['equipments_type'], 'identificator' => $_GET['id'], 'date' => date('Y-m-d H:i:s'), 'status' => KnightsPurchases::STATUS_PURCHASED, 'knights_card_charisma' => $this->user_data['knights_card']->charisma, 'knights_card_trade' => $this->user_data['knights_card']->trade);
                             if (!$purchase->save()) {
                                 Yii::log('No salva el historial de la compra.');
                             }
                             $output['errno'] = 0;
                             $output['html'] = '<p>Ya tienes el objeto en tu <a href="/character/inventory/sir/' . $this->user_data['knights']->name . '">inventario</a> listo para utilizar.</p>';
                             $output['coins'] = number_format($this->user_data['knights']->coins, 0, ',', '.');
                         } else {
                             $output['html'] = '<p>No tienes suficiente espacio en el inventario secundario.</p>';
                         }
                     } else {
                         $output['html'] = '<p>¡No tienes suficiente dinero!</p><p>Siempre puedes <a href="/jobs">ganar algo de dinero</a> prestando tus servicios como caballero.</p>';
                     }
                 } else {
                     $output['html'] = '<p>No cumples con alguno de los requisitos.</p>';
                 }
             } else {
                 $output['html'] = '<p>El objecto no se ha encontrado.</p>';
             }
         } else {
             $output['html'] = '<p>Los datos del item no son correctos.</p>';
         }
     } else {
         $output['html'] = '<p>La sesión ha expirado. Necesitas volver a hacer login.</p>';
     }
     echo CJSON::encode($output);
 }
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = Spears::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
 /**
  * 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);
 }
 /**
  * knight's equipment are repaired automatically. Looking for equipment with pde loosed, calculate repair cost, substract to knight coins and add pde points. 
  * Return if error 
  * @param unknown_type $combat
  * @param unknown_type $knight
  * @return multitype:number boolean
  */
 public static function autorepairObjectsEquipment(&$combat, &$knight)
 {
     //
     $output = array('errno' => 0, 'error' => '', 'automatic_repair' => true, 'repair_cost' => 0, 'not_enought_money' => false);
     //Prepared statement
     $sql = '';
     //Load all items of inventory of knight
     $inventory = Inventory::model()->findAll('knights_id = :knights_id AND (type = ' . Inventory::EQUIPMENT_TYPE_ARMOUR . ' OR type = ' . Inventory::EQUIPMENT_TYPE_SPEAR . ' )', array(':knights_id' => $knight->id));
     if (count($inventory)) {
         //For each item check maximun pde
         foreach ($inventory as $item) {
             //Load class of item
             if ($item['type'] == Inventory::EQUIPMENT_TYPE_ARMOUR) {
                 $object = ArmoursObjects::model()->findByPk($item['identificator']);
                 $classItem = Armours::model()->findByPk($object->armours_id);
             } else {
                 $object = SpearsObjects::model()->findByPk($item['identificator']);
                 $classItem = Spears::model()->findByPk($object->spears_id);
             }
             //echo "\n".$knight->name.": ".$classItem->name." PDE MAX (".$classItem->pde.") object pde (".$object->current_pde.") ";
             //Check if need a repair
             if ($object->current_pde < $classItem->pde) {
                 //Check prize of reparation
                 $percentPDEloose = 1 - $object->current_pde / $classItem->pde;
                 $repair_cost = ceil($classItem->prize * $percentPDEloose);
                 //echo "coins (".$knight->coins.") percent ($percentPDEloose) prize class item(".$classItem->prize.") repair cost (".$repair_cost.")";
                 //Check coins and cost
                 if ($knight->coins > $repair_cost) {
                     Yii::log('Reparando ' . $classItem->name . ' por ' . $repair_cost . ' MO');
                     //Add autorepair row
                     $objectRepair = new ObjectRepairs();
                     $objectRepair->attributes = array('knights_id' => $knight->id, 'inventory_type' => $item['type'], 'combats_id' => $combat->id, 'object_identificator' => $item['identificator'], 'class_identificator' => $classItem->id, 'current_pde' => $object->current_pde, 'maximum_pde' => $classItem->pde, 'repair_cost' => $repair_cost, 'date' => date('Y-m-d H:m:s'));
                     if (!$objectRepair->save()) {
                         $output['errno'] = 2;
                         $output['error'] .= $objectRepair->getErrors();
                     }
                     //We can repair the object
                     $object->current_pde = $classItem->pde;
                     if (!$object->save()) {
                         $output['errno'] = 4;
                     }
                     //Subtract coins
                     $knight->coins -= $repair_cost;
                     $output['repair_cost'] += $repair_cost;
                 } else {
                     //Upsss, knight has not enought money!! we break loop
                     Yii::log('¡¡No se puede reparar!!');
                     $output['not_enought_money'] = true;
                     break;
                 }
             }
         }
     } else {
         $output['errno'] = 1;
     }
     //var_dump($output);
     return $output;
 }
    /**
     * Return spear, shield and armour in use for a knight in one round.
     * @param unknown_type $knigth_id
     * @param unknown_type $armourPosition
     * @param unknown_type $shieldPosition
     * @param unknown_type $spearPosition
     * @return multitype:NULL
     */
    public static function getCurrentEquipment4Round($knigth_id, $armourPosition = "null", $shieldPosition = self::POSITION_SHIELD, $spearPosition = self::POSITION_SPEAR)
    {
        $equipment = array('spear_object' => null, 'spear' => null, 'shield_object' => null, 'shield' => null, 'armour_object' => null, 'armour' => null);
        $sql = 'SELECT
					identificator,
					position 
				FROM 
					inventory
				WHERE 
					knights_id = :knights_id AND
					(position = ' . $armourPosition . ' OR position = ' . $shieldPosition . ' OR position = ' . $spearPosition . ' )';
        //echo $sql;die;
        $command = Yii::app()->db->createCommand($sql);
        $command->bindValue('knights_id', $knigth_id);
        $result = $command->queryAll();
        foreach ($result as $element) {
            switch ($element['position']) {
                case Inventory::POSITION_SHIELD:
                    $equipment['shield_object'] = ArmoursObjects::model()->findByPk($element['identificator']);
                    $equipment['shield'] = Armours::model()->findByPk($equipment['shield_object']->armours_id);
                    break;
                case Inventory::POSITION_SPEAR:
                    $equipment['spear_object'] = SpearsObjects::model()->findByPk($element['identificator']);
                    $equipment['spear'] = Spears::model()->findByPk($equipment['spear_object']->spears_id);
                    break;
                default:
                    $equipment['armour_object'] = ArmoursObjects::model()->findByPk($element['identificator']);
                    $equipment['armour'] = Armours::model()->findByPk($equipment['armour_object']->armours_id);
            }
        }
        return $equipment;
    }
 public function actionShowFinishedRound()
 {
     $output = array('errno' => 1, 'html' => '', 'isFinishedRound' => true, 'isCombatFinished' => false);
     //Valid input
     if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0 && isset($_GET['round']) && is_numeric($_GET['round']) && $_GET['round'] > 0) {
         //Load combat
         if ($combat = Combats::model()->with('fromKnight', 'toKnight', array('rounds' => array('condition' => 'number=' . $_GET['round'])))->findByPk($_GET['combat'])) {
             //Check if combat exist
             if ($combat->combatsPrecombat) {
                 //Check if round is finished
                 Yii::trace('STATUS combat(' . $_GET['combat'] . ') - round(' . $_GET['combat'] . ') total rounds (' . count($combat->rounds) . ')-> combat(' . $combat->rounds[$_GET['round'] - 1]->combats_id . ') round (' . $combat->rounds[$_GET['round'] - 1]->number . ') status ' . $combat->rounds[$_GET['round'] - 1]->status);
                 if ($combat->rounds[$_GET['round'] - 1]->status != Rounds::STATUS_PENDING) {
                     // Check if round is finished by descalification
                     if ($combat->result_by != Combats::RESULT_BY_DESQUALIFY) {
                         //Load round data
                         $from_knight_round_data = RoundsData::model()->find('rounds_combats_id = :combats_id AND rounds_number = :number AND knights_id = :knights_id', array(':combats_id' => $combat->id, ':number' => $_GET['round'], ':knights_id' => $combat->from_knight));
                         $to_knight_round_data = RoundsData::model()->find('rounds_combats_id = :combats_id AND rounds_number = :number AND knights_id = :knights_id', array(':combats_id' => $combat->id, ':number' => $_GET['round'], ':knights_id' => $combat->to_knight));
                         $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;
                         $output['isCombatFinished'] = $combat->status == Combats::STATUS_FINISHED;
                     } else {
                         $data = array('combat' => $combat);
                         $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_result_disqualified.php', $data, true);
                     }
                 } else {
                     //Round is pending
                     $output['errno'] = 0;
                     $output['isFinishedRound'] = false;
                 }
             } else {
                 $output['html'] = 'Se ha producido un error al cargar el precombate';
             }
         } else {
             $output['html'] = 'No se ha encontrado al combate.';
         }
     } else {
         $output['html'] = 'El identificador del combate no es válido.';
     }
     echo CJSON::encode($output);
 }