<?php
// Blog Form Debug Test
require_once '../config.php';

echo "🔧 Blog Form Save Button Debug Test\n";
echo "=====================================\n\n";

// Test 1: Check if the save_blog POST parameter is being received
echo "1. Testing POST parameters:\n";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "   ✅ POST request received\n";
    echo "   📋 POST data received:\n";
    foreach ($_POST as $key => $value) {
        $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['save_blog'])) {
        echo "   ✅ save_blog button was clicked\n";
    } else {
        echo "   ❌ save_blog button NOT detected\n";
    }
    
    // Test required fields
    $required_fields = ['blog_title', 'blog_excerpt', 'blog_content', 'blog_category'];
    echo "\n   📝 Required fields check:\n";
    foreach ($required_fields as $field) {
        if (isset($_POST[$field]) && !empty(trim($_POST[$field]))) {
            echo "      ✅ $field: Present\n";
        } else {
            echo "      ❌ $field: Missing or empty\n";
        }
    }
    
    // Test image upload
    echo "\n   🖼️  Image upload check:\n";
    if (isset($_FILES['featured_image'])) {
        echo "      ✅ Image upload field detected\n";
        echo "      📊 Upload status: " . $_FILES['featured_image']['error'] . "\n";
        echo "      📏 File size: " . $_FILES['featured_image']['size'] . " bytes\n";
    } else {
        echo "      ℹ️  No image upload detected\n";
    }
    
} else {
    echo "   ℹ️  No POST request received (this is normal for testing)\n";
}

echo "\n2. Testing database connection:\n";
if ($link && !mysqli_connect_error()) {
    echo "   ✅ Database connection working\n";
} else {
    echo "   ❌ Database connection failed\n";
}

echo "\n3. Testing blog functions:\n";
require_once 'blog-functions.php';

$functions_to_test = ['saveBlogPost', 'handleImageUpload', 'validateBlogData'];
foreach ($functions_to_test as $func) {
    if (function_exists($func)) {
        echo "   ✅ $func - Available\n";
    } else {
        echo "   ❌ $func - Missing\n";
    }
}

echo "\n4. Testing upload directory:\n";
$upload_dir = '../uploads/blog/';
if (file_exists($upload_dir)) {
    echo "   ✅ Upload directory exists\n";
    if (is_writable($upload_dir)) {
        echo "   ✅ Upload directory is writable\n";
    } else {
        echo "   ⚠️  Upload directory is not writable\n";
    }
} else {
    echo "   ⚠️  Upload directory missing\n";
}

// If this is a POST request, simulate the blog save process
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_blog'])) {
    echo "\n5. Simulating blog save process:\n";
    
    try {
        $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' => '',
            'category' => $_POST['blog_category'] ?? '',
            'tags' => $_POST['blog_tags'] ?? '',
            'status' => $_POST['blog_status'] ?? 'draft'
        ];
        
        echo "   📋 Blog data prepared:\n";
        foreach ($blog_data as $key => $value) {
            $display_value = strlen($value) > 30 ? substr($value, 0, 30) . '...' : $value;
            echo "      - $key: $display_value\n";
        }
        
        // Validate required fields
        if (empty($blog_data['title']) || empty($blog_data['excerpt']) || empty($blog_data['content']) || empty($blog_data['category'])) {
            echo "   ❌ Required fields missing - blog save would fail\n";
            if (empty($blog_data['title'])) echo "      - Missing: title\n";
            if (empty($blog_data['excerpt'])) echo "      - Missing: excerpt\n";
            if (empty($blog_data['content'])) echo "      - Missing: content\n";
            if (empty($blog_data['category'])) echo "      - Missing: category\n";
        } else {
            echo "   ✅ All required fields present\n";
            
            // Try to save the blog
            $result = saveBlogPost($link, $blog_data);
            if ($result) {
                echo "   ✅ Blog saved successfully with ID: $result\n";
            } else {
                echo "   ❌ Blog save failed\n";
            }
        }
        
    } catch (Exception $e) {
        echo "   ❌ Exception during blog save: " . $e->getMessage() . "\n";
    }
}

echo "\n=====================================\n";
echo "🎯 Debug Summary:\n";
echo "✅ Use this script to test form submission\n";
echo "✅ Check browser console for JavaScript errors\n";
echo "✅ Verify all form fields are filled out\n";
echo "✅ Ensure CKEditor is loading properly\n";
echo "\n💡 Instructions:\n";
echo "1. Fill out the blog form completely\n";
echo "2. Click 'Save Blog Post' button\n";
echo "3. Check if this debug script shows the POST data\n";
echo "4. Look for any specific error messages\n";
?>
<!DOCTYPE html>
<html>
<head>
    <title>Blog Form Debug Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .debug-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: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
    <h2>🧪 Blog Form Debug Test</h2>
    <p>Use this simple form to test if the blog saving is working:</p>
    
    <div class="debug-form">
        <form method="POST" action="test-blog-form.php" enctype="multipart/form-data">
            <div class="form-group">
                <label for="blog_title">Blog Title *</label>
                <input type="text" id="blog_title" name="blog_title" required placeholder="Enter blog title">
            </div>
            
            <div class="form-group">
                <label for="blog_excerpt">Excerpt *</label>
                <textarea id="blog_excerpt" name="blog_excerpt" required placeholder="Enter blog excerpt" rows="3"></textarea>
            </div>
            
            <div class="form-group">
                <label for="blog_content">Content *</label>
                <textarea id="blog_content" name="blog_content" required placeholder="Enter blog content" rows="6"></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">Strategies</option>
                    <option value="tips">Tips & Tricks</option>
                    <option value="news">News</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="featured_image">Featured Image</label>
                <input type="file" id="featured_image" name="featured_image" accept="image/*">
            </div>
            
            <button type="submit" name="save_blog" value="1">🧪 Test Save Blog Post</button>
        </form>
    </div>
</body>
</html>