<?php
// .env 파일 로드
function loadEnv() {
  $envFile = $_SERVER['DOCUMENT_ROOT'] . '/.env';
  if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
      if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
      }
    }
  }
}

function db_connect(){  //DB연결을 함수로 정의
  loadEnv();

  $db_host = $_ENV['DB_HOST'] ?? 'localhost';
  $db_name = $_ENV['DB_NAME'] ?? 'chandj';
  $db_user = $_ENV['DB_USER'] ?? 'chandj';
  $db_pass = $_ENV['DB_PASS'] ?? '';

  $dsn = "mysql:host=".$db_host.";dbname=".$db_name.";charset=utf8mb4";

  try {
    $pdo = new PDO($dsn, $db_user, $db_pass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_EMULATE_PREPARES => false,
      PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4, sql_mode='NO_ENGINE_SUBSTITUTION'"
    ]);
  } catch (PDOException $Exception) {
    die('오류:'.$Exception->getMessage());
  }
  return $pdo;
}
?>