<?php
/**
 * API DIAGNOSTIC TOOL
 * Automatically detect and report API issues
 * 
 * Usage: Upload to same folder as api.php, then access via browser
 * URL: http://localhost/debug_api.php
 */

// Prevent caching
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Diagnostic Tool</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .test-section {
            background: white;
            padding: 20px;
            margin: 15px 0;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section h2 {
            margin-top: 0;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        .success {
            color: #22c55e;
            font-weight: bold;
        }
        .error {
            color: #ef4444;
            font-weight: bold;
        }
        .warning {
            color: #f59e0b;
            font-weight: bold;
        }
        .info {
            background: #dbeafe;
            padding: 15px;
            border-left: 4px solid #3b82f6;
            margin: 10px 0;
            border-radius: 4px;
        }
        .code {
            background: #1e293b;
            color: #e2e8f0;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        .button {
            background: #667eea;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            margin: 5px;
        }
        .button:hover {
            background: #5568d3;
        }
        ul {
            line-height: 1.8;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        .stat-box {
            background: #f8fafc;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
        }
        .stat-label {
            color: #64748b;
            font-size: 14px;
        }
    </style>
</head>
<body>

<div class="header">
    <h1>🔍 API Diagnostic Tool</h1>
    <p>Automatic detection of common API issues</p>
</div>

<?php
$issues = [];
$passed = 0;
$failed = 0;

// ============================================
// TEST 1: PHP Version
// ============================================
echo '<div class="test-section">';
echo '<h2>1️⃣ PHP Environment</h2>';

$phpVersion = phpversion();
echo "<p><strong>PHP Version:</strong> $phpVersion ";

if (version_compare($phpVersion, '7.4.0', '>=')) {
    echo '<span class="success">✅ OK</span></p>';
    $passed++;
} else {
    echo '<span class="error">❌ FAIL - Need PHP 7.4+</span></p>';
    $issues[] = "PHP version too old. Current: $phpVersion, Required: 7.4+";
    $failed++;
}

// Check mysqli extension
echo "<p><strong>MySQLi Extension:</strong> ";
if (extension_loaded('mysqli')) {
    echo '<span class="success">✅ Loaded</span></p>';
    $passed++;
} else {
    echo '<span class="error">❌ NOT loaded</span></p>';
    $issues[] = "MySQLi extension not loaded. Install with: sudo apt-get install php-mysqli";
    $failed++;
}

// Check JSON extension
echo "<p><strong>JSON Extension:</strong> ";
if (extension_loaded('json')) {
    echo '<span class="success">✅ Loaded</span></p>';
    $passed++;
} else {
    echo '<span class="error">❌ NOT loaded</span></p>';
    $issues[] = "JSON extension not loaded";
    $failed++;
}

echo '</div>';

// ============================================
// TEST 2: Database Configuration Files
// ============================================
echo '<div class="test-section">';
echo '<h2>2️⃣ Configuration Files</h2>';

// Check for api.php
$apiFile = __DIR__ . '/api.php';
echo "<p><strong>api.php:</strong> ";
if (file_exists($apiFile)) {
    echo '<span class="success">✅ Found</span><br>';
    echo "Location: <code>$apiFile</code><br>";
    echo "Readable: " . (is_readable($apiFile) ? '<span class="success">✅</span>' : '<span class="error">❌</span>') . '<br>';
    echo "Size: " . filesize($apiFile) . " bytes</p>";
    $passed++;
} else {
    echo '<span class="error">❌ NOT found</span></p>';
    $issues[] = "api.php file not found in: " . __DIR__;
    $failed++;
}

// Try to extract database config from api.php
if (file_exists($apiFile)) {
    $apiContent = file_get_contents($apiFile);
    
    // Try to extract DB config
    preg_match('/\$host\s*=\s*["\'](.+?)["\']/', $apiContent, $hostMatch);
    preg_match('/\$user\s*=\s*["\'](.+?)["\']/', $apiContent, $userMatch);
    preg_match('/\$db\s*=\s*["\'](.+?)["\']/', $apiContent, $dbMatch);
    
    if ($hostMatch && $userMatch && $dbMatch) {
        echo '<div class="info">';
        echo '<strong>Detected Configuration:</strong><br>';
        echo "Host: <code>" . htmlspecialchars($hostMatch[1]) . "</code><br>";
        echo "User: <code>" . htmlspecialchars($userMatch[1]) . "</code><br>";
        echo "Database: <code>" . htmlspecialchars($dbMatch[1]) . "</code>";
        echo '</div>';
        
        $dbHost = $hostMatch[1];
        $dbUser = $userMatch[1];
        $dbName = $dbMatch[1];
    }
}

echo '</div>';

// ============================================
// TEST 3: Database Connection
// ============================================
echo '<div class="test-section">';
echo '<h2>3️⃣ Database Connection</h2>';

// Use detected config or defaults
$host = $dbHost ?? "localhost";
$user = $dbUser ?? "root";
$pass = "";
$db   = $dbName ?? "inventory_acf";

echo "<p>Testing connection with:</p>";
echo "<ul>";
echo "<li>Host: <code>$host</code></li>";
echo "<li>User: <code>$user</code></li>";
echo "<li>Database: <code>$db</code></li>";
echo "</ul>";

try {
    $conn = new mysqli($host, $user, $pass);
    
    if ($conn->connect_error) {
        echo '<p class="error">❌ Connection failed: ' . htmlspecialchars($conn->connect_error) . '</p>';
        $issues[] = "Cannot connect to MySQL: " . $conn->connect_error;
        $failed++;
        
        echo '<div class="info">';
        echo '<strong>Troubleshooting:</strong>';
        echo '<ol>';
        echo '<li>Check if MySQL is running: <code>sudo systemctl status mysql</code></li>';
        echo '<li>Check username and password</li>';
        echo '<li>Check MySQL user privileges</li>';
        echo '</ol>';
        echo '</div>';
    } else {
        echo '<p class="success">✅ MySQL connection successful</p>';
        $passed++;
        
        // Check if database exists
        echo "<p><strong>Database '$db':</strong> ";
        $result = $conn->query("SHOW DATABASES LIKE '$db'");
        if ($result->num_rows > 0) {
            echo '<span class="success">✅ Exists</span></p>';
            $passed++;
            
            // Select database
            if ($conn->select_db($db)) {
                
                // Check table
                echo "<p><strong>Table 'kepatuhan_pembayaran':</strong> ";
                $result = $conn->query("SHOW TABLES LIKE 'kepatuhan_pembayaran'");
                if ($result->num_rows > 0) {
                    echo '<span class="success">✅ Exists</span></p>';
                    $passed++;
                    
                    // Check data
                    $result = $conn->query("SELECT COUNT(*) as cnt FROM kepatuhan_pembayaran");
                    if ($result) {
                        $row = $result->fetch_assoc();
                        $count = $row['cnt'];
                        
                        echo "<p><strong>Records:</strong> ";
                        if ($count > 0) {
                            echo "<span class='success'>$count records found ✅</span></p>";
                            $passed++;
                            
                            // Check periods
                            $result = $conn->query("SELECT DISTINCT period FROM kepatuhan_pembayaran ORDER BY period DESC");
                            if ($result->num_rows > 0) {
                                echo "<p><strong>Available Periods:</strong></p>";
                                echo "<ul>";
                                while ($row = $result->fetch_assoc()) {
                                    echo "<li><code>" . htmlspecialchars($row['period']) . "</code></li>";
                                }
                                echo "</ul>";
                                $passed++;
                            } else {
                                echo '<p class="warning">⚠️ No periods found</p>';
                                $issues[] = "No periods in database";
                            }
                        } else {
                            echo '<span class="error">0 records ❌</span></p>';
                            $issues[] = "Table is empty. Run: SOURCE setup_database.sql";
                            $failed++;
                        }
                    }
                } else {
                    echo '<span class="error">❌ NOT found</span></p>';
                    $failed++;
                    $issues[] = "Table 'kepatuhan_pembayaran' does not exist";
                    
                    // Show available tables
                    $result = $conn->query("SHOW TABLES");
                    if ($result->num_rows > 0) {
                        echo "<p><strong>Available tables:</strong></p><ul>";
                        while ($row = $result->fetch_array()) {
                            echo "<li><code>" . htmlspecialchars($row[0]) . "</code></li>";
                        }
                        echo "</ul>";
                    } else {
                        echo "<p>No tables found in database.</p>";
                    }
                    
                    echo '<div class="info">';
                    echo '<strong>Fix:</strong> Import the database schema:<br>';
                    echo '<code>mysql -u root -p ' . $db . ' < setup_database.sql</code>';
                    echo '</div>';
                }
            } else {
                echo '<p class="error">❌ Cannot select database: ' . $conn->error . '</p>';
                $failed++;
            }
        } else {
            echo '<span class="error">❌ NOT found</span></p>';
            $failed++;
            $issues[] = "Database '$db' does not exist";
            
            // Show available databases
            $result = $conn->query("SHOW DATABASES");
            echo "<p><strong>Available databases:</strong></p><ul>";
            while ($row = $result->fetch_array()) {
                echo "<li><code>" . htmlspecialchars($row[0]) . "</code></li>";
            }
            echo "</ul>";
            
            echo '<div class="info">';
            echo '<strong>Fix:</strong> Create the database:<br>';
            echo '<code>CREATE DATABASE ' . $db . ';</code><br>';
            echo '<code>USE ' . $db . ';</code><br>';
            echo '<code>SOURCE setup_database.sql;</code>';
            echo '</div>';
        }
        
        $conn->close();
    }
} catch (Exception $e) {
    echo '<p class="error">❌ Exception: ' . htmlspecialchars($e->getMessage()) . '</p>';
    $issues[] = "Database error: " . $e->getMessage();
    $failed++;
}

echo '</div>';

// ============================================
// TEST 4: API Endpoint Test
// ============================================
echo '<div class="test-section">';
echo '<h2>4️⃣ API Endpoint Test</h2>';

if (file_exists($apiFile)) {
    $apiUrl = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/api.php?action=get_periods';
    
    echo "<p>Testing endpoint: <code>$apiUrl</code></p>";
    
    // Test using file_get_contents
    $context = stream_context_create([
        'http' => [
            'timeout' => 5,
            'ignore_errors' => true
        ]
    ]);
    
    $response = @file_get_contents($apiUrl, false, $context);
    
    if ($response === false) {
        echo '<p class="error">❌ Cannot reach API endpoint</p>';
        $issues[] = "Cannot connect to API endpoint";
        $failed++;
    } else {
        echo "<p><strong>Raw Response:</strong></p>";
        echo '<div class="code">' . htmlspecialchars(substr($response, 0, 500)) . (strlen($response) > 500 ? '...' : '') . '</div>';
        
        // Check if valid JSON
        $json = json_decode($response, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            echo '<p class="success">✅ Valid JSON response</p>';
            $passed++;
            
            if (isset($json['success']) && $json['success'] === true) {
                echo '<p class="success">✅ API returned success</p>';
                $passed++;
                
                if (isset($json['data']) && is_array($json['data'])) {
                    echo '<p class="success">✅ Data array present</p>';
                    echo "<p><strong>Periods found:</strong> " . count($json['data']) . "</p>";
                    $passed++;
                } else {
                    echo '<p class="error">❌ Data array missing</p>';
                    $failed++;
                }
            } else {
                echo '<p class="error">❌ API returned error: ' . ($json['error'] ?? 'Unknown') . '</p>';
                $issues[] = "API error: " . ($json['error'] ?? 'Unknown');
                $failed++;
            }
        } else {
            echo '<p class="error">❌ Invalid JSON response</p>';
            echo '<p>JSON Error: ' . json_last_error_msg() . '</p>';
            $issues[] = "API returns HTML/text instead of JSON. This is the main issue!";
            $failed++;
            
            echo '<div class="info">';
            echo '<strong>This is likely your main problem!</strong><br>';
            echo 'The API is returning HTML error messages instead of JSON.<br>';
            echo 'Common causes:';
            echo '<ul>';
            echo '<li>PHP errors/warnings before JSON output</li>';
            echo '<li>Database connection failure</li>';
            echo '<li>Syntax errors in API file</li>';
            echo '</ul>';
            echo '</div>';
        }
    }
} else {
    echo '<p class="error">❌ Cannot test - api.php not found</p>';
    $failed++;
}

echo '</div>';

// ============================================
// SUMMARY
// ============================================
echo '<div class="test-section">';
echo '<h2>📊 Summary</h2>';

echo '<div class="stats">';
echo '<div class="stat-box">';
echo '<div class="stat-number" style="color: #22c55e;">' . $passed . '</div>';
echo '<div class="stat-label">Tests Passed</div>';
echo '</div>';
echo '<div class="stat-box">';
echo '<div class="stat-number" style="color: #ef4444;">' . $failed . '</div>';
echo '<div class="stat-label">Tests Failed</div>';
echo '</div>';
echo '<div class="stat-box">';
echo '<div class="stat-number">' . round($passed / ($passed + $failed) * 100) . '%</div>';
echo '<div class="stat-label">Success Rate</div>';
echo '</div>';
echo '</div>';

if (count($issues) > 0) {
    echo '<h3 style="color: #ef4444;">⚠️ Issues Found:</h3>';
    echo '<ol>';
    foreach ($issues as $issue) {
        echo '<li>' . htmlspecialchars($issue) . '</li>';
    }
    echo '</ol>';
} else {
    echo '<p class="success" style="font-size: 20px;">🎉 All tests passed! Your API should work correctly.</p>';
}

echo '</div>';

// ============================================
// NEXT STEPS
// ============================================
echo '<div class="test-section">';
echo '<h2>🚀 Next Steps</h2>';

if ($failed > 0) {
    echo '<ol>';
    echo '<li><strong>Fix the issues listed above</strong></li>';
    echo '<li>Refresh this page to re-test</li>';
    echo '<li>Once all tests pass, test your dashboard</li>';
    echo '</ol>';
    
    echo '<h3>Quick Fixes:</h3>';
    echo '<ul>';
    echo '<li><strong>Database not found?</strong> Run: <code>mysql -u root -p < setup_database.sql</code></li>';
    echo '<li><strong>Table not found?</strong> Check database name in api.php matches your actual database</li>';
    echo '<li><strong>No data?</strong> Run: <code>mysql -u root -p ' . ($db ?? 'inventory_acf') . ' < setup_database.sql</code></li>';
    echo '<li><strong>Cannot connect?</strong> Check MySQL is running: <code>sudo systemctl status mysql</code></li>';
    echo '</ul>';
} else {
    echo '<p class="success">✅ Everything looks good! Try these:</p>';
    echo '<ol>';
    echo '<li><a href="api.php?action=get_periods" class="button" target="_blank">Test API Directly</a></li>';
    echo '<li><a href="index.php" class="button">Open Dashboard</a></li>';
    echo '</ol>';
}

echo '</div>';
?>

<div class="test-section">
    <h2>📚 Additional Resources</h2>
    <ul>
        <li><a href="DEBUG_JSON_ERROR.md" target="_blank">Full Debugging Guide</a></li>
        <li><a href="TESTING_GUIDE.md" target="_blank">Complete Testing Guide</a></li>
        <li><a href="README.md" target="_blank">Installation Instructions</a></li>
    </ul>
</div>

</body>
</html>