<?php
/**
 * Database Configuration
 * VeloDrive System
 */

// Use environment variables or defaults
if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
if (!defined('DB_NAME')) define('DB_NAME', 'car_rental_db');
if (!defined('DB_USER')) define('DB_USER', 'root');
if (!defined('DB_PASS')) define('DB_PASS', '');

// Currency Configuration
if (!defined('DEFAULT_CURRENCY')) define('DEFAULT_CURRENCY', 'PHP');
if (!defined('CURRENCY_SYMBOL')) define('CURRENCY_SYMBOL', '₱');
if (!defined('EXCHANGE_RATES')) define('EXCHANGE_RATES', [
    'PHP' => 1.00,
    'USD' => 0.018,
    'EUR' => 0.016,
    'GBP' => 0.014,
    'JPY' => 2.65
]);

// Initialize session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Database connection
function getDBConnection() {
    static $pdo_instance = null;
    if ($pdo_instance !== null) return $pdo_instance;

    try {
        $pdo_instance = 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
            ]
        );
        return $pdo_instance;
    } catch (PDOException $e) {
        // Throw exception instead of die() to allow graceful fallbacks
        throw new Exception("Database connection failed: " . $e->getMessage());
    }
}

// For compatibility with scripts that expect a global $pdo variable
try {
    $pdo = getDBConnection();
} catch (Exception $e) {
    $pdo = null;
}

// Currency helper functions
function formatCurrency($amount, $currency = DEFAULT_CURRENCY) {
    global $CURRENCY_SYMBOLS;
    $symbol = isset($CURRENCY_SYMBOLS[$currency]) ? $CURRENCY_SYMBOLS[$currency] : $currency . ' ';
    return $symbol . number_format($amount, 2);
}

function convertCurrency($amount, $from = 'USD', $to = DEFAULT_CURRENCY) {
    if ($from === $to) return $amount;

    $inBase = $amount * (EXCHANGE_RATES[$from] ?? 1);
    return $inBase / (EXCHANGE_RATES[$to] ?? 1);
}

$CURRENCY_SYMBOLS = [
    'PHP' => '₱',
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£',
    'JPY' => '¥'
];

// Helper functions
function isLoggedIn() {
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

function redirect($url) {
    header("Location: $url");
    exit;
}

function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

function generateReference($prefix = 'REF') {
    return $prefix . '-' . strtoupper(bin2hex(random_bytes(4)));
}

/**
 * Get Site Name from database
 */
function getSiteName() {
    // Forward to unified branding utility if available
    if (file_exists(__DIR__ . '/branding.php')) {
        require_once __DIR__ . '/branding.php';
        return getBrandName();
    }
    return 'VeloDrive';
}
