<?php

declare(strict_types=1);

\main_tts\registry::get('di')->register('db', function(array $args) {
    if (isset($args[0])) {
      $db_select = $args[0];
    } else {
      $db_select = 'database';
    } 
    
    $error_mode = \main_tts\configure::get('database', 'PDO_ERROR');
    if ($error_mode === null) {
      $error_mode = PDO::ERRMODE_EXCEPTION;
    }

    $options = array(
      PDO::ATTR_PERSISTENT => \main_tts\configure::get('database', 'PDO_PERSISTENT'),
      PDO::ATTR_ERRMODE => $error_mode,
      PDO::ATTR_TIMEOUT => \main_tts\configure::get('database', 'PDO_TIMEOUT'),
    );

    $db_info = \main_tts\configure::get($db_select);
    \main_tts\configure::wipe($db_select);
    $db_socket = (isset($db_info['SOCKET'])) ? $db_info['SOCKET'] : false;
    
    try {
      $pdo_set_time = \bs_tts\common::get_bool(\main_tts\configure::get('database', 'PDO_SET_TIME'));
    } catch (\tts\exceptions\Bool_Exception $e) {
      echo $e->errorMessage();
    }

    try {
      if (! empty($db_socket)) {
        $dsn = $db_info['TYPE'] . ':unix_socket=' . $db_socket . ';dbname=' . $db_info['NAME'];       
      } else {
        $dsn = $db_info['TYPE'] . ':host=' . $db_info['HOST'] . ';port=' . $db_info['PORT'] . ';dbname=' . $db_info['NAME'];
      }
      $pdo = new PDO($dsn, $db_info['USER'], $db_info['PASS'], $options);
      \bs_tts\common::wipe($dsn);
      
      if ($pdo_set_time === true) {
        $pdo->query("SET NAMES 'utf8';");
        $pdo->query("SET CHARACTER SET utf8;");
        $pdo->query("SET CHARACTER_SET_CONNECTION=utf8;");
        $pdo->query("SET SQL_MODE = '';");
        $pdo->query("SET time_zone = '+00:00';");
      }
      
      return $pdo;
    } catch (\PDOException $e) {
        \tts\exceptions\DB_Exception::customMessage($e);
    }
});