<?php
/**
 * DIAGNOSTIC SCRIPT - Troubleshoot Blank Screen
 * File: pages/dashboard_piutang_system/diagnostic.php
 * 
 * Jalankan file ini di browser untuk melihat apa yang salah
 */

// Force display errors
error_reporting(E_ALL);
ini_set('display_errors', '1');

echo "<h1>🔍 Diagnostic Report - Dashboard Kepatuhan Pembayaran</h1>";
echo "<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
.section { background: white; padding: 20px; margin: 15px 0; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.success { color: #10b981; font-weight: bold; }
.error { color: #ef4444; font-weight: bold; }
.warning { color: #f59e0b; font-weight: bold; }
h2 { color: #4D869C; border-bottom: 2px solid #7AB2B2; padding-bottom: 10px; }
pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; }
</style>";

// ==================== TEST 1: PHP VERSION ====================
echo "<div class='section'>";
echo "<h2>1. PHP Version Check</h2>";
$phpVersion = phpversion();
if (version_compare($phpVersion, '8.0.0', '>=')) {
    echo "<p class='success'>✅ PHP Version: $phpVersion (OK)</p>";
} else {
    echo "<p class='warning'>⚠️ PHP Version: $phpVersion (Recommended: 8.0+)</p>";
}
echo "</div>";

// ==================== TEST 2: REQUIRED EXTENSIONS ====================
echo "<div class='section'>";
echo "<h2>2. Required PHP Extensions</h2>";
$extensions = ['mysqli', 'mbstring', 'zip', 'xml', 'gd'];
foreach ($extensions as $ext) {
    if (extension_loaded($ext)) {
        echo "<p class='success'>✅ Extension '$ext' loaded</p>";
    } else {
        echo "<p class='error'>❌ Extension '$ext' NOT loaded</p>";
    }
}
echo "</div>";

// ==================== TEST 3: DATABASE CONFIG ====================
echo "<div class='section'>";
echo "<h2>3. Database Configuration</h2>";

$configPaths = [
    __DIR__ . '/../../config/connection.php',
    __DIR__ . '/../config/connection.php'
];

$configFound = false;
foreach ($configPaths as $path) {
    if (file_exists($path)) {
        echo "<p class='success'>✅ Config found at: $path</p>";
        require_once $path;
        $configFound = true;
        break;
    } else {
        echo "<p class='warning'>⚠️ Config NOT found at: $path</p>";
    }
}

if (!$configFound) {
    echo "<p class='error'>❌ CRITICAL: No config file found!</p>";
} else {
    // Test database constants
    $constants = ['DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME'];
    foreach ($constants as $const) {
        if (defined($const)) {
            $value = constant($const);
            $displayValue = $const === 'DB_PASS' ? '***' : $value;
            echo "<p class='success'>✅ $const = $displayValue</p>";
        } else {
            echo "<p class='error'>❌ $const NOT defined</p>";
        }
    }
}
echo "</div>";

// ==================== TEST 4: DATABASE CONNECTION ====================
echo "<div class='section'>";
echo "<h2>4. Database Connection Test</h2>";

if ($configFound) {
    try {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        
        if ($conn->connect_error) {
            throw new Exception($conn->connect_error);
        }
        
        echo "<p class='success'>✅ Database connected successfully!</p>";
        echo "<p>Server: " . $conn->server_info . "</p>";
        
        // Test table existence
        $result = $conn->query("SHOW TABLES LIKE 'kepatuhan_pembayaran'");
        if ($result->num_rows > 0) {
            echo "<p class='success'>✅ Table 'kepatuhan_pembayaran' exists</p>";
            
            // Count records
            $count = $conn->query("SELECT COUNT(*) as total FROM kepatuhan_pembayaran");
            $row = $count->fetch_assoc();
            echo "<p>📊 Total records: " . $row['total'] . "</p>";
        } else {
            echo "<p class='error'>❌ Table 'kepatuhan_pembayaran' NOT found!</p>";
            echo "<p class='warning'>⚠️ Please run the database migration script</p>";
        }
        
        $conn->close();
        
    } catch (Exception $e) {
        echo "<p class='error'>❌ Database connection failed: " . $e->getMessage() . "</p>";
        echo "<p class='warning'>Check your database credentials in config/connection.php</p>";
    }
} else {
    echo "<p class='error'>❌ Cannot test database (config not found)</p>";
}
echo "</div>";

// ==================== TEST 5: COMPOSER AUTOLOAD ====================
echo "<div class='section'>";
echo "<h2>5. Composer Autoload (PhpSpreadsheet)</h2>";

$autoloadPaths = [
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../vendor/autoload.php',
    'D:/laragon/www/inventoryACF/vendor/autoload.php'
];

$autoloadFound = false;
foreach ($autoloadPaths as $path) {
    if (file_exists($path)) {
        echo "<p class='success'>✅ Autoload found at: $path</p>";
        require_once $path;
        $autoloadFound = true;
        break;
    } else {
        echo "<p class='warning'>⚠️ Autoload NOT found at: $path</p>";
    }
}

if ($autoloadFound) {
    if (class_exists('PhpOffice\PhpSpreadsheet\IOFactory')) {
        echo "<p class='success'>✅ PhpSpreadsheet loaded successfully</p>";
    } else {
        echo "<p class='error'>❌ PhpSpreadsheet NOT available</p>";
        echo "<p class='warning'>Run: composer require phpoffice/phpspreadsheet</p>";
    }
} else {
    echo "<p class='error'>❌ Composer autoload not found</p>";
    echo "<p class='warning'>Run: composer install</p>";
}
echo "</div>";

// ==================== TEST 6: FILE PERMISSIONS ====================
echo "<div class='section'>";
echo "<h2>6. File Permissions</h2>";

$logsDir = __DIR__ . '/logs';
if (!is_dir($logsDir)) {
    echo "<p class='warning'>⚠️ Logs directory doesn't exist: $logsDir</p>";
    if (mkdir($logsDir, 0755, true)) {
        echo "<p class='success'>✅ Created logs directory</p>";
    } else {
        echo "<p class='error'>❌ Cannot create logs directory</p>";
    }
} else {
    echo "<p class='success'>✅ Logs directory exists</p>";
    
    if (is_writable($logsDir)) {
        echo "<p class='success'>✅ Logs directory is writable</p>";
    } else {
        echo "<p class='error'>❌ Logs directory is NOT writable</p>";
        echo "<p class='warning'>Run: chmod 755 $logsDir</p>";
    }
}
echo "</div>";

// ==================== TEST 7: SESSION ====================
echo "<div class='section'>";
echo "<h2>7. Session Check</h2>";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

echo "<p>Session Status: " . (session_status() === PHP_SESSION_ACTIVE ? 
    "<span class='success'>✅ Active</span>" : 
    "<span class='error'>❌ Inactive</span>") . "</p>";

if (isset($_SESSION['login'])) {
    echo "<p class='success'>✅ User is logged in</p>";
    echo "<p>Role: " . ($_SESSION['role'] ?? 'undefined') . "</p>";
    echo "<p>Username: " . ($_SESSION['username'] ?? 'undefined') . "</p>";
} else {
    echo "<p class='warning'>⚠️ No active session (user not logged in)</p>";
}
echo "</div>";

// ==================== TEST 8: ERROR LOG ====================
echo "<div class='section'>";
echo "<h2>8. Recent Error Log</h2>";

$errorLog = __DIR__ . '/logs/php_error.log';
if (file_exists($errorLog)) {
    echo "<p class='success'>✅ Error log exists</p>";
    
    $lines = @file($errorLog);
    if ($lines && count($lines) > 0) {
        echo "<p>Last 10 errors:</p>";
        echo "<pre>" . htmlspecialchars(implode('', array_slice($lines, -10))) . "</pre>";
    } else {
        echo "<p class='success'>✅ No errors logged (good!)</p>";
    }
} else {
    echo "<p class='success'>✅ No error log file (no errors yet)</p>";
}
echo "</div>";

// ==================== TEST 9: PHP INFO ====================
echo "<div class='section'>";
echo "<h2>9. PHP Configuration Summary</h2>";
echo "<pre>";
echo "PHP Version: " . PHP_VERSION . "\n";
echo "Server API: " . PHP_SAPI . "\n";
echo "upload_max_filesize: " . ini_get('upload_max_filesize') . "\n";
echo "post_max_size: " . ini_get('post_max_size') . "\n";
echo "memory_limit: " . ini_get('memory_limit') . "\n";
echo "max_execution_time: " . ini_get('max_execution_time') . "\n";
echo "</pre>";
echo "</div>";

// ==================== RECOMMENDATIONS ====================
echo "<div class='section'>";
echo "<h2>🎯 Recommendations</h2>";

$issues = [];

if (!$configFound) {
    $issues[] = "❌ Fix database config path";
}

if (!$autoloadFound) {
    $issues[] = "❌ Run 'composer install' to install dependencies";
}

if (!extension_loaded('mysqli')) {
    $issues[] = "❌ Enable mysqli extension in php.ini";
}

if (empty($issues)) {
    echo "<p class='success'><strong>✅ All checks passed! Your system is ready.</strong></p>";
    echo "<p>If you still see a blank page, check:</p>";
    echo "<ul>";
    echo "<li>Browser console for JavaScript errors</li>";
    echo "<li>Network tab for failed requests</li>";
    echo "<li>Error log file in logs/php_error.log</li>";
    echo "</ul>";
} else {
    echo "<p class='error'><strong>Issues found:</strong></p>";
    echo "<ul>";
    foreach ($issues as $issue) {
        echo "<li>$issue</li>";
    }
    echo "</ul>";
}
echo "</div>";

// ==================== NEXT STEPS ====================
echo "<div class='section'>";
echo "<h2>📝 Next Steps</h2>";
echo "<ol>";
echo "<li>Fix any <span class='error'>red errors</span> shown above</li>";
echo "<li>Replace your index.php with index_FIXED.php</li>";
echo "<li>Clear browser cache (Ctrl+Shift+Delete)</li>";
echo "<li>Try accessing the dashboard again</li>";
echo "<li>If still blank, check browser console (F12)</li>";
echo "</ol>";
echo "</div>";

echo "<hr>";
echo "<p style='text-align:center; color:#888; font-size:12px;'>Diagnostic completed at " . date('Y-m-d H:i:s') . "</p>";
?>