<?php
// db.php - Database connection helper using PDO with .env support

if (!function_exists('load_env')) {
    function load_env($path) {
        if (!file_exists($path)) {
            return false;
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            // Skip comments
            if (strpos(trim($line), '#') === 0) {
                continue;
            }

            // Split key and value
            $parts = explode('=', $line, 2);
            if (count($parts) === 2) {
                $key = trim($parts[0]);
                $value = trim($parts[1]);

                // Remove surrounding quotes if any
                $value = trim($value, "\"'");

                $_ENV[$key] = $value;
                putenv("$key=$value");
            }
        }
        return true;
    }
}

// Load env variables
load_env(__DIR__ . '/.env');

// Retrieve DB configurations with fallbacks
$db_host = getenv('DB_HOST') ?: '127.0.0.1';
$db_port = getenv('DB_PORT') ?: '3306';
$db_user = getenv('DB_USER') ?: 'root';
$db_pass = getenv('DB_PASSWORD') ?: '';
$db_name = getenv('DB_NAME') ?: 'ecommerce_db';

$pdo = null;

try {
    $dsn = "mysql:host=$db_host;port=$db_port;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,
    ];
    
    $pdo = new PDO($dsn, $db_user, $db_pass, $options);
    
    // Log success (can be customized or silenced to prevent log clutter)
    // We log it only once per session or simple error_log for tracing
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (!isset($_SESSION['db_connected'])) {
        error_log("Database connection successful to host: $db_host");
        $_SESSION['db_connected'] = true;
    }
} catch (PDOException $e) {
    error_log("Database connection failed to host: $db_host. Error: " . $e->getMessage());
    // Send a clean JSON error response instead of crashing with an uncaught exception/HTTP 500
    header('Content-Type: application/json');
    echo json_encode(array(
        "status" => "error",
        "message" => "Database connection failed: " . $e->getMessage()
    ));
    exit;
}

/**
 * Helper function to retrieve PDO instance
 */
function get_db_connection() {
    global $pdo;
    return $pdo;
}
