<?php
setlocale(LC_ALL, 'fr', 'fr_FR', 'french', 'fra', 'fra_FRA', 'fr_FR.ISO_8859-1', 'fra_FRA.ISO_8859-1', 'fr_FR.utf8', 'fr_FR.utf-8', 'fra_FRA.utf8', 'fra_FRA.utf-8');

require_once dirname(__DIR__, 3) . '/config/Database.php';

$today = date("Y-m-d H:i:s");
$dateFr = date("d/m/Y");
$dateTimeFr = date("d/m/Y H:i:s");
$timeFr = date("H:i:s");

$jour = array("Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi");
$jour_abr = array("Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam");
$mois = array("", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
$mois_abr = array("", "Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aoû", "Sep", "Oct", "Nov", "Déc");

function getinfos($cSQL, $dbn = "gen", $format = "normal") {
  try {
    $db = Database::getInstance();
    $result = $db->fetchAll($cSQL);
    
    if (strtolower($format) == "json") {
      return json_encode($result);
    }
    return $result;
    
  } catch (Exception $e) {
    if ($_ENV['APP_DEBUG'] ?? false) {
      error_log("Erreur getinfos: " . $e->getMessage());
    }
    return ($format == "json") ? json_encode([]) : [];
  }
}

function qSQL($qsql, $dbn = "gen", $lastid = false) {
  try {
    $db = Database::getInstance();
    
    $queryType = strtoupper(substr(trim($qsql), 0, 6));
    
    if ($queryType === 'INSERT' || $queryType === 'UPDATE' || $queryType === 'DELETE') {
      $stmt = $db->query($qsql);
      
      if ($lastid && $queryType === 'INSERT') {
        return $db->lastInsertId();
      }
      
      if ($stmt instanceof PDOStatement) {
        return $stmt->rowCount() > 0;
      }
      
      return $stmt;
    } else {
      return $db->query($qsql);
    }
    
  } catch (Exception $e) {
    if ($_ENV['APP_DEBUG'] ?? false) {
      error_log("Erreur qSQL: " . $e->getMessage());
    }
    return false;
  }
}

function hashPsswd($p) {
  $options = [
    'cost' => 11,
  ];
  $psswd = password_hash($p, PASSWORD_BCRYPT, $options);
  return $psswd;
}

function createPsswd($id, $p, $dbgen = "gen") {
  global $Conf;
  global $Route;

  $psswd = hashPsswd($p);
  
  try {
    $db = Database::getInstance();
    
    $table = $Conf->_tbusers ?? 'users';
    $sql = "UPDATE $table SET password = :password WHERE rowid = :id";
    
    $result = $db->query($sql, ['password' => $psswd, 'id' => $id]);
    
    if ($result instanceof PDOStatement && $result->rowCount() > 0) {
      eLog(0, "Changement de mot de passe réussi pour l'utilisateur ID: $id");
      return true;
    }
    
    return false;
    
  } catch (Exception $e) {
    error_log("Erreur createPsswd: " . $e->getMessage());
    return false;
  }
}

function vPassword($p, $hashed) {
  if (password_verify($p, $hashed)) {
    return true;
  } else {
    return false;
  }
}

function nettoie_chaine($input) {
  if (is_null($input)) {
    $input = "";
  }
  $res = trim(str_replace("'", "'", $input));
  $res = trim(str_replace('"', """, $res));
  $res = str_replace('<', '&lt;', $res);
  $res = str_replace('>', '&gt;', $res);
  return $res;
}

function nettoie_input($input) {
  if (is_null($input)) {
    $input = "";
  }
  $input = trim($input);
  $input = stripslashes($input);
  $input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
  return $input;
}

function nettoie($input) {
  if (is_null($input)) {
    $input = "";
  }
  $res = trim($input);
  $res = str_replace("'", "'", $res);
  $res = str_replace('"', '"', $res);
  $res = str_replace('<', '', $res);
  $res = str_replace('>', '', $res);
  return $res;
}

function dateEN($date) {
  if ($date == '') return '';
  if (strpos($date, '/') !== false) {
    list($jour, $mois, $annee) = explode('/', $date);
    return $annee . '-' . $mois . '-' . $jour;
  }
  return $date;
}

function dateFR($date) {
  if ($date == '' || $date == '0000-00-00') return '';
  if (strpos($date, '-') !== false) {
    list($annee, $mois, $jour) = explode('-', substr($date, 0, 10));
    return $jour . '/' . $mois . '/' . $annee;
  }
  return $date;
}

function datetimeFR($datetime) {
  if ($datetime == '' || $datetime == '0000-00-00 00:00:00') return '';
  list($date, $time) = explode(' ', $datetime);
  return dateFR($date) . ' ' . substr($time, 0, 5);
}

function eLog($user = 0, $comment = "", $notif = false) {
  global $Conf;
  global $Session;
  global $Route;
  
  if ($comment == "") return;
  
  $script = isset($Route->_script) ? $Route->_script : "";
  $dt = date("Y-m-d H:i:s");
  
  if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  } else {
    $ip = $_SERVER["REMOTE_ADDR"];
  }
  
  $hn = getHostByName($ip);
  $ha = @getHostByAddr($hn);
  $us = substr($_SERVER["HTTP_USER_AGENT"] ?? '', 0, 100);
  
  if (isset($Session->_user["rowid"])) {
    $user = $Session->_user["rowid"];
    if ($user == "") {
      $user = 0;
    }
  }

  $appname = isset($Conf->_appname) ? $Conf->_appname : '';
  
  try {
    $db = Database::getInstance();
    
    $sql = "INSERT INTO z_logs (fk_user, script, user_agent, http_host, ip_client, appname, commentaire, date_histo, notif) 
            VALUES (:user, :script, :user_agent, :host, :ip, :appname, :comment, :date, :notif)";
    
    $params = [
      'user' => $user,
      'script' => $script,
      'user_agent' => $us,
      'host' => $ha,
      'ip' => $ip,
      'appname' => $appname,
      'comment' => $comment,
      'date' => $dt,
      'notif' => $notif ? 1 : 0
    ];
    
    $db->query($sql, $params);
    
  } catch (Exception $e) {
    error_log("Erreur eLog: " . $e->getMessage());
  }

  if (strpos(strtolower($comment), 'erreur') !== false) {
    error_log($dt . ";" . $ip . ";" . $script . ";" . $comment . "\r\n", 3, "./" . $Conf->_appname . ".log");
  }
}

function debug($data, $type = 'DEBUG', $level = 3) {
  global $Conf;
  
  if (!isset($Conf)) return;
  
  if (method_exists($Conf, 'debug')) {
    $Conf->debug($data, $type, $level);
  } else {
    if ($Conf->_debug_level >= $level) {
      $timestamp = date('Y-m-d H:i:s');
      $message = "[$timestamp] [$type] " . (is_array($data) ? json_encode($data) : $data);
      error_log($message);
    }
  }
}

function timeStart() {
  return microtime(true);
}

function timeEnd($start, $label = '') {
  $end = microtime(true);
  $time = round(($end - $start) * 1000, 2);
  
  global $Conf;
  if (isset($Conf) && $Conf->_log_performance) {
    debug("Performance [$label]: {$time}ms", 'PERFORMANCE', 3);
  }
  
  return $time;
}