<?php
session_start();
class Database
{
    private $host = "localhost";
    private $db_name = "yoveraes_botica";
    private $username = "yoveraes_userdb";
    private $password = "t7@s5FxYn1GB";
    public $conn;

    public function getConnection()
    {
        $this->conn = null;
        try {
            $this->conn = new mysqli($this->host, $this->username, $this->password, $this->db_name);

            if ($this->conn->connect_error) {
                throw new Exception("Error de conexión: " . $this->conn->connect_error);
            }

            $this->conn->set_charset("utf8mb4");

            // Configurar zona horaria si es necesario
            $this->conn->query("SET time_zone = '-05:00'"); // Para Perú

        } catch (Exception $e) {
            die("<div class='alert alert-danger'>
                    <h4>Error de Conexión a la Base de Datos</h4>
                    <p>" . $e->getMessage() . "</p>
                    <p>Por favor, verifica la configuración en config/database.php</p>
                </div>");
        }
        return $this->conn;
    }

    // Método para cerrar la conexión
    public function closeConnection()
    {
        if ($this->conn) {
            $this->conn->close();
        }
    }
}

// Crear instancia global de base de datos
$database = new Database();
$conn = $database->getConnection();

// Función para sanitizar datos
function sanitize($data)
{
    global $conn;
    return mysqli_real_escape_string($conn, trim($data));
}

// Función para registrar errores
function logError($error, $file = '', $line = '')
{
    $logMessage = date('Y-m-d H:i:s') . " - Error: $error";
    if ($file)
        $logMessage .= " - File: $file";
    if ($line)
        $logMessage .= " - Line: $line";
    $logMessage .= PHP_EOL;

    file_put_contents('logs/error_log.txt', $logMessage, FILE_APPEND);
}
?>