/**
  * 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 html for to show in dialog
  */
 public function actionConfirmAcceptChallenge()
 {
     $output = array('errno' => 1, 'html' => '');
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0) {
             //Check if combat exit
             if ($combat = Combats::model()->findByPk($_GET['combat'])) {
                 //Check who is rival
                 $rival = $combat->toKnight->id == Yii::app()->user->knights_id ? $combat->fromKnight : $combat->toKnight;
                 //Check if rival is online
                 //if( Sessions::model()->exists( 'users_id = :users_id AND expire > :expire', array(':users_id'=>$rival->users_id,':expire'=>time())) ){
                 if (Yii::app()->cache->get(Yii::app()->params['cacheKeys']['knight_connected'] . $rival->id)) {
                     //Check if rival is enable to combat
                     if ($combat->toKnight->id == Yii::app()->user->knights_id && $combat->toKnight->status == Knights::STATUS_ENABLE || $combat->fromKnight->id == Yii::app()->user->knights_id && $combat->fromKnight->status == Knights::STATUS_ENABLE) {
                         //Check if rival has minimum equipment
                         if (Inventory::checkIfPrimaryEquipmentIsCompleted($rival->id)) {
                             $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/confirmAcceptChallenge.php', array(), true);
                             $output['errno'] = 0;
                         } else {
                             $output['html'] = '<p>No puedes retar al caballero ahora mismo.</p><p>Al parecer le falta algún componente de su armadura y no puede combatir. Seguramente es una excusa para no perder ante ti. Vigílalo hasta que tenga el equipo completo y MACHÁCALO.</p>';
                         }
                     } else {
                         //Check if is working or at combat
                         if ($combat->toKnight->id == Yii::app()->user->knights_id && $combat->toKnight->status == Knights::STATUS_AT_WORK || $combat->fromKnight->id == Yii::app()->user->knights_id && $combat->fromKnight->status == Knights::STATUS_AT_WORK) {
                             $output['html'] = '<p>El adversario está trabajando y no puede combatir.</p>';
                         }
                         if ($combat->toKnight->id == Yii::app()->user->knights_id && $combat->toKnight->status == Knights::STATUS_AT_COMBAT || $combat->fromKnight->id == Yii::app()->user->knights_id && $combat->fromKnight->status == Knights::STATUS_AT_COMBAT) {
                             $output['html'] = '<p>El adversario está en otro combate y no puede combatir.</p>';
                         }
                     }
                 } else {
                     $output['html'] = '<p>¡Tu rival no está conectado!</p><p>Para poder resolver un combate los dos caballeros tienen que estar "online".</p><p>Puedes ver si un caballero está "online" si en la parte superior de su perfil sale como: "¡CONECTADO!"</p>';
                 }
             } else {
                 //Combat not exist
                 $output['html'] = '<p>El combate no existe.</p>';
             }
         } else {
             $output['html'] = '<p>El identificador del combate no es válido.</p>';
         }
     } else {
         $output['html'] = '<p>La sesión ha expirado. Necesitas volver a hacer login.</p>';
     }
     echo CJSON::encode($output);
 }
 /**
  * Cancel a jobs. Change status of job to cancelled and is not payed
  */
 public function actionCancel()
 {
     $data = array('errno' => 1, 'error' => '');
     //Check input
     if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
         //Find job
         if ($job = Jobs::model()->findByPk($_GET['id'])) {
             //Check if job belong to knight
             if ($job->knights_id == Yii::app()->user->knights_id && $job->status == Jobs::STATUS_WORKING) {
                 $job->status = Jobs::STATUS_CANCELLED;
                 if (!$job->save()) {
                     Yii::trace('[JOBS][actionCancel] El job ' . $job->id . ' no se puede actualizar.', 'error');
                 }
                 //Check status of knight
                 if (Inventory::checkIfPrimaryEquipmentIsCompleted($this->user_data['knights']->id)) {
                     $this->user_data['knights']->status = Knights::STATUS_ENABLE;
                 } else {
                     $this->user_data['knights']->status = Knights::STATUS_WITHOUT_EQUIPMENT;
                 }
                 if (!$this->user_data['knights']->save()) {
                     Yii::trace('[JOBS][actionCancel] No se puede actualizar el status del caballero a disponible', 'error');
                 }
             }
         }
     }
     //Redirect to job
     $this->redirect('/jobs');
 }