<?php
// Blog Editor View
$isEdit = isset($post);
require 'sidebar.php';
?>

<!--Page Container-->
<section class="page-container">
  <div class="page-content-wrapper">

    <!--Main Content-->
    <div class="content sm-gutter">
      <div class="container-fluid padding-25 sm-padding-10">
        <div class="row">
          <div class="col-12">
            <div class="section-title">
              <h5><i class="dripicons-article"></i> <?php echo $isEdit ? 'Edit Post' : 'New Post'; ?></h5>
            </div>
          </div>

          <div class="col-md-12">
            <div class="form-block mb-4">

              <form enctype="multipart/form-data" method="post">

                <?php if($isEdit): ?>
                <input type="hidden" value="<?php echo $post['post_id']; ?>" name="post_id">
                <?php endif; ?>
                <input type="hidden" name="action" value="save">

                <div class="form-row">
                  <!-- Main Content Column -->
                  <div class="form-group col-md-9">
                    <div class="block col-md-12">

                      <label class="required">Post Title</label>
                      <input type="text" name="post_title" id="post_title" class="form-control" 
                             value="<?php echo $isEdit ? htmlspecialchars($post['post_title']) : ''; ?>" 
                             placeholder="Enter post title..." required>

                      <label>URL Slug</label>
                      <input type="text" name="post_slug" id="post_slug" class="form-control" 
                             value="<?php echo $isEdit ? htmlspecialchars($post['post_slug']) : ''; ?>" 
                             placeholder="auto-generated-from-title">
                      <small class="form-text text-muted">Leave empty to auto-generate from title</small>

                      <label class="required">Content</label>
                      <textarea name="post_content" id="post_content" class="advancedtinymce form-control"><?php echo $isEdit ? $post['post_content'] : ''; ?></textarea>

                      <label>Excerpt (Optional)</label>
                      <textarea name="post_excerpt" class="form-control" rows="3" 
                                placeholder="Brief summary of the post..."><?php echo $isEdit ? htmlspecialchars($post['post_excerpt']) : ''; ?></textarea>
                      <small class="form-text text-muted">Used in post listings and meta descriptions</small>

                      <!-- SEO Section -->
                      <hr class="mt-4 mb-4">
                      <h6><i class="fa fa-search"></i> SEO Settings</h6>

                      <label>SEO Title</label>
                      <input type="text" name="post_seo_title" class="form-control" 
                             value="<?php echo $isEdit ? htmlspecialchars($post['post_seo_title']) : ''; ?>" 
                             placeholder="Leave empty to use post title">

                      <label>SEO Description</label>
                      <textarea name="post_seo_description" class="form-control" rows="2" 
                                placeholder="Meta description for search engines"><?php echo $isEdit ? htmlspecialchars($post['post_seo_description']) : ''; ?></textarea>

                      <label>Tags (comma separated)</label>
                      <input type="text" name="post_tags" class="form-control" 
                             value="<?php echo $isEdit ? htmlspecialchars($post['post_tags']) : ''; ?>" 
                             placeholder="tech, deals, shopping">

                      <hr class="mt-4 mb-4">

                      <!-- Author Bio Section -->
                      <fieldset>
                        <legend><i class="fa fa-user-circle"></i> Author Information</legend>

                        <label>Author Name</label>
                        <input type="text" name="post_author_name" class="form-control" 
                               value="<?php echo $isEdit ? htmlspecialchars($post['post_author_name'] ?? '') : ''; ?>" 
                               placeholder="Leave empty to use your username">
                        <small class="form-text text-muted">Override the default author name for this post</small>

                        <label class="mt-3">Author Bio</label>
                        <textarea name="post_author_bio" class="form-control" rows="3" 
                                  placeholder="Brief bio about the author..."><?php echo $isEdit ? htmlspecialchars($post['post_author_bio'] ?? '') : ''; ?></textarea>
                        <small class="form-text text-muted">Displayed in the author box on the post page</small>

                      </fieldset>

                    </div>
                  </div>

                  <!-- Sidebar Column -->
                  <div class="form-group col-md-3">
                    <div class="block col-md-12">

                      <!-- Publish Box -->
                      <h6><i class="fa fa-send"></i> Publish</h6>

                      <label>Author</label>
                      <select name="post_author" class="custom-select form-control">
                        <?php foreach($allAuthors as $author): ?>
                        <option value="<?php echo $author['user_id']; ?>" 
                                <?php echo ($isEdit && $post['post_author'] == $author['user_id']) || (!$isEdit && $author['user_id'] == $_SESSION['user_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($author['user_name']); ?>
                        </option>
                        <?php endforeach; ?>
                      </select>
                      <small class="form-text text-muted">Select the post author</small>

                      <label class="mt-3">Status</label>
                      <select name="post_status" class="custom-select form-control">
                        <option value="draft" <?php echo ($isEdit && $post['post_status'] == 'draft') ? 'selected' : ''; ?>>Draft</option>
                        <option value="published" <?php echo ($isEdit && $post['post_status'] == 'published') ? 'selected' : ''; ?>>Published</option>
                        <option value="scheduled" <?php echo ($isEdit && $post['post_status'] == 'scheduled') ? 'selected' : ''; ?>>Scheduled</option>
                      </select>

                      <div class="form-check mt-3 mb-3">
                        <input type="checkbox" name="post_featured" class="form-check-input" value="1" 
                               <?php echo ($isEdit && $post['post_featured']) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Featured Post</label>
                      </div>

                      <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-save"></i> <?php echo $isEdit ? 'Update Post' : 'Publish Post'; ?>
                      </button>

                      <?php if($isEdit): ?>
                      <a href="../controller/blog_preview.php?id=<?php echo $post['post_id']; ?>" target="_blank" class="btn btn-info btn-block mt-2">
                        <i class="fa fa-eye"></i> Preview
                      </a>
                      <?php endif; ?>
                      
                      <?php if($isEdit && $post['post_status'] == 'published'): ?>
                      <a href="<?php echo SITE_URL; ?>/Post/<?php echo $post['post_slug']; ?>" target="_blank" class="btn btn-success btn-block mt-2">
                        <i class="fa fa-external-link-alt"></i> View Live
                      </a>
                      <?php endif; ?>

                      <hr class="mt-4 mb-4">

                      <!-- Category -->
                      <h6><i class="fa fa-folder"></i> Category</h6>
                      <select name="post_category" id="categorySelect" class="custom-select form-control">
                        <option value="">Uncategorized</option>
                        <?php foreach($blogCategories as $cat): ?>
                        <option value="<?php echo $cat['blog_cat_id']; ?>" 
                                <?php echo ($isEdit && $post['post_category'] == $cat['blog_cat_id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['blog_cat_name']); ?>
                        </option>
                        <?php endforeach; ?>
                        <option value="new_category" style="background: #e8f5e9; font-weight: bold;">+ Add New Category</option>
                      </select>
                      
                      <!-- New Category Form (Hidden by default) -->
                      <div id="newCategoryForm" style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 4px;">
                        <h6 style="margin-bottom: 10px;">Create New Category</h6>
                        <div class="form-group">
                          <label>Category Name</label>
                          <input type="text" id="newCategoryName" class="form-control" placeholder="e.g., Tech News">
                        </div>
                        <button type="button" class="btn btn-success btn-sm" onclick="createCategory()">
                          <i class="fa fa-plus"></i> Create
                        </button>
                        <button type="button" class="btn btn-secondary btn-sm" onclick="cancelNewCategory()">
                          Cancel
                        </button>
                        <div id="categoryMessage" style="margin-top: 10px;"></div>
                      </div>

                      <hr class="mt-4 mb-4">

                      <!-- Featured Image -->
                      <h6><i class="fa fa-image"></i> Featured Image</h6>

                      <div id="featured-image-preview" class="mb-3">
                        <?php if($isEdit && $post['post_featured_image']): ?>
                        <img src="<?php echo getImageUrl($post['post_featured_image_cdn_url'], $post['post_use_cdn'], $post['post_featured_image']); ?>" 
                             alt="Featured Image" 
                             style="width: 100%; border-radius: 4px;">
                        <?php else: ?>
                        <div style="width: 100%; height: 150px; background: #f0f0f0; border-radius: 4px; display: flex; align-items: center; justify-content: center;">
                            <i class="fa fa-image" style="font-size: 48px; color: #999;"></i>
                        </div>
                        <?php endif; ?>
                      </div>

                      <label>Upload Image</label>
                      <input type="file" name="post_featured_image" class="form-control-file" accept="image/*" onchange="previewImage(this)">

                      <label class="mt-3">Or use CDN URL</label>
                      <input type="text" name="post_featured_image_cdn_url" class="form-control" 
                             value="<?php echo $isEdit ? htmlspecialchars($post['post_featured_image_cdn_url']) : ''; ?>" 
                             placeholder="https://cdn.example.com/image.jpg">

                    </div>
                  </div>

                </div>

              </form>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
// Auto-generate slug from title
document.getElementById('post_title').addEventListener('blur', function() {
    const slugInput = document.getElementById('post_slug');
    if (!slugInput.value) {
        const slug = this.value
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
        slugInput.value = slug;
    }
});

// Auto-generate slug from title
document.getElementById('post_title').addEventListener('blur', function() {
    const slugInput = document.getElementById('post_slug');
    if (!slugInput.value) {
        const slug = this.value
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
        slugInput.value = slug;
    }
});

// Preview featured image
function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('featured-image-preview').innerHTML = 
                '<img src="' + e.target.result + '" style="width: 100%; border-radius: 4px;">';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// Category Management
document.getElementById('categorySelect').addEventListener('change', function() {
    if (this.value === 'new_category') {
        document.getElementById('newCategoryForm').style.display = 'block';
        this.value = ''; // Reset select
    }
});

function cancelNewCategory() {
    document.getElementById('newCategoryForm').style.display = 'none';
    document.getElementById('newCategoryName').value = '';
    document.getElementById('categoryMessage').innerHTML = '';
}

function createCategory() {
    const categoryName = document.getElementById('newCategoryName').value.trim();
    const messageDiv = document.getElementById('categoryMessage');
    
    if (!categoryName) {
        messageDiv.innerHTML = '<div class="alert alert-danger">Please enter a category name</div>';
        return;
    }
    
    // Show loading
    messageDiv.innerHTML = '<div class="alert alert-info">Creating category...</div>';
    
    // AJAX request to create category
    fetch('../controller/ajax_create_blog_category.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'category_name=' + encodeURIComponent(categoryName)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Add new option to select
            const select = document.getElementById('categorySelect');
            const newOption = document.createElement('option');
            newOption.value = data.category_id;
            newOption.text = categoryName;
            newOption.selected = true;
            
            // Insert before "Add New Category" option
            select.insertBefore(newOption, select.options[select.options.length - 1]);
            
            // Hide form and show success
            messageDiv.innerHTML = '<div class="alert alert-success">Category created successfully!</div>';
            setTimeout(() => {
                cancelNewCategory();
            }, 1500);
        } else {
            messageDiv.innerHTML = '<div class="alert alert-danger">' + data.message + '</div>';
        }
    })
    .catch(error => {
        messageDiv.innerHTML = '<div class="alert alert-danger">Error creating category</div>';
    });
}
</script>
