<?php
class Database {
    private $host;
    private $user;
    private $pass;
    private $db_name;
    private $conn;

    public function __construct() {
        $this->host = getenv('DB_HOST') ?: 'localhost';
        $this->user = getenv('DB_USER') ?: 'root';
        $this->pass = getenv('DB_PASS') ?: '';
        $this->db_name = getenv('DB_NAME') ?: 'carikospwtdb';
    }

    public function connect() {
        try {
            $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->db_name);
            
            if ($this->conn->connect_error) {
                throw new Exception("Koneksi database gagal: " . $this->conn->connect_error);
            }
            
            if (!$this->conn->set_charset("utf8mb4")) {
                throw new Exception("Error setting charset: " . $this->conn->error);
            }
            
            return $this->conn;
        } catch (Exception $e) {
            error_log("Database connection error: " . $e->getMessage());
            die("Terjadi kesalahan pada sistem. Silakan coba lagi nanti.");
        }
    }

    public function close() {
        if ($this->conn) {
            $this->conn->close();
        }
    }
}
?>