<?php

class DBconnection
{
    private $host;
    private $dbname;
    private $username;
    private $password;
    private $charset = 'utf8mb4';

    public function __construct()
    {
        // Detectar entorno automaticamente
        if ($this->isLocalEnvironment()) {
            // Configuracion local
            $this->host = "localhost";
            $this->dbname = "diamond_db";
            $this->username = "root";
            $this->password = "";
        } else {
            // Configuracion servidor
            $this->host = 'localhost';
            $this->dbname = 'diamondfp_sitio';
            $this->username = 'diamondfp_usuarioSitio';
            $this->password = 'Diamond2025$$';
        }
    }

    private function isLocalEnvironment()
    {
        $localHosts = [
            'localhost',
            '127.0.0.1',
            'diamond.local',
            'diamond.test'
        ];

        $currentHost = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
        
        // Verificar si estamos en local
        return in_array($currentHost, $localHosts) || 
               strpos($currentHost, '.local') !== false ||
               strpos($currentHost, '.test') !== false ||
               strpos($currentHost, 'localhost') !== false;
    }

    public function connect()
    {
        try {
            $dsn = "mysql:host={$this->host};dbname={$this->dbname};charset={$this->charset}";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            return new PDO($dsn, $this->username, $this->password, $options);
        } catch (PDOException $e) {
            die(json_encode([
                'status' => 'error',
                'message' => 'Error de conexi贸n: ' . $e->getMessage()
            ]));
        }
    }
}