<?php

class blogBase {

  protected $blog = null;

  public function blogBase(Tblblog $blog) {
    $this->blog = $blog;
  }

  public function getLocationQuery() {
    $type = $this->blog->getBlType();
    $admin = TblblogcheckinfoPeer::retrieveByPK($this->blog->getBlUser());
    if ($type==4) return 'ci_province='.$admin->getCiProvince();
    if ($type==3) return 'ci_district='.$admin->getCiDistrict();
    if ($type==2) return 'ci_school='.$admin->getCiSchool();
    return '';
  }

  public function listActiveBlogs($blogType, $activeType = 'day') {
    $reftype = ($blogType >= 2? ">=": "=").$blogType;
    $sql = $this->getActiveBlogSql($activeType, $reftype);
    $results = myUtility::execSql($sql);
    $tblblogs = array();
    foreach ($results as $result) {
      $blog = TblblogPeer::retrieveByPk($result[0]);
      if ($blog->getBlId() == $this->blog->getBlId()) continue;
      $title = myUtility::mb_truncate_text($blog->getBlTitle(), 40);
      $tblblogs[] = array($title, $blog->getRootUrl(), $result[1]);
      if (count($tblblogs) >= 8) break;
    }
    return $tblblogs;
  }

  protected function getActiveMemberSql($activeType, $with_location_query='') {
    switch ($activeType) {
      case 'all':
        return
        "select us_id, us_score from tbluser, tblblogcheckinfo where us_id=ci_userid $with_location_query ".
        "order by ci_score desc limit 8";

      case 'week':
        $week = myUtility::dateToWeek(date('Y-m-d'));
        return
        "select udsc_user, sum(udsc_score) as scores, ci_province, ci_district, ci_school ".
        "from tbluserdayscore, tblblogcheckinfo where udsc_user=ci_userid and udsc_date>='$week' ".
        "group by udsc_user $with_location_query ".
        "order by scores desc limit 8";

      case 'day':
        $today = date('Y-m-d');
        return
        "select utsc_user, utsc_score from tblusertempscore, tblblogcheckinfo ".
        "where utsc_user=ci_userid $with_location_query and utsc_date='$today' ".
        "order by utsc_score desc limit 8";
    }
  }

  public function listActiveMembers($activeType = 'day') {
    $location_query = $this->getLocationQuery();
    if ($location_query != '') $location_query = ($activeType=='week'? 'having ':'and ').$location_query;
    $sql = $this->getActiveMemberSql($activeType, $location_query);
    $userscores = myUtility::execSql($sql);
    foreach ($userscores as &$userscore) {
      $userscore[2] = TbluserPeer::retrieveByPk($userscore[0]);
    }
    return $userscores;
  }

  public static function getBlogObject($blog) {
    switch ($blog->getBlType()) {
      case -1:
      case 0:
        return new blogMain($blog);
      case 1:
        return new blogPersonal($blog);
      case 2:
      case 3:
      case 4:
        return new blogOffice($blog);
    }
  }
}
?>
