<?php
class Member extends BaseCode {
  var $member_id;
  var $TB;

  function __construct( $member_id="" ){
    parent::__construct();
    $this->DB->tableExists(TB_member);
    $this->DB->tableExists(TB_member_log);
    $this->DB->tableExists(TB_member_union);

    $this->member_id = $member_id?:(isset($GLOBALS['_Umem']['member_id'])?$GLOBALS['_Umem']['member_id']:"");

    $this->TB = " (select mem.*, meu.cust_id, meu.cust_name from ". TB_member ." as mem left join ". TB_member_union . " as meu on mem.member_id = meu.member_id) as m ";
  }

  public function getMemberList( $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 ".$this->TB." where {$whereqry} ".(($orderby)?"order by {$orderby}":""). $this->DB->_limit($limit[0],$limit[1]);
    $sql = $this->DB->addLimit("select {$field} from ".$this->TB." where {$whereqry}", $orderby, $limit[0],$limit[1]);
    $rst = $this->DB->qry($sql, $whererow);
    $row = array();
    while( $tmp = $this->DB->fetch_array($rst) ){
      $row[] = $this->getMemberInfo($tmp);
    }
    return $row;
  }

  public function getMemberSel( $field="*", $where="", $orderby="", $limit=array() ){
    if( !$where ){
      $where = new DB_where("and");
    }
    $where->add("member_status = ?",1);

    $mlist = $this->getMemberList("member_id, part_name",$where,"part_name, member_name asc", $limit);
    $mem_list = array();
    for( $a=0 ; $a<@count($mlist) ; $a++ ){
      $mem_list[] = array(
        "id" => $mlist[$a]['member_id'],
        "text" => $mlist[$a]['part_name'],
      );
    }
    return $mem_list;
  }

  public function getMemberSelect($key, $val, $where=""){
    $rows = $this->getMemberList("{$key}, {$val}", $where, "member_name asc");
    $selrows = array();
    foreach( (array)$rows as $row ){
      $selrows[$row[$key]] = $row[$val];
    }
    return $selrows;
  }

  public function getMemberPage($sqldata=array(), $query=array(), $where=""){ //관리자 리스트 (페이징)
    if( !$where ){
      $where = new DB_where("and");
    }

    $where->add("reg_date >= ?", ($sqldata['sdate']?$sqldata['sdate']:_SDATENULL_)." 00:00:00.000");
    $where->add("reg_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("member_id     like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("member_name   like ?", "%{$sqldata['stxt']}%");
      }
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $orderby = "reg_date 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']?:$GLOBALS['_varsBaseCode']['line_num'];
    $lists->rownum   = $query['rownum']?:$GLOBALS['_varsBaseCode']['page_num'];
    $lists->getCommonList($this->TB);

    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){
      $lists->rows[$a] = $this->getMemberInfo($lists->rows[$a]);
    }

    return $lists;
  }

  public function getMemberLogList($field="*",$where="", $orderby="",$limit=array()){ //관리자 리스트
    $tbl = "(select L.*, M.member_name, M.company_name from ".TB_member_log." as L left join ".TB_member." as M on L.member_id = M.member_id) as L";

    if( !$where ){
      $where = new DB_where("and");
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

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

  public function getMemberLogPage($sqldata=array(), $query=array(), $where=""){ //관리자 리스트 (페이징)
    $tbl = "(select L.*, M.member_name from ".TB_member_log." as L left join ".TB_member." as M on L.member_id = M.member_id) as L";

    if( !$where ){
      $where = new DB_where("and");
    }

    $where->add("login_date >= ?", ($sqldata['sdate']?$sqldata['sdate']:_SDATENULL_)." 00:00:00.000");
    $where->add("login_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("member_id    like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("member_name  like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("ip_addr      like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("browser      like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("con_domain   like ?", "%{$sqldata['stxt']}%");
        $subwhere->add("OS           like ?", "%{$sqldata['stxt']}%");
      }
    }

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

    $orderby = "login_date 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']?:$GLOBALS['_varsBaseCode']['line_num'];
    $lists->rownum   = $query['rownum']?:$GLOBALS['_varsBaseCode']['page_num'];
    $lists->getCommonList($tbl);

    for( $a=0 ; $a<@count($lists->rows) ; $a++ ){
      $lists->rows[$a]['login_date'] = getDT_datetime($lists->rows[$a]['login_date']);
    }

    return $lists;
  }

  public function getMember( $member_id="", $where="" ) {
    $member_id = $member_id?:$this->member_id;

    if( !$member_id ) return 0;

    if( !$where ){
      $where = new DB_where("and");
    }
    $where->add("member_id = ?",$member_id);

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

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

    $sql = "select * from ".$this->TB." where {$whereqry}";
    $rst = $this->DB->qry($sql, $whererow);
    $row = $this->DB->fetch_array($rst);
    $row = $this->getMemberInfo($row);

    $where = new DB_where("and");
    $where->add("member_id = ?",$member_id);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    if( $this->isAdmin() ){ //관리자의 경우 회원의 마지막 로그인 정보를 주고, 일반회원은 자신의 현재 로그인 이전의 로그인 정보를 준다.
      $sql = "select login_date as last_login, ip_addr as last_ip from ".TB_member_log." where {$whereqry} order by login_date desc";
      $rst = $this->DB->qry($sql, $whererow);
      $lrow = $this->DB->fetch_array($rst);
      $row['login_ip'] = $lrow['last_ip']?:"";
      $row['login_date'] = $lrow['last_login'];
    }

    $this->DB->query_record = true; //query log 기록 재개

    return $row;
  }

  public function getMemberWhere( $wrow ) {
    $where = new DB_where("and");
    foreach( $wrow as $key => $val ){
      $where->add("{$key} = ?",$val);
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ".$this->TB." where {$whereqry}";
    $rst = $this->DB->qry($sql, $whererow);
    $row = $this->getMemberInfo($this->DB->fetch_array($rst));

    return $row;
  }

  public function getMemberInfo( $row ){
    if( isset($row['member_mobile']) && $row['member_mobile'] ) $row['member_mobile'] = $this->lcrypt->dec_secure($row['member_mobile']);
    if( isset($row['member_mail']) && $row['member_mail'] ) $row['member_mail'] = $this->lcrypt->dec_secure($row['member_mail']);
    if( isset($row['member_phone']) && $row['member_phone'] ) $row['member_phone'] = $this->lcrypt->dec_secure($row['member_phone']);

    return $row;
  }

  public function putMember( $sqldata=array() ) { //가입
    if( $this->DB->tableExists( TB_member ) ){
      $sql_row = array(
        "member_id"          => $sqldata['member_id']?:"",
        "member_pw"          => $sqldata['member_pw']?$this->lcrypt->pw_make($sqldata['member_pw']):"",
        "member_name"        => $sqldata['member_name']?:"",
        "member_mobile"      => $sqldata['member_mobile']?$this->lcrypt->enc_secure($sqldata['member_mobile']):"",
        "member_mail"        => $sqldata['member_mail']?$this->lcrypt->enc_secure($sqldata['member_mail']):"",
        "member_certi_key"   => $sqldata['member_certi_key']?:"",
        "member_status"      => $sqldata['member_status']?:1,
        "member_auth"        => $sqldata['member_auth']?:"",
        "reg_date"           => $this->DB->sqleval("getdate()"),
        "mod_date"           => $this->DB->sqleval("getdate()"),
      );

      return $this->DB->insert( TB_member, $sql_row);
    }
    return 0;
  }

  public function setMember( $sqldata ) { //정보 수정
    if( !$this->isAdmin() ){
      $sqldata['member_id'] = $GLOBALS['_Umem']['member_id'];
    }
    $sql_row = array(
      "member_name"    => $sqldata['member_name'],
      "member_mobile"  => $sqldata['member_mobile']?$this->lcrypt->enc_secure($sqldata['member_mobile']):"",
      "member_mail"    => $sqldata['member_mail']?$this->lcrypt->enc_secure($sqldata['member_mail']):"",
      "mod_date"       => $this->DB->sqleval("getdate()"),
    );
    if( $this->isAdmin() ){
      if( $sqldata['member_certi_key'] ){
        $sql_row['member_certi_key'] = $sqldata['member_certi_key'];
      }
    }
    if( $sqldata['member_status'] ){
      $sql_row['member_status'] = $sqldata['member_status'];
    }
    if( $sqldata['member_auth'] ){
      $sql_row['member_auth'] = $sqldata['member_auth'];
    }
    if( $sqldata['member_pw'] ){
      $sql_row["member_pw"] = $this->lcrypt->pw_make($sqldata['member_pw']);
    }

    return $this->DB->update( TB_member, $sql_row, "member_id = ?", array($sqldata['member_id']));
  }

  public function setMemberParts( $sqldata ){
    if( !$sqldata['member_id'] || $GLOBALS['_Umem']['member_id'] && !$this->isAdmin() ){
      $sqldata['member_id'] = $GLOBALS['_Umem']['member_id'];
    }
    $where = new DB_where("and");
    if( is_array($sqldata['member_id']) ){
      //$where->add("member_id in ?",$sqldata['member_id']);
      $subwhere = $where->sub_where("or");
      foreach( $sqldata['member_id'] as $val ){
        $subwhere->add("member_id = ?",$val);
      }
    }else{
      $where->add("member_id = ?",$sqldata['member_id']);
    }
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    unset($sqldata['member_id']);
    return $this->DB->update( TB_member, $sqldata, $whereqry, $whererow );
  }

  public function delMember( $member_id ) { //회원 삭제
    if( $this->isAdmin() ){
      $where = new DB_where("and");
      $where->add("member_id = ?",$member_id);
      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      return $this->DB->delete( TB_member, $whereqry, $whererow );
    }
    return 0;
  }

  public function getMemberUnion($member_id, $where=""){
    if( !$where ){
      $where = new DB_where("and");
    }
    $where->add("member_id = ?", $member_id);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    $sql = "select * from ".TB_member_union." where {$whereqry}";
    return $this->DB->queryFirstRow($sql, $whererow);
  }

  public function putMemberUnion($sqldata){
    $sql_row = Array(
      "member_id" => $sqldata['member_id'],
      "cust_id"   => $sqldata['cust_id']?:"",
      "cust_name" => $sqldata['cust_name']?:"",
    );
    return $this->DB->insert(TB_member_union, $sql_row);
  }

  public function setMemberUnion($sqldata){
    $sql_row = Array(
      "member_id" => $sqldata['member_id'],
      "cust_id"   => $sqldata['cust_id']?:"",
      "cust_name" => $sqldata['cust_name']?:"",
    );

    $uinfo = $this->getMemberUnion($sql_row['member_id']);
    if( $uinfo['member_id'] && $uinfo['member_id'] == $sql_row['member_id'] ){
      $where = new DB_where("and");
      $where->add("member_id = ?", $sql_row['member_id']);
      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      return $this->DB->update(TB_member_union, $sql_row, $whereqry, $whererow);
    }else{
      return $this->putMemberUnion($sql_row);
    }
  }

  public function delMemberUnion($member_id){
    $where = new DB_where("and");
    $where->add("member_id = ?", $member_id);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    return $this->DB->delete(TB_member_union, $whereqry, $whererow);
  }

  public function active( $member_id ) { //활동
    return $this->setMemberParts( array(
      "member_id" => $member_id,
      "member_status" => 1
    ));
  }

  public function pause( $member_id ) { //임시정지
    return $this->setMemberParts( array(
      "member_id" => $member_id,
      "member_status" => 2
    ));
  }

  public function withdraw( $member_id ) { //탈퇴 / 퇴사처리
    return $this->setMemberParts( array(
      "member_id" => $member_id,
      "member_status" => 3
    ));
  }

  public function join( $sqldata ) { //가입
    return $this->putMember( $sqldata );
  }

  public function login($member_id, $member_pw) { // 로그인
    $result = 0;
    if( !$member_id || !$member_pw ){
      return $result;
    }

    $row = $this->pwCheck($member_id, $member_pw);
    if( $row ){
      if( $row['member_status'] == 1 && $row['member_auth'] ){
        $_SESSION['auth_mem_id'] = $member_id;

        // 로그인 시점의 microtime
        list ( $usec, $sec ) = explode ( " ", microtime () );
        $rand_no = rand ( 100000, 999999 );
        $login_security_key = str_replace ( '.', '', get_ip() ) . $sec . str_replace ( '.', '', $usec ) . $rand_no;
        $_SESSION['auth_login_security_key'] = $login_security_key;
        //$result = $row; //가입요청 및 임시중지등 등록된 회원 상태를 알리기 위해 if 밖으로 조정

        if( class_exists("Visit") && $_SESSION['visit_sess'] ){ //방문세션이 존재하면 방문세션 테이블에 ID를 기록한다.
          $vsobj = new Visit();
          $vsobj->setLoginRec();
        }
      }
      $result = $row;
    }

    return $result;
  }

  public function loginAforce($member_id) { // 관리자용 회원 강제 로그인
    $result = 0;
    if( !$member_id || !$this->isAdmin() ){
      return $result;
    }

    $row = $this->getMember($member_id);
    if( $row['member_id'] ){
      $where = new DB_where("and");
      $where->add("member_id = ?",$member_id);
      $where->add("login_success = ?",1);
      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      //$sql = "select login_security_key from ".TB_member_log." where {$whereqry} order by login_date desc ".$this->DB->_limit(0,1);
      $sql = $this->DB->addLimit("select login_security_key from ".TB_member_log." where {$whereqry}","login_date desc",0,1);
      $login_security_key = $this->DB->queryFirstField($sql,$whererow);

      $_SESSION['auth_mem_id'] = $member_id;
      $_SESSION['auth_login_security_key'] = $login_security_key;

      $result = 1;
    }else{
      $result = 0;
    }

    return $result;
  }

  public function pwCheck( $member_id, $member_pw ){ //비밀번호 체크
    $row = $this->getMember($member_id);
    if( $row['member_pw'] ){
      if( $this->lcrypt->pw_match($member_pw, $row['member_pw']) ){
        return $row;
      }
    }
    return 0;
  }

  public function logout(){ //로그아웃
    //session_destroy();
    $_SESSION['auth_mem_id'] = "";
    $_SESSION['auth_login_security_key'] = "";
    return 1;
  }

  public function logRec( $member_id, $login_page, $log_rst ){ //로그인 기록
    $result = 0;
    if( $this->DB->tableExists( TB_member_log ) ){
      $where = new DB_where("and");
      $where->add("member_id = ?",$member_id);
      $where->add("login_success = ?",1);
      $wqry = $where->get_where();
      $whereqry = $wqry['qry'];
      $whererow = $wqry['val'];

      //자신의 현재 로그인 이전의 로그인 정보를 기록한다.
      $crow = $this->DB->queryFirstRow( "select count(*)+1 as login_count from ".TB_member_log." where {$whereqry}", $whererow );
      $lrow = $this->DB->queryFirstRow( "select top 1 login_date, ip_addr as last_ip from ".TB_member_log." where {$whereqry} order by login_date desc", $whererow );
      $sql_row = array(
        "member_id"   => $member_id,
        "login_count" => $crow['login_count']?:0,
        "login_ip"    => $lrow['last_ip']?:"",
        "login_date"  => getDT_datetime($lrow['login_date']),
      );
      $this->setMemberParts($sql_row);

      $connect_info = parse_user_agent();
      if( is_array($connect_info['browser']) ){
        $connect_info['browser'] = substr(json_encode($connect_info['browser']),0,40);
      }
      $sql_row = array(
        "member_id"          => $member_id,
        "ip_addr"            => get_ip(),
        "login_page"         => $login_page,
        "login_success"      => $log_rst?1:0,
        "login_date"         => $this->DB->sqleval("getdate()"),
        "login_security_key" => $_SESSION['auth_login_security_key']?:"",
        "sess_file_name"     => session_id(),
        "browser"            => "{$connect_info['browser']} | {$connect_info['version']}",
        "con_domain"         => $_SERVER['HTTP_HOST']?:"",
        "os"                 => $connect_info['platform']?:"",
        "os_bit"             => ""
      );
      $result = $this->DB->insert( TB_member_log, $sql_row);
    }
    return $result;
  }

  public function loginCheck( $member_id="" ){ //로그인 체크
    $member_id = $member_id?:$_SESSION['auth_mem_id'];
    if( $member_id ){
      if( !defined('_SINGLE_LOGIN_') || !_SINGLE_LOGIN_ || _SINGLE_LOGIN_ && $this->multiLoginBlock() ){
        $row = $this->getMember( $member_id );
        unset($row['member_pw']);
        return $row;
      }else{
        return $this->logout();
      }
    }
    return 0;
  }

  public function multiLoginBlock(){ //멀티 로그인 차단
    $where = new DB_where("and");
    $where->add("member_id = ?",$GLOBALS['_Umem']['member_id']);
    $where->add("login_success = ?",1);
    $wqry = $where->get_where();
    $whereqry = $wqry['qry'];
    $whererow = $wqry['val'];

    //$sql = "select login_security_key from ".TB_member_log." where {$whereqry} order by login_date desc ".$this->DB->_limit(0,1);
    $sql = $this->DB->addLimit("select login_security_key from ".TB_member_log." where {$whereqry}","login_date desc",0,1);
    $match_login_security_key = $this->DB->queryFirstField($sql,$whererow);

    if( $match_login_security_key == $_SESSION['auth_login_security_key'] ){
      return 1;
    }
    return 0;
  }

  public function temp_pw_gen( $len=0 ){ //임시비밀번호 생성
    if( $len < 1 ) $len = 8;
    $str = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $temp_pw = "";
    for($i=0; $i<$len; $i++) {
      $temp_pw .= $str[random_int(0, strlen($str)-1)];
    }
    return $temp_pw;
  }

  public function isAdmin($admin_id="", $suonly=""){ //관리 권한 있는지 확인
    if( !$admin_id || $admin_id && $admin_id == $GLOBALS['_Umem']['member_id'] ){
      $arow = $GLOBALS['_Umem'];
    }else{
      $arow = $this->getMember($admin_id);
    }

    if( $suonly ){//기준정보에서 SA 코드자체를 변경할수 있으므로 suonly 는 사용에 주의
      $adminrow = array("SA");
    }else{
      if( is_array($GLOBALS['_varsAuthAdmin']) ){
        $adminrow = array_keys($GLOBALS['_varsAuthAdmin']);
      }else{
        $adminrow = array("SA","A");
      }
    }

    if( in_array($arow['member_auth'], $adminrow) ){
      return true;
    }else{
      return false;
    }
  }
}