<?php
// Konfigurasi Database Umbul Tirtomarto V2
// Wahana Kreasi Nusantara

// Untuk production, sesuaikan dengan konfigurasi hosting
// Bisa juga menggunakan environment variables atau file .env
define('DB_HOST', getenv('DB_HOST') ?: 'localhost');
define('DB_USER', getenv('DB_USER') ?: 'umbultir_lkt');
define('DB_PASS', getenv('DB_PASS') ?: 'Sukses2026');
define('DB_NAME', getenv('DB_NAME') ?: 'umbultir_lkt');

// Koneksi Database
function getConnection() {
    static $conn = null;
    
    if ($conn === null) {
        try {
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            
            if ($conn->connect_error) {
                throw new Exception("Koneksi database gagal: " . $conn->connect_error);
            }
            
            $conn->set_charset("utf8mb4");
        } catch (Exception $e) {
            die("Error: " . $e->getMessage());
        }
    }
    
    return $conn;
}

// Fungsi untuk query dengan prepared statement
function query($sql, $params = [], $types = '') {
    $conn = getConnection();
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    return $result;
}

// Fungsi untuk insert dan return last ID
function insert($sql, $params = [], $types = '') {
    $conn = getConnection();
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    $stmt->execute();
    $lastId = $conn->insert_id;
    $stmt->close();
    
    return $lastId;
}

// Fungsi untuk update/delete dan return affected rows
function execute($sql, $params = [], $types = '') {
    $conn = getConnection();
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    
    return $affected;
}
?>
