<?php
/**
 * Diagnostic Script for Live Server
 * Upload this to the live server and access it via browser
 * URL: https://brandwave.aurigaconsulting.co.in/diagnose.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>Server Diagnostics</h1>";
echo "<style>body{font-family:Arial;padding:20px;} .ok{color:green;} .error{color:red;} .warning{color:orange;}</style>";

// 1. PHP Version Check
echo "<h2>1. PHP Version</h2>";
echo "<p class='ok'>PHP Version: " . phpversion() . "</p>";
if (version_compare(phpversion(), '7.4', '<')) {
    echo "<p class='error'>⚠️ PHP version is too old. Minimum required: 7.4</p>";
} elseif (version_compare(phpversion(), '8.0', '>=')) {
    echo "<p class='warning'>⚠️ PHP 8+ detected. CodeIgniter 3 may have compatibility issues.</p>";
}

// 2. Required Extensions
echo "<h2>2. Required PHP Extensions</h2>";
$required = ['mysqli', 'mbstring', 'json', 'session'];
foreach ($required as $ext) {
    if (extension_loaded($ext)) {
        echo "<p class='ok'>✓ $ext extension loaded</p>";
    } else {
        echo "<p class='error'>✗ $ext extension NOT loaded</p>";
    }
}

// 3. Directory Permissions
echo "<h2>3. Directory Permissions</h2>";
$dirs = [
    'application/logs',
    'application/cache',
    'uploads/attachments'
];
foreach ($dirs as $dir) {
    if (is_dir($dir)) {
        if (is_writable($dir)) {
            echo "<p class='ok'>✓ $dir is writable</p>";
        } else {
            echo "<p class='error'>✗ $dir is NOT writable (chmod 755 or 777 needed)</p>";
        }
    } else {
        echo "<p class='error'>✗ $dir does NOT exist</p>";
    }
}

// 4. Database Connection
echo "<h2>4. Database Connection</h2>";
$hostname = '162.215.11.244';
$username = 'ac3_marketing_portal';
$password = '=Y^3GIyrG;J)TV]z';
$database = 'ac3_marketing_portal';
$port = 3306;

try {
    $conn = @new mysqli($hostname, $username, $password, $database, $port);
    if ($conn->connect_error) {
        echo "<p class='error'>✗ Database connection failed: " . htmlspecialchars($conn->connect_error) . "</p>";
    } else {
        echo "<p class='ok'>✓ Database connection successful</p>";
        echo "<p class='ok'>Database: $database</p>";
        
        // Test portal_id existence
        $result = $conn->query("SELECT * FROM portals WHERE id = 3 LIMIT 1");
        if ($result && $result->num_rows > 0) {
            $portal = $result->fetch_assoc();
            echo "<p class='ok'>✓ Portal ID 3 exists: " . htmlspecialchars($portal['name'] ?? 'N/A') . "</p>";
        } else {
            echo "<p class='error'>✗ Portal ID 3 not found in database</p>";
        }
        
        $conn->close();
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Database error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// 5. File Checks
echo "<h2>5. Critical File Checks</h2>";
$files = [
    'index.php',
    '.htaccess',
    'application/config/config.php',
    'application/config/database.php',
    'application/config/portal.php',
    'application/config/autoload.php',
    'application/controllers/Auth.php',
    'application/helpers/marketing_helper.php'
];
foreach ($files as $file) {
    if (file_exists($file)) {
        echo "<p class='ok'>✓ $file exists</p>";
    } else {
        echo "<p class='error'>✗ $file does NOT exist</p>";
    }
}

// 6. Check .htaccess
echo "<h2>6. .htaccess File</h2>";
if (file_exists('.htaccess')) {
    echo "<pre>" . htmlspecialchars(file_get_contents('.htaccess')) . "</pre>";
} else {
    echo "<p class='error'>✗ .htaccess file is missing!</p>";
    echo "<h3>Create .htaccess with this content:</h3>";
    echo "<pre>";
    echo htmlspecialchars("RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]");
    echo "</pre>";
}

// 7. Error Logs
echo "<h2>7. Recent Error Logs</h2>";
if (file_exists('php_error.log')) {
    $logs = file_get_contents('php_error.log');
    $lines = explode("\n", $logs);
    $recent = array_slice($lines, -20); // Last 20 lines
    echo "<pre style='background:#f5f5f5;padding:10px;'>" . htmlspecialchars(implode("\n", $recent)) . "</pre>";
} else {
    echo "<p class='warning'>No php_error.log file found</p>";
}

if (file_exists('application/logs/log-' . date('Y-m-d') . '.php')) {
    echo "<h3>Today's CodeIgniter Log:</h3>";
    $log = file_get_contents('application/logs/log-' . date('Y-m-d') . '.php');
    echo "<pre style='background:#f5f5f5;padding:10px;max-height:300px;overflow:auto;'>" . htmlspecialchars($log) . "</pre>";
}

// 8. Environment Check
echo "<h2>8. Environment Configuration</h2>";
echo "<p>Current ENVIRONMENT constant: " . (defined('ENVIRONMENT') ? ENVIRONMENT : 'Not set') . "</p>";
echo "<p>Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "</p>";
echo "<p>Script Filename: " . $_SERVER['SCRIPT_FILENAME'] . "</p>";
echo "<p>HTTP Host: " . $_SERVER['HTTP_HOST'] . "</p>";
echo "<p>Request URI: " . $_SERVER['REQUEST_URI'] . "</p>";

echo "<hr>";
echo "<p><strong>Next Steps:</strong></p>";
echo "<ol>";
echo "<li>If database connection failed, verify credentials in application/config/database.php</li>";
echo "<li>If .htaccess is missing, create it with the content shown above</li>";
echo "<li>If directories are not writable, run: <code>chmod 755 application/logs application/cache uploads/attachments</code></li>";
echo "<li>Check the error logs above for specific PHP errors</li>";
echo "<li>After fixing issues, try accessing /auth/login again</li>";
echo "</ol>";

echo "<hr>";
echo "<p><em>After resolving issues, delete this diagnose.php file for security.</em></p>";
?>
