<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Admin Posts Management
 * Blog posts and news articles
 */

if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

// For now, we'll use Pages model with a 'post' type filter
$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;
$successMessage = null;
$errorMessage = null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'save') {
        $data = [
            'title' => $_POST['title'],
            'slug' => 'blog/' . $_POST['slug'], // Posts have blog/ prefix
            'content' => $_POST['content'],
            'status' => $_POST['status']
        ];

        try {
            if (isset($_POST['post_id']) && $_POST['post_id']) {
                \Models\Page::update($_POST['post_id'], $data);
                $postId = $_POST['post_id'];

                // Save metas
                \Models\Meta::set($postId, 'post', 'excerpt', $_POST['excerpt'] ?? '');
                \Models\Meta::set($postId, 'post', 'category', $_POST['category'] ?? '');
                \Models\Meta::set($postId, 'post', 'author', $_POST['author'] ?? '');
                \Models\Meta::set($postId, 'post', 'type', 'post');

                $successMessage = 'Post updated successfully!';
            } else {
                $postId = \Models\Page::create($data);

                // Save metas
                \Models\Meta::set($postId, 'post', 'excerpt', $_POST['excerpt'] ?? '');
                \Models\Meta::set($postId, 'post', 'category', $_POST['category'] ?? '');
                \Models\Meta::set($postId, 'post', 'author', $_POST['author'] ?? 'Admin');
                \Models\Meta::set($postId, 'post', 'type', 'post');
                \Models\Meta::set($postId, 'post', 'published_at', date('Y-m-d H:i:s'));

                $successMessage = 'Post created successfully!';
            }

            \Core\Cache::clear();
            header('Location: /admin/posts.php?success=1');
            exit;
        } catch (Exception $e) {
            $errorMessage = 'Error: ' . $e->getMessage();
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'delete') {
        \Models\Page::delete($_POST['post_id']);
        \Core\Cache::clear();
        header('Location: /admin/posts.php?deleted=1');
        exit;
    }
}

// Check for success messages from redirects
if (isset($_GET['success'])) {
    $successMessage = 'Post saved successfully!';
}
if (isset($_GET['deleted'])) {
    $successMessage = 'Post deleted successfully!';
}

// Get all posts (pages with blog/ prefix or post type meta)
$allPages = \Models\Page::all();
$posts = array_filter($allPages, function ($p) {
    return strpos($p['slug'], 'blog/') === 0;
});

// Categories for dropdown
$categories = ['News', 'Blog', 'Announcement', 'Case Study', 'Legal Update'];

// Page settings
$pageTitle = ($action === 'create') ? 'Create Post' : (($action === 'edit') ? 'Edit Post' : 'Posts');
$currentPage = 'posts';
$headerActions = '<a href="/admin/posts.php?action=create" class="button is-primary">
    <span class="icon"><i class="fas fa-plus"></i></span>
    <span>New Post</span>
</a>';

// Start content buffer
ob_start();

if ($action === 'create' || $action === 'edit'):
    $post = null;
    $excerpt = '';
    $category = '';
    $author = 'Admin';

    if ($id) {
        $post = \Models\Page::find($id);
        $excerpt = \Models\Meta::get($id, 'post', 'excerpt') ?? '';
        $category = \Models\Meta::get($id, 'post', 'category') ?? '';
        $author = \Models\Meta::get($id, 'post', 'author') ?? 'Admin';
        // Remove blog/ prefix for editing
        if ($post) {
            $post['slug'] = str_replace('blog/', '', $post['slug']);
        }
    }

    if (!$post) {
        $post = ['title' => '', 'slug' => '', 'content' => '', 'status' => 'draft'];
    }
    ?>

    <div class="admin-card">
        <h2 class="card-header-title">
            <span class="icon mr-2"><i class="fas fa-pen"></i></span>
            <?= $action === 'create' ? 'Create New Post' : 'Edit: ' . htmlspecialchars($post['title']) ?>
        </h2>

        <form method="POST" class="admin-form">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
            <?php if ($id): ?><input type="hidden" name="post_id" value="<?= $id ?>"><?php endif; ?>

            <div class="columns">
                <div class="column is-8">
                    <!-- Main Content -->
                    <div class="field">
                        <label class="label">Title</label>
                        <div class="control">
                            <input class="input is-medium" type="text" name="title"
                                value="<?= htmlspecialchars($post['title']) ?>" placeholder="Post Title" required>
                        </div>
                    </div>

                    <div class="field">
                        <label class="label">URL Slug</label>
                        <div class="control has-icons-left">
                            <input class="input" type="text" name="slug" value="<?= htmlspecialchars($post['slug']) ?>"
                                placeholder="my-blog-post" required>
                            <span class="icon is-small is-left">
                                <i class="fas fa-link"></i>
                            </span>
                        </div>
                        <p class="help">URL: /blog/<?= htmlspecialchars($post['slug'] ?: 'your-post-slug') ?></p>
                    </div>

                    <div class="field">
                        <label class="label">Excerpt</label>
                        <div class="control">
                            <textarea class="textarea" name="excerpt" rows="3"
                                placeholder="Brief summary of the post (for listings)"><?= htmlspecialchars($excerpt) ?></textarea>
                        </div>
                    </div>

                    <div class="field">
                        <label class="label">Content</label>
                        <div class="control">
                            <textarea class="textarea" name="content" rows="15"
                                placeholder="Write your post content here..."><?= htmlspecialchars($post['content']) ?></textarea>
                        </div>
                        <p class="help">
                            <i class="fas fa-info-circle"></i>
                            HTML and shortcodes like <code>[component:name]</code> are supported.
                        </p>
                    </div>
                </div>

                <div class="column is-4">
                    <!-- Sidebar -->
                    <div class="box">
                        <h3 class="title is-6 mb-4">
                            <i class="fas fa-paper-plane"></i> Publish
                        </h3>

                        <div class="field">
                            <label class="label">Status</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="status">
                                        <option value="draft" <?= $post['status'] === 'draft' ? 'selected' : '' ?>>
                                            📝 Draft
                                        </option>
                                        <option value="published" <?= $post['status'] === 'published' ? 'selected' : '' ?>>
                                            ✅ Published
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <div class="buttons">
                            <button type="submit" class="button is-primary is-fullwidth">
                                <span class="icon"><i class="fas fa-save"></i></span>
                                <span>Save Post</span>
                            </button>
                        </div>

                        <?php if ($id): ?>
                            <a href="/blog/<?= htmlspecialchars($post['slug']) ?>" target="_blank"
                                class="button is-light is-fullwidth">
                                <span class="icon"><i class="fas fa-external-link-alt"></i></span>
                                <span>View Post</span>
                            </a>
                        <?php endif; ?>
                    </div>

                    <!-- Post Details -->
                    <div class="box">
                        <h3 class="title is-6 mb-4">
                            <i class="fas fa-tag"></i> Details
                        </h3>

                        <div class="field">
                            <label class="label">Category</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="category">
                                        <option value="">-- Select --</option>
                                        <?php foreach ($categories as $cat): ?>
                                            <option value="<?= $cat ?>" <?= $category === $cat ? 'selected' : '' ?>>
                                                <?= $cat ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">Author</label>
                            <div class="control">
                                <input class="input" type="text" name="author" value="<?= htmlspecialchars($author) ?>"
                                    placeholder="Author name">
                            </div>
                        </div>
                    </div>

                    <!-- Featured Image (future) -->
                    <div class="box">
                        <h3 class="title is-6 mb-4">
                            <i class="fas fa-image"></i> Featured Image
                        </h3>
                        <div class="has-text-centered p-4 has-background-light" style="border-radius: 4px;">
                            <span class="icon is-large has-text-grey-light">
                                <i class="fas fa-image fa-2x"></i>
                            </span>
                            <p class="is-size-7 has-text-grey mt-2">
                                Coming in Phase 5
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <hr>

        <div class="level">
            <div class="level-left">
                <a href="/admin/posts.php" class="button is-light">
                    <span class="icon"><i class="fas fa-arrow-left"></i></span>
                    <span>Back to Posts</span>
                </a>
            </div>
            <div class="level-right">
                <?php if ($id): ?>
                    <form method="POST" style="display: inline;"
                        onsubmit="return confirm('Are you sure you want to delete this post?')">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                        <input type="hidden" name="post_id" value="<?= $id ?>">
                        <button type="submit" class="button is-danger is-light">
                            <span class="icon"><i class="fas fa-trash"></i></span>
                            <span>Delete</span>
                        </button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

<?php else: ?>

    <!-- Info about Posts feature -->
    <div class="notification is-info is-light mb-5">
        <div class="columns is-vcentered">
            <div class="column">
                <p>
                    <strong><i class="fas fa-info-circle"></i> Posts vs Pages</strong><br>
                    Posts are blog articles and news. They have dates, categories, and authors.
                    Pages are static content like "About Us" or "Contact".
                </p>
            </div>
        </div>
    </div>

    <!-- Posts List -->
    <div class="admin-card">
        <h2 class="card-header-title">
            <span class="icon mr-2"><i class="fas fa-newspaper"></i></span>
            All Posts (<?= count($posts) ?>)
        </h2>

        <?php if (empty($posts)): ?>
            <div class="has-text-centered p-6">
                <span class="icon is-large has-text-grey-light">
                    <i class="fas fa-newspaper fa-3x"></i>
                </span>
                <p class="has-text-grey mt-4 mb-4">No posts yet. Create your first blog post!</p>
                <a href="/admin/posts.php?action=create" class="button is-primary">
                    <span class="icon"><i class="fas fa-plus"></i></span>
                    <span>Create First Post</span>
                </a>
            </div>
        <?php else: ?>
            <div class="table-container">
                <table class="table is-fullwidth admin-table">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Category</th>
                            <th>Author</th>
                            <th>Status</th>
                            <th width="150">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($posts as $p):
                            $pCategory = \Models\Meta::get($p['id'], 'post', 'category') ?? '-';
                            $pAuthor = \Models\Meta::get($p['id'], 'post', 'author') ?? 'Admin';
                            ?>
                            <tr>
                                <td>
                                    <strong><?= htmlspecialchars($p['title']) ?></strong>
                                    <br>
                                    <small class="has-text-grey">/<?= htmlspecialchars($p['slug']) ?></small>
                                </td>
                                <td>
                                    <?php if ($pCategory !== '-'): ?>
                                        <span class="tag is-info is-light"><?= htmlspecialchars($pCategory) ?></span>
                                    <?php else: ?>
                                        <span class="has-text-grey">-</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($pAuthor) ?></td>
                                <td>
                                    <span class="status-badge is-<?= $p['status'] ?>">
                                        <?= ucfirst($p['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="/admin/posts.php?action=edit&id=<?= $p['id'] ?>"
                                            class="button is-small is-info is-light" title="Edit">
                                            <span class="icon"><i class="fas fa-edit"></i></span>
                                        </a>
                                        <a href="/<?= htmlspecialchars($p['slug']) ?>" target="_blank"
                                            class="button is-small is-success is-light" title="View">
                                            <span class="icon"><i class="fas fa-eye"></i></span>
                                        </a>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this post?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                                            <input type="hidden" name="post_id" value="<?= $p['id'] ?>">
                                            <button type="submit" class="button is-small is-danger is-light" title="Delete">
                                                <span class="icon"><i class="fas fa-trash"></i></span>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

<?php endif; ?>

<?php
$content = ob_get_clean();
include __DIR__ . '/layouts/admin_layout.php';