<?php
// inc/db.php - Database Connection

class Database {
    private $pdo;
    
    public function __construct() {
        try {
            $this->pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch(PDOException $e) {
            error_log("Database connection failed: " . $e->getMessage());
            throw new Exception("Database connection failed");
        }
    }
    
    public function getConnection() {
        return $this->pdo;
    }
}

// Helper function for database queries
function db_query($sql, $params = []) {
    global $db;
    $stmt = $db->getConnection()->prepare($sql);
    $stmt->execute($params);
    return $stmt;
}

// Initialize database connection
try {
    $db = new Database();
} catch(Exception $e) {
    error_log("Database initialization failed: " . $e->getMessage());
}
?>