<?php
// ============================================================
// Database configuration — update credentials before deploy
// ============================================================
function envOrDefault(string $key, string $default): string {
    $val = getenv($key);
    return ($val === false || $val === '') ? $default : $val;
}

define('DB_HOST', envOrDefault('DB_HOST', 'localhost'));
define('DB_PORT', envOrDefault('DB_PORT', '3306'));
define('DB_NAME', envOrDefault('DB_NAME', 'zehhtcjdcq_stile_lpg'));
define('DB_USER', envOrDefault('DB_USER', 'zehhtcjdcq_umer'));
define('DB_PASS', envOrDefault('DB_PASS', 'UmerShaikh12'));
define('DB_CHARSET', 'utf8mb4');

function getDB(): PDO {
    static $pdo = null;
    if ($pdo !== null) return $pdo;

    $dsn = sprintf(
        'mysql:host=%s;port=%s;dbname=%s;charset=%s',
        DB_HOST, DB_PORT, DB_NAME, DB_CHARSET
    );
    $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);
    } catch (PDOException $e) {
        error_log('Stiles LPG DB connection failed: ' . $e->getMessage());
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Database connection failed']);
        exit;
    }
    return $pdo;
}
