<?php
// Load Dolibarr environment
if (file_exists('../../main.inc.php')) 
  {
    require_once '../../main.inc.php';
  } else { 
    if (file_exists('../../../main.inc.php')) 
    {
      require_once '../../../main.inc.php';
    } else {
      require_once '../../../../main.inc.php';
    }
  }
  

/**
 * Execute une requete (INSERT, DELETE, UDPATE) et retourne le nombre de ligne affecte
 */
function doQuery($sql){
  global $db;
  $res = -1;

  $resql = $db->query($sql);
  if($resql){
    $res = $db->affected_rows($resql);
  } else {
    $error = "Error " . $db->lasterror();
    dol_syslog(__METHOD__ . " " . $error, LOG_ERR);
  }

  return $res;
}


/**
 * Execute la requete (SELECT) et retourne tout les resultats
 * Index avec $key (defini a rowid par defaut) s il fait parti des champs
 */
function dbFetch($sql, $key='rowid'){
  global $db;
  $t_rows = array();

  dol_syslog("sql= " . $sql, LOG_DEBUG);
  $resql = $db->query($sql);
  if($resql){
    $num_rows = $db->num_rows($resql);
    for($i=0;$i<$num_rows;$i++) {
      $row = $db->fetch_object($resql);
      $k = ( isset($row->{$key}) ? $row->{$key} : $i );
      $t_rows[$k] = $row;
    }
  } else {
    $error = "Error " . $db->lasterror();
    dol_syslog(__METHOD__ . " " . $error, LOG_ERR);
  }

  return $t_rows;
}


/**
 * Execute la requete (SELECT) et retourne le premier resultat
 */
function dbFetchOnce($sql){
  global $db;
  $row = array();

  dol_syslog("sql= " . $sql, LOG_DEBUG);
  $resql = $db->query($sql);
  if ($resql) {
    $num_rows = $db->num_rows($resql);
    if($num_rows){
      $row = $db->fetch_object($resql);
    }
  } else {
    $error = "Error " . $db->lasterror();
    dol_syslog(__METHOD__ . " " . $error, LOG_ERR);
  }

  return $row;
}

// --------------------------------------------------------------------------------

/**
 * Retourne une ligne d enregistrement a partir de son id
 */
function dbFetchId($tableName, $rowid){
  return dbFetchOnce(
    'SELECT * FROM '.MAIN_DB_PREFIX.$tableName.' WHERE rowid='.$rowid
  );
}

/**
 * Permet l insertion dans une table
 * A utiliser en tant qu alias
 * @param $tableName nom de la table
 * @param $t_data donnees a inserer
 * @param $t_field champs de la table pouvant etre insere
 * @param array $_defaultValue valeur par defaut
 * @return int rowid du nouvel enregistrement
 */
function dbInsert($tableName, $t_data, $t_field, $_defaultValue=array()){
  global $db;
  $inserted_rowid = 0;

  // recupere tout les valeurs inserable
  $t_value = array();
  foreach($t_field as $f){
    if( isset($t_data[$f]) ){
      $t_value[$f] = _dbProtectValue($t_data[$f]);
    }
  }

  // mets les valeurs par defaut
  foreach($_defaultValue as $field=>$val){
    if( !isset($t_value[$field]) ) $t_value[$field] = $val;
  }

  if(!$t_value) return 0;

  // insertion en DB
  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$tableName;
  $sql.= ' (`'.implode('`,`', array_keys($t_value)).'`)';
  $sql.= ' VALUES';
  $sql.= ' ('.implode(',', $t_value).')';

  $resql = $db->query($sql);
  if($resql){
    $inserted_rowid = $db->last_insert_id(MAIN_DB_PREFIX.$tableName);
  } else {
    $inserted_rowid = -1;
    $error = "Error " . $db->lasterror();
    dol_syslog(__METHOD__ . " " . $error, LOG_ERR);
  }

  return $inserted_rowid;

}


/**
 * Permet la mise a jour dans une table
 * A utiliser en tant qu alias
 * @param $tableName nom de la table
 * @param $t_data donnees a mettre a jour
 * @param $t_field champs de la table pouvant etre mis a jour
 * @param $where condition :
 *     si c est une chaine, considere que c est une condition: "WHERE [where]"
 *     si c est un entier, considere que c est le rowid : "WHERE rowid=[where]"
 *     si c est un tableau, considere que c est un t_where
 * @return int nombre d enregistrement mis a jour
 */
function dbUpdate($tableName, $t_data, $t_field, $where){
  global $db;

  // recupere tout les valeurs inserable
  $t_value = array();
  $t_set = array();
  foreach($t_field as $f){
    if( isset($t_data[$f]) ){
      $t_value[$f] = _dbProtectValue($t_data[$f]);
      $t_set[$f]   = '`'.$f.'`='.$t_value[$f];
    }
  }

  // construit la condition
  $sql_where = '';
  switch ( gettype($where) ){
    case 'integer' :
      $sql_where = _dbParseTwhere(array( 'rowid'=>$where ));
      break;
    case 'string' :
      $sql_where = $where;
      break;
    case 'array' :
      $sql_where = _dbParseTwhere($where);
      break;
  }

  if(!$t_value || $sql_where=='') return 0;

  // insertion en DB
  $sql = 'UPDATE '.MAIN_DB_PREFIX.$tableName;
  $sql.= ' SET '.implode(',', $t_set);
  $sql.= ' WHERE '.$sql_where;

  return doQuery($sql);

}

// --------------------------------------------------------------------------------


/**
 * Protege une valeur : ajoute des "" si besoin
 */
function _dbProtectValue($value){
  $return = $value;

  switch (gettype($value)){
    case 'NULL':
      $return = 'NULL';
      break;
    case 'string':
      $return = '"'.$value.'"';
      break;
    case 'array':case 'object':case 'resource':case 'unknown type':
    $return = '""';
    break;
    case 'boolean':
      $return = ($value?1:0);
      break;
    default :
      $return = $value;
      break;
  }

  return $return;
}


/**
 * Converti un tableau de condition en chaine
 */
function _dbParseTwhere($t_where){
  $sql_where = '';

  $t_op = array('>', '=>', '=', '=<', '<', 'LIKE');
  foreach($t_where as $key=>$val){
    $key = trim($key);
    $last_key = end(explode(' ',$key));

    if($sql_where!="")
      $sql_where .= " AND ";

    if( in_array($last_key, $t_op) )
      $sql_where .= $key.'"'.$val.'"';
    else
      $sql_where .= $key.'="'.$val.'"';
  }

  return $sql_where;
}

// --------------------------------------------------------------------------------

/**
 * Creer un fichier text
 */
function create_file_text( $filepath, $content ){
  $pathinfo = pathinfo($filepath);
  if(!is_dir($pathinfo['dirname'])){
    mkdir($pathinfo['dirname'], 0777, TRUE);
  } else {
    dol_syslog( 'Creation fichier impossible '.$pathinfo['dirname'], LOG_WARNING );
  }

  if( $_file=fopen($filepath,'w') ){
    fwrite($_file, $content);
    fclose($_file);
  } else {
    dol_syslog( 'Ecriture impossible dans '.$filepath, LOG_WARNING );
  }
}


/**
 * Retourne le chemin vers un fichier (dans documents) a partir de l'url
 */
function url_to_path($url){
  $path = '';

  if(strpos($url, DOL_MAIN_URL_ROOT)!==0) return FALSE;

  $url = str_replace(DOL_MAIN_URL_ROOT, '', $url);
  $t_url = explode('/', $url);
  $path =  DOL_DOCUMENT_ROOT . implode(DIRECTORY_SEPARATOR, $t_url);

  return $path;
}

/**
 * Retire les accents d'un texte
 */
function stripAccents($stripAccents){
  return strtr(utf8_decode($stripAccents),'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
}



// --------------------------------------------------------------------

/**
 * Retourne le nom des mois
 */
function getMonthNames(){
  return [
    1 => 'janvier',
    2 => 'fevrier',
    3 => 'mars',
    4 => 'avril',
    5 => 'mai',
    6 => 'juin',
    7 => 'juillet',
    8 => 'aout',
    9 => 'septembre',
    10 => 'octobre',
    11 => 'novembre',
    12 => 'decembre',
  ];
}


/**
 * Affiche "joliement" la date a partir d un date au format yyyymmddhhiiss
 */
function prettyDate($date, $calc_date_expression=NULL){
  $prettyDate = $date;

  // parse la date
  $t_date = ar²y();
  if(preg_match('/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/',$date,$t_match)){ //yyyymmddhhiiss
    $t_date = array(
      'y' => $t_match[1], 'm' => $t_match[2], 'd' => $t_match[3],
      'h' => $t_match[4], 'i' => $t_match[5], 's' => $t_match[6],
    );
  } elseif(preg_match('/^(\d{4})(\d{2})(\d{2})$/',$date,$t_match)) { //yyyymmdd
    $t_date = array(
      'y' => $t_match[1], 'm' => $t_match[2], 'd' => $t_match[3],
      'h' => 0, 'i' => 0, 's' => 0,
    );
  } elseif(preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d)?$/',$date,$t_match)){ //yyyy-mm-dd hh:ii:ss(.s)
    $t_date = array(
      'y' => $t_match[1], 'm' => $t_match[2], 'd' => $t_match[3],
      'h' => $t_match[4], 'i' => $t_match[5], 's' => $t_match[6],
    );
  } elseif(preg_match('/^(\d{4})-(\d{2})-(\d{2})$/',$date,$t_match)){ //yyyy-mm-dd
    $t_date = array(
      'y' => $t_match[1], 'm' => $t_match[2], 'd' => $t_match[3],
      'h' => 0, 'i' => 0, 's' => 0,
    );
  }

  // applique un calcul a la date
  if($t_date and $calc_date_expression){
    $strtime =  $t_date['y'].'-'.$t_date['m'].'-'.$t_date['d'].' '.$t_date['h'].':'.$t_date['i'].':'.$t_date['s'];
    $strtimecalc = date('Y m d H i s',strtotime($calc_date_expression, strtotime($strtime)));
    $t_timecalc = explode(' ', $strtimecalc);
    if($t_timecalc){
      $t_date = array(
        'y' => $t_timecalc[0], 'm' => $t_timecalc[1], 'd' => $t_timecalc[2],
        'h' => $t_timecalc[3], 'i' => $t_timecalc[4], 's' => $t_timecalc[5],
      );
    }
  }

  // creer la jolie date a partir de ce qui a ete parse
  if($t_date){
    $t_monthName = getMonthNames();
    $prettyDate = $t_date['d'].'/'.$t_date['m'].'/'.$t_date['y'];
  }

  return $prettyDate;
}


/**
 * Affiche "joliement" l heure a partir de la consommation en seconde
 */
function prettyTime($time){
  $prettyTime = '';

  $s = $time%60;
  $m = (($time-$s)/60)%60;
  $h = (((($time-$s)/60)-$m)/60);

  $ss = str_pad($s, 2, '0', STR_PAD_LEFT);
  $mm = str_pad($m, 2, '0', STR_PAD_LEFT);
  $hh = str_pad($h, 2, '0', STR_PAD_LEFT);

//    $prettyTime = $hh.':'.$mm.':'.$ss;
  if($h>0 && $m>0){ $prettyTime = $h.' h '.$mm.' min'; }
  elseif($h>0){ $prettyTime = $h.' h'; }
  elseif($m>0){ $prettyTime = $m.' min'; }
  elseif($s>=0){ $prettyTime = $s.' s'; }

  return $prettyTime;
}


/**
 * Affiche "joliement" un entier : 'ducducdu' -> 'du cdu cdu'
 */
function prettyPrice($int){
  return number_format($int, 0, ',', ' ').' XPF';
}


/**
 * Affiche "joliement" un entier : 'ducducdu' -> 'du cdu cdu'
 */
function prettySMS($int){
  return number_format($int, 0, ',', ' ').' SMS';
}


/**
 * Affiche "joliement" un entier : 'ducducdu' -> 'du cdu cdu'
 */
function prettyInt($int){
  return number_format($int, 0, ',', ' ');
}


/**
 * Affiche "joliement" un nombre : 'ducducdu(.dcmdcm)' -> 'du cdu cdu.dcmdcm'
 */
function prettyFloat($float, $decimal=NULL){
  $prettyFloat = $float;

  if( !isset($decimal) ){
    if(preg_match('/^(\d+)\.?(\d*)$/',$float,$t_match)){ //yyyy-mm-dd
      if($t_match[2]){
        $prettyFloat = number_format($t_match[1],0,',',' ').','.$t_match[2];
      } else {
        $prettyFloat = number_format($t_match[1],0,',',' ');
      }
    }
  } else {
    $prettyFloat = number_format($float, 0, ',', ' ');
  }

  return $prettyFloat;
}


/**
 * Affiche "joliement" un numero de telephone : '00000000' -> '00 00 00 00'
 */
function prettyPhoneNumber($phoneNumber){
  return chunk_split($phoneNumber, 2, ' ');;
}


/**
 * Affiche "joliement" la data a partir de la consommation en octet
 */
function prettyOctet($octet, $precision=2){
  $units = array('o', 'Ko', 'Mo', 'Go', 'To');

  $octet = max($octet, 0);
  $pow = floor(($octet ? log($octet) : 0) / log(1024));
  $pow = min($pow, count($units) - 1);

  $octet /= pow(1024, $pow);
  // $bytes /= (1 << (10 * $pow));

  return prettyFloat(round($octet, $precision)) . ' ' . $units[$pow];
}


/**
 * Affiche "joliement" la RIB
 */
function prettyRIB($rib){
  $rib = str_replace(' ','', $rib);
  return substr($rib,0,5).' '.substr($rib,5,5).' '.substr($rib,10,11).' '.substr($rib,21,2);
}