<?php
/**
 * Security Audit Script
 * Run this to check for common security vulnerabilities
 * DELETE THIS FILE BEFORE PRODUCTION DEPLOYMENT
 */

require_once 'config.php';

// Only allow in development mode
if (getConfig('ENVIRONMENT') === 'production') {
    die("This script is disabled in production mode");
}

$issues = [];
$warnings = [];
$passed = [];

echo "<h1>Security Audit Report</h1>";
echo "<style>
    .pass { color: green; }
    .fail { color: red; }
    .warn { color: orange; }
    body { font-family: Arial, sans-serif; margin: 20px; }
    .section { margin: 20px 0; padding: 10px; border: 1px solid #ccc; }
</style>";

// 1. Check PHP version
echo "<div class='section'>";
echo "<h2>1. PHP Version Check</h2>";
if (version_compare(PHP_VERSION, '7.4.0', '>=')) {
    $passed[] = "PHP version " . PHP_VERSION . " is supported";
    echo "<p class='pass'>✓ PHP version " . PHP_VERSION . " is supported</p>";
} else {
    $issues[] = "PHP version " . PHP_VERSION . " is outdated. Upgrade to 7.4+";
    echo "<p class='fail'>✗ PHP version " . PHP_VERSION . " is outdated</p>";
}
echo "</div>";

// 2. Check session configuration
echo "<div class='section'>";
echo "<h2>2. Session Security</h2>";
if (ini_get('session.cookie_httponly')) {
    $passed[] = "Session cookies are HTTP-only";
    echo "<p class='pass'>✓ Session cookies are HTTP-only</p>";
} else {
    $issues[] = "Session cookies are not HTTP-only";
    echo "<p class='fail'>✗ Session cookies are not HTTP-only</p>";
}

if (ini_get('session.use_only_cookies')) {
    $passed[] = "Sessions use only cookies";
    echo "<p class='pass'>✓ Sessions use only cookies</p>";
} else {
    $issues[] = "Sessions don't use only cookies";
    echo "<p class='fail'>✗ Sessions don't use only cookies</p>";
}

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    if (ini_get('session.cookie_secure')) {
        $passed[] = "Session cookies are secure (HTTPS-only)";
        echo "<p class='pass'>✓ Session cookies are secure</p>";
    } else {
        $warnings[] = "Session cookies are not marked as secure";
        echo "<p class='warn'>⚠ Session cookies should be secure on HTTPS</p>";
    }
} else {
    echo "<p class='warn'>⚠ Not using HTTPS - secure cookies disabled</p>";
}
echo "</div>";

// 3. Check database configuration
echo "<div class='section'>";
echo "<h2>3. Database Security</h2>";
require 'db.php';

try {
    // Check if using prepared statements
    $passed[] = "PDO is configured with exception error mode";
    echo "<p class='pass'>✓ PDO is configured correctly</p>";
    
    // Check charset
    $stmt = $pdo->query("SHOW VARIABLES LIKE 'character_set_database'");
    $charset = $stmt->fetch(PDO::FETCH_ASSOC);
    if (strpos($charset['Value'], 'utf8mb4') !== false) {
        $passed[] = "Database uses utf8mb4 charset";
        echo "<p class='pass'>✓ Database uses utf8mb4 charset</p>";
    } else {
        $warnings[] = "Database not using utf8mb4 charset";
        echo "<p class='warn'>⚠ Database should use utf8mb4 charset</p>";
    }
} catch (Exception $e) {
    $issues[] = "Database connection error";
    echo "<p class='fail'>✗ Database connection error</p>";
}
echo "</div>";

// 4. Check file permissions
echo "<div class='section'>";
echo "<h2>4. File Permissions</h2>";
$sensitiveFiles = ['config.env', 'db.php', 'config.php'];
foreach ($sensitiveFiles as $file) {
    if (file_exists($file)) {
        $perms = fileperms($file);
        $readable = ($perms & 0x0004) ? true : false;
        if (!$readable) {
            $warnings[] = "$file might have too restrictive permissions";
            echo "<p class='warn'>⚠ $file permissions: " . substr(sprintf('%o', $perms), -4) . "</p>";
        } else {
            echo "<p class='pass'>✓ $file is accessible</p>";
        }
    } else {
        if ($file === 'config.env') {
            $issues[] = "$file not found - using fallback configuration";
            echo "<p class='fail'>✗ $file not found</p>";
        }
    }
}
echo "</div>";

// 5. Check for common security headers
echo "<div class='section'>";
echo "<h2>5. Security Headers</h2>";
$headers = [
    'X-Content-Type-Options' => 'nosniff',
    'X-Frame-Options' => ['SAMEORIGIN', 'DENY'],
    'X-XSS-Protection' => '1; mode=block'
];

echo "<p>Note: Headers are set by security_headers.php</p>";
$passed[] = "Security headers are configured in security_headers.php";
echo "<p class='pass'>✓ Security headers configured</p>";
echo "</div>";

// 6. Check for SQL injection vulnerabilities
echo "<div class='section'>";
echo "<h2>6. SQL Injection Protection</h2>";
$phpFiles = glob("*.php");
$vulnerableFiles = [];
foreach ($phpFiles as $file) {
    if ($file === 'security_audit.php') continue;
    $content = file_get_contents($file);
    // Look for direct SQL concatenation
    if (preg_match('/\$pdo->query\s*\(\s*["\'].*\$_(?:GET|POST|REQUEST)/', $content) ||
        preg_match('/\$pdo->exec\s*\(\s*["\'].*\$_(?:GET|POST|REQUEST)/', $content)) {
        $vulnerableFiles[] = $file;
    }
}

if (empty($vulnerableFiles)) {
    $passed[] = "No obvious SQL injection vulnerabilities found";
    echo "<p class='pass'>✓ No obvious SQL injection vulnerabilities</p>";
} else {
    $issues[] = "Potential SQL injection in: " . implode(', ', $vulnerableFiles);
    echo "<p class='fail'>✗ Potential SQL injection in: " . implode(', ', $vulnerableFiles) . "</p>";
}
echo "</div>";

// 7. Check for XSS vulnerabilities
echo "<div class='section'>";
echo "<h2>7. XSS Protection</h2>";
$xssProtected = true;
foreach ($phpFiles as $file) {
    if ($file === 'security_audit.php') continue;
    $content = file_get_contents($file);
    // Check if outputting user data without htmlspecialchars
    if (preg_match('/echo\s+\$(?:_GET|_POST|_REQUEST|_SESSION)\[/', $content)) {
        if (!preg_match('/htmlspecialchars/', $content)) {
            $xssProtected = false;
            $warnings[] = "Potential XSS in $file";
        }
    }
}

if ($xssProtected) {
    $passed[] = "XSS protection appears to be in place";
    echo "<p class='pass'>✓ XSS protection in place</p>";
} else {
    echo "<p class='warn'>⚠ Review XSS protection in files</p>";
}
echo "</div>";

// 8. Check CSRF protection
echo "<div class='section'>";
echo "<h2>8. CSRF Protection</h2>";
if (file_exists('csrf.php')) {
    $passed[] = "CSRF protection module exists";
    echo "<p class='pass'>✓ CSRF protection module exists</p>";
    
    // Check if forms use CSRF
    $formsProtected = true;
    foreach (['login.php', 'register.php'] as $file) {
        if (file_exists($file)) {
            $content = file_get_contents($file);
            if (!strpos($content, 'csrf_token')) {
                $formsProtected = false;
                $warnings[] = "$file might not have CSRF protection";
            }
        }
    }
    
    if ($formsProtected) {
        $passed[] = "Forms appear to have CSRF protection";
        echo "<p class='pass'>✓ Forms have CSRF protection</p>";
    }
} else {
    $issues[] = "CSRF protection module not found";
    echo "<p class='fail'>✗ CSRF protection module not found</p>";
}
echo "</div>";

// 9. Check rate limiting
echo "<div class='section'>";
echo "<h2>9. Rate Limiting</h2>";
if (file_exists('rate_limiter.php')) {
    $passed[] = "Rate limiting module exists";
    echo "<p class='pass'>✓ Rate limiting module exists</p>";
} else {
    $issues[] = "Rate limiting module not found";
    echo "<p class='fail'>✗ Rate limiting module not found</p>";
}
echo "</div>";

// 10. Check password hashing
echo "<div class='section'>";
echo "<h2>10. Password Security</h2>";
if (file_exists('register.php')) {
    $content = file_get_contents('register.php');
    if (strpos($content, 'password_hash') !== false && strpos($content, 'PASSWORD_DEFAULT') !== false) {
        $passed[] = "Using secure password hashing";
        echo "<p class='pass'>✓ Using secure password hashing</p>";
    } else {
        $issues[] = "Not using secure password hashing";
        echo "<p class='fail'>✗ Check password hashing method</p>";
    }
}
echo "</div>";

// Summary
echo "<div class='section'>";
echo "<h2>Summary</h2>";
echo "<p><strong>Passed:</strong> " . count($passed) . " checks</p>";
echo "<p><strong>Warnings:</strong> " . count($warnings) . " warnings</p>";
echo "<p><strong>Failed:</strong> " . count($issues) . " issues</p>";

if (count($issues) > 0) {
    echo "<h3>Critical Issues to Fix:</h3>";
    echo "<ul>";
    foreach ($issues as $issue) {
        echo "<li class='fail'>$issue</li>";
    }
    echo "</ul>";
}

if (count($warnings) > 0) {
    echo "<h3>Warnings to Review:</h3>";
    echo "<ul>";
    foreach ($warnings as $warning) {
        echo "<li class='warn'>$warning</li>";
    }
    echo "</ul>";
}

echo "<p><strong>Security Score: " . round((count($passed) / (count($passed) + count($issues) + count($warnings))) * 100) . "%</strong></p>";
echo "</div>";

echo "<div class='section'>";
echo "<h2>⚠️ IMPORTANT</h2>";
echo "<p style='color: red; font-weight: bold;'>DELETE THIS FILE BEFORE DEPLOYING TO PRODUCTION!</p>";
echo "</div>";
?>
