<?php

function dbConnect($verbose)
{
	$getConfig = false;
	
	// Chercher config.php dans différents emplacements possibles
	$configPaths = [
		__DIR__ . '/../../config.php',  // Depuis Parametre/taghilt/
		dirname(dirname(__DIR__)) . '/config.php',  // Racine du projet
		'../config.php',
		'./config.php',
		'../../config.php'
	];
	
	foreach ($configPaths as $configPath) {
		if (file_exists($configPath)) {
			require_once $configPath;
			$getConfig = true;
			break;
		}
	}

	if ($getConfig) {
		$dbsystem = defined('DB_SYSTEM') ? DB_SYSTEM : 'mysql';
		$dbhost   = defined('DB_HOST')   ? DB_HOST   : 'localhost';
		$dbname   = defined('DB_NAME')   ? DB_NAME   : '';
		$user     = defined('DB_USER')   ? DB_USER   : '';
		$pass     = defined('DB_PASS')   ? DB_PASS   : '';

		$db = new mysqlDB($dbhost, $dbname, $user, $pass, $verbose);
		
		// Log de débogage en cas d'échec de connexion
		if (!$db->connected && $verbose) {
			error_log("Échec de connexion à la base de données: host=$dbhost, db=$dbname, user=$user");
		}
		
		return $db->connected ? $db : false;
	} else {
		// Log d'erreur si config.php n'est pas trouvé
		if ($verbose) {
			error_log("Fichier config.php introuvable. Chemins testés: " . implode(', ', $configPaths));
		}
		return false;
	}
}

class mysqlDB
{
    private string $host;
    private string $db;
    private string $user;
    private string $pass;
    private bool $verbose;
    public $link_id;
    public $result;
    public int $rows = 0;
    public array $data = [];
    public bool $connected = false;
    public $connexion;

    public function __construct($dbhost, $dbname, $user, $pass, $verbose = false)
    {
        $this->host = $dbhost;
        $this->db = $dbname;
        $this->user = $user;
        $this->pass = $pass;
        $this->verbose = $verbose;


        $this->connect();
    }

    private function connect(): void
    {
        try {
            $this->link_id = @mysqli_connect($this->host, $this->user, $this->pass, $this->db);

            if (!$this->link_id) {
                $this->connected = false;
            } else {
                mysqli_set_charset($this->link_id, 'utf8');
                $this->connected = true;
            }

        } catch (Exception $e) {
            $this->connected = false;
        }
    }

    public function isConnected(): bool
    {
        return $this->connected;
    }

    public function close(): void
    {
        if ($this->link_id) {
            mysqli_close($this->link_id);
        }
    }

    public function exec($sql): int
    {
        $this->data = [];
        $this->result = mysqli_query($this->link_id, $sql);
        $this->rows = mysqli_affected_rows($this->link_id);

        if (stripos(trim($sql), 'select') === 0 && $this->rows > 0) {
            while ($row = mysqli_fetch_array($this->result, MYSQLI_ASSOC)) {
                $this->data[] = $row;
            }
        }

        return $this->rows;
    }

    public function execMulti($sql): bool
    {
        return mysqli_multi_query($this->link_id, $sql);
    }

    public function execQuery($sql): bool
    {
        return (bool)mysqli_query($this->link_id, $sql);
    }

    public function fetchArray($sql): array
    {
        $result = mysqli_query($this->link_id, $sql);
        $data = [];
        if ($result) {
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $data[] = $row;
            }
        }
        return $data;
    }

    public function getData(): array
    {
        return $this->data;
    }

    public function getRow(int $index = 0): ?array
    {
        return $this->data[$index] ?? null;
    }

    public function getColumn(string $key): array
    {
        return array_column($this->data, $key);
    }

    public function escape(string $value): string
    {
        return mysqli_real_escape_string($this->link_id, $value);
    }
}
