<?php

// -------------------------------------------------------------------------------------------------
class ListopiaUser extends ListopiaAuth // extends ListopiaCore
{
  // -----------------------------------------------------------------------------------------------
  public function echoUserName()
  {
    $sesh = Session::getInstance();
    if (isset($sesh->gl_loggedin))
    {
      echo $sesh->gl_username;
    }
    else
    {
      FB::error("[Listopia] echoUserName - not logged in");
      echo "Unknown";
    }
  }
  
  // -----------------------------------------------------------------------------------------------
  public function getUnreadMessagesCount($userID)
  {
    $query = $this->ldb->query("select count(*) as new_messages from messages where mess_to = ".((int)$userID)." and mess_to_status = 'unread'");
    if (empty($query[0]))
      return 0;
    
    return $query[0][0]['new_messages'];
  }
  
  // -----------------------------------------------------------------------------------------------
  public function getUserThumbKarma($userID, $stats) 
  {
    $dateCreated = date_parse($stats['created']);
  
    $thumbs = array();
    $thumbs['given']['like'] = 0;
    $thumbs['given']['hate'] = 0;
    $thumbs['received']['like'] = 0;
    $thumbs['received']['hate'] = 0;
    $thumbs['karma'] = 'Unclassifiable';
    
    $query = $this->ldb->query("select vote, count(*) as count from itemlikes where user_id = ".((int)$userID)." group by vote", false, false);
    
    if (!empty($query[0]))
    {
      $thumbs['given'][$query[0]['vote']] = $query[0]['count'];
    }
    if (!empty($query[1]))
    {
      $thumbs['given'][$query[1]['vote']] = $query[1]['count'];
    }
    
    $query = $this->ldb->query("select vote, count(*) as count from itemlikes where createdby = ".((int)$userID)." group by vote", false, false);

    if (!empty($query[0]))
    {
      $thumbs['received'][$query[0]['vote']] = $query[0]['count'];
    }
    if (!empty($query[1]))
    {
      $thumbs['received'][$query[1]['vote']] = $query[1]['count'];
    }
    
    $gUP = intval($thumbs['given']['like']);
    $gDN = intval($thumbs['given']['hate']);
    $rUP = intval($thumbs['received']['like']);
    $rDN = intval($thumbs['received']['hate']);
    
    // figure out some stats to give the user a 'rating'
    if ($gUP < 10 && $gDN < 10 && $rUP < 10 && $rDN < 10)
    {
      $thumbs['karma'] = "Fresh Meat";
    }
    else
    {
      $analysis = array();
    
      if ($gDN > $gUP)
      {
        // person is a bit crappy
        array_push($analysis, "Miserable");
        
        // person is really crappy. this is pretty rare
        $hateRatio = (($gDN + 1.0) / ($gUP + 1.0));
        if ($hateRatio > 1.5)
          array_push($analysis, "Dismal Cunt");
      }
      else
      {
        // person is basically good
        if ($dateCreated['year'] <= 2008)
          array_push($analysis, "Veteran");
        else if ($dateCreated['year'] <= 2009)
          array_push($analysis, "Pioneer");
        else if ($dateCreated['year'] <= 2011)
          array_push($analysis, "Evergreen");
        else 
          array_push($analysis, "Contributor");
      
        // add a rating based on the number of given/recv thumbs they've got
        $postLevels = array(
          500  => "Bright Eyes",
          1000 => "Fresh Breath",
          2000 => "Winning Smile",
          4000 => "Firm Buttocks",
          5000 => "Pert Breasts",
          7000 => "Fabulous Genitals"
          );
        array_push($analysis, closestKeyNumberInArray($postLevels, max($gUP, $rUP)) );

        if ($rUP > 10000)
        {
          array_push($analysis, "Priceless");
        }
        else if ($rUP > 7500)
        {
          array_push($analysis, "Artisan");
        }
        
        if ($gUP > 10000)
        {
          array_push($analysis, "Honourable");
        }
        else if ($gUP > 7500)
        {
          array_push($analysis, "Bounteous");
        }
        
        if ($gUP + $rUP > 20000)
        {
          array_push($analysis, "Elite");
        }
        else if ($gUP + $rUP > 15000)
        {
          array_push($analysis, "Paragon");
        }
        else if ($gUP + $rUP > 10000)
        {
          array_push($analysis, "Adept");
        }        
        
        if ($stats['lists'] >= 100)
        {
          array_push($analysis, "Architect");
        }
        else if ($stats['lists'] >= 50)
        {
          array_push($analysis, "Prolific");
        }
        else if ($stats['lists'] >= 25)
        {
          array_push($analysis, "Inventor");
        }
        
        if ($stats['views'] > 20000)
        {
          array_push($analysis, "Drenched");
        }
        else if ($stats['views'] > 10000)
        {
          array_push($analysis, "Saturated");
        }
        else if ($stats['views'] > 5000)
        {
          array_push($analysis, "Immersed");
        }
        
        // if the give/recv delta is big enough, work out a rating based on the difference
        $grDelta = abs($gUP - $rUP);
        if ($grDelta > 250)
        {
          $likeRatio = (($gUP + 1.0) / ($rUP + 1.0));
          if ($likeRatio > 1.1)
            if ($likeRatio > 1.5)
              if ($likeRatio > 2.0)
                array_push($analysis, "Tantric");
              else
                array_push($analysis, "Erogenous");
            else
              array_push($analysis, "Generous Lover");
          else
            if ($likeRatio < 0.9)
              if ($likeRatio < 0.5)
                if ($likeRatio < 0.25)
                  if ($likeRatio < 0.1)
                    array_push($analysis, "Rapacious");
                  else
                    array_push($analysis, "Thumb Suckah");
                else
                  array_push($analysis, "Scrooge McDuck");
              else
                array_push($analysis, "Thumb Thief");
        }
      }
      
      shuffle ($analysis);
      $thumbs['karma'] = implode(". ", $analysis) . ".";
    }
    
    return $thumbs;
  }
  
  // -----------------------------------------------------------------------------------------------
  public function getUserThumbExchange($userA, $userB) 
  {
    $thumbs = array();
    $thumbs['a2b']['like'] = 'none';
    $thumbs['a2b']['hate'] = 'none';
    $thumbs['b2a']['like'] = 'none';
    $thumbs['b2a']['hate'] = 'none';

    $query = $this->ldb->query("select vote, count(*) as count from itemlikes where user_id = ".((int)$userA)." and createdby = ".((int)$userB)." group by vote", false, false);
    
    if (!empty($query[0]))
    {
      $thumbs['a2b'][$query[0]['vote']] = intval($query[0]['count'] > 0) ? ($query[0]['count']) : 'none';
    }
    if (!empty($query[1]))
    {
      $thumbs['a2b'][$query[1]['vote']] = intval($query[1]['count'] > 0) ? ($query[1]['count']) : 'none';
    }

    $query = $this->ldb->query("select vote, count(*) as count from itemlikes where user_id = ".((int)$userB)." and createdby = ".((int)$userA)." group by vote", false, false);

    if (!empty($query[0]))
    {
      $thumbs['b2a'][$query[0]['vote']] = intval($query[0]['count'] > 0) ? ($query[0]['count']) : 'none';
    }
    if (!empty($query[1]))
    {
      $thumbs['b2a'][$query[1]['vote']] = intval($query[1]['count'] > 0) ? ($query[1]['count']) : 'none';
    }
    
    return $thumbs;
  }
  
  // -----------------------------------------------------------------------------------------------
  function getUserStats($userID)
  {
    $stats = array(
      'created' => 0,
      'last_login' => 0,
      'views' => 0,
      'lists' => 0,
      'items' => 0,
      'discussions' => 0,
      'faveday' => 'Unknown'
    );
    
    // timestamps
    $query = $this->ldb->select(array(
                        'fields' => 'users.user_created, users.user_last_login',
                        'table' => 'users',
                        'condition' => 'users.user_id = '.((int)$userID),
                        'limit' => 1
                        ));
    $query = $query[0];
    if (!empty($query))
    {
      $stats['created'] = $query['users']['user_created'];
      $stats['last_login'] = $query['users']['user_last_login'];
    }

    // logged visits
    $query = $this->ldb->select(array(
                        'fields' => 'sum(last_visits.visit_count) as counter',
                        'table' => 'last_visits',
                        'condition' => 'last_visits.user_id = '.((int)$userID),
                        'limit' => 1
                        ));
    $query = $query[0];                        
    if (!empty($query) && isset($query[0]['counter']))
      $stats['views'] = $query[0]['counter'];
      
    // lists made
    $query = $this->ldb->select(array(
                        'fields' => 'count(*) as counter',
                        'table' => 't_lists',
                        'condition' => 't_lists.list_createdby = '.((int)$userID),
                        'limit' => 1
                        ));
    $query = $query[0];
    if (!empty($query))
      $stats['lists'] = $query[0]['counter'];      
    
    // things posted
    $query = $this->ldb->select(array(
                        'fields' => 'count(*) as counter',
                        'table' => 't_items',
                        'condition' => 't_items.item_createdby = '.((int)$userID),
                        'limit' => 1
                        ));
    $query = $query[0];
    if (!empty($query))
      $stats['items'] = $query[0]['counter'];
    
    // comments posted
    $query = $this->ldb->select(array(
                        'fields' => 'count(*) as counter',
                        'table' => 't_discussion',
                        'condition' => 't_discussion.disc_user = '.((int)$userID),
                        'limit' => 1
                        ));
    $query = $query[0];
    if (!empty($query))
      $stats['discussions'] = $query[0]['counter'];
    
    $query = $this->ldb->select(array(
                        'fields' => 'count(*) as counter, weekday(t_items.item_created) as dayg',
                        'table' => 't_items',
                        'condition' => 't_items.item_createdby = '.((int)$userID),
                        'group' => 'dayg',
                        'order' => 'counter desc'
                        ));
    $query = $query[0];
    if (!empty($query))
    {
      // SQL docs: (0 = Monday, 1 = Tuesday, � 6 = Sunday).
      $days = array(
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday');
      
      $stats['faveday'] = $days[ $query[0]['dayg'] ];
    }

    return $stats;
  }
  
  // -----------------------------------------------------------------------------------------------
  function getUserMostRecentPost($userID)
  {
    $query = $this->ldb->select(array(
                        'fields' => 't_items.item_extra, t_items.item_blurb, t_items.item_created, t_items.item_id, t_lists.list_id, t_lists.list_headline',
                        'table' => 't_items',
                        'join' => 't_lists on t_lists.list_id = t_items.item_list',
                        'condition' => 't_items.item_createdby = '.((int)$userID),
                        'order' => 't_items.item_created desc',
                        'limit' => 1
                        ));
    return $query[0];
  }
  
  // -----------------------------------------------------------------------------------------------
  function getUserFirstPost($userID)
  {
    $query = $this->ldb->select(array(
                        'fields' => 't_items.item_extra, t_items.item_blurb, t_items.item_created, t_items.item_id, t_lists.list_id, t_lists.list_headline',
                        'table' => 't_items',
                        'join' => 't_lists on t_lists.list_id = t_items.item_list',
                        'condition' => 't_items.item_createdby = '.((int)$userID),
                        'order' => 't_items.item_created asc',
                        'limit' => 1
                        ));
    return $query[0];
  }  
  
  // -----------------------------------------------------------------------------------------------
  function getUserGradedPosts($userID, $ascdesc)
  {
    $query = $this->ldb->select(array(
                        'fields' => 't_lists.list_id, t_lists.list_headline, t_lists.list_type, t_items.item_extra, t_items.item_id, t_items.item_blurb, (t_items.item_votesup - t_items.item_votesdown) as score',
                        'table' => 't_items',
                        'join' => 't_lists on t_lists.list_id = t_items.item_list',
                        'condition' => DBQ_CONDITION_PUBLIC_LIST.'and t_items.item_createdby = '.((int)$userID),
                        'order' => 'score '.$ascdesc,
                        'limit' => 20
                        ));
    return $query;
  }  

  // -----------------------------------------------------------------------------------------------
  function userHasAnyComments($userID)
  {
    $query = $this->ldb->select(array(
                        'fields' => 't_discussion.disc_user',
                        'table' => 't_discussion',
                        'condition' => 't_discussion.disc_user = '.((int)$userID),
                        'limit' => 1
                        ));

    return !empty($query[0]);
  }
  
  // -----------------------------------------------------------------------------------------------
  function emitUserMostRecentDiscussions($userID, $limit)
  {
    $query = $this->ldb->select(array(
                        'fields' => 't_discussion.disc_comment, t_items.item_blurb, t_items.item_id, t_items.item_list, t_lists.list_headline',
                        'table' => 't_discussion',
                        'join' => 't_items on t_items.item_id = t_discussion.disc_item join t_lists on t_items.item_list = t_lists.list_id',
                        'condition' => 't_discussion.disc_user = '.((int)$userID),
                        'order' => 't_discussion.disc_datetime desc',
                        'limit' => ((int)$limit)
                        ));
                        
    printf("<div id='recent_comments'>");
    $firstEntry = null;
    
    foreach ($query as &$dsc)
    {
      if ($firstEntry != null)
        print("<div style='border-top:1px dashed #ddd';><br>");
      
      $content = ConditionCommentForDisplay($this->ldb, $dsc['t_discussion']['disc_comment']);
      printf("<p>&quot;%s&quot;</p>", $content);

      printf("<p style='text-align:right; font-size:0.9em;'><a %s>%s</a> on <a %s>%s</a></p>", 
        ListLink($dsc['t_items']['item_list'], "#entry_" . $dsc['t_items']['item_id']), 
        Truncate(stripslashes($dsc['t_items']['item_blurb']), 60),
        ListLink($dsc['t_items']['item_list'], "#PageContent"), 
        stripslashes($dsc['t_lists']['list_headline']));

      if ($firstEntry != null)
        print("</div>");
      $firstEntry = $dsc;
    }
  }
  
  // -----------------------------------------------------------------------------------------------
  function getUserListPersmission($listID)
  {
    $authResult = array();
    
    if ($this->isLoggedIn())
    {
      $query = $this->ldb->select(array(
                    'table' => 't_lists',
                    'condition' => 't_lists.list_id = '.((int)$listID),
                    'limit' => 1
                    ));
      if (empty($query[0]))
        $authResult['reason'] = 'list not found';
      
      // while we're rifling through the lists, return the max-chars & sort mode, as the Add tab will need it anyway
      $listMaxChars = $query[0]['t_lists']['list_maxchars'];
      $authResult['maxchars'] = (empty($listMaxChars)) ? 0 : $listMaxChars;
      $authResult['orderby'] = $query[0]['t_lists']['list_orderby'];
       
      $listFeat     = $query[0]['t_lists']['list_featured'];
      $listSub      = $query[0]['t_lists']['list_submission'];
      $listCreated  = $query[0]['t_lists']['list_createdby'];
      $listType     = $query[0]['t_lists']['list_type'];
      $listSealed   = $query[0]['t_lists']['list_sealed'] == 1;

      $listWasMadeByMe = ($listCreated == Session::getInstance()->gl_userid);

      // you are king, you can do anything
      if ($this->isAdminUser())
        $authResult['allowed'] = true;
      
      if ($listSealed)
      {
        $authResult['reason'] = 'The list is sealed, you cannot add to it. I am so, SO sorry.';
        $authResult['allowed'] = false;      
      }
      
      // locked down
      else if ($listFeat == 'deleted') 
      {
        $authResult['reason'] = 'list is dead';
        $authResult['allowed'] = false;
      }
        
      else if ($listType == 'video') 
        $authResult['reason'] = 'video lists are closed for business';

      else if ($listSub != 'members' && !$listWasMadeByMe) 
        $authResult['reason'] = 'author only';

      // essentially open to all (logged in)
      else if ($listFeat != 'only you') 
        $authResult['allowed'] = true;
      
      // open only to the creator
      else if ($listFeat == 'only you' && $listWasMadeByMe) 
        $authResult['allowed'] = true;
      else
        $authResult['reason'] = 'only open to the list author';
    }
    
    return $authResult;
  }
  
  // -----------------------------------------------------------------------------------------------
  function setOrUpdateUserAvatar($userID, $imageData)
  {
    $imgPrefix = "data:image/png;base64";
    if (strncmp($imageData, $imgPrefix, strlen($imgPrefix)) != 0)
      return false;
  
    // check to see if it already exists
    $query = $this->ldb->select(array(
                            'table' => 'avatars',
                            'condition' => 'userid = '.((int)$userID),
                            'limit' => 1
                            ));
    if (!empty($query[0]))
    {
      $data = array(
        'imagedata'     => $imageData
      );
      $innerResult = $this->ldb->update('avatars', $data, 'userid = '.((int)$userID));
    }
    else
    {
      $data = array(
        'userid'        => array((int)$userID),
        'imagedata'     => $imageData
      );
      $innerResult = $this->ldb->insert('avatars', $data);
    }
    
    return $innerResult;
  }
  
  // -----------------------------------------------------------------------------------------------
  function isUserAbleToEditNewsPage()
  {
    if ($this->isLoggedIn())
    {
      if ($this->isAdminUser())
        return true;
      if (Session::getInstance()->gl_userid == 101) // Kodiak can News it up
        return true;
    }
    return false;
  }
}
