<?php

/**
 * SAP RFC Environment Checker
 * run with: php check-sap.php
 */
echo "\e[1;34m=== SAP RFC ENVIRONMENT CHECKER ===\e[0m\n\n";

// 1. Check PHP Extension
echo "[1] Checking PHP Extension 'sapnwrfc'...\n";
if (extension_loaded('sapnwrfc')) {
    echo "\e[32m[OK]\e[0m Extension 'sapnwrfc' is loaded.\n";
} else {
    echo "\e[31m[FAIL]\e[0m Extension 'sapnwrfc' is NOT loaded.\n";
    echo "      Tip: Check your php.ini and ensure 'extension=sapnwrfc.so' is present.\n";
}

// 2. Check SAPNWRFC Class
echo "\n[2] Checking SAPNWRFC Class existence...\n";
if (class_exists('SAPNWRFC\Connection')) {
    echo "\e[32m[OK]\e[0m SAPNWRFC classes are available.\n";
} else {
    echo "\e[31m[FAIL]\e[0m SAPNWRFC classes are NOT found.\n";
}

// 3. Check SAP SDK via ldconfig
echo "\n[3] Checking SAP NW RFC SDK in system libraries...\n";
$ldOutput = shell_exec('ldconfig -p | grep sap');
if ($ldOutput) {
    echo "\e[32m[OK]\e[0m SAP libraries found in ldconfig:\n";
    echo $ldOutput;
} else {
    echo "\e[33m[WARNING]\e[0m No SAP libraries found in ldconfig.\n";
    echo "          You might need to add the SDK 'lib' path to /etc/ld.so.conf.d/sap.conf\n";
}

// 4. Check for common SDK locations
echo "\n[4] Searching for SDK in common paths...\n";
$commonPaths = [
    '/usr/local/sap/nwrfcsdk',
    '/opt/sap/nwrfcsdk',
    '/usr/sap/nwrfcsdk',
];
$found = false;
foreach ($commonPaths as $path) {
    if (is_dir($path)) {
        echo "\e[32m[FOUND]\e[0m SDK directory detected at: $path\n";
        $found = true;
    }
}
if (! $found) {
    echo "\e[31m[NOT FOUND]\e[0m Could not find SDK in common locations.\n";
}

// 5. Check Project Config
echo "\n[5] Checking Project .env configuration...\n";
$envContent = file_get_contents('.env');
if (strpos($envContent, 'SAP_RFC_ASHOST') !== false) {
    echo "\e[32m[OK]\e[0m SAP configuration keys found in .env\n";
} else {
    echo "\e[33m[INFO]\e[0m SAP keys not found in .env. Ensure you've saved them via the System Configuration page.\n";
}

echo "\n\e[1;34m=== CHECK COMPLETED ===\e[0m\n";
