<?php
class RealnameAttach extends Cmanage {
  function __construct( $table ){
    parent::__construct($table);

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

    $this->DB->tableExists($this->TB);
  }

//  public function getFilePath( $gubun, $nid, $sid ){
//    $target_dir = _UP_PATH_."/{$gubun}";
//    if( !file_exists($target_dir) ){ mkdir($target_dir); }
//
//    return $target_dir;
//  }
//
//  public function getLoadFileinfo( $gubun, $nid, $sid ){
//    $target_dir = $this->getFilePath($gubun, $nid, $sid);
//
//    $frow = Array(
//      "target_dir" => $target_dir,
//      "file_name"  => "{$nid}_{$sid}.dat",
//      "file_path"  => "{$target_dir}/{$nid}_{$sid}.dat",
//    );
//    return $frow;
//  }
//
//  public function getSaveFileinfo( $gubun, $nid, $sid, $filename="" ){
//    $target_dir = $this->getFilePath($gubun, $nid, $sid);
//
//    $new_filename = "{$nid}_{$sid}.dat";
//    $frow = Array(
//      "target_dir" => $target_dir,
//      "file_name"  => $filename,
//      "file_path"  => $target_dir."/".$new_filename,
//    );
//    return $frow;
//  }
//
//  public function getConvFileinfo( $gubun, $nid, $sid, $filename="" ){
//    $target_dir = $this->getFilePath($gubun, $nid, $sid);
//
//    $frow = Array(
//      "target_dir" => $target_dir,
//      "file_name"  => "{$nid}_{$sid}.dat",
//      "file_path"  => "{$target_dir}/{$nid}_{$sid}.dat?*",
//    );
//    return $frow;
//  }

  public function getFilePath( $gubun, $nid, $sid="" ){
    $target_dir = _UP_PATH_."/{$gubun}";
    if( !file_exists($target_dir) ){ mkdir($target_dir); }

    if( !is_array($nid) ){
      $nid = explode("/",$nid);
    }

    foreach( $nid as $new_dir ){
      $target_dir .= "/{$new_dir}";
      if( !file_exists($target_dir) ){ mkdir($target_dir); }
    }

//    $target_dir .= "/{$sid}";
//    if( !file_exists($target_dir) ){ mkdir($target_dir); }
    return $target_dir;
  }

  public function getLoadFileinfo( $gubun, $nid, $sid ){
    //$target_dir = $this->getFilePath( $gubun, $nid, $sid );
    $target_dir = _UP_PATH_."/{$gubun}/";
    $frow = $this->getAttach( $gubun, $nid, $sid );
    $target_dir .= $frow['nid'];
    $frow['target_dir'] = $target_dir;
    $frow['file_path']  = "{$target_dir}/{$frow['file_name']}";
    return $frow;
  }

  public function getSaveFileinfo( $gubun, $nid, $sid, $filename="" ){
    $target_dir = $this->getFilePath( $gubun, $nid, $sid );

    $new_filename = $this->getDupFilename($target_dir, $filename);
    $frow = Array(
      "target_dir" => $target_dir,
      "file_name"  => $new_filename,
      "file_path"  => $target_dir."/".$new_filename,
    );
    return $frow;
  }

  public function getConvFileinfo( $gubun, $nid, $sid, $filename="" ){
    //$target_dir = $this->getFilePath( $gubun, $nid, $sid );
    $target_dir = _UP_PATH_."/{$gubun}/";

    $frow = $this->getAttach( $gubun, $nid, $sid );
    $target_dir .= $frow['nid'];
    $frow['target_dir'] = $target_dir;
    $frow['file_path']  = "{$target_dir}/{$frow['file_name']}?*";
    return $frow;
  }

  public function getAttachList($fields, $gubun, $nid="", $adfleld=array(), $orderby=""){
    $where = new DB_where("and");
    if( $gubun ){
      $where->add("gubun = ?", $gubun);
    }
    if( $nid ){
      $where->add("nid = ?", $this->getNidPath($nid));
    }

    if( $adfleld ){
      if( is_array($adfleld) ){
        foreach( $adfleld as $key => $val ){
          $where->add("{$key} = ?", $val);
        }
      }else{
        $orderby = $orderby ?: $adfleld;
      }
    }

    $orderby=$orderby?:"file_id desc";
    $limit=array();

    $rows = $this->getDataList($fields, $where, $orderby, $limit);
    for( $a=0 ; $a<count($rows) ; $a++ ){
      $rows[$a]['file_url'] = _SITE_INC_URL_."/getFile.php?gubun={$rows[$a]['gubun']}&sid={$rows[$a]['sid']}";
    }
    return $rows;
  }

  public function getAttach( $gubun, $nid, $sid ){
    $whererow = Array(
      "gubun" => $gubun,
      //"nid" => $this->getNidPath($nid),
      "sid" => $sid,
    );
    if( $nid ){
      $whererow["nid"] = $this->getNidPath($nid);
    }
    $row = $this->getData("*", $whererow);
    $row['file_url'] = _SITE_INC_URL_."/getFile.php?gubun={$row['gubun']}&sid={$row['sid']}";
    return $row;
  }
  public function getAttachId( $file_id ) {
    $whererow = Array(
      "file_id" => $file_id,
    );
    $row = $this->getData("*", $whererow);
    $row['file_url'] = _SITE_INC_URL_."/getFile.php?gubun={$row['gubun']}&sid={$row['sid']}";
    return $row;
  }

  public function getNidPath( $nid ){
    if( !is_array($nid) ){
      $nid = explode("/",$nid);
    }
    return implode("/",$nid);
  }

  public function putAttach( $upfile, $gubun, $nid, $sid="", $adfield=array(), $upload_user_name="", $code_id="") {
    $sfile = $this->getSaveFileinfo($gubun, $nid, $sid, $upfile['name']);
    $save_file = $sfile['file_path'];

    $rst = move_uploaded_file($upfile['tmp_name'], $save_file);
    if( !$rst ) return false;

    if( strpos($upfile['type'], "image") !== false ){
      $iinfo = getimagesize($save_file);
      $upfile['width'] = $iinfo[0];
      $upfile['height'] = $iinfo[1];
    }

    $sid = $sid ?: uniqid();

    $sqldata = Array(
      "gubun"           => $gubun?:"",
      "nid"             => $this->getNidPath($nid)?:"",
      "sid"             => $sid?:"",
      "file_name"       => $sfile['file_name']?:$upfile['name'],
      "file_size"       => $upfile['size']?:0,
      "file_type"       => $upfile['type']?:"",
      "file_width"      => $upfile['width']?:"",
      "file_height"     => $upfile['height']?:"",
      "file_remk"       => $upfile['file_remk']?:"",
      "file_sig_flg"    => $upfile['file_sig_flg']?:"",
      "upload_user_name"=> $upload_user_name?:"",
      "code_id"         => $code_id?:"",
      "reg_date"        => $this->DB->sqleval("getdate()"),
    );

    if( $adfield ) {
      $sqldata = array_merge($sqldata, $adfield);
    }

    return $this->putData( $sqldata );
  }

  public function putAppAttach($upfile, $sid="", $adfield=array(), $upload_user_name=""){ //앱용 업로드
    $nid = $upfile['nid'];
    $gubun = $upfile['gubun'];
    $code_id = $upfile['code_id'];
    $this->putAttach( $upfile, $gubun, $nid, $sid, $adfield, $upload_user_name,  $code_id );
  }

  public function setAttach( $upfile, $gubun, $nid, $sid, $adfield=array(), $upload_user_name="",  $code_id="" ) {
    $sfile = $this->getSaveFileinfo($gubun, $nid, $sid, $upfile['name']);
    $save_file = $sfile['file_path'];

    $rst = move_uploaded_file($upfile['tmp_name'], $save_file);
    if( !$rst ) return false;

    if( strpos($upfile['type'], "image") !== false ){
      $iinfo = getimagesize($save_file);
      $upfile['width'] = $iinfo[0];
      $upfile['height'] = $iinfo[1];
    }

    $sqldata = Array(
      "gubun"           => $gubun?:"",
      "nid"             => $this->getNidPath($nid)?:"",
      "sid"             => $sid?:"",
      "file_name"       => $sfile['file_name']?:$upfile['name'],
      "file_size"       => $upfile['size']?:0,
      "file_type"       => $upfile['type']?:"",
      "file_width"      => $upfile['width']?:"",
      "file_height"     => $upfile['height']?:"",
      "file_remk"       => $upfile['file_remk']?:"",
      "file_sig_flg"    => $upfile['file_sig_flg']?:"",
      "upload_user_name"=> $upload_user_name?:"",
      "code_id"         => $code_id?:"",
      "reg_date"        => $this->DB->sqleval("getdate()"),
    );

    if( $adfield ) {
      $sqldata = array_merge($sqldata, $adfield);
    }

    $whererow = Array(
      "gubun" => $gubun?:"",
      "nid" => $this->getNidPath($nid)?:"",
      "sid" => $sid?:"",
    );

    return $this->setData( $sqldata, $whererow );
  }
  public function setAttachId( $upfile, $file_id, $upload_user_name="" ) {
    $ainfo = $this->getAttachId( $file_id );
    if( !$ainfo['file_id'] ) return false;

    return $this->setAttach( $upfile, $ainfo['gubun'], $ainfo['nid'], $ainfo['sid'], $upload_user_name );
  }

  public function delAttach( $gubun, $nid, $sid ){
    $urow = Array();
    $urow['gubun'] = $gubun;
    $urow['nid'] = $this->getNidPath($nid);
    $urow['sid'] = $sid;
    $where = "";

    $load_finfo = $this->getLoadFileinfo($gubun, $this->getNidPath($nid), $sid);
    $conv_finfo = $this->getConvFileinfo($gubun, $this->getNidPath($nid), $sid);
    $load_file = $load_finfo['file_path'];
    $conv_file = $conv_finfo['file_path'];

    $rst =         $this->fileRemove("{$load_file}");
    $rst = $rst && $this->fileRemove("{$conv_file}");
    p($remake);
    if( !$rst ) return false;

    return $this->delData($urow, $where);
  }
  public function delAttachId( $file_id ){
    $ainfo = $this->getAttachId( $file_id );
    return $this->delAttach( $ainfo['gubun'], $ainfo['nid'], $ainfo['sid'] );
  }

  static function fByte($bytes, $precision=2) {
    $unit = ["B", "KB", "MB", "GB"];
    $exp = floor(log($bytes, 1024)) ?: 0;
    return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
  }

  static function fileRemove($filepath, $unremove=""){
    $glob = glob($filepath);
    foreach( $glob as $filename ) {
      if( !$unremove || $filename != $unremove ){
        @unlink($filename);
      }
    }
    return true;
  }

  public function getDupFilename( $target_dir, $oriFilename, $cnt=0 ){
    if( !$oriFilename ) return "";

    if( $cnt === 0 ){
      $chkFilename = $oriFilename;
    }else{
      $orin = explode(".",$oriFilename);
      if( count($orin) > 1 ){
        $orin[count($orin)-2] .= "({$cnt})";
      }else{
        $orin[count($orin)-1] .= "({$cnt})";
      }
      $chkFilename = implode(".", $orin);
    }
    if( file_exists("{$target_dir}/{$chkFilename}") ){
      $chkFilename = $this->getDupFilename( $target_dir, $oriFilename, ++$cnt );
    }
    return $chkFilename;
  }

  public function file_reverse( $upfile ){
    $files = Array();
    if( is_array($upfile['name']) ){
      foreach( $upfile as $key => $val ){
        foreach( $val as $k => $v ){
          $files[$k][$key] = $v;
        }
      }
    }else{
      $files[] = $upfile;
    }
    return $files;
  }
}