<?php
/**
 * cPanel Diagnostic Script
 * This script helps identify what's wrong on the cPanel server
 */

// Enable detailed error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

echo "<!DOCTYPE html><html><head><style>";
echo "body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }";
echo ".container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }";
echo "h1 { color: #333; }";
echo ".status { padding: 15px; margin: 15px 0; border-radius: 6px; border-left: 4px solid; }";
echo ".success { background: #d4edda; color: #155724; border-color: #28a745; }";
echo ".error { background: #f8d7da; color: #721c24; border-color: #dc3545; }";
echo ".warning { background: #fff3cd; color: #856404; border-color: #ffc107; }";
echo ".info { background: #d1ecf1; color: #0c5460; border-color: #17a2b8; }";
echo ".code { background: #f4f4f4; padding: 15px; border-radius: 4px; font-family: monospace; overflow-x: auto; margin: 10px 0; border: 1px solid #ddd; }";
echo "table { width: 100%; border-collapse: collapse; margin: 15px 0; }";
echo "th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }";
echo "th { background: #f0f0f0; font-weight: 600; }";
echo "</style></head><body>";

echo "<div class='container'>";
echo "<h1>🔍 cPanel Server Diagnostic</h1>";

// Test 1: PHP Version
echo "<h2>1. PHP Configuration</h2>";
echo "<div class='status info'>";
echo "<strong>PHP Version:</strong> " . phpversion() . "<br>";
echo "<strong>Max Upload:</strong> " . ini_get('upload_max_filesize') . "<br>";
echo "<strong>Memory Limit:</strong> " . ini_get('memory_limit') . "<br>";
echo "<strong>Max Execution Time:</strong> " . ini_get('max_execution_time') . "s<br>";
echo "</div>";

// Test 2: Detect Environment
echo "<h2>2. Server Environment</h2>";
$environment = $_SERVER['HTTP_HOST'] ?? 'unknown';
$is_cpanel = (strpos($environment, 'localhost') === false && strpos($environment, '127.0.0.1') === false);

echo "<div class='status info'>";
echo "<strong>Domain:</strong> " . htmlspecialchars($environment) . "<br>";
echo "<strong>Server:</strong> " . htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . "<br>";
echo "<strong>Detected Environment:</strong> " . ($is_cpanel ? "<span style='color: green;'>✅ cPanel</span>" : "<span style='color: orange;'>Local</span>") . "<br>";
echo "<strong>Script Path:</strong> " . htmlspecialchars(__DIR__) . "<br>";
echo "</div>";

// Test 3: Check Required Files
echo "<h2>3. Required Files Check</h2>";
echo "<div class='status info'>";

$files_to_check = [
    'db_config.php' => 'Main database config',
    'blogs.php' => 'Blog page',
    'footer.php' => 'Footer component',
    'header.php' => 'Header component',
    'blog_helpers.php' => 'Blog helper functions'
];

$all_exist = true;
echo "<table>";
echo "<tr><th>File</th><th>Status</th><th>Path</th></tr>";
foreach ($files_to_check as $file => $desc) {
    $path = __DIR__ . '/' . $file;
    $exists = file_exists($path);
    $all_exist = $all_exist && $exists;
    echo "<tr>";
    echo "<td>" . htmlspecialchars($file) . " ($desc)</td>";
    echo "<td>" . ($exists ? "<span style='color: green;'>✅ Found</span>" : "<span style='color: red;'>❌ Missing</span>") . "</td>";
    echo "<td style='font-size: 11px;'>" . htmlspecialchars($path) . "</td>";
    echo "</tr>";
}
echo "</table>";
if (!$all_exist) {
    echo "<p style='color: red;'><strong>⚠️ Some required files are missing!</strong></p>";
}
echo "</div>";

// Test 4: Database Connection Test
echo "<h2>4. Database Connection Test</h2>";

require_once __DIR__ . '/db_config.php';

if (isset($conn)) {
    if ($conn->connect_error) {
        echo "<div class='status error'>";
        echo "<strong>❌ Database Connection Failed</strong><br>";
        echo "<strong>Error:</strong> " . htmlspecialchars($conn->connect_error) . "<br>";
        echo "<strong>Host Attempted:</strong> " . htmlspecialchars($DB_HOST) . "<br>";
        echo "<strong>User Attempted:</strong> " . htmlspecialchars($DB_USER) . "<br>";
        echo "<strong>Database Attempted:</strong> " . htmlspecialchars($DB_NAME) . "<br>";
        echo "</div>";
        
        echo "<h3>Troubleshooting Steps:</h3>";
        echo "<div class='status warning'>";
        echo "<ol>";
        echo "<li><strong>Verify cPanel Credentials</strong><br>";
        echo "   Check MySQL Databases in cPanel:<br>";
        echo "   <div class='code'>";
        echo "   Database: mahamusa_db<br>";
        echo "   User: mahamusa<br>";
        echo "   Password: tCG!c&lpxW8Q<br>";
        echo "   Remote Host: Allow connection<br>";
        echo "   </div>";
        echo "</li>";
        echo "<li><strong>Check Username Prefix</strong><br>";
        echo "   cPanel might prefix username (e.g., cpaneluser_mahamusa)<br>";
        echo "   Update db_config.php line 15 if different<br>";
        echo "</li>";
        echo "<li><strong>Check Remote MySQL Host</strong><br>";
        echo "   In cPanel, go to MySQL Remote<br>";
        echo "   Verify remote host settings<br>";
        echo "</li>";
        echo "</ol>";
        echo "</div>";
    } else {
        echo "<div class='status success'>";
        echo "<strong>✅ Database Connected Successfully</strong><br>";
        echo "<strong>Database:</strong> " . htmlspecialchars($DB_NAME) . "<br>";
        echo "<strong>Host:</strong> " . htmlspecialchars($DB_HOST) . "<br>";
        echo "</div>";
        
        // Get database info
        $result = $conn->query("SELECT DATABASE() as db_name");
        if ($result) {
            $row = $result->fetch_assoc();
            echo "<div class='status info'>";
            echo "<strong>Connected to:</strong> " . htmlspecialchars($row['db_name']) . "<br>";
            echo "</div>";
        }
        
        // Check tables
        echo "<h3>Database Tables</h3>";
        echo "<div class='status info'>";
        $result = $conn->query("SHOW TABLES");
        if ($result && $result->num_rows > 0) {
            echo "<strong>Tables Found: " . $result->num_rows . "</strong><br>";
            echo "<table>";
            echo "<tr><th>Table Name</th></tr>";
            while ($row = $result->fetch_row()) {
                echo "<tr><td>" . htmlspecialchars($row[0]) . "</td></tr>";
            }
            echo "</table>";
        } else {
            echo "<p style='color: orange;'>⚠️ No tables found in database</p>";
        }
        echo "</div>";
        
        $conn->close();
    }
} else {
    echo "<div class='status error'>";
    echo "<strong>❌ db_config.php Error</strong><br>";
    echo "The db_config.php file did not properly initialize the \$conn variable.<br>";
    echo "Check the file for syntax errors.";
    echo "</div>";
}

// Test 5: Check Permissions
echo "<h2>5. File Permissions</h2>";
echo "<div class='status info'>";

$dirs_to_check = [
    'data' => 'Data folder',
    'uploads' => 'Uploads folder',
    '.' => 'Root folder'
];

echo "<table>";
echo "<tr><th>Directory</th><th>Writable</th><th>Readable</th></tr>";
foreach ($dirs_to_check as $dir => $name) {
    $path = $dir === '.' ? __DIR__ : __DIR__ . '/' . $dir;
    $writable = is_writable($path) ? "✅ Yes" : "❌ No";
    $readable = is_readable($path) ? "✅ Yes" : "❌ No";
    echo "<tr>";
    echo "<td>" . htmlspecialchars($name) . "</td>";
    echo "<td>" . $writable . "</td>";
    echo "<td>" . $readable . "</td>";
    echo "</tr>";
}
echo "</table>";
echo "</div>";

// Test 6: Test Specific Functions
echo "<h2>6. PHP Extensions Check</h2>";
echo "<div class='status info'>";

$extensions = [
    'mysqli' => 'MySQLi Extension',
    'curl' => 'cURL Extension',
    'json' => 'JSON Extension',
    'mbstring' => 'Multibyte String'
];

echo "<table>";
echo "<tr><th>Extension</th><th>Status</th></tr>";
foreach ($extensions as $ext => $name) {
    $loaded = extension_loaded($ext) ? "✅ Loaded" : "❌ Not Loaded";
    echo "<tr>";
    echo "<td>" . htmlspecialchars($name) . "</td>";
    echo "<td>" . $loaded . "</td>";
    echo "</tr>";
}
echo "</table>";

if (!extension_loaded('mysqli')) {
    echo "<p style='color: red;'><strong>⚠️ MySQLi extension not found! This is required.</strong></p>";
    echo "<p>Contact your hosting provider to enable MySQLi extension.</p>";
}
echo "</div>";

// Test 7: Error Log
echo "<h2>7. Error Log</h2>";
echo "<div class='status info'>";
$error_log = __DIR__ . '/php_errors.log';
if (file_exists($error_log)) {
    $logs = file_get_contents($error_log);
    if (!empty($logs)) {
        echo "<strong>Recent Errors:</strong>";
        echo "<div class='code' style='max-height: 300px; overflow-y: auto;'>";
        echo htmlspecialchars($logs);
        echo "</div>";
    } else {
        echo "<p style='color: green;'>✅ No errors logged</p>";
    }
} else {
    echo "<p style='color: gray;'>No error log file yet</p>";
}
echo "</div>";

// Test 8: Summary & Recommendations
echo "<h2>8. Summary & Recommendations</h2>";
echo "<div class='status info'>";
echo "<h3>If blog page shows HTTP 500 error:</h3>";
echo "<ol>";
echo "<li><strong>Most Common:</strong> Database connection to cPanel<br>";
echo "   → Check credentials in cPanel → MySQL Databases<br>";
echo "   → Check username isn't prefixed (cpaneluser_mahamusa)<br>";
echo "   → Verify remote MySQL host settings<br>";
echo "</li>";
echo "<li><strong>Second Most Common:</strong> Missing MySQLi extension<br>";
echo "   → Contact hosting support to enable MySQLi<br>";
echo "</li>";
echo "<li><strong>File Issues:</strong> Missing or wrong permissions<br>";
echo "   → Upload all files from /ecoms folder<br>";
echo "   → Ensure PHP files have correct permissions<br>";
echo "</li>";
echo "<li><strong>Check this diagnostic:</strong><br>";
echo "   → Run this script to see what's actually failing<br>";
echo "   → Look for red ❌ items<br>";
echo "   → Follow the troubleshooting steps<br>";
echo "</li>";
echo "</ol>";
echo "</div>";

echo "</div>";
echo "</body></html>";
?>
