<?php
/**
 * Admin Blog Posts View — Gmind Institute
 *
 * List view + Create/Edit form in a single file.
 * Uses Quill.js rich text editor for content.
 * Handles: listing, filtering, creating, editing, publishing, deleting.
 *
 * Expected variables:
 *   $posts          — array of blog post records
 *   $categories     — array of blog_categories records
 *   $usedCategories — array of distinct category values from blog_posts
 *   $editPost       — single post record for edit mode, or null
 *   $showForm       — bool, true when creating/editing
 *   $filterCategory — string, current category filter
 *   $filterSearch   — string, current search filter
 *   $filterStatus   — string, current status filter
 */

$posts          = $posts          ?? [];
$categories     = $categories     ?? [];
$usedCategories = $usedCategories ?? [];
$editPost       = $editPost       ?? null;
$showForm       = $showForm       ?? false;
$filterCategory = $filterCategory ?? '';
$filterSearch   = $filterSearch   ?? '';
$filterStatus   = $filterStatus   ?? '';
$basePath       = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrfToken      = $csrfToken      ?? '';
?>

<?php if ($showForm): ?>
<!-- ============================================================
     CREATE / EDIT FORM
     ============================================================ -->
<div class="admin-card">
    <div class="admin-card-header">
        <h2><?= $editPost ? 'Edit Blog Post' : 'Add New Blog Post' ?></h2>
        <a href="<?= $basePath ?>/admin/blog-posts" class="admin-btn admin-btn-secondary">Back to List</a>
    </div>
    <div class="admin-card-body">
        <form method="POST" action="<?= $basePath ?>/admin/blog-posts<?= $editPost ? '/' . (int) $editPost['id'] : '' ?>" enctype="multipart/form-data" id="blogForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">

            <!-- Title -->
            <div class="admin-form-group">
                <label for="title" class="admin-form-label">Title <span class="required">*</span></label>
                <input type="text" id="title" name="title" class="admin-form-control" value="<?= htmlspecialchars($editPost['title'] ?? '', ENT_QUOTES, 'UTF-8') ?>" required placeholder="Enter blog post title" oninput="autoGenerateSlug()">
            </div>

            <!-- Slug -->
            <div class="admin-form-group">
                <label for="slug" class="admin-form-label">Slug (SEO URL)</label>
                <div style="display:flex;gap:8px;align-items:center;">
                    <input type="text" id="slug" name="slug" class="admin-form-control" value="<?= htmlspecialchars($editPost['slug'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="auto-generated-from-title">
                    <button type="button" class="admin-btn admin-btn-secondary" onclick="regenerateSlug()" title="Regenerate slug from title" style="white-space:nowrap;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
                        Re-generate
                    </button>
                </div>
                <small class="admin-form-hint">Leave empty to auto-generate from title. Used in the URL: /blog/your-slug</small>
            </div>

            <!-- Short Description -->
            <div class="admin-form-group">
                <label for="short_description" class="admin-form-label">Short Description</label>
                <textarea id="short_description" name="short_description" class="admin-form-control" rows="3" placeholder="Brief description for listing pages and SEO (max 300 characters)" maxlength="300"><?= htmlspecialchars($editPost['short_description'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                <small class="admin-form-hint">Displayed on blog listing cards and search results. Max 300 characters.</small>
            </div>

            <!-- Content (Rich Text Editor) -->
            <div class="admin-form-group">
                <label class="admin-form-label">Full Content</label>
                <div id="quill-editor" style="min-height:350px;background:#fff;border:1px solid #ddd;border-radius:8px;font-size:0.92rem;"><?= $editPost['content'] ?? '' ?></div>
                <input type="hidden" name="content" id="contentHidden">
                <small class="admin-form-hint">Use the rich text editor to format your blog content. You can add headings, lists, links, images, and more.</small>
            </div>

            <!-- Two Column: Category + Tags -->
            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="category" class="admin-form-label">Category</label>
                    <select id="category" name="category" class="admin-form-control">
                        <option value="">-- Select Category --</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= htmlspecialchars($cat['slug'], ENT_QUOTES, 'UTF-8') ?>" <?= ($editPost['category'] ?? '') === $cat['slug'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="admin-form-group">
                    <label for="tags" class="admin-form-label">Tags</label>
                    <input type="text" id="tags" name="tags" class="admin-form-control" value="<?= htmlspecialchars($editPost['tags'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="e.g., CCC, Computer, Tips (comma-separated)">
                    <small class="admin-form-hint">Separate tags with commas</small>
                </div>
            </div>

            <!-- Featured Image -->
            <div class="admin-form-group">
                <label for="image" class="admin-form-label">Featured Image</label>
                <?php if (!empty($editPost['image'])): ?>
                <div style="margin-bottom:10px;">
                    <img src="<?= htmlspecialchars(upload_url($editPost['image']), ENT_QUOTES, 'UTF-8') ?>" alt="Current featured image" style="max-width:250px;max-height:150px;border-radius:8px;border:1px solid #ddd;">
                    <br><small>Current image. Upload a new one to replace.</small>
                </div>
                <?php endif; ?>
                <input type="file" id="image" name="image" class="admin-form-control" accept="image/jpeg,image/png,image/gif,image/webp">
                <small class="admin-form-hint">Recommended: 1200x630px. Max 5MB. JPG, PNG, GIF, WebP.</small>
            </div>

            <!-- Publish Settings -->
            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label class="admin-form-label">Publish Status</label>
                    <div style="display:flex;align-items:center;gap:12px;margin-top:4px;">
                        <label class="admin-toggle">
                            <input type="checkbox" name="is_published" value="1" <?= !empty($editPost['is_published']) ? 'checked' : '' ?> id="is_published_toggle">
                            <span class="admin-toggle-slider"></span>
                        </label>
                        <span id="publishLabel"><?= !empty($editPost['is_published']) ? 'Published' : 'Draft' ?></span>
                    </div>
                </div>
                <div class="admin-form-group">
                    <label for="published_at" class="admin-form-label">Publish Date/Time</label>
                    <input type="datetime-local" id="published_at" name="published_at" class="admin-form-control" value="<?= !empty($editPost['published_at']) ? date('Y-m-d\TH:i', strtotime($editPost['published_at'])) : '' ?>">
                    <small class="admin-form-hint">Leave empty to publish immediately when toggling on.</small>
                </div>
            </div>

            <!-- SEO Section -->
            <div style="margin-top:20px;padding:16px;background:#f8f9fa;border-radius:8px;border:1px solid #e9ecef;">
                <h3 style="margin:0 0 12px 0;font-size:0.95rem;color:#0d2b6e;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:middle;margin-right:4px;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    SEO Settings
                </h3>

                <div class="admin-form-group">
                    <label for="meta_title" class="admin-form-label">Meta Title</label>
                    <input type="text" id="meta_title" name="meta_title" class="admin-form-control" value="<?= htmlspecialchars($editPost['meta_title'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="SEO title (defaults to post title)" maxlength="70">
                    <small class="admin-form-hint">Recommended: 50-60 characters. Leave empty to use post title.</small>
                </div>

                <div class="admin-form-group">
                    <label for="meta_description" class="admin-form-label">Meta Description</label>
                    <textarea id="meta_description" name="meta_description" class="admin-form-control" rows="2" placeholder="Brief description for search engines" maxlength="160"><?= htmlspecialchars($editPost['meta_description'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                    <small class="admin-form-hint">Recommended: 150-160 characters. Leave empty to use short description.</small>
                </div>

                <div class="admin-form-group">
                    <label for="meta_keywords" class="admin-form-label">Meta Keywords</label>
                    <input type="text" id="meta_keywords" name="meta_keywords" class="admin-form-control" value="<?= htmlspecialchars($editPost['meta_keywords'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="keyword1, keyword2, keyword3">
                    <small class="admin-form-hint">Comma-separated keywords for SEO.</small>
                </div>

                <div class="admin-form-group">
                    <label for="og_image" class="admin-form-label">Open Graph Image</label>
                    <?php if (!empty($editPost['og_image'])): ?>
                    <div style="margin-bottom:10px;">
                        <img src="<?= htmlspecialchars(upload_url($editPost['og_image']), ENT_QUOTES, 'UTF-8') ?>" alt="OG image" style="max-width:250px;max-height:100px;border-radius:8px;border:1px solid #ddd;">
                        <br><small>Current OG image. Upload new to replace.</small>
                    </div>
                    <?php endif; ?>
                    <input type="file" id="og_image" name="og_image" class="admin-form-control" accept="image/jpeg,image/png,image/gif,image/webp">
                    <small class="admin-form-hint">Used when sharing on Facebook, WhatsApp, etc. Recommended: 1200x630px.</small>
                </div>
            </div>

            <!-- Submit -->
            <div style="margin-top:20px;display:flex;gap:10px;">
                <button type="submit" class="admin-btn admin-btn-primary" onclick="saveContent()">
                    <?= $editPost ? 'Update Post' : 'Create Post' ?>
                </button>
                <a href="<?= $basePath ?>/admin/blog-posts" class="admin-btn admin-btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<!-- Quill.js Rich Text Editor -->
<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
// Initialize Quill editor
var quill = new Quill('#quill-editor', {
    theme: 'snow',
    placeholder: 'Write your blog post content here...',
    modules: {
        toolbar: [
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'align': [] }],
            ['blockquote', 'code-block'],
            ['link', 'image'],
            ['clean']
        ]
    }
});

// Copy Quill content to hidden input before form submit
function saveContent() {
    document.getElementById('contentHidden').value = quill.root.innerHTML;
}

// Auto-generate slug from title
function autoGenerateSlug() {
    var titleInput = document.getElementById('title');
    var slugInput = document.getElementById('slug');
    // Only auto-generate if slug is empty or hasn't been manually edited
    if (slugInput.dataset.auto !== '0') {
        var title = titleInput.value;
        var slug = title.toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/[\s-]+/g, '-')
            .replace(/^-+|-+$/g, '');
        slugInput.value = slug;
    }
}

// Mark slug as manually edited
document.getElementById('slug').addEventListener('input', function() {
    this.dataset.auto = '0';
});

// Regenerate slug button
function regenerateSlug() {
    var title = document.getElementById('title').value;
    var slug = title.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/[\s-]+/g, '-')
        .replace(/^-+|-+$/g, '');
    var slugInput = document.getElementById('slug');
    slugInput.value = slug;
    slugInput.dataset.auto = '1';
}

// Toggle publish label
document.getElementById('is_published_toggle').addEventListener('change', function() {
    document.getElementById('publishLabel').textContent = this.checked ? 'Published' : 'Draft';
});
</script>

<?php else: ?>
<!-- ============================================================
     LIST VIEW
     ============================================================ -->

<!-- Filter Bar -->
<div class="admin-card" style="margin-bottom:20px;">
    <div class="admin-card-body" style="padding:12px 20px;">
        <form method="GET" action="<?= $basePath ?>/admin/blog-posts" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
            <input type="text" name="search" class="admin-form-control" placeholder="Search posts..." value="<?= htmlspecialchars($filterSearch, ENT_QUOTES, 'UTF-8') ?>" style="max-width:220px;">
            <select name="category" class="admin-form-control" style="max-width:180px;">
                <option value="">All Categories</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?= htmlspecialchars($cat['slug'], ENT_QUOTES, 'UTF-8') ?>" <?= $filterCategory === $cat['slug'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
                <?php endforeach; ?>
            </select>
            <select name="status" class="admin-form-control" style="max-width:140px;">
                <option value="">All Status</option>
                <option value="published" <?= $filterStatus === 'published' ? 'selected' : '' ?>>Published</option>
                <option value="draft" <?= $filterStatus === 'draft' ? 'selected' : '' ?>>Draft</option>
            </select>
            <button type="submit" class="admin-btn admin-btn-secondary">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                Filter
            </button>
            <a href="<?= $basePath ?>/admin/blog-posts" class="admin-btn admin-btn-secondary" style="background:#e9ecef;color:#495057;">Clear</a>
        </form>
    </div>
</div>

<!-- Action Bar -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <h3 style="margin:0;font-size:1rem;"><?= count($posts) ?> Post<?= count($posts) !== 1 ? 's' : '' ?></h3>
    <a href="<?= $basePath ?>/admin/blog-posts/create" class="admin-btn admin-btn-primary">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Add New Post
    </a>
</div>

<!-- Posts Table -->
<?php if (!empty($posts)): ?>
<div class="admin-card">
    <div class="admin-card-body" style="padding:0;">
        <div class="admin-table-wrapper">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th style="width:60px;">Image</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Author</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th style="width:140px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($posts as $post): ?>
                    <tr>
                        <td>
                            <?php if (!empty($post['image'])): ?>
                            <img src="<?= htmlspecialchars(upload_url($post['image']), ENT_QUOTES, 'UTF-8') ?>" alt="" style="width:50px;height:35px;object-fit:cover;border-radius:4px;">
                            <?php else: ?>
                            <div style="width:50px;height:35px;background:#f0f0f0;border-radius:4px;display:flex;align-items:center;justify-content:center;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong><?= htmlspecialchars(mb_substr($post['title'] ?? '', 0, 60), ENT_QUOTES, 'UTF-8') ?></strong>
                            <?php if (!empty($post['short_description'])): ?>
                            <br><small style="color:#888;"><?= htmlspecialchars(mb_substr($post['short_description'], 0, 80), ENT_QUOTES, 'UTF-8') ?>...</small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!empty($post['category'])): ?>
                            <span style="background:#eaf0fb;color:#1a4fa0;padding:2px 10px;border-radius:50px;font-size:0.75rem;font-weight:600;"><?= htmlspecialchars($post['category'], ENT_QUOTES, 'UTF-8') ?></span>
                            <?php else: ?>
                            <span style="color:#999;">—</span>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($post['author_name'] ?? 'Unknown', ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                            <form method="POST" action="<?= $basePath ?>/admin/blog-posts/<?= (int) $post['id'] ?>/toggle-publish" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                                <button type="submit" class="admin-toggle-btn <?= !empty($post['is_published']) ? 'active' : '' ?>" title="<?= !empty($post['is_published']) ? 'Click to unpublish' : 'Click to publish' ?>">
                                    <?= !empty($post['is_published']) ? 'Published' : 'Draft' ?>
                                </button>
                            </form>
                        </td>
                        <td style="font-size:0.82rem;color:#888;">
                            <?= htmlspecialchars(date('M d, Y', strtotime($post['created_at'] ?? 'now')), ENT_QUOTES, 'UTF-8') ?>
                        </td>
                        <td>
                            <div style="display:flex;gap:6px;">
                                <a href="<?= $basePath ?>/admin/blog-posts/<?= (int) $post['id'] ?>/edit" class="admin-btn-sm admin-btn-edit" title="Edit">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                                </a>
                                <a href="<?= $basePath ?>/blog/<?= htmlspecialchars($post['slug'] ?? '#', ENT_QUOTES, 'UTF-8') ?>" target="_blank" class="admin-btn-sm admin-btn-view" title="View on site">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                                </a>
                                <form method="POST" action="<?= $basePath ?>/admin/blog-posts/<?= (int) $post['id'] ?>/delete" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this blog post? This cannot be undone.');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="submit" class="admin-btn-sm admin-btn-delete" title="Delete">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php else: ?>
<div class="admin-card">
    <div class="admin-card-body" style="text-align:center;padding:40px;">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5"><path d="M4 19.5A2.5 2.5 0 016.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z"/></svg>
        <h3 style="color:#999;margin-top:12px;">No Blog Posts Found</h3>
        <p style="color:#bbb;">Create your first blog post to get started.</p>
        <a href="<?= $basePath ?>/admin/blog-posts/create" class="admin-btn admin-btn-primary" style="margin-top:12px;">Add New Post</a>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

<!-- Admin toggle button styles -->
<style>
.admin-toggle-btn {
    padding: 3px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 600;
    border: 1px solid #ddd; background: #f8f9fa; color: #666; cursor: pointer;
    transition: all 0.2s;
}
.admin-toggle-btn.active { background: #eafaf1; color: #27ae60; border-color: #27ae60; }
.admin-toggle-btn:hover { opacity: 0.85; }
.admin-form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 768px) { .admin-form-row { grid-template-columns: 1fr; } }
.admin-btn-sm { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 6px; border: none; cursor: pointer; transition: all 0.2s; text-decoration: none; }
.admin-btn-edit { background: #eaf0fb; color: #1a4fa0; }
.admin-btn-edit:hover { background: #1a4fa0; color: #fff; }
.admin-btn-view { background: #eafaf1; color: #27ae60; }
.admin-btn-view:hover { background: #27ae60; color: #fff; }
.admin-btn-delete { background: #fff5f5; color: #e84118; }
.admin-btn-delete:hover { background: #e84118; color: #fff; }
.required { color: #e84118; }
.admin-form-hint { display: block; margin-top: 4px; font-size: 0.78rem; color: #888; }
/* Quill editor overrides for admin */
.ql-container { min-height: 300px; font-size: 0.92rem; }
.ql-editor { min-height: 300px; }
.ql-toolbar { border-radius: 8px 8px 0 0 !important; border-color: #ddd !important; }
.ql-container { border-radius: 0 0 8px 8px !important; border-color: #ddd !important; }
</style>
