<?php
// Blog Edit Debug Test
require_once '../config.php';
require_once 'blog-functions.php';

echo "🔧 Blog Edit Functionality Debug Test\n";
echo "======================================\n\n";

// Test 1: Check if we can retrieve a blog for editing
echo "1. Testing blog retrieval for editing:\n";
$blogs = getAllBlogsAdmin($link, 5, 0);
if (!empty($blogs)) {
    $test_blog = $blogs[0];
    echo "   ✅ Found test blog: ID {$test_blog['id']} - '{$test_blog['title']}'\n";
    
    // Test getBlogByIdAdmin function
    $blog_details = getBlogByIdAdmin($link, $test_blog['id']);
    if ($blog_details) {
        echo "   ✅ getBlogByIdAdmin working - retrieved full blog data\n";
        echo "   📋 Blog details:\n";
        echo "      - ID: {$blog_details['id']}\n";
        echo "      - Title: {$blog_details['title']}\n";
        echo "      - Status: {$blog_details['status']}\n";
        echo "      - Category: {$blog_details['category']}\n";
        echo "      - Content length: " . strlen($blog_details['content']) . " chars\n";
        echo "      - Featured image: " . ($blog_details['featured_image'] ? $blog_details['featured_image'] : 'None') . "\n";
    } else {
        echo "   ❌ getBlogByIdAdmin failed\n";
    }
} else {
    echo "   ❌ No blogs found for testing\n";
    exit(1);
}

echo "\n2. Testing edit form submission:\n";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_blog'])) {
    echo "   ✅ Edit form submission detected\n";
    echo "   📋 POST data received:\n";
    foreach ($_POST as $key => $value) {
        if ($key === 'blog_content') {
            echo "      - $key: " . strlen($value) . " characters\n";
        } else {
            $display_value = is_string($value) ? (strlen($value) > 30 ? substr($value, 0, 30) . '...' : $value) : print_r($value, true);
            echo "      - $key: $display_value\n";
        }
    }
    
    $blog_id = intval($_POST['blog_id']);
    echo "\n   🎯 Attempting to update blog ID: $blog_id\n";
    
    if ($blog_id > 0) {
        $blog_data = [
            'title' => $_POST['blog_title'],
            'meta_title' => $_POST['blog_meta_title'] ?? '',
            'meta_description' => $_POST['blog_meta_description'] ?? '',
            'excerpt' => $_POST['blog_excerpt'],
            'content' => $_POST['blog_content'],
            'featured_image' => $_POST['existing_image'] ?? '',
            'category' => $_POST['blog_category'],
            'tags' => $_POST['blog_tags'] ?? '',
            'status' => $_POST['blog_status'] ?? 'draft'
        ];
        
        // Handle new image upload
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
            echo "   🖼️  New image upload detected\n";
            $upload_result = handleImageUpload($_FILES['featured_image']);
            if ($upload_result['success']) {
                $blog_data['featured_image'] = $upload_result['filename'];
                echo "   ✅ Image uploaded: {$upload_result['filename']}\n";
            } else {
                echo "   ❌ Image upload failed: {$upload_result['message']}\n";
            }
        }
        
        // Validate required fields
        $missing_fields = [];
        if (empty($blog_data['title'])) $missing_fields[] = 'title';
        if (empty($blog_data['excerpt'])) $missing_fields[] = 'excerpt';
        if (empty($blog_data['content'])) $missing_fields[] = 'content';
        if (empty($blog_data['category'])) $missing_fields[] = 'category';
        
        if (!empty($missing_fields)) {
            echo "   ❌ Missing required fields: " . implode(', ', $missing_fields) . "\n";
        } else {
            echo "   ✅ All required fields present\n";
            
            // Try to update the blog
            $result = updateBlog($link, $blog_id, $blog_data);
            if ($result) {
                echo "   ✅ Blog updated successfully!\n";
                echo "   🎉 Edit functionality is working properly\n";
            } else {
                echo "   ❌ Blog update failed - SQL error: " . mysqli_error($link) . "\n";
            }
        }
    } else {
        echo "   ❌ Invalid blog ID: $blog_id\n";
    }
} else {
    echo "   ℹ️  No edit form submission received (this is normal for testing)\n";
}

echo "\n3. Testing updateBlog function directly:\n";
if (!empty($blogs)) {
    $test_blog = $blogs[0];
    $test_data = [
        'title' => $test_blog['title'] . ' (TEST)',
        'excerpt' => $test_blog['excerpt'],
        'content' => $test_blog['content'],
        'category' => $test_blog['category'],
        'tags' => $test_blog['tags'],
        'status' => $test_blog['status'],
        'meta_title' => $test_blog['meta_title'] ?? '',
        'meta_description' => $test_blog['meta_description'] ?? '',
        'featured_image' => $test_blog['featured_image'] ?? ''
    ];
    
    echo "   🧪 Testing updateBlog function with test data...\n";
    $result = updateBlog($link, $test_blog['id'], $test_data);
    if ($result) {
        echo "   ✅ updateBlog function working\n";
        
        // Revert the test change
        $revert_data = $test_data;
        $revert_data['title'] = $test_blog['title']; // Remove (TEST)
        updateBlog($link, $test_blog['id'], $revert_data);
        echo "   ✅ Test change reverted\n";
    } else {
        echo "   ❌ updateBlog function failed: " . mysqli_error($link) . "\n";
    }
}

echo "\n======================================\n";
echo "🎯 Edit Functionality Test Summary:\n";
if (!empty($blogs)) {
    echo "✅ Blog retrieval working\n";
    echo "✅ getBlogByIdAdmin function working\n";
    echo "✅ updateBlog function available\n";
    echo "\n🔧 Next steps to test edit:\n";
    echo "1. Go to Admin Dashboard\n";
    echo "2. Click 'Edit' on any blog post\n";
    echo "3. Modify some content and click 'Update Blog Post'\n";
    echo "4. Check if it saves successfully\n";
} else {
    echo "❌ No blogs available for testing\n";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Blog Edit Debug Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-form { background: #f5f5f5; padding: 20px; border-radius: 8px; margin-top: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea, select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        button { background: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #218838; }
    </style>
</head>
<body>
    <h2>🧪 Blog Edit Test Form</h2>
    <p>Use this form to test the blog edit functionality:</p>
    
    <?php if (!empty($blogs)): ?>
    <div class="test-form">
        <form method="POST" action="test-blog-edit.php" enctype="multipart/form-data">
            <input type="hidden" name="blog_id" value="<?php echo $blogs[0]['id']; ?>">
            <input type="hidden" name="existing_image" value="<?php echo $blogs[0]['featured_image'] ?? ''; ?>">
            
            <div class="form-group">
                <label>Editing Blog ID: <?php echo $blogs[0]['id']; ?></label>
            </div>
            
            <div class="form-group">
                <label for="blog_title">Blog Title *</label>
                <input type="text" id="blog_title" name="blog_title" required value="<?php echo htmlspecialchars($blogs[0]['title']); ?>">
            </div>
            
            <div class="form-group">
                <label for="blog_excerpt">Excerpt *</label>
                <textarea id="blog_excerpt" name="blog_excerpt" required rows="3"><?php echo htmlspecialchars($blogs[0]['excerpt']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="blog_content">Content *</label>
                <textarea id="blog_content" name="blog_content" required rows="6"><?php echo htmlspecialchars($blogs[0]['content']); ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="blog_category">Category *</label>
                <select id="blog_category" name="blog_category" required>
                    <option value="">Select Category</option>
                    <option value="strategies" <?php echo $blogs[0]['category'] === 'strategies' ? 'selected' : ''; ?>>Strategies</option>
                    <option value="tips" <?php echo $blogs[0]['category'] === 'tips' ? 'selected' : ''; ?>>Tips & Tricks</option>
                    <option value="news" <?php echo $blogs[0]['category'] === 'news' ? 'selected' : ''; ?>>News</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="blog_status">Status</label>
                <select id="blog_status" name="blog_status">
                    <option value="draft" <?php echo $blogs[0]['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                    <option value="published" <?php echo $blogs[0]['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="featured_image">Featured Image (optional)</label>
                <input type="file" id="featured_image" name="featured_image" accept="image/*">
                <?php if (!empty($blogs[0]['featured_image'])): ?>
                    <p>Current: <?php echo $blogs[0]['featured_image']; ?></p>
                <?php endif; ?>
            </div>
            
            <button type="submit" name="update_blog" value="1">🧪 Test Update Blog</button>
        </form>
    </div>
    <?php else: ?>
    <p>❌ No blogs available for testing. Create a blog first.</p>
    <?php endif; ?>
</body>
</html>