<?php
// Define a base URL for the application to make URLs portable
if (!defined('BASE_URL')) {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $script_name = $_SERVER['SCRIPT_NAME']; // The path to the current script, e.g., /public/index.php
    define('BASE_URL', $protocol . $host . $script_name);
}

// Database configuration for SI-INAL Asset IT System
define('DB_HOST', 'localhost');
define('DB_USER', 'root'); // Default XAMPP user
define('DB_PASS', '');     // Default XAMPP password (often empty)
define('DB_NAME', 'rsjantun_sinal_asset_db'); // Recommended database name

/**
 * Establishes a database connection using PDO.
 *
 * @return PDO PDO object on successful connection.
 * @throws PDOException if the connection fails.
 */
function connectDB() {
    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    try {
        $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        return $pdo;
    } catch (PDOException $e) {
        // In a production environment, log the error and show a generic message.
        // For development, displaying the error is acceptable.
        error_log("Database connection failed: " . $e->getMessage());
        die("Koneksi database gagal: " . $e->getMessage());
    }
}

// Optionally, you can test the connection here or in a separate script
// $pdo = connectDB();
// if ($pdo) {
//     echo "Database connected successfully!";
// }
