<?php

  function PrintListVoteHTML(Listopia $lst)
  {
    if ($lst->isLoggedIn() && !$lst->isUserOnProbation())
    {
      $listID = $_GET['id'];
      if (!isset($listID) || !is_numeric($listID))
        return;
      
      $listVotes = $lst->getListVote($listID);
      
      $thumbDownOnClick = " onclick='list_HandleListVote(this, false, $listID); return false;'";
      $thumbUpOnClick   = " onclick='list_HandleListVote(this, true, $listID); return false;'";
      $voteUp = sprintf("%02d", intval( $listVotes['upvote'] ));
      $voteDown = sprintf("%02d", -intval( $listVotes['downvote'] ));
        
$thumbHTML = <<<HTML
        <div style='margin-top:10px; padding-top:10px; border-top: 1px solid #DDD;'>
        Vote for this list:
        <div class='thumb-down'>
          <a class='button thumb-button' $thumbDownOnClick ><img src='images/thumb-dn.png' width=14 height=15/><span id='vote-down-the-list'>$voteDown</span></a>
        </div>
        
        <div class='thumb-up'>
          <a class='button thumb-button' $thumbUpOnClick ><span id='vote-up-the-list'>$voteUp</span><img src='images/thumb-up.png' width=14 height=15/></a>
        </div>
        <br>
        </div>
HTML;
      print($thumbHTML);
    }
  }
  
class SidebarBuilder
{
 
  // -----------------------------------------------------------------------------------------------
  public static function Welcome(Listopia $lst)
  {
    printf("<div>%s</div>", LS_WECLOME_HTML_MSG);
    
    if (!$lst->isLoggedIn())
      printf("Already a member? <a href='#StuffTab'>Go log in</a>.");
  }
  
  // -----------------------------------------------------------------------------------------------
  public static function AddToList(Listopia $lst)
  {
    if ($lst->isLoggedIn())
    {
      $listID = $_GET['id'];
      $listAddState = $lst->getUserListPersmission($listID);
      $isImageList = $lst->isImageList($listID);
      

      if ($listAddState['allowed'] == true)
      {
        if ($isImageList)
        {
          print("<p>Get yer art out - add a lovely picture</p>");
          print("<div style='text-align:center'>");
          print("<a tabindex='0' id='UIAddImagePostButton' style='cursor:pointer;' class='half-width button'>Add A Picture...</a>");
          print("</div>");
        }
        else
        {
          // encode the cookie auth key in there as a tiny bit of spam protection (we check it in the ajax php)
          $cookieCodeStamp = $_COOKIE[__LAUTH_KEY__];
          if (!isset($cookieCodeStamp))
            die("AUTH ERROR 444.");

          $lst->UI_Misc()->GenTextEntry("listAddEntry", "Express Yourself", $listAddState['maxchars']);

          // encode the current ordering mode, saves looking it up again in the post-AddPost ajax
          $listDefaultOrdering = $listAddState['orderby'];
          $sesh = Session::getInstance();
          if (isset($sesh->list_order))
          {
            $listDefaultOrdering = $sesh->list_order;
          }
        
          print("<a id='UIAddToListButton' title='list_AddPost($(\"#UIAddToListButton\"), $listID, \"$listDefaultOrdering\", \"$cookieCodeStamp\");' style='cursor:pointer;' class='full-width button'>Tack It On</a>");
          
          PrintListVoteHTML($lst);
        }
      }
      else
      {
        printf("<p>You're not allowed to add things to this list (%s).</p>", $listAddState['reason']);
      }
    }
    else
    {
      print("<p>Please <a href='#StuffTab'>login</a> to add things to lists.</p>");
    }
  }
  
  // -----------------------------------------------------------------------------------------------
  public static function BasicListNavigator(Listopia $lst)
  {
    $randomList = $lst->Database()->select(array(
                            'fields' => 'list_id',
                            'table' => 't_lists',
                            'condition' => DBQ_CONDITION_PUBLIC_LIST,
                            'order' => 'rand()',
                            'limit' => 1
                            ));
    if (!empty($randomList[0]))
    {
      $listRandomID = intval($randomList[0]['t_lists']['list_id']);
    }
    else
    {
      $listRandomID = mt_rand(0 , $lst->getListCount());
    }



    $unseen_id = -1;
    $unseenq = $lst->Database()->chooseUnseenList( Session::getInstance()->gl_userid );
    if ( !empty($unseenq) && count($unseenq) > 0 )
    {
       $chosen_v = $unseenq[array_rand($unseenq)];

        if (!empty($chosen_v) && !empty($chosen_v[0]))
        {
          $unseen_id = ($chosen_v[0]['gap_start']);
        }
    }

    
    $query = $lst->Database()->select(array(
                            'fields' => 'list_id, list_headline, list_type',
                            'table' => 't_lists',
                            'condition' => DBQ_CONDITION_PUBLIC_LIST,
                            'order' => 'list_updated desc',
                            'limit' => 8
                            ));
    if (!empty($query[0]))
    {
      $listLinkExtra = "&tab=".SideBarItem::BasicListNavigator."#PageContent";
      
      print("<p class='lst-subtitle'>Recent Entries</p>");
      print("<ul class='lst-sidebar'>");
      
      foreach ($query as &$list)
      {
        $listID = $list['t_lists']['list_id'];
        $headline = stripslashes($list['t_lists']['list_headline']);
        $suffix = "";
        if ($list['t_lists']['list_type'] == "image")
          $suffix = $lst->getImageListAdornmentHTML();
        
        printf("<li><a %s>%s</a>%s</li>\n", ListLink($listID, $listLinkExtra), $headline, $suffix);
      }
      
      print("</ul>\n");
    }
    /*
    $query = $lst->Database()->select(array(
                            'fields' => 'list_id, list_headline',
                            'table' => 't_lists',
                            'condition' => DBQ_CONDITION_PUBLIC_LIST,
                            'order' => 'list_created desc',
                            'limit' => 3
                            ));
    if (!empty($query[0]))
    {
      $listLinkExtra = "&tab=".SideBarItem::BasicListNavigator."#PageContent";
      
      print("<p class='lst-subtitle'>Brand New Lists</p>");
      print("<ul class='lst-sidebar'>");
      
      foreach ($query as &$list)
      {
        $listID = $list['t_lists']['list_id'];
        $headline = stripslashes($list['t_lists']['list_headline']);

        printf("<li><a %s>%s</a></li>\n", ListLink($listID, $listLinkExtra), $headline);
      }
      
      print("</ul>\n");
    }
    */
    print("<p class='lst-subtitle'>Or show me...</p>");
?>
    
    <a id="UIMoreListsButton" class="full-width button" href="overview.php?mode=latest" style="margin-right:2px">The list browser</a>
    <a id="UIRandomListButton" class="full-width button" <?php echo ListLink($listRandomID, $listLinkExtra); ?>>A Random List</a>

<?php
    if ( $unseen_id > 0 ) {
?>
    <a id="UIRandomListButton" class="full-width button" <?php echo ListLink($unseen_id, $listLinkExtra); ?>>A List I've Never Visited</a>
<?php
    }

    if (getCurrentFileNoExt() == "list")
      PrintListVoteHTML($lst);
  }
  
  // -----------------------------------------------------------------------------------------------
  static function AdvancedListNavigator(Listopia $lst)
  {
    print("<ul class='lst-sidebar'>");
    
    $mode = $_GET['mode'];
    
    $searches = $lst->GetGenericSearches();
    foreach ($searches as $key => $value)
    {
      $isActive = ($mode == $key);
      
      printf("<li>%s<a href='overview.php?mode=%s'>%s</a>%s<p style='line-height: 1.1em;'>%s</p></li>",
        $isActive ? "<strong>" : "",
        $key,
        $value[0],
        $isActive ? "</strong>" : "",
        $value[1]);
    }
    
    print("</ul>");
  }

  // -----------------------------------------------------------------------------------------------
  static function Profile_LoggedIn(Listopia $lst)
  {
    $userID = Session::getInstance()->gl_userid;
    
    $inboxMessageCount = $lst->getUnreadMessagesCount($userID);
    $inboxPluralize = ($inboxMessageCount != 1) ? "s" : "";

    $profileLink = ProfileLink($userID, '#PageContent');
       
    $logLink = ProfileLink(1, '#PageContent');
    $logStats = $lst->getUserStats(1);
    
    $logDateFrom = new DateTime("now");
    $logDateTo = new DateTime($logStats['last_login']);
    $logInterval = $logDateTo->diff($logDateFrom);
    if ($logInterval->d == 0)
      $logDaysElapsed = "today";
    else if ($logInterval->d == 1)
      $logDaysElapsed = "yesterday";
    else
      $logDaysElapsed = $logInterval->format('%a days ago');
    
  ?>
    <h4>Hello <?php $lst->echoUserName(); ?>!</h4>
    <p>You have <?=$inboxMessageCount?> message<?=$inboxPluralize?> in <a href="messages.php">your inbox</a></p>
    <a class="full-width button" id="UILogout" style="margin: 0px 0px 20px 0px">Logout</a>
    <br/>
    <p>Things to make and do:</p>
    <ul class="lst-sidebar">
      <li><a href="lateststuff.php">Check what's new</a><p>The latest gits</p></li>
      <li><a href="activity.php">Your activity feed</a><p>Comments and such on your content</p></li>
      <li><a <?=$profileLink?>>View your profile</a><p>Admire your stats, fiddle with your bits</p></li>
      <li><a href="newlist.php">Start a new list</a><p>Got a good idea for a list? Or just drunk?</p></li>
      <li><a href="ai.php">Gaze at the Listopia AI</a><p>Like a digital sewage pipe outflow </p></li>
      <li><a href="search.php">Find something</a><p>Search the site for specific damage</p></li>
  <?php if ($lst->isAdminUser()) : ?>
      <li><a href="admin.php">Administration</a><p>Flex your powers and break the database</p></li>
  <?php endif; ?>
    </ul>

    <p><a <?=$logLink?>>Log</a> was last seen <strong><?=$logDaysElapsed?></strong>.</p>

  <?php
  }
  
  // -----------------------------------------------------------------------------------------------
  static function Profile_Guest(Listopia $lst)
  {
    $loginTitles = $GLOBALS['LS_LOGIN_TITLES'];
    $loginTitle = $loginTitles[array_rand($loginTitles)];
  
  ?>
  <p class="smaller-centered"><?=$loginTitle?></p>
  <a class="full-width button" id="UILogin">Login</a>
  <p>&nbsp;</p>
  <?php
  }
  
  // -----------------------------------------------------------------------------------------------
  public static function Profile(Listopia $lst)
  {
    print("<div style='padding:2px'> \n");
    
    if ( $lst->isLoggedIn() )
      SidebarBuilder::Profile_LoggedIn($lst);
    else
      SidebarBuilder::Profile_Guest($lst);

    print("</div> \n");
  }

  // -----------------------------------------------------------------------------------------------
  public static function Messages(Listopia $lst)
  {
    if ( $lst->isLoggedIn() )
    {
?>    
      <ul class='lst-sidebar'>
      <li><a href="messages.php?box=inbox#PageContent">Inbox</a> <span id="UIMessagesUnread"></span></li>
      <li><a href="messages.php?box=archived#PageContent">Archived</a> <span id="UIMessagesArchived"></span></li>
      <li><a href="messages.php?box=sent#PageContent">Sent</a> <span id="UIMessagesSent"></span></li>
      </ul>
      <br/>
      <ul class='lst-sidebar'>
      <li><a href="messages.php?box=compose#PageContent">Compose New...</a></li>
      </ul>
<?php 
    }
    else
    {
?>
    <p>Please <a href="#StuffTab">login</a> to shout at each other using the messaging system.</p>
<?php
    }
  }
  
  // -----------------------------------------------------------------------------------------------
  public static function MiniStats(Listopia $lst)
  {
    $listCount = $lst->getListCount();
    $userCounts = $lst->getUserCounts();
    $topiaStats = $lst->getListopiaStats();
    
    print("<div>");
    printf("<p>Listopia kicked off %s - <strong>%s</strong></p>", $topiaStats['start'], $topiaStats['start_days']);
    printf("<p>We have <strong>%s</strong> lists crammed with <strong>%s</strong> items.</p>", $listCount, number_format($topiaStats['num_items']));
    printf("<p><strong>%d</strong> people have signed up, of which <strong>%d</strong> of them have actually contributed something.</p>", $userCounts['total'], $userCounts['active']);
    print("</div>");
  }  
  
  // -----------------------------------------------------------------------------------------------
  public static function NewListInstructions(Listopia $lst)
  {
?> 
  <table id="list-creation-table">
  <tbody>
  
  <tr>
    <td>
      <img src='images/list-create-step1.jpg'/>
    </td>
    <td>
      <img src='images/list-create-step2.jpg'/>
    </td>
  </tr>
  <tr>
    <td>
      <p>1. Fill In The Forms And Create It</p>
    </td>
    <td>
      <p>2. Add Some Items</p>
    </td>
  </tr>
  <tr>
    <td>
      <img src='images/list-create-step3.jpg'/>
    </td>
    <td>
      <img src='images/list-create-step4.jpg'/>
    </td>
  </tr>
  <tr>
    <td>
      <p>3. Open It Up</p>
    </td>
    <td>
      <p>4. Hilarity Ensues</p>
    </td>
  </tr>
  
  </tbody>
  </table>
<?php
  }

  public static function NewUserInstructions(Listopia $lst)
  {
?>
  <p class="smaller-centered">Sign up, or Trump eats the baby</p>
  <img style="display: block; margin: 0px auto 5px auto; border: 1px solid black;" src='images/mascot-signup-page.jpg'/>
  <p class="smaller-centered">Look at those eyes. He'll fucking do it.</p>
<?php
  }

  public static function PublicDisplayStub(Listopia $lst)
  {
    $listID = $_GET['id'];
    $query = $lst->getListBlurb($listID);

    $rules = "";

    if (!empty($query[0]))
    {
      $listData = $query[0];
      
      $rules = UnStarr(stripslashes($listData['t_lists']['list_blurb']));
      if (substr($rules, 0, 2) !== "<p")
        $rules = "<p>" . $rules . "</p>";
      $rules = MakeClickableLinks($rules);
    }
?>
    <p class="smaller-centered"><?=$rules?></p>
<?php
  }
  
}