<?php
/**
 * ULTIMATE DIAGNOSTIC - Find out exactly what's wrong
 * Upload to root and visit: https://ensi.online/ultimate_test.php
 */

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

?>
<!DOCTYPE html>
<html>
<head>
    <title>Ultimate Hero Banners Diagnostic</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; max-width: 1000px; margin: 0 auto; }
        .pass { color: green; font-weight: bold; }
        .fail { color: red; font-weight: bold; }
        .warn { color: orange; font-weight: bold; }
        .box { border: 2px solid #ddd; padding: 15px; margin: 15px 0; border-radius: 8px; background: #f9f9f9; }
        pre { background: #fff; padding: 10px; border: 1px solid #ddd; overflow-x: auto; }
        h2 { border-bottom: 2px solid #333; padding-bottom: 5px; }
        .action { background: #ffffcc; padding: 10px; border-left: 4px solid #ff9900; margin: 10px 0; }
    </style>
</head>
<body>
    <h1>🔍 Ultimate Hero Banners Diagnostic</h1>
    <p>Finding exactly why hero_banners.php isn't working...</p>
    <hr>

<?php

// ============================================
// TEST 1: Config File
// ============================================
echo "<div class='box'>";
echo "<h2>1️⃣ Config & Database</h2>";

try {
    require_once 'admin/config.php';
    echo "<p class='pass'>✅ admin/config.php loaded</p>";
    
    // Check constants
    echo "<p>Database: <code>" . DB_NAME . "</code></p>";
    echo "<p>Session Name: <code>" . ADMIN_SESSION_NAME . "</code></p>";
    
    // Test DB connection
    $pdo = getDBConnection();
    if ($pdo) {
        echo "<p class='pass'>✅ Database connected</p>";
    } else {
        echo "<p class='fail'>❌ Database connection failed</p>";
    }
} catch (Exception $e) {
    echo "<p class='fail'>❌ Error: " . $e->getMessage() . "</p>";
}

echo "</div>";

// ============================================
// TEST 2: Session
// ============================================
echo "<div class='box'>";
echo "<h2>2️⃣ Session Status</h2>";

// Start session properly
if (session_status() === PHP_SESSION_NONE) {
    session_name(ADMIN_SESSION_NAME);
    session_start();
    echo "<p class='pass'>✅ Session started with name: <code>" . ADMIN_SESSION_NAME . "</code></p>";
} else {
    echo "<p class='pass'>✅ Session already active</p>";
}

echo "<p>Session ID: <code>" . session_id() . "</code></p>";

if (isset($_SESSION['admin_id'])) {
    echo "<p class='pass'>✅ Admin logged in!</p>";
    echo "<p>Admin ID: <strong>" . $_SESSION['admin_id'] . "</strong></p>";
    
    if (isset($_SESSION['admin_username'])) {
        echo "<p>Username: <strong>" . $_SESSION['admin_username'] . "</strong></p>";
    }
} else {
    echo "<p class='fail'>❌ NOT logged in</p>";
    echo "<div class='action'>";
    echo "<strong>ACTION NEEDED:</strong> <a href='admin/login.php'>Login to admin panel</a>";
    echo "</div>";
}

echo "</div>";

// ============================================
// TEST 3: Tables
// ============================================
echo "<div class='box'>";
echo "<h2>3️⃣ Database Tables</h2>";

$tables = ['hero_banners', 'user_dismissed_banners', 'admins'];
foreach ($tables as $table) {
    $check = $pdo->query("SHOW TABLES LIKE '$table'");
    if ($check->rowCount() > 0) {
        echo "<p class='pass'>✅ <code>$table</code> exists</p>";
        
        if ($table === 'hero_banners') {
            $count = $pdo->query("SELECT COUNT(*) FROM hero_banners")->fetchColumn();
            echo "<p style='margin-left: 20px;'>Records: <strong>$count</strong></p>";
        }
    } else {
        echo "<p class='fail'>❌ <code>$table</code> NOT FOUND</p>";
    }
}

echo "</div>";

// ============================================
// TEST 4: API File Test
// ============================================
echo "<div class='box'>";
echo "<h2>4️⃣ API Direct Test (Server-Side)</h2>";

if (isset($_SESSION['admin_id'])) {
    echo "<p>Testing API as if called from hero_banners.php page...</p>";
    
    // Check if API file exists
    if (file_exists('admin/api/hero_banners.php')) {
        echo "<p class='pass'>✅ admin/api/hero_banners.php file exists</p>";
        
        // Read the file and check for session handling
        $apiContent = file_get_contents('admin/api/hero_banners.php');
        
        if (strpos($apiContent, 'session_name(ADMIN_SESSION_NAME)') !== false) {
            echo "<p class='pass'>✅ API uses correct session name</p>";
        } else {
            echo "<p class='warn'>⚠️ API might not be using ADMIN_SESSION_NAME</p>";
            echo "<div class='action'>";
            echo "<strong>ACTION:</strong> Re-upload admin/api/hero_banners.php with session fix";
            echo "</div>";
        }
        
        if (strpos($apiContent, 'getDBConnection()') !== false) {
            echo "<p class='pass'>✅ API uses getDBConnection()</p>";
        } else {
            echo "<p class='warn'>⚠️ API might have database connection issue</p>";
        }
        
    } else {
        echo "<p class='fail'>❌ admin/api/hero_banners.php NOT FOUND</p>";
        echo "<div class='action'>";
        echo "<strong>ACTION:</strong> Upload admin/api/hero_banners.php";
        echo "</div>";
    }
} else {
    echo "<p class='warn'>⚠️ Cannot test API - not logged in</p>";
}

echo "</div>";

// ============================================
// TEST 5: Make Actual API Call
// ============================================
echo "<div class='box'>";
echo "<h2>5️⃣ Live API Call Test</h2>";

if (isset($_SESSION['admin_id'])) {
    echo "<p>Making actual HTTP request to API...</p>";
    
    $apiUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . '/admin/api/hero_banners.php?action=list';
    echo "<p>URL: <code>$apiUrl</code></p>";
    
    // Use cURL to test
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id()); // Pass session cookie
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    echo "<p>HTTP Status: <strong>$httpCode</strong></p>";
    
    if ($error) {
        echo "<p class='fail'>❌ cURL Error: $error</p>";
    } elseif ($httpCode == 200) {
        $data = json_decode($response, true);
        
        if ($data && isset($data['success'])) {
            if ($data['success']) {
                echo "<p class='pass'>✅ API returned success!</p>";
                echo "<p>Banners found: <strong>" . count($data['data']) . "</strong></p>";
                echo "<details><summary>View Response</summary><pre>" . json_encode($data, JSON_PRETTY_PRINT) . "</pre></details>";
            } else {
                echo "<p class='fail'>❌ API returned error: " . ($data['message'] ?? 'Unknown') . "</p>";
                echo "<pre>" . json_encode($data, JSON_PRETTY_PRINT) . "</pre>";
            }
        } else {
            echo "<p class='fail'>❌ API response is not valid JSON</p>";
            echo "<pre>" . htmlspecialchars($response) . "</pre>";
        }
    } else {
        echo "<p class='fail'>❌ HTTP Error: $httpCode</p>";
        echo "<pre>" . htmlspecialchars($response) . "</pre>";
    }
    
} else {
    echo "<p class='warn'>⚠️ Cannot test - not logged in</p>";
}

echo "</div>";

// ============================================
// TEST 6: JavaScript Test
// ============================================
echo "<div class='box'>";
echo "<h2>6️⃣ JavaScript API Test</h2>";
echo "<p>This simulates what the hero_banners.php page does:</p>";
echo "<button onclick='testJavaScriptAPI()' style='padding: 10px 20px; font-size: 16px; cursor: pointer;'>Test API via JavaScript</button>";
echo "<div id='jsTestResult' style='margin-top: 10px;'></div>";
echo "</div>";

// ============================================
// SUMMARY
// ============================================
echo "<hr>";
echo "<div class='box' style='background: #e8f5e9;'>";
echo "<h2>📋 Summary & Actions</h2>";

$issues = [];
$actions = [];

if (!isset($_SESSION['admin_id'])) {
    $issues[] = "Not logged in";
    $actions[] = "<a href='admin/login.php'><strong>Login to admin panel</strong></a>";
}

if (!file_exists('admin/api/hero_banners.php')) {
    $issues[] = "API file missing";
    $actions[] = "Upload <code>admin/api/hero_banners.php</code>";
}

$heroCheck = $pdo->query("SHOW TABLES LIKE 'hero_banners'")->rowCount();
if ($heroCheck === 0) {
    $issues[] = "Tables missing";
    $actions[] = "Run SQL migration: <code>create_hero_banners_SAFE.sql</code>";
}

if (empty($issues)) {
    echo "<p class='pass' style='font-size: 20px;'>🎉 NO ISSUES FOUND!</p>";
    echo "<p><strong>The page should be working.</strong></p>";
    echo "<p><a href='admin/hero_banners.php' style='font-size: 18px;'>→ Try Hero Banners Page Now</a></p>";
} else {
    echo "<p class='fail' style='font-size: 18px;'>❌ Issues Found:</p>";
    echo "<ol>";
    foreach ($issues as $issue) {
        echo "<li><strong>$issue</strong></li>";
    }
    echo "</ol>";
    
    echo "<p style='font-size: 18px;'><strong>Actions to Fix:</strong></p>";
    echo "<ol>";
    foreach ($actions as $action) {
        echo "<li>$action</li>";
    }
    echo "</ol>";
}

echo "</div>";

?>

<script>
async function testJavaScriptAPI() {
    const resultDiv = document.getElementById('jsTestResult');
    resultDiv.innerHTML = '<p>Testing...</p>';
    
    try {
        const response = await fetch('admin/api/hero_banners.php?action=list');
        const data = await response.json();
        
        if (data.success) {
            resultDiv.innerHTML = `
                <p style="color: green; font-weight: bold;">✅ JavaScript API call SUCCESS!</p>
                <p>Found ${data.data.length} banners</p>
                <p><strong>The hero_banners.php page SHOULD work!</strong></p>
                <pre>${JSON.stringify(data, null, 2)}</pre>
            `;
        } else {
            resultDiv.innerHTML = `
                <p style="color: red; font-weight: bold;">❌ API Error: ${data.message}</p>
                <pre>${JSON.stringify(data, null, 2)}</pre>
            `;
        }
    } catch (error) {
        resultDiv.innerHTML = `
            <p style="color: red; font-weight: bold;">❌ JavaScript Error: ${error.message}</p>
            <p>Check browser console (F12) for details</p>
        `;
    }
}
</script>

<hr>
<p style="text-align: center;"><a href="admin/hero_banners.php">→ Go to Hero Banners Page</a></p>
<p style="text-align: center; color: #999;"><small>Delete ultimate_test.php after testing</small></p>

</body>
</html>
