<?php

require_once dirname(__FILE__) . '/Database.php';

class Conf {
  const admin = 1;
  const intra = 1;
  const erp = 1;
  const magazine = 0;

  public $_appname = "cleo";
  public $_appscript = "login";
  public $_appversion = "2.0.4";
  public $_appenv;
  public $_apptitle = "CLEO - Gestion de devis";

  public $_brandname;
  public $_brandadresse1;
  public $_brandadresse2;
  public $_brandcp;
  public $_brandville;
  public $_brandtel;
  public $_brandemail;
  public $_brandlogo;
  public $_brandgroupe;
  public $_brandmulti;

  public $_piwikid;
  public $_googlid;

  public $_excludeIp;
  public $_clientIp;
  public $_devIp = false;

  public $_debug_level = 0;
  public $_log_sql = false;
  public $_log_performance = false;
  public $_log_file_path = '';

  public $_pathupload;

  public $_dbhost;
  public $_dbname;
  public $_dbuser;
  public $_dbpass;

  public $_entite = '';
  public $_new_version = false;

  public function __construct() {
    $this->loadEnvironment();
    $this->loadConfiguration();
    $this->setupDebug();
  }

  private function loadEnvironment() {
    $envFile = dirname(__DIR__) . '/.env';
    if (file_exists($envFile)) {
      $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;

        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);

        if (!isset($_ENV[$name])) {
          putenv(sprintf('%s=%s', $name, $value));
          $_ENV[$name] = $value;
          $_SERVER[$name] = $value;
        }
      }
    }

    $this->_dbhost = $_ENV['DB_HOST'] ?? 'localhost';
    $this->_dbname = $_ENV['DB_DATABASE'] ?? 'cleo';
    $this->_dbuser = $_ENV['DB_USERNAME'] ?? 'cleo_user';
    $this->_dbpass = $_ENV['DB_PASSWORD'] ?? '';

    $this->_excludeIp = $_ENV['EXCLUDE_IP'] ?? '';
    $this->_pathupload = $_ENV['UPLOAD_PATH'] ?? '/pub/files/upload/';

    $this->_appenv = $_ENV['APP_ENV'] ?? 'production';
    $this->_debug_level = $_ENV['LOG_LEVEL'] === 'debug' ? 4 : 0;
    $this->_log_sql = filter_var($_ENV['LOG_SQL'] ?? false, FILTER_VALIDATE_BOOLEAN);
    $this->_log_performance = filter_var($_ENV['LOG_PERFORMANCE'] ?? false, FILTER_VALIDATE_BOOLEAN);
  }

  private function loadConfiguration() {
    $http_host = $_SERVER['HTTP_HOST'];

    try {
      $db = Database::getInstance();

      $sql = "SELECT * FROM users_entites WHERE http_host LIKE :host AND active = 1 LIMIT 1";
      $entite = $db->fetchOne($sql, ['host' => "%$http_host%"]);

      if (empty($entite)) {
        $sql = "SELECT * FROM users_entites WHERE rowid = 1";
        $entite = $db->fetchOne($sql);
      }

      if ($entite) {
        $this->_entite = $entite;
        $this->_appname = $entite["appname"] ?? "cleo";
        $this->_apptitle = $entite["libelle"] ?? "CLEO";
        $this->_brandname = $entite["libelle"] ?? "";
        $this->_brandadresse1 = $entite["adresse1"] ?? "";
        $this->_brandadresse2 = $entite["adresse2"] ?? "";
        $this->_brandcp = $entite["cp"] ?? "";
        $this->_brandville = $entite["ville"] ?? "";
        $this->_brandtel = $entite["tel1"] ?? "";
        $this->_brandemail = $entite["email"] ?? "";
        $this->_brandlogo = $entite["appname"] ?? "cleo";
      }
    } catch (Exception $e) {
      error_log("Erreur de configuration: " . $e->getMessage());
      $this->setDefaultConfiguration();
    }
  }

  private function setDefaultConfiguration() {
    $this->_appname = "cleo";
    $this->_apptitle = "CLEO - Gestion de devis";
    $this->_brandname = "CLEO";
    $this->_brandemail = $_ENV['MAIL_FROM_ADDRESS'] ?? "noreply@example.com";
  }

  private function setupDebug() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
      $this->_clientIp = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
      $this->_clientIp = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else {
      $this->_clientIp = $_SERVER["REMOTE_ADDR"];
    }

    $http_host = $_SERVER['HTTP_HOST'] ?? '';
    $isDev = strpos($http_host, 'dcleo.unikoffice.com') !== false;
    $isRecette = strpos($http_host, 'rcleo.unikoffice.com') !== false;
    $isDebugEnv = $_ENV['APP_DEBUG'] === 'true' || $_ENV['APP_ENV'] === 'development';

    if ($isDev || $isRecette || $isDebugEnv) {
      ini_set('error_reporting', -1);
      ini_set('display_errors', '1');
      $this->_devIp = true;

      $this->_debug_level = 4;
      $this->_log_sql = true;
      $this->_log_performance = true;
      $this->_log_file_path = dirname(__DIR__) . '/log/' . date('md') . '.log';

      ini_set('log_errors', '1');
      ini_set('error_log', $this->_log_file_path);
      ini_set('display_startup_errors', '1');
    } else {
      ini_set('error_reporting', 0);
      ini_set('display_errors', '0');
      ini_set('log_errors', '0');
      $this->_debug_level = 0;
      $this->_log_sql = false;
      $this->_log_performance = false;
    }
  }

  public function debug($data, $type = 'DEBUG', $level = 3) {
    if ($this->_debug_level < $level) return;

    $levels = ['ERROR', 'WARNING', 'INFO', 'DEBUG'];
    $timestamp = date('Y-m-d H:i:s');
    $message = "[$timestamp] [$type] " . (is_array($data) ? json_encode($data) : $data) . PHP_EOL;

    if ($this->_log_file_path) {
      error_log($message, 3, $this->_log_file_path);
    }

    // Ne pas afficher les commentaires HTML pour les requêtes AJAX
    $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
      strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

    if ($this->_devIp && ini_get('display_errors') && !$isAjax) {
      echo "<!-- $message -->\n";
    }
  }
}
