<?php
// Blog Update Button Debug Test
session_start();
require_once '../config.php';
require_once 'blog-functions.php';

// Simple admin check (bypass for testing)
if (!isset($_SESSION['admin_id'])) {
    $_SESSION['admin_id'] = 1;
    $_SESSION['admin_name'] = 'Test Admin';
}

echo "🔧 Blog Update Button Debug Test\n";
echo "=================================\n\n";

// Handle the update if posted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "📥 POST Request Received:\n";
    echo "Request Time: " . date('Y-m-d H:i:s') . "\n";
    echo "POST Data:\n";
    foreach ($_POST as $key => $value) {
        if ($key === 'blog_content') {
            echo "  - $key: " . strlen($value) . " characters\n";
        } else {
            $display_value = is_string($value) ? (strlen($value) > 50 ? substr($value, 0, 50) . '...' : $value) : print_r($value, true);
            echo "  - $key: $display_value\n";
        }
    }
    
    if (isset($_POST['update_blog'])) {
        echo "\n✅ UPDATE_BLOG detected - processing update...\n";
        
        $blog_id = intval($_POST['blog_id']);
        echo "Blog ID: $blog_id\n";
        
        if ($blog_id > 0) {
            // Get existing blog
            $existing_blog = getBlogByIdAdmin($link, $blog_id);
            if ($existing_blog) {
                echo "✅ Existing blog found: {$existing_blog['title']}\n";
                
                $featured_image = $_POST['existing_image'] ?? '';
                
                // Handle new image upload
                if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
                    echo "🖼️  Processing image upload...\n";
                    $upload_result = handleImageUpload($_FILES['featured_image']);
                    if ($upload_result['success']) {
                        $featured_image = $upload_result['filename'];
                        echo "✅ Image uploaded: {$upload_result['filename']}\n";
                    } else {
                        echo "❌ Image upload failed: {$upload_result['message']}\n";
                    }
                }
                
                $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' => $featured_image,
                    'category' => $_POST['blog_category'],
                    'tags' => $_POST['blog_tags'] ?? '',
                    'status' => $_POST['blog_status'] ?? 'draft'
                ];
                
                echo "\n📋 Blog data to update:\n";
                foreach ($blog_data as $key => $value) {
                    if ($key === 'content') {
                        echo "  - $key: " . strlen($value) . " characters\n";
                    } else {
                        $display_value = strlen($value) > 30 ? substr($value, 0, 30) . '...' : $value;
                        echo "  - $key: $display_value\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 "\n❌ Missing required fields: " . implode(', ', $missing_fields) . "\n";
                } else {
                    echo "\n✅ All required fields present\n";
                    
                    // Try to update the blog
                    echo "🔄 Calling updateBlog function...\n";
                    $result = updateBlog($link, $blog_id, $blog_data);
                    
                    if ($result) {
                        echo "✅ BLOG UPDATE SUCCESSFUL!\n";
                        echo "🎉 Blog ID $blog_id has been updated successfully\n";
                        
                        // Verify the update
                        $updated_blog = getBlogByIdAdmin($link, $blog_id);
                        if ($updated_blog && $updated_blog['title'] === $blog_data['title']) {
                            echo "✅ Update verified - title matches: {$updated_blog['title']}\n";
                        } else {
                            echo "⚠️  Update verification failed\n";
                        }
                    } else {
                        echo "❌ BLOG UPDATE FAILED!\n";
                        echo "SQL Error: " . mysqli_error($link) . "\n";
                    }
                }
            } else {
                echo "❌ Blog not found with ID: $blog_id\n";
            }
        } else {
            echo "❌ Invalid blog ID: $blog_id\n";
        }
    } elseif (isset($_POST['save_blog'])) {
        echo "\n🆕 SAVE_BLOG detected - this should be CREATE mode\n";
        echo "❌ ERROR: Form is in CREATE mode but should be UPDATE mode\n";
    } else {
        echo "\n❌ No valid action detected in POST data\n";
        echo "Available POST keys: " . implode(', ', array_keys($_POST)) . "\n";
    }
}

// Get a blog for testing
$blogs = getAllBlogsAdmin($link, 1, 0);
if (empty($blogs)) {
    echo "❌ No blogs available for testing\n";
    exit;
}

$test_blog = $blogs[0];
echo "\n🧪 Using test blog: ID {$test_blog['id']} - '{$test_blog['title']}'\n";
echo "=================================\n";
?>
<!DOCTYPE html>
<html>
<head>
    <title>Blog Update Button Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .form-container { background: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea, select { width: 100%; max-width: 500px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        textarea { height: 100px; }
        button { background: #007bff; color: white; padding: 12px 24px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background: #0056b3; }
        .debug { background: #e9ecef; padding: 10px; margin: 10px 0; border-radius: 4px; font-family: monospace; }
    </style>
</head>
<body>
    <h2>🧪 Blog Update Button Test</h2>
    <p><strong>Testing blog update functionality with real form submission</strong></p>
    
    <div class="debug">
        <strong>Debug Info:</strong><br>
        - Blog ID: <?php echo $test_blog['id']; ?><br>
        - Current Title: <?php echo htmlspecialchars($test_blog['title']); ?><br>
        - Current Status: <?php echo $test_blog['status']; ?><br>
        - Form Action: Should send POST with 'update_blog' parameter
    </div>
    
    <div class="form-container">
        <form method="POST" action="test-update-button.php" enctype="multipart/form-data" onsubmit="return confirmUpdate()">
            <!-- Hidden fields for edit mode -->
            <input type="hidden" name="blog_id" value="<?php echo $test_blog['id']; ?>">
            <input type="hidden" name="existing_image" value="<?php echo $test_blog['featured_image'] ?? ''; ?>">
            
            <div class="form-group">
                <label><strong>Editing Blog ID:</strong> <?php echo $test_blog['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($test_blog['title']); ?> (UPDATED)">
            </div>
            
            <div class="form-group">
                <label for="blog_excerpt">Excerpt *</label>
                <textarea id="blog_excerpt" name="blog_excerpt" required><?php echo htmlspecialchars($test_blog['excerpt']); ?> - Updated via test form</textarea>
            </div>
            
            <div class="form-group">
                <label for="blog_content">Content *</label>
                <textarea id="blog_content" name="blog_content" required><?php echo htmlspecialchars($test_blog['content']); ?>

Updated content added via test form at <?php echo date('Y-m-d H:i:s'); ?></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 $test_blog['category'] === 'strategies' ? 'selected' : ''; ?>>Strategies</option>
                    <option value="tips" <?php echo $test_blog['category'] === 'tips' ? 'selected' : ''; ?>>Tips & Tricks</option>
                    <option value="news" <?php echo $test_blog['category'] === 'news' ? 'selected' : ''; ?>>News</option>
                    <option value="guides" <?php echo $test_blog['category'] === 'guides' ? 'selected' : ''; ?>>Guides</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 $test_blog['status'] === 'draft' ? 'selected' : ''; ?>>Draft</option>
                    <option value="published" <?php echo $test_blog['status'] === 'published' ? 'selected' : ''; ?>>Published</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="blog_meta_title">Meta Title</label>
                <input type="text" id="blog_meta_title" name="blog_meta_title" 
                       value="<?php echo htmlspecialchars($test_blog['meta_title'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label for="blog_meta_description">Meta Description</label>
                <textarea id="blog_meta_description" name="blog_meta_description"><?php echo htmlspecialchars($test_blog['meta_description'] ?? ''); ?></textarea>
            </div>
            
            <button type="submit" name="update_blog" value="1" style="background: #28a745;">
                🧪 Test Update Blog Post
            </button>
        </form>
    </div>
    
    <script>
        function confirmUpdate() {
            return confirm('Are you sure you want to test update this blog post?\n\nThis will modify the actual blog in the database.');
        }
        
        console.log('Test form loaded for blog ID:', <?php echo $test_blog['id']; ?>);
    </script>
</body>
</html>