<?php
require_once 'config/db.php';
function blog_edit_redirect($url) { header("Location: $url"); exit; }

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    blog_edit_redirect('blog_posts.php');
}

$id = (int)$_GET['id'];

// Fetch Post
$stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE id = ?");
$stmt->execute([$id]);
$post = $stmt->fetch();

if (!$post) {
    blog_edit_redirect('blog_posts.php');
}

// Fetch all categories
$cat_stmt = $pdo->query("SELECT id, name FROM blog_categories WHERE status = 'active' ORDER BY name ASC");
$categories = $cat_stmt->fetchAll();

// Fetch all subcategories
$sub_stmt = $pdo->query("SELECT id, category_id, name FROM blog_subcategories WHERE status = 'active' ORDER BY name ASC");
$subcategories = $sub_stmt->fetchAll();

// Fetch all tags
$tag_stmt = $pdo->query("SELECT id, name FROM blog_tags ORDER BY name ASC");
$all_tags = $tag_stmt->fetchAll();

// Fetch current post tags
$pt_stmt = $pdo->prepare("SELECT tag_id FROM blog_post_tags WHERE post_id = ?");
$pt_stmt->execute([$id]);
$current_tags = $pt_stmt->fetchAll(PDO::FETCH_COLUMN);

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $title = trim($_POST['title']);
    $category_id = (int)$_POST['category_id'];
    $subcategory_id = !empty($_POST['subcategory_id']) ? (int)$_POST['subcategory_id'] : null;
    $author = trim($_POST['author']);
    $status = $_POST['status'];
    $content = trim($_POST['content']);
    
    // Status transition tracking
    $published_at = $post['published_at'];
    if ($post['status'] !== 'published' && $status === 'published') {
        $published_at = date('Y-m-d H:i:s'); // Newly published
    }

    // Image Upload Logic (Optional on update)
    $image_path = $post['image_path'];
    
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $filename = $_FILES['image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = uniqid('blog_') . '.' . $ext;
            $destination = "../uploads/blogs/" . $new_filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
                // Remove old image
                if (!empty($post['image_path']) && file_exists("../" . $post['image_path'])) {
                    unlink("../" . $post['image_path']);
                }
                $image_path = "uploads/blogs/" . $new_filename;
            } else {
                $error = "Failed to move uploaded cover image.";
            }
        } else {
            $error = "Invalid file type. Only JPG, PNG, WEBP, and GIF are allowed.";
        }
    }

    if (!isset($error)) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("UPDATE blog_posts SET category_id=?, subcategory_id=?, title=?, author=?, content=?, image_path=?, status=?, published_at=? WHERE id=?");
            $stmt->execute([$category_id, $subcategory_id, $title, $author, $content, $image_path, $status, $published_at, $id]);
            
            // Handle Tags Update
            // 1. Delete existing
            $del_tags = $pdo->prepare("DELETE FROM blog_post_tags WHERE post_id = ?");
            $del_tags->execute([$id]);
            
            // 2. Insert new
            if (isset($_POST['tags']) && is_array($_POST['tags'])) {
                $tag_stmt = $pdo->prepare("INSERT INTO blog_post_tags (post_id, tag_id) VALUES (?, ?)");
                foreach ($_POST['tags'] as $tag_id) {
                    $tag_stmt->execute([$id, (int)$tag_id]);
                }
            }

            $pdo->commit();

            $_SESSION['success_msg'] = "Blog post updated successfully.";
            blog_edit_redirect('blog_posts.php');
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = "Database Error: " . $e->getMessage();
        }
    }
}
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-pen-to-square"></i> Edit Blog Post</h2>
        <p>Modify the content, category assignments, or cover image of your article.</p>
    </div>

    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="recent-activity">
        <form action="blog_edit.php?id=<?= $id ?>" method="POST" enctype="multipart/form-data">
            
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 20px;">
                <!-- Title -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Article Title *</label>
                    <input type="text" name="title" required value="<?= htmlspecialchars($post['title']) ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                </div>
                <!-- Status -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Status</label>
                    <select name="status" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="published" <?= $post['status'] == 'published' ? 'selected' : '' ?>>Published</option>
                        <option value="draft" <?= $post['status'] == 'draft' ? 'selected' : '' ?>>Draft</option>
                    </select>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <!-- Category -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Category *</label>
                    <select name="category_id" id="category_select" required style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="">-- Select Category --</option>
                        <?php foreach($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= $post['category_id'] == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Subcategory -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Subcategory (Optional)</label>
                    <select name="subcategory_id" id="subcategory_select" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                        <option value="">-- Select Subcategory --</option>
                        <!-- Populated via JS -->
                    </select>
                </div>
                <!-- Author -->
                <div>
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Author Name (Optional)</label>
                    <input type="text" name="author" value="<?= htmlspecialchars($post['author'] ?? '') ?>" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px;">
                </div>
            </div>

            <div style="margin-bottom: 20px;">
                <!-- Tags -->
                <div>
                    <label style="display:block; margin-bottom:10px; font-weight:600; color:var(--text); font-size: 0.9rem;">Select Tags (Optional)</label>
                    <div style="display: flex; flex-wrap: wrap; gap: 10px; padding: 15px; border: 1px solid var(--border); border-radius: 6px; background: var(--white); min-height: 80px;">
                        <?php foreach($all_tags as $tag): ?>
                            <label style="cursor: pointer; margin: 0;">
                                <input type="checkbox" name="tags[]" value="<?= $tag['id'] ?>" <?= in_array($tag['id'], $current_tags) ? 'checked' : '' ?> style="display: none;" class="tag-checkbox">
                                <span class="tag-pill" style="display: inline-block; padding: 6px 14px; background: #f8fafc; color: #64748b; border-radius: 20px; font-size: 0.85rem; font-weight: 500; border: 1px solid #cbd5e1; transition: all 0.2s; user-select: none;">
                                    <?= htmlspecialchars($tag['name']) ?>
                                </span>
                            </label>
                        <?php endforeach; ?>
                        <?php if(empty($all_tags)): ?>
                            <span style="color: #94a3b8; font-size: 0.9rem;">No tags available. <a href="blog_tags.php" style="color: var(--primary);">Create some tags</a> first.</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <style>
                .tag-checkbox:checked + .tag-pill {
                    background-color: var(--primary) !important;
                    color: white !important;
                    border-color: var(--primary) !important;
                    box-shadow: 0 2px 4px rgba(24, 170, 223, 0.2);
                }
                .tag-pill:hover {
                    background-color: #f1f5f9;
                }
            </style>

            <!-- Image Upload -->
            <div style="margin-bottom: 20px; display: flex; gap: 20px; align-items: flex-start;">
                <?php if (!empty($post['image_path'])): ?>
                    <img src="../<?= htmlspecialchars($post['image_path']) ?>" alt="Current Cover" style="width: 120px; height: 120px; object-fit: cover; border-radius: 8px; border: 1px solid var(--border);">
                <?php endif; ?>
                <div style="flex:1;">
                    <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Replace Cover Image (Optional) (JPG, PNG, WEBP)</label>
                    <input type="file" name="image" accept="image/*" style="width:100%; padding:10px; border:1px solid var(--border); border-radius:6px; background:#f8fafc;">
                    <small style="color: #64748b; margin-top: 5px; display: block;">Leave blank to keep the current image.</small>
                </div>
            </div>

            <!-- Content -->
            <div style="margin-bottom: 25px;">
                <label style="display:block; margin-bottom:5px; font-weight:600; color:var(--text); font-size: 0.9rem;">Article Content *</label>
                <p style="font-size: 0.8rem; color: #64748b; margin-bottom: 10px;">HTML tags are allowed for formatting (e.g. &lt;b&gt;, &lt;h3&gt;, &lt;p&gt;).</p>
                <textarea name="content" required rows="15" style="width:100%; padding:15px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical; line-height: 1.6;"><?= htmlspecialchars($post['content']) ?></textarea>
            </div>

            <div style="display: flex; gap: 15px;">
                <button type="submit" name="submit" class="logout-btn" style="background:var(--primary); border:none; padding:12px 25px; cursor:pointer; font-weight:600;">Update Blog Post</button>
                <a href="blog_posts.php" class="logout-btn" style="background:#e2e8f0; color:var(--text); text-decoration:none; padding:12px 25px; font-weight:600;">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
    const allSubcategories = <?= json_encode($subcategories) ?>;
    const categorySelect = document.getElementById('category_select');
    const subcategorySelect = document.getElementById('subcategory_select');
    const currentSubcatId = <?= json_encode($post['subcategory_id']) ?>;

    function populateSubcategories(catId) {
        subcategorySelect.innerHTML = '<option value="">-- Select Subcategory --</option>'; // Reset
        if (catId) {
            const filtered = allSubcategories.filter(sub => sub.category_id == catId);
            filtered.forEach(sub => {
                const opt = document.createElement('option');
                opt.value = sub.id;
                opt.textContent = sub.name;
                if (sub.id == currentSubcatId) {
                    opt.selected = true;
                }
                subcategorySelect.appendChild(opt);
            });
        }
    }

    // Initial load
    populateSubcategories(categorySelect.value);

    // On change
    categorySelect.addEventListener('change', function() {
        populateSubcategories(this.value);
    });
</script>

<?php require_once 'includes/footer.php'; ?>
