/**
     * Before action load knight data of user
     * @param unknown_type $action
     */
    public function beforeAction($action)
    {
        //Load user's knight data
        if (!Yii::app()->user->isGuest) {
            $this->user_data['knights'] = Knights::model()->with('knightsCard', 'knightsStats')->find('id=:id', array(':id' => Yii::app()->user->knights_id));
            $this->user_data['knights_card'] =& $this->user_data['knights']->knightsCard;
            //Load stats of knight
            $this->user_data['knights_stats'] =& $this->user_data['knights']->knightsStats;
            //Load if user has new friendship request
            $sql = 'SELECT friends.id as id, k1.name as name, k1.avatars_id as avatars_id FROM friends
					INNER JOIN users ON users.id = friends.from_user
					INNER JOIN knights as k1 ON k1.users_id = users.id
					WHERE friends.status = :status AND to_user = :users_knights_id1
					ORDER BY start_date DESC';
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(':status', Friends::STATUS_ONWAITING, PDO::PARAM_INT);
            $command->bindValue(':users_knights_id1', $this->user_data['knights']->id, PDO::PARAM_INT);
            $this->user_data['knights_new_friends'] = $command->queryAll();
            //Load last messages
            $this->user_data['new_messages'] = Messages::getNewMessages(Yii::app()->user->users_id);
            //Load all attributes name attributes
            $this->app_data['attribute_list'] = Constants::model()->findAll('type=:type', array(':type' => Constants::KNIGHTS_ATTRIBUTES));
        }
        return true;
    }
 public function actionIndex()
 {
     $data = array();
     //Load totalknights by letter
     $data['yellow_pages_total'] = YellowPagesTotal::model()->with('letter0')->findAll();
     //Load last 10 knights
     $data['last_knights_suscribe'] = Knights::model()->findAll(array('condition' => 'status != :status_pending AND unsuscribe_date IS NULL', 'params' => array(':status_pending' => Knights::STATUS_PENDING_VALIDATION), 'order' => 'suscribe_date DESC', 'limit' => 9));
     $this->render('index', $data);
 }
 /**
  * Load a users_id and knights_id from validete account
  * @param unknown_type $users_id
  * @param unknown_type $knights_id
  */
 public function autenticateFromValidateAccount()
 {
     $user = Users::model()->findByAttributes(array('email' => $this->username));
     if ($user === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         //No hace falta comprobar el password ya que en teoría viene de activar la cuenta
         //Load id of user
         $this->setState('users_id', $user->id);
         //$this->_users_id = $user->id;
         //load knight id
         $knight = Knights::model()->find('users_id=:users_id', array(':users_id' => $user->id));
         //$this->_knights_id = $knight->id;
         $this->setState('knights_id', $knight->id);
         $this->setState('knights_name', $knight->name);
         $this->errorCode = self::ERROR_NONE;
     }
     return !$this->errorCode;
 }
 /**
  * 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;
 }
 public function actionAccountActivation2()
 {
     $template = 'accountActivation';
     $data = array('knights' => Knights::model()->find('id=:id', array(':id' => 1)));
     $model = new LoginForm();
     $model->attributes = array('username' => '*****@*****.**', 'password' => 'nolosabemos');
     //Check if all is ok
     if (!$model->loginFromValidation()) {
         $template = 'error';
         $data['message'] = 'Se ha producido un error al validar la cuenta. Escribenos un correo a ' . Yii::app()->params['adminEmail'];
     }
     //Display index
     $this->render($template, $data);
 }
 /**
  * Desqualify a rival. Knight win combat by desqualify
  */
 public function actionDesqualifyRival()
 {
     $output = array('errno' => 1, 'html' => '', 'isDesqualify' => false);
     //Check session is enable
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0) {
             //Check combat
             if ($combat = Combats::model()->with(array('combatsPrecombat', 'rounds', array('fromKnight' => array('with' => array('knightsCard'))), array('toKnight' => array('with' => 'knightsCard'))))->findByPk($_GET['combat'])) {
                 //Check if user is in combat
                 if ($combat->fromKnight->id == Yii::app()->user->knights_id || $combat->toKnight->id == Yii::app()->user->knights_id) {
                     //Check if combat is enable
                     if ($combat->status == Combats::STATUS_ENABLE) {
                         //Check last round
                         if ($round_data = RoundsData::model()->find('rounds_combats_id = :combats_id AND rounds_number = :rounds_id AND knights_id = :knights_id', array(':combats_id' => $combat->id, ':rounds_id' => count($combat->rounds), ':knights_id' => Yii::app()->user->knights_id))) {
                             //Check time of desqualify
                             $timeLimit = strtotime($round_data->date) + Yii::app()->params['desqualifyTime'];
                             $requestTime = strtotime('now');
                             Yii::trace('[CHARACTER][actionDesqualifyRival] Check limit time of desqualify request (' . $requestTime . ') > $timelimit (' . $timeLimit . ') ');
                             if ($requestTime >= $timeLimit) {
                                 //Finish combat
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FINISH COMBAT  ');
                                 $output['isDesqualified'] = true;
                                 $combat->status = Combats::STATUS_FINISHED;
                                 $combat->result_by = Combats::RESULT_BY_DESQUALIFY;
                                 //Load round and knights
                                 $round = Rounds::model()->find('combats_id=:combats_id AND number=:number', array(':combats_id' => $combat->id, ':number' => count($combat->rounds)));
                                 if (Yii::app()->user->knights_id == $combat->from_knight) {
                                     $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_FROM_KNIGHT_WIN;
                                     $fromKnight =& $this->user_data['knights'];
                                     $toKnight = Knights::model()->findByPk($combat->toKnight->id);
                                 } else {
                                     $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_TO_KNIGHT_WIN;
                                     $fromKnight = Knights::model()->findByPk($combat->fromKnight->id);
                                     $toKnight =& $this->user_data['knights'];
                                 }
                                 /*
                                  * Update round and combat
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update round and combat  ');
                                 if (!$round->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el round');
                                 }
                                 if ($combat->save()) {
                                     //Update combat cache
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['combat'] . $combat->id, $combat, Yii::app()->params['cachetime']['combat']);
                                 } else {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el combate');
                                 }
                                 /*
                                  * Update knights to ready to challenge 
                                  */
                                 $fromKnight->endurance = ($combat->fromKnight->knightsCard->will + $combat->fromKnight->knightsCard->constitution) * 3;
                                 $fromKnight->life = $combat->fromKnight->knightsCard->constitution * 2;
                                 $fromKnight->status = Knights::STATUS_ENABLE;
                                 $toKnight->endurance = ($combat->toKnight->knightsCard->will + $combat->toKnight->knightsCard->constitution) * 3;
                                 $toKnight->life = $combat->toKnight->knightsCard->constitution * 2;
                                 $toKnight->status = Knights::STATUS_ENABLE;
                                 /*
                                  *Calcula postcombat 
                                  */
                                 //Calculate experience
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] CALCULATE EXPERIENCE');
                                 $precombat = $combat->combatsPrecombat;
                                 $postcombatData = CombatsPostcombat::calculateEarnedExperience($combat, $combat->fromKnight->level, $combat->toKnight->level);
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] SAVE POSTCOMBATS');
                                 $from_knight_post_combat = new CombatsPostcombat();
                                 $from_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->fromKnight->id, 'knight_rival_level' => $combat->fromKnight->level, 'experience_generate' => $postcombatData['from_knight_experience_generate'], 'percent_by_result' => $postcombatData['from_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['from_knight_percent_by_injury'], 'earned_experience' => $postcombatData['from_knight_earned_experience'], 'total_experience' => $combat->fromKnight->experiencie_earned + $postcombatData['from_knight_earned_experience'], 'total_coins' => $precombat->from_knight_gate + $combat->fromKnight->coins, 'earned_coins' => $precombat->from_knight_gate, 'injury_type' => null);
                                 if (!$from_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para from knight', 'error');
                                 }
                                 $to_knight_post_combat = new CombatsPostcombat();
                                 $to_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->toKnight->id, 'knight_rival_level' => $combat->toKnight->level, 'experience_generate' => $postcombatData['to_knight_experience_generate'], 'percent_by_result' => $postcombatData['to_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['to_knight_percent_by_injury'], 'earned_experience' => $postcombatData['to_knight_earned_experience'], 'total_experience' => $combat->toKnight->experiencie_earned + $postcombatData['to_knight_earned_experience'], 'total_coins' => $precombat->to_knight_gate + $combat->toKnight->coins, 'earned_coins' => $precombat->to_knight_gate, 'injury_type' => null);
                                 if (!$to_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para to knight', 'error');
                                 }
                                 //Update experience of knights
                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EXPERIECE');
                                 $fromKknight->experiencie_earned = $from_knight_post_combat->total_experience;
                                 $toKnight->experiencie_earned = $to_knight_post_combat->total_experience;
                                 /*
                                  * Calculate repair prize equipment
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival]CALCULATE REPAIR PRIZE');
                                 $from_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->fromKnight);
                                 if ($from_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] FROM KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 $to_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->toKnight);
                                 if ($to_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] TO KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 /*
                                  * Update coins of knights
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE COINS OF KNIGHTS');
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FROM_KNIGHT earned coins: current coinds(' . $combat->fromKnight->coins . ') + gate coins (' . $precombat->from_knight_gate . ') - autorrepair coins (' . $from_knight_autorepair['repair_cost'] . ') ');
                                 $fromKnight->coins += $precombat->from_knight_gate - $from_knight_autorepair['repair_cost'];
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] TO_KNIGHT earned coins: current coinds(' . $toKnight->coins . ') + gate coins (' . $precombat->to_knight_gate . ') - autorrepair coins (' . $to_knight_autorepair['repair_cost'] . ') ');
                                 $toKnight->coins += $precombat->to_knight_gate - $to_knight_autorepair['repair_cost'];
                                 /*
                                  * Update healings of knights
                                  */
                                 if ($combat->fromKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for from knigth');
                                     $healing = Healings::model()->findByPk($combat->fromKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update from knight next healing date', 'error');
                                     }
                                 }
                                 if ($combat->toKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for to knigth');
                                     $healing = Healings::model()->findByPk($combat->toKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update to knight next healing date', 'error');
                                     }
                                 }
                                 /*
                                  * STATS
                                  * Update stats of knights and platform
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update stats');
                                 $from_knight_stats = KnightsStats::model()->findByPk($combat->fromKnight->id);
                                 $to_knight_stats = KnightsStats::model()->findByPk($combat->toKnight->id);
                                 $from_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $fromKnight->id, ':opponent' => $toKnight->id));
                                 $to_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $toKnight->id, ':opponent' => $fromKnight->id));
                                 if (!$from_knight_stats_vs) {
                                     $from_knight_stats_vs = new KnightsStatsVs();
                                     $from_knight_stats_vs->attributes = array('knights_id' => $combat->fromKnight->id, 'opponent' => $combat->toKnight->id, 'money_total_earned' => 0);
                                 }
                                 if (!$to_knight_stats_vs) {
                                     $to_knight_stats_vs = new KnightsStatsVs();
                                     $to_knight_stats_vs->attributes = array('knights_id' => $combat->toKnight->id, 'opponent' => $combat->fromKnight->id, 'money_total_earned' => 0);
                                 }
                                 $from_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $fromKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 $to_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $toKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 if (!$from_knight_stats_by_date) {
                                     $from_knight_stats_by_date = new KnightsStatsByDate();
                                     $from_knight_stats_by_date = array('knights_id' => $combat->fromKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if (!$to_knight_stats_by_date) {
                                     $to_knight_stats_by_date = new KnightsStatsByDate();
                                     $to_knight_stats_by_date = array('knights_id' => $combat->toKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if ($combat->result == Combats::RESULT_FROM_KNIGHT_WIN) {
                                     $from_knight_stats->combats_wins += 1;
                                     $from_knight_stats_vs->combats_wins += 1;
                                     $from_knight_stats_by_date->combats_wins += 1;
                                     $to_knight_stats->combats_loose += 1;
                                     $to_knight_stats_vs->combats_loose += 1;
                                     $to_knight_stats_by_date->combats_loose += 1;
                                 } else {
                                     if ($combat->result == Combats::RESULT_TO_KNIGHT_WIN) {
                                         $to_knight_stats->combats_wins += 1;
                                         $to_knight_stats_vs->combats_wins += 1;
                                         $to_knight_stats_by_date->combats_wins += 1;
                                         $from_knight_stats->combats_loose += 1;
                                         $from_knight_stats_vs->combats_loose += 1;
                                         $from_knight_stats_by_date->combats_loose += 1;
                                     } else {
                                         $to_knight_stats->combats_draw += 1;
                                         $to_knight_stats_vs->combats_draw += 1;
                                         $to_knight_stats_by_date->combats_draw += 1;
                                         $from_knight_stats->combats_draw += 1;
                                         $from_knight_stats_vs->combats_draw += 1;
                                         $from_knight_stats_by_date->combats_draw += 1;
                                     }
                                 }
                                 //stats desquality
                                 if (Yii::app()->user->knights_id == $combat->fromKnight->id) {
                                     $from_knight_stats->desquality_produced += 1;
                                     $to_knight_stats->desquality_received += 1;
                                 } else {
                                     $from_knight_stats->desquality_received += 1;
                                     $to_knight_stats->desquality_produced += 1;
                                 }
                                 //stats money
                                 $from_knight_stats->money_total_earned += $precombat->from_knight_gate;
                                 $to_knight_stats->money_total_earned += $precombat->to_knight_gate;
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE STATS ');
                                 if (!$from_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de from knight', 'error');
                                 }
                                 if (!$from_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de from knight stats', 'error');
                                 }
                                 if (!$from_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística por dia de from knight stats', 'error');
                                 }
                                 if (!$to_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística diarias de to knight', 'error');
                                 }
                                 //UPDATE knights
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update knights ');
                                 if (!$fromKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero from knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight->name, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 if (!$toKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero to knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 //Show desqualify
                                 $desqualifyKnight = Yii::app()->user->knights_id == $combat->fromKnight->id ? $combat->fromKnight->name : $combat->toKnight->name;
                                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_desqualified_by.php', array('desqualifiedKnight' => $desqualifyKnight), true);
                                 $output['errno'] = 0;
                             } else {
                                 $output['html'] = 'Todavía no ha pasado el tiempo para que le puedas descalificar. Faltan ' . ($timeLimit - $requestTime) . ' segundos.';
                             }
                         } else {
                             $output['html'] = 'No puedes descalificar a tu adversario si no has enviado los datos para la última ronda.';
                         }
                     } else {
                         $output['html'] = 'Este combate no está en curso.';
                     }
                 } else {
                     $output['html'] = 'No puedes toquetear combates que no son tuyos.';
                 }
             } else {
                 $output['html'] = 'No se ha encontrado el combate.';
             }
         } else {
             $output['html'] = 'El identificador del combate no es válido.';
         }
     } else {
         $output['html'] = 'La sesión ha expirado. Necesitas volver a hacer login.';
     }
     //Show output
     echo CJSON::encode($output);
 }
 /**
  * This function pay for all jobs in working and date is expired.
  * This function is a cronjob. Only use for cron
  * Identificator job: 1
  */
 public function actionPayJobs()
 {
     $controlCronJobId = 1;
     //Find all jobs for to pay
     Yii::trace('[JOBS][actionPayJobs] Pay jobs finished before' . date("Y-m-d H:i:s"));
     $jobs_list = Jobs::model()->findAll('status = :status AND date <= :date', array(':status' => Jobs::STATUS_WORKING, 'date' => date("Y-m-d H:i:s")));
     Yii::trace('[JOBS][actionPayJobs] Pay jobs (' . count($jobs_list) . ')');
     if (count($jobs_list) > 0) {
         //Load cache of knights
         $app_rule_level = AppRulesLevel::model()->findAll(array('index' => 'level'));
         foreach ($jobs_list as $job) {
             //Update Knight
             $knight = Knights::model()->findByPk($job->knights_id);
             $knight->coins += $job->hours * $app_rule_level[$job->knight_level]->cache;
             //Check status of knight
             if (Inventory::checkIfPrimaryEquipmentIsCompleted($knight->id)) {
                 $knight->status = Knights::STATUS_ENABLE;
             } else {
                 $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT;
             }
             if (!$knight->save()) {
                 Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el caballero con sus rupias nuevas.');
             }
             //Update job
             $job->status = Jobs::STATUS_PAYED;
             if (!$job->save()) {
                 Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el trabajo con el status "pagado".');
             }
             //Create event for knight
             $event = new KnightsEvents();
             $event->attributes = array('knights_id' => $job->knights_id, 'type' => KnightsEvents::TYPE_JOB, 'identificator' => $job->id);
             if (!$event->save()) {
                 Yii::trace('[JOBS][actionPayJobs] No se ha podido guardar un evento nuevo.', 'error');
             }
             //Update old event
             $lastEvent = KnightsEventsLast::getOldLastEvent($job->knights_id);
             $lastEvent->type = KnightsEvents::TYPE_JOB;
             $lastEvent->identificator = $job->id;
             $lastEvent->date = date('Y-m-d H:i:s');
             if (!$lastEvent->save()) {
                 Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el último evento más viejo.', 'error');
             }
             //Update stats and  stats by day with coins earned.
             $knight_stats = KnightsStats::model()->findByPk($job->knights_id);
             if ($knight_stats) {
                 $knight_stats->money_total_earned += $job->hours * $app_rule_level[$job->knight_level]->cache;
                 if (!$knight_stats->save()) {
                     Yii::trace('[JOBS][actionPayJobs] No se han podido actualizar las estadisticas del caballero', 'error');
                 }
             } else {
                 Yii::trace('[JOBS][actionPayJobs] No hay stats del caballero', 'error');
             }
             $knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $job->knights_id, 'date' => substr($job->date, 0, 10)));
             if (!$knight_stats) {
                 $knight_stats_by_date = new KnightsStatsByDate();
                 $knight_stats_by_date->attributes = array('knights_id' => $job->knights_id, 'date' => substr($job->date, 0, 10));
             }
             $knight_stats_by->money_total_earned += $job->hours * $app_rule_level[$job->knight_level]->cache;
             if (!$knight_stats_by_date->save()) {
                 Yii::trace('[JOBS][actionPayJobs] No se han podido actualizar las estadisticas por día del caballero', 'error');
             }
         }
     }
 }
 /**
  * Return JSON with results for header search
  */
 public function actionHeaderSearch()
 {
     //Init
     $output = array('errno' => 1, 'html' => '');
     //Check input
     if (isset($_GET['value']) && $_GET['value'] != '') {
         //Check value of input
         if (preg_match(Knights::PATTERN_FOR_SEARCH_NAME, $_GET['value'])) {
             //Search knights
             $knightList = Knights::model()->findAll(array('condition' => 'name LIKE :name', 'params' => array(':name' => $_GET['value'] . "%"), 'limit' => '10'));
             //$knightList = Knights::model()->findAll('name like :name',array(':name'=>"3"));
             if (count($knightList) > 0) {
                 //Make  html
                 foreach ($knightList as $knight) {
                     $output['html'] .= $this->renderPartial('_view_header_search_bar', array('knight' => $knight), true);
                 }
             } else {
                 $output['html'] = '<p>No hay resultados para "' . $_GET['value'] . '"</p>';
             }
             $output['errno'] = 0;
         } else {
             //
             $output['html'] = '<p>Los nombres tienen que empezar por una letra o un número.</p>';
         }
     } else {
         $output['html'] = '<p>Valor vacio</p>';
     }
     echo CJSON::encode($output);
 }