<?php
session_start();
require_once 'db_config.php';
require_once 'blog_helpers.php';

echo "<!DOCTYPE html>
<html>
<head>
    <title>Blog System Test</title>
    <style>
        body { font-family: Arial; margin: 20px; background: #f5f5f5; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        .test { margin: 20px 0; padding: 15px; border-left: 4px solid #3498db; background: #ecf7ff; }
        .pass { border-left-color: #27ae60; background: #e8f8f5; }
        .fail { border-left-color: #e74c3c; background: #fadbd8; }
        .test h3 { margin: 0 0 10px 0; }
        .test p { margin: 5px 0; }
        strong { font-weight: bold; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        table th, table td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        table th { background: #3498db; color: white; }
        .status-pass { color: green; font-weight: bold; }
        .status-fail { color: red; font-weight: bold; }
        .btn { display: inline-block; padding: 10px 15px; margin: 5px; border-radius: 4px; text-decoration: none; color: white; }
        .btn-admin { background: #c76b8a; }
        .btn-blog { background: #3498db; }
        .btn-home { background: #27ae60; }
    </style>
</head>
<body>
    <div class='container'>
        <h1>🧪 Blog System Test Suite</h1>
        <p style='color: #666;'>Testing all blog functionality...</p>
";

$testsPassed = 0;
$testsFailed = 0;

// TEST 1: Database Connection
echo "<div class='test'>";
echo "<h3>Test 1: Database Connection</h3>";
if ($conn && !$conn->connect_error) {
    echo "<p class='status-pass'>✓ PASS: Connected to database</p>";
    $testsPassed++;
    echo "</div>";
} else {
    echo "<p class='status-fail'>✗ FAIL: Database connection failed</p>";
    $testsFailed++;
    echo "</div>";
    die("Cannot continue without database");
}

// TEST 2: Blog Tables Exist
echo "<div class='test'>";
echo "<h3>Test 2: Blog Tables Exist</h3>";
$tables = ['blogs', 'blog_categories', 'blog_tags', 'blog_tag_relations'];
$allTablesExist = true;
foreach ($tables as $table) {
    $result = $conn->query("SHOW TABLES LIKE '$table'");
    if ($result && $result->num_rows > 0) {
        echo "<p>✓ Table '$table' exists</p>";
    } else {
        echo "<p>✗ Table '$table' missing</p>";
        $allTablesExist = false;
    }
}
if ($allTablesExist) {
    $testsPassed++;
    echo "<p class='status-pass'>✓ PASS: All tables exist</p>";
} else {
    $testsFailed++;
    echo "<p class='status-fail'>✗ FAIL: Missing tables</p>";
}
echo "</div>";

// TEST 3: Blog Count
echo "<div class='test'>";
echo "<h3>Test 3: Blog Records</h3>";
$result = $conn->query("SELECT COUNT(*) as total FROM blogs");
$row = $result->fetch_assoc();
$totalBlogs = $row['total'];
echo "<p>Total blogs: <strong>$totalBlogs</strong></p>";
if ($totalBlogs > 0) {
    echo "<p class='status-pass'>✓ PASS: Blogs found in database</p>";
    $testsPassed++;
    
    // Show blog details
    $result = $conn->query("SELECT id, title, status, show_on_home, featured_image FROM blogs ORDER BY id DESC");
    echo "<table>";
    echo "<tr><th>ID</th><th>Title</th><th>Status</th><th>Show on Home</th><th>Image</th></tr>";
    while ($row = $result->fetch_assoc()) {
        $status = $row['status'] === 'published' ? '<span style=\"color:green;\">published</span>' : '<span style=\"color:orange;\">draft</span>';
        $showHome = $row['show_on_home'] ? '✓ Yes' : '✗ No';
        $image = $row['featured_image'] ? '✓ Yes' : '✗ No';
        echo "<tr><td>{$row['id']}</td><td>" . htmlspecialchars(substr($row['title'], 0, 40)) . "</td><td>$status</td><td>$showHome</td><td>$image</td></tr>";
    }
    echo "</table>";
} else {
    echo "<p class='status-fail'>✗ FAIL: No blogs found</p>";
    $testsFailed++;
}
echo "</div>";

// TEST 4: getBlogs Function - All Blogs
echo "<div class='test'>";
echo "<h3>Test 4: getBlogs() - All Blogs (with drafts)</h3>";
$allBlogs = getBlogs($conn, ['include_drafts' => true, 'limit' => 100]);
echo "<p>Returned: <strong>" . count($allBlogs) . "</strong> blogs</p>";
if (count($allBlogs) === $totalBlogs) {
    echo "<p class='status-pass'>✓ PASS: Function returns all blogs</p>";
    $testsPassed++;
} else {
    echo "<p class='status-fail'>✗ FAIL: Function returned " . count($allBlogs) . " but database has $totalBlogs</p>";
    $testsFailed++;
}
echo "</div>";

// TEST 5: getBlogs Function - Published Only
echo "<div class='test'>";
echo "<h3>Test 5: getBlogs() - Published Blogs Only</h3>";
$publishedBlogs = getBlogs($conn, ['limit' => 100]);
echo "<p>Published blogs: <strong>" . count($publishedBlogs) . "</strong></p>";
if (count($publishedBlogs) > 0) {
    echo "<p class='status-pass'>✓ PASS: Found published blogs</p>";
    $testsPassed++;
    foreach ($publishedBlogs as $blog) {
        echo "<p>- " . htmlspecialchars(substr($blog['title'], 0, 40)) . " (Author: " . htmlspecialchars($blog['author_name'] ?? 'Unknown') . ")</p>";
    }
} else {
    echo "<p class='status-fail'>✗ FAIL: No published blogs found</p>";
    $testsFailed++;
}
echo "</div>";

// TEST 6: getBlogs Function - Show on Home
echo "<div class='test'>";
echo "<h3>Test 6: getBlogs() - Blogs Marked for Homepage</h3>";
$homeBlogs = getBlogs($conn, ['show_on_home' => 1, 'limit' => 100]);
echo "<p>Homepage blogs: <strong>" . count($homeBlogs) . "</strong></p>";
if (count($homeBlogs) > 0) {
    echo "<p class='status-pass'>✓ PASS: Found blogs for homepage</p>";
    $testsPassed++;
    foreach ($homeBlogs as $blog) {
        echo "<p>- " . htmlspecialchars(substr($blog['title'], 0, 40)) . "</p>";
    }
} else {
    echo "<p>ℹ INFO: No blogs marked for homepage (this is OK, just mark some blogs)</p>";
}
echo "</div>";

// TEST 7: getBlogById Function
echo "<div class='test'>";
echo "<h3>Test 7: getBlogById() Function</h3>";
if ($totalBlogs > 0) {
    $result = $conn->query("SELECT id FROM blogs LIMIT 1");
    $row = $result->fetch_assoc();
    $testBlogId = $row['id'];
    
    $blog = getBlogById($testBlogId, $conn);
    if ($blog) {
        echo "<p class='status-pass'>✓ PASS: Retrieved blog ID $testBlogId</p>";
        $testsPassed++;
        echo "<p>Title: " . htmlspecialchars($blog['title']) . "</p>";
        echo "<p>Author: " . htmlspecialchars($blog['author_name'] ?? 'Unknown') . "</p>";
    } else {
        echo "<p class='status-fail'>✗ FAIL: Could not retrieve blog</p>";
        $testsFailed++;
    }
} else {
    echo "<p>ℹ INFO: Skipped (no blogs to test)</p>";
}
echo "</div>";

// TEST 8: getBlogBySlug Function
echo "<div class='test'>";
echo "<h3>Test 8: getBlogBySlug() Function</h3>";
if (count($publishedBlogs) > 0) {
    $testSlug = $publishedBlogs[0]['slug'];
    $blog = getBlogBySlug($testSlug, $conn);
    if ($blog) {
        echo "<p class='status-pass'>✓ PASS: Retrieved blog by slug: $testSlug</p>";
        $testsPassed++;
        echo "<p>Title: " . htmlspecialchars($blog['title']) . "</p>";
    } else {
        echo "<p class='status-fail'>✗ FAIL: Could not retrieve blog by slug</p>";
        $testsFailed++;
    }
} else {
    echo "<p>ℹ INFO: Skipped (no published blogs to test)</p>";
}
echo "</div>";

// TEST 9: slugExists Function
echo "<div class='test'>";
echo "<h3>Test 9: slugExists() Function</h3>";
if ($totalBlogs > 0) {
    $result = $conn->query("SELECT slug FROM blogs LIMIT 1");
    $row = $result->fetch_assoc();
    $existingSlug = $row['slug'];
    
    if (slugExists($existingSlug, $conn)) {
        echo "<p class='status-pass'>✓ PASS: Detected existing slug: $existingSlug</p>";
        $testsPassed++;
    } else {
        echo "<p class='status-fail'>✗ FAIL: Failed to detect existing slug</p>";
        $testsFailed++;
    }
} else {
    echo "<p>ℹ INFO: Skipped (no blogs)</p>";
}
echo "</div>";

// TEST 10: Admin Auth
echo "<div class='test'>";
echo "<h3>Test 10: Admin Authentication</h3>";
if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true) {
    echo "<p class='status-pass'>✓ PASS: Logged in as admin</p>";
    $testsPassed++;
} else {
    echo "<p>ℹ INFO: Not logged in as admin (login first)</p>";
}
echo "</div>";

// Summary
echo "<div class='test' style='margin-top: 30px; border-left-color: #9b59b6;'>";
echo "<h3>📊 Test Summary</h3>";
echo "<p><strong style='color: green;'>Passed: $testsPassed</strong></p>";
echo "<p><strong style='color: red;'>Failed: $testsFailed</strong></p>";
if ($testsFailed === 0) {
    echo "<p style='color: green; font-weight: bold;'>✓ All tests passed!</p>";
} else {
    echo "<p style='color: red; font-weight: bold;'>✗ Some tests failed</p>";
}
echo "</div>";

// Quick Links
echo "<div style='margin-top: 30px; padding: 20px; background: #ecf0f1; border-radius: 8px;'>";
echo "<h3>Quick Links</h3>";
echo "<p><a href='admin_add_blog.php' class='btn btn-admin'>+ Add Blog Post</a></p>";
echo "<p><a href='admin_blogs.php' class='btn btn-blog'>Manage Blogs</a></p>";
echo "<p><a href='index.php' class='btn btn-home'>View Homepage</a></p>";
echo "<p><a href='blogs.php' class='btn btn-blog'>View All Blogs</a></p>";
echo "</div>";

echo "</div>";
echo "</body></html>";
?>
