<?php
declare(strict_types=1);

if (defined('EDEN_DB_BOOTSTRAPPED')) return;
define('EDEN_DB_BOOTSTRAPPED', true);

// Turn OFF strict crash for now (debug friendly)
mysqli_report(MYSQLI_REPORT_OFF);

// Load config if exists
$cfg = __DIR__ . '/config.php';
if (is_file($cfg)) {
  require_once $cfg;
}

// DB credentials
$host = defined('DB_HOST') ? DB_HOST : 'localhost';
$name = defined('DB_NAME') ? DB_NAME : 'elms';
$user = defined('DB_USER') ? DB_USER : 'root';
$pass = defined('DB_PASS') ? DB_PASS : '';
$port = defined('DB_PORT') ? (int)DB_PORT : 0;

try {
  $mysqli = new mysqli($host, $user, $pass, $name, $port);
  $mysqli->set_charset('utf8mb4');

  // Make globally available
  $GLOBALS['mysqli'] = $mysqli;
  $GLOBALS['conn']   = $mysqli;

  // Timezone sync (safe)
  $tzId = date_default_timezone_get();
  if ($tzId) {
    $tz  = new DateTimeZone($tzId);
    $now = new DateTime('now', $tz);
    $off = $tz->getOffset($now);

    $sign = $off < 0 ? '-' : '+';
    $off = abs($off);
    $hh = str_pad((string)floor($off / 3600), 2, '0', STR_PAD_LEFT);
    $mm = str_pad((string)floor(($off % 3600) / 60), 2, '0', STR_PAD_LEFT);

    $mysqli->query("SET time_zone='{$sign}{$hh}:{$mm}'");
  }

} catch (Throwable $e) {
  http_response_code(500);
  echo "<pre>DB ERROR: " . htmlspecialchars($e->getMessage()) . "</pre>";
  exit;
}

// SINGLE helper function (only one!)
function ec_db(): mysqli {
  return $GLOBALS['mysqli'];
}