<?php
    /*
       *****************************************************************************
       * MEGA Digital Space - by MEGA Digital Studio                               *
       * ------------------------------------------------------------------------- *
       * CMS Website:  https://megadigital.space                                   *
       * License:  https://megadigital.space/license                               *
       * Owner:  Giorgi Basharuli                                                  *
       * Contact:  online@megadigital.studio                                       *
       * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
       * Website:  https://megadigital.studio                                      *
       * ------------------------------------------------------------------------- *
       * Description: This file is a part of the MEGA Digital Space CMS system.    *
       * Unauthorized distribution, modification, or commercial use is strictly -  *
       * prohibited without prior written permission.                              *
       * ------------------------------------------------------------------------- *
       * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
       * All rights reserved.                                                      *
       *****************************************************************************
    */

    loadEnv(__DIR__ . '/../../engine/data/.env');

    $enabledDatabase = getenv('DB_ENABLED') ?: 'mysql';

    $databaseSettings = [
        'enabled_database' => $enabledDatabase,
        'mysql' => [
            'user' => getenv('DB_USER'),
            'password' => getenv('DB_PASSWORD'),
            'database' => getenv('DB_NAME'),
            'host' => getenv('DB_HOST'),
        ],
        'pgsql' => [
            'user' => getenv('DB_USER'),
            'password' => getenv('DB_PASSWORD'),
            'database' => getenv('DB_NAME'),
            'host' => getenv('DB_HOST'),
        ],
        'mongo' => [],
    ];

    $databaseSettings = $databaseSettings[$enabledDatabase] ?? [];

    $db_connect = new \Medoo\Medoo([
        'type' => $enabledDatabase,
        'host' => $databaseSettings['host'],
        'database' => $databaseSettings['database'],
        'username' => $databaseSettings['user'],
        'password' => $databaseSettings['password']
    ]);

    function mailingLog($message)
    {
        file_put_contents(__DIR__ . '/main.log', $message . "\n", FILE_APPEND);
    }

    function loadEnv($file) {
        if (!file_exists($file)) return;
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            if (strpos(trim($line), '#') === 0) continue;
            [$name, $value] = explode('=', $line, 2);
            putenv(trim($name) . '=' . trim($value));
            $_ENV[trim($name)] = trim($value);
        }
    }