<?php
// Database configuration (use env vars for Docker)
$host = getenv('DB_HOST') ?: '127.0.0.1';
$dbname = getenv('DB_NAME') ?: 'attendance_system';
$username = getenv('DB_USER') ?: 'root';
$password = getenv('DB_PASS') !== false ? getenv('DB_PASS') : '';

try {
    // Create PDO connection
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
    
    // Optional: Set timezone
    $pdo->exec("SET time_zone = '+08:00'");
    
    // Uncomment for debugging
    // error_log("Database connected successfully");
    
} catch (PDOException $e) {
    // Log the error and show user-friendly message
    error_log("Database connection failed: " . $e->getMessage());
    
    // For development - show detailed error
    if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin') {
        die("Database connection failed: " . $e->getMessage());
    } else {
        die("System temporarily unavailable. Please try again later.");
    }
}
?>