<?php
// db.php
$host = 'localhost';
$user = 'u329947844_ems2025';
$password = 'Ems@2025';
$dbname = 'u329947844_ems2025';
$port = null;
$socket = null;

error_reporting(E_ALL);
ini_set('display_errors', 1); // Temporarily enable to debug error 500

// ✅ Enable mysqli to throw exceptions BEFORE the connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = new mysqli($host, $user, $password, $dbname, $port, $socket);

    if ($conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }

    if (!$conn->set_charset("utf8mb4")) {
        throw new Exception("Error loading character set utf8mb4: " . $conn->error);
    }

    $conn->query("SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'");
    $conn->query("SET time_zone = '+00:00'");

} catch (Exception $e) {
    error_log("Database connection error: " . $e->getMessage());
    die("We're experiencing technical difficulties. Please try again later.");
}

function close_db_connection() {
    global $conn;
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
}
register_shutdown_function('close_db_connection');
?>