<?php

require_once __DIR__ . '/env.php';

class Database
{
    public function connect(): PDO
    {
        $host = env('DB_HOST');
        $port = env('DB_PORT', 3306);
        $dbName = env('DB_NAME');
        $username = env('DB_USER');
        $password = env('DB_PASSWORD');
        $charset = env('DB_CHARSET', 'utf8mb4');

        if (!$host || !$dbName || !$username || !$password) {
            http_response_code(500);

            echo json_encode([
                'success' => false,
                'message' => 'Faltan variables de conexión a la base de datos'
            ], JSON_UNESCAPED_UNICODE);

            exit;
        }

        try {
            $dsn = "mysql:host={$host};port={$port};dbname={$dbName};charset={$charset}";

            return new PDO($dsn, $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]);
        } catch (PDOException $e) {
            error_log('Error de conexión a la base de datos: ' . $e->getMessage());

            http_response_code(500);

            echo json_encode([
                'success' => false,
                'message' => 'Error de conexión a la base de datos'
            ], JSON_UNESCAPED_UNICODE);

            exit;
        }
    }
}