<?php
class Visit extends BaseCode {
  function __construct(){
    parent::__construct();

    $this->DB->query_record = false; //query log 기록 금지

    $this->DB->tableExists( TB_visit_sess );
    $this->DB->tableExists( TB_visit_sess_count );
    $this->DB->tableExists( TB_visit_log );
    $this->DB->tableExists( TB_visit_log_count );
  }

  function getVisitList( $tb, $field="*", $where="", $orderby="", $limit=array() ){ //방문 리스트 (공통)
    if( !$where ){
      $where = new DB_where("and");
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select {$field} from {$tb} where {$whereqry} ".(($orderby)?"order by {$orderby}":""). $this->DB->_limit($limit[0],$limit[1]);
    $sql = $this->DB->addLimit("select {$field} from {$tb} where {$whereqry}",$orderby,$limit[0],$limit[1]);
    $rst = $this->DB->qry($sql, $whererow);
    $row = array();
    while( $tmp = $this->DB->fetch_array($rst) ){
      $tmp['visit_date'] = getDT_datetime($tmp['visit_date']);
      $row[] = $tmp;
    }
    return $row;
  }

  function getVisitPage($tb, $sqldata=array(), $query=array(), $where=""){ //방문 리스트 (공통-페이징)
    if( !$where ){
      $where = new DB_where("and");
    }

    $where->add("visit_date >= ?", ($sqldata['sdate']?$sqldata['sdate']:_SDATENULL_)." 00:00:00.000");
    $where->add("visit_date <= ?", ($sqldata['fdate']?$sqldata['fdate']:_FDATENULL_)." 23:59:59.999");

    if( $sqldata['stxt'] ){
      $subwhere = $where->sub_where("or");
      if( $sqldata['sfld'] ){
        $subwhere->add("{$sqldata['sfld']} like ?", "%{$sqldata['stxt']}%");
      }else{
        $subwhere->add("visit_url  like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("visit_ref  like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("visit_ip   like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("visit_sess like ?", "%{$sqldata['stxt']}%");
      }
    }

    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $orderby = "nid desc";
    if( $sqldata['ofld'] && $sqldata['oasc'] ) $orderby = "{$sqldata['ofld']} {$sqldata['oasc']}";

    $query = array_merge(array(
      "mode"          => $sqldata['mode'],
      "viewnum"       => $sqldata['viewnum'],
      "sdate"         => $sqldata['sdate']?:"",
      "fdate"         => $sqldata['fdate']?:"",
      "sfld"          => $sqldata['sfld'],
      "stxt"          => $sqldata['stxt'],
      "ofld"          => $sqldata['ofld'],
      "oasc"          => $sqldata['oasc'],
    ), $query);

    $lists = new clist();
    $lists->fld      = "*";
    $lists->where    = $whereqry;
    $lists->whererow = $whererow;
    $lists->orderby  = $orderby;
    $lists->url      = $_SERVER['PHP_SELF'];
    $lists->query    = $query;
    $lists->page     = $sqldata['page']?:1;
    $lists->linktype = "";
    $lists->viewnum  = $query['viewnum']?:20;
    $lists->rownum   = $query['rownum']?:5;
    $lists->getCommonList($tb);
    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){;
      $lists->rows[$a]['visit_date'] = getDT_datetime($lists->rows[$a]['visit_date']);
    }
    return $lists;
  }

  function getVisitSessList( $field="*", $where="", $orderby="", $limit=array() ){ //사이트 접근 리스트
    return $this->getVisitList(TB_visit_sess, $field, $where, $orderby, $limit);
  }

  function getVisitSessPage( $sqldata=array(), $query=array(), $where="" ){ //사이트 접근 리스트 페이지
    return $this->getVisitPage(TB_visit_sess, $sqldata, $query, $where);
  }

  function getVisitLogList( $field="*", $where="", $orderby="", $limit=array() ){ //사이트 조회 리스트
    return $this->getVisitList(TB_visit_log, $field, $where, $orderby, $limit);
  }

  function getVisitLogPage( $sqldata=array(), $query=array(), $where="" ){ //사이트 조회 리스트 페이지
    return $this->getVisitPage(TB_visit_log, $sqldata, $query, $where);
  }

  function putVisitRec($vtype="",$cate_id=""){ //방문자 로그 기록
    $ip = get_ip();
    $time = time();

    //세션생성
    if( !$_SESSION['visit_sess'] ){
      $_SESSION['visit_sess'] = md5($time.$ip);
    }

    if( 
      $_SESSION['visit_last_urls'] != $_SERVER['REQUEST_URI'] && $_SESSION['visit_last_ajax'] != $_SERVER['REQUEST_URI'] || //새로고침은 기록 안함
      ($_SESSION['visit_last_time'] + ($GLOBALS['_varsBaseCode']['refresh_time']?:3600)) < time() //새로고침이라 할지라도 일정시간 이내의 새로고침은 기록
     ){
      //로그기록 등록
      $this->putVisitDetailRec($vtype,$cate_id);
    }

    //마지막 페이지 접근내역
    if( preg_match("/\.ajax\./i", $_SERVER['REQUEST_URI']) ){
      $_SESSION['visit_last_ajax'] = $_SERVER['REQUEST_URI'];
    }else{
      $_SESSION['visit_last_urls'] = $_SERVER['REQUEST_URI'];
    }
    $_SESSION['visit_last_time'] = $time;
  }

  function putVisitDetailRec($vtype="",$cate_id=""){ //로그기록 등록
    if( !$_SESSION['visit_sess'] ) return false;

    //세션 로그기록 등록
    $this->putVisitSessRec($vtype);

    //방문 로그 등록 (페이지뷰)
    $this->putVisitLogRec($vtype,$cate_id);
  }

  function putVisitSessRec($vtype=""){ //방문 세션 기록
    if( !$_SESSION['visit_sess'] ) return false;

    $where = new DB_where("and");
    $where->add("visit_sess = ?", $_SESSION['visit_sess']);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];
    $sql = "select count(*) from ".TB_visit_sess." where {$whereqry}";
    $cnt = $this->DB->queryFirstField($sql,$whererow);
    if( !$cnt ){ //최초 세션 등록
      $this->DB->insert( TB_visit_sess, array("visit_sess"=>$_SESSION['visit_sess'], "member_id"=>($GLOBALS['_Umem']['member_id']?:""), "visit_ip"=>get_ip(), "visit_total"=>1) ); //세션 추가

      $where = new DB_where("and");
      $where->add("visit_date = ?", date("Y-m-d"));
      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];
      $sql = "select count(*) from ".TB_visit_sess_count." where {$whereqry}";
      $cnt = $this->DB->queryFirstField($sql, $whererow);
      if( !$cnt ){ //시간별 세션등록통계가 없으면 insert
        $this->DB->insert( TB_visit_sess_count, array("visit_week"=>date("w")) );
      }

      $sql = "update ".TB_visit_sess_count." set visit_total = visit_total + 1, h".date("H")." = h".date("H")." + 1 where {$whereqry}";
      $this->DB->qry( $sql, $whererow );
    }else{ //세션이 방문한 페이지수 증가
      $sqladd = "";
      if( $GLOBALS['_Umem']['member_id'] ){
        $sqladd = "member_id = '{$GLOBALS['_Umem']['member_id']}',";
      }
      $sql = "update ".TB_visit_sess." set {$sqladd} visit_total = visit_total + 1, visit_fdate = CURRENT_TIMESTAMP where {$whereqry}";
      $this->DB->qry( $sql, $whererow );
    }
  }

  function putVisitLogRec($vtype="",$cate_id=""){ //방문페이지(페이지뷰) 기록
    if( !$_SESSION['visit_sess'] ) return false;

    $where = new DB_where("and");
    $where->add("visit_date = ?", date("Y-m-d"));
    $where->add("visit_type = ?", $vtype);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];
    $sql = "select count(*) from ".TB_visit_log_count." where {$whereqry}";
    $cnt = $this->DB->queryFirstField($sql, $whererow);
    if( !$cnt ){ //시간별 페이지뷰통계가 없으면 insert
      $this->DB->insert( TB_visit_log_count, array("visit_type"=>$vtype,"visit_week"=>date("w")) );
    }

    //시간별 페이지뷰통계 증가
    $sql = "update ".TB_visit_log_count." set visit_total = visit_total + 1, h".date("H")." = h".date("H")." + 1 where {$whereqry}";
    $this->DB->qry( $sql, $whererow );


    $connect_info = parse_user_agent();
    $sql_row = array(
      "visit_type"    => $vtype,
      "cate_id"       => $cate_id?:"",
      "visit_sess"    => $_SESSION['visit_sess']?:"",
      "visit_url"     => $_SERVER['REQUEST_URI']?:"",
      "visit_ref"     => $_SERVER['HTTP_REFERER']?:"",
      "visit_browser" => "{$connect_info['browser']} | {$connect_info['version']}",
      "visit_os"      => $connect_info['platform']?:"",
      "visit_ip"      => get_ip(),
    );

    //개별 페이지 방문 기록
    return $this->DB->insert( TB_visit_log, $sql_row );
  }

  function setLoginRec(){ //로그인시 ID 기록
    $where = new DB_where("and");
    $where->add("visit_sess = ?", $_SESSION['visit_sess']);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];
    $sql = "update ".TB_visit_sess." set member_id = ? where {$whereqry}";
    return $this->DB->qry($sql, array_merge(array($_SESSION['auth_mem_id']?:""),$whererow));
  }

  function getVisitData($mode, $type="LOG", $vtype="", $start_day="", $end_day="", $where=""){
    if( !$end_day ) $end_day = date("Y-m-d");
    if( !$start_day ) $start_day = date("Y-m-d",strtotime($end_day." -1 Month +1 day"));

    if( !$where ){
      $where = new DB_where("and");
    }
    $where->add("visit_date >= ?", $start_day);
    $where->add("visit_date <= ?", $end_day);

    if( $type == "LOG" ){
      $where->add("visit_type = ?", $vtype);
      $tbl = TB_visit_log_count;
    }else{
      $tbl = TB_visit_sess_count;
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $row = array();
    switch( $mode ){
      case "hour":
        $h_row = array();
        for( $a=0 ; $a<24 ; $a++ ){
          $h_str = "h".str_pad($a, 2, "0", STR_PAD_LEFT);
          $h_row[] = "sum({$h_str}) as {$h_str}";
        }
        $sql = "select ".implode(",",$h_row)." from {$tbl} where {$whereqry} ";
        $row = $this->DB->queryFirstRow($sql, $whererow);
      break;

      case "day":
        if( (strtotime($end_day) - strtotime($start_day)) > 31*86400 ) $end_day = date("Y-m-d",strtotime($start_day." +1 Month -1 day")); //1개월이내로 제한
        $days = floor((strtotime($end_day) - strtotime($start_day)) / 86400);

        for( $a=0 ; $a<=$days ; $a++ ){
          $nday = date("Y-m-d", strtotime("{$start_day} +{$a} day"));
          $row[$nday] = 0;
        }

        $sql = "select visit_date as date, visit_total as visit from {$tbl} where {$whereqry} ";
        $rst = $this->DB->qry($sql, $whererow);

        while( $tmp = $this->DB->fetch_array($rst) ){
          $row[getDT_date($tmp['date'])] = $tmp['visit'];
        }
      break;

      case "dayw":
        $days = floor((strtotime($end_day) - strtotime($start_day)) / 86400);

        $sql = "select visit_date as date, visit_total as visit from {$tbl} where {$whereqry} order by visit_date asc";
        $rst = $this->DB->qry($sql, $whererow);

        $trow = array();
        while( $tmp = $this->DB->fetch_array($rst) ){
          $trow[getDT_date($tmp['date'])] = $tmp['visit'];
        }
        $row = array();
        for( $a=0 ; $a<7 ; $a++ ){
          $dword = date("Y-m-d", strtotime($start_day." +{$a} days"));
          $row[] = $trow[$dword] ?: 0;
        }

      break;

      case "week":
        $h_row = array();
        for( $a=0 ; $a<7 ; $a++ ){
          $h_row[] = "sum(iif(visit_week = {$a}, visit_total, 0)) as w{$a}";
        }
        $sql = "select ".implode(",",$h_row)." from {$tbl} where {$whereqry} ";
        $row = $this->DB->queryFirstRow($sql, $whererow);
      break;

      case "mon":
        $sday = explode("-",$start_day);
        $eday = explode("-",$end_day);
        if( (($eday[0]*12+intval($eday[1])) - ($eday[0]*12+intval($eday[1]))) != 12 ) $start_day = date("Y-m-d",strtotime($end_day." -11 Month")); //12개월이내로 제한

        $sday = explode("-",$start_day);
        $mons = ($eday[0]*12+intval($eday[1])) - ($sday[0]*12+intval($sday[1]));

        $m_row = array();
        for( $a=0 ; $a<=$mons ; $a++ ){
          $m_str = date("Y-m",strtotime("{$sday[0]}-{$sday[1]}-01 +{$a} month"));
          $m_row[] = "sum(iif(visit_date like '{$m_str}%', visit_total, 0)) as '{$m_str}'";
        }
        $sql = "select ".implode(",",$m_row)." from {$tbl} where {$whereqry} ";
        $row = $this->DB->queryFirstRow($sql, $whererow);
      break;
    }

    return array(
      "start_day" => $start_day,
      "end_day"   => $end_day,
      "mons"      => $mons,
      "days"      => $days,
      "data"      => $row,
    );
  }
}