/**
  *checks if the user has finished viewing the advert
  * if so records advert as has been visited and decrements the display value
  * if display has reached 0 then advert is removed from session
  * This method is called from javascript and prints OK on success or
  * prints ERROR on failure
  */
 public function checkAction()
 {
     $end = time();
     $state = 'OK';
     $session = new Zend_Session_NameSpace('user');
     //check if the user has started viewing an advert
     if ($session->timer == null || !isset($session->timer->advertID)) {
         $state = 'ERROR';
     } else {
         if ($end - $session->timer->start < $session->timer->interval) {
             $state = 'ERROR';
         } else {
             foreach ($session->adverts as $key => $advert) {
                 if ($advert->advertID == $session->timer->advertID) {
                     //log that the user has visted this advert on this day
                     $log = array('advertID' => $advert->advertID, 'userID' => $session->user->accountID, 'clickedDate' => date('Y-m-d'));
                     $history = new Advert_Models_AdvertHistory($log);
                     $history->save();
                     //update users balance
                     $session->user->balance += $session->user->role->ppc;
                     $session->user->update(array());
                     //unset to stop replay of viewing advert more than once
                     unset($session->timer->advertID);
                     unset($session->timer->start);
                     $advert->display -= 1;
                     break;
                 }
             }
         }
     }
     $this->getHelper('viewRenderer')->setNoRender();
     print $state;
 }
 public function indexAction()
 {
     //make sure the user is logged in
     $session = new Zend_Session_Namespace('user');
     if ($session->user == null) {
         $this->_redirect('/user');
         return;
     }
     //get and assign user adverts if they already haven't been assigned
     if ($session->adverts == null) {
         //get available adverts
         $adverts = Advert_Models_Advert::getAdvertsForDisplay(4);
         //assigned the adverts to the user
         $session->adverts = $adverts;
         //log that the adverts were assigned to this user but have not been click yet
         foreach ($adverts as $advert) {
             $log = array('advertID' => $advert->advertID, 'userID' => $session->user->accountID, 'assignedDate' => date('Y-m-d'));
             $history = new Advert_Models_AdvertHistory($log);
             for ($i = 0; $i < $advert->display; $i++) {
                 $history->save();
             }
         }
     }
     //make adverts accessible in the view
     $this->view->adverts = $session->adverts;
 }