<?php
/**
 * Debug File
 * GHAMECC Choir Management Platform
 * 
 * This file helps diagnose issues with the application on different environments.
 * IMPORTANT: Remove or secure this file after troubleshooting is complete!
 */

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start output buffering to capture any errors
ob_start();

echo "<h1>GHAMECC App Diagnostic Tool</h1>";
echo "<p>This page displays diagnostic information to help troubleshoot issues.</p>";
echo "<hr>";

// Environment Information
echo "<h2>Environment Information</h2>";
echo "<ul>";
echo "<li><strong>Server Software:</strong> " . htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . "</li>";
echo "<li><strong>HTTP Host:</strong> " . htmlspecialchars($_SERVER['HTTP_HOST'] ?? 'Unknown') . "</li>";
echo "<li><strong>Document Root:</strong> " . htmlspecialchars($_SERVER['DOCUMENT_ROOT'] ?? 'Unknown') . "</li>";
echo "<li><strong>Script Filename:</strong> " . htmlspecialchars($_SERVER['SCRIPT_FILENAME'] ?? 'Unknown') . "</li>";
echo "<li><strong>PHP Version:</strong> " . phpversion() . "</li>";
echo "</ul>";

// Check if cPanel is detected
echo "<h3>cPanel Detection</h3>";
if (file_exists('/usr/local/cpanel')) {
    echo "<p style='color:green;'>✓ cPanel detected</p>";
} else {
    echo "<p style='color:orange;'>⚠ cPanel not detected (likely local environment)</p>";
}

// Include environment config
echo "<h2>Environment Configuration</h2>";
try {
    require_once __DIR__ . '/config/env_config.php';
    echo "<p>Environment detected: <strong>" . htmlspecialchars($currentEnv) . "</strong></p>";
    
    // Display database credentials (partially masked for security)
    echo "<h3>Database Configuration</h3>";
    echo "<ul>";
    echo "<li><strong>Host:</strong> " . htmlspecialchars($host) . "</li>";
    echo "<li><strong>Username:</strong> " . htmlspecialchars($username) . "</li>";
    echo "<li><strong>Password:</strong> " . (empty($password) ? "<span style='color:red;'>Empty!</span>" : "********") . "</li>";
    echo "<li><strong>Database:</strong> " . htmlspecialchars($database) . "</li>";
    echo "</ul>";
} catch (Exception $e) {
    echo "<p style='color:red;'>Error loading environment config: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Test database connection
echo "<h2>Database Connection Test</h2>";
try {
    if (!isset($conn)) {
        require_once __DIR__ . '/config/database.php';
    }
    
    if ($conn->ping()) {
        echo "<p style='color:green;'>✓ Database connection successful</p>";
        
        // Test some basic queries
        echo "<h3>Basic Query Tests</h3>";
        
        // Test users table
        $userResult = $conn->query("SELECT COUNT(*) as count FROM users");
        if ($userResult) {
            $userCount = $userResult->fetch_assoc()['count'];
            echo "<p>Users table: <strong>" . $userCount . " records found</strong></p>";
        } else {
            echo "<p style='color:red;'>Error querying users table: " . htmlspecialchars($conn->error) . "</p>";
        }
        
        // Test members table
        $memberResult = $conn->query("SELECT COUNT(*) as count FROM members");
        if ($memberResult) {
            $memberCount = $memberResult->fetch_assoc()['count'];
            echo "<p>Members table: <strong>" . $memberCount . " records found</strong></p>";
        } else {
            echo "<p style='color:red;'>Error querying members table: " . htmlspecialchars($conn->error) . "</p>";
        }
    } else {
        echo "<p style='color:red;'>Database connection failed: Unable to ping database server</p>";
    }
} catch (Exception $e) {
    echo "<p style='color:red;'>Database connection error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Test sidebar menu JavaScript
echo "<h2>JavaScript Resources Check</h2>";
$jsFiles = [
    "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js",
    "https://code.jquery.com/jquery-3.6.0.min.js"
];

echo "<ul>";
foreach ($jsFiles as $jsFile) {
    $headers = get_headers($jsFile);
    $status = strpos($headers[0], '200') !== false ? 'Accessible' : 'Not accessible';
    $color = strpos($headers[0], '200') !== false ? 'green' : 'red';
    echo "<li><strong>" . htmlspecialchars($jsFile) . ":</strong> <span style='color:" . $color . ";'>" . $status . "</span></li>";
}
echo "</ul>";

// Check file permissions for key directories
echo "<h2>File Permissions Check</h2>";
$directories = [
    __DIR__ . '/includes',
    __DIR__ . '/config',
    __DIR__ . '/logs'
];

echo "<ul>";
foreach ($directories as $dir) {
    if (file_exists($dir)) {
        $perms = substr(sprintf('%o', fileperms($dir)), -4);
        echo "<li><strong>" . htmlspecialchars($dir) . ":</strong> Permissions: " . $perms . "</li>";
    } else {
        echo "<li><strong>" . htmlspecialchars($dir) . ":</strong> <span style='color:red;'>Directory not found</span></li>";
    }
}
echo "</ul>";

// Capture any errors
$output = ob_get_clean();
$errors = error_get_last();

// Display the page with any errors at the top
if ($errors) {
    echo "<div style='background-color: #ffdddd; border: 1px solid #ff0000; padding: 10px; margin-bottom: 20px;'>";
    echo "<h2>PHP Errors Detected</h2>";
    echo "<pre>" . print_r($errors, true) . "</pre>";
    echo "</div>";
}

echo $output;

// Security warning
echo "<hr>";
echo "<div style='background-color: #ffffdd; border: 1px solid #ffcc00; padding: 10px; margin-top: 20px;'>";
echo "<h3>⚠️ Security Warning</h3>";
echo "<p>This debug file displays sensitive information about your application. Delete or secure this file after troubleshooting is complete!</p>";
echo "</div>";
?>
