<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Post Types Manager
 * Admin page for managing custom post types
 */

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

// Models and DB already handled.
// Seed defaults if needed
\Models\PostType::createTables();
\Models\PostType::seedDefaults();
\Models\Taxonomy::seedDefaults();

$message = '';
$messageType = '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $name = preg_replace('/[^a-z0-9_]/', '', strtolower($_POST['name'] ?? ''));
        if ($name && !empty($_POST['label_singular'])) {
            try {
                \Models\PostType::create([
                    'name' => $name,
                    'label_singular' => $_POST['label_singular'],
                    'label_plural' => $_POST['label_plural'] ?: $_POST['label_singular'] . 's',
                    'icon' => $_POST['icon'] ?: 'fas fa-file',
                    'slug_prefix' => $_POST['slug_prefix'] ?: $name . '/',
                    'has_archive' => isset($_POST['has_archive']) ? 1 : 0,
                    'is_system' => 0
                ]);
                $message = 'Post type created successfully!';
                $messageType = 'success';
            } catch (Exception $e) {
                $message = 'Error: ' . $e->getMessage();
                $messageType = 'danger';
            }
        }
    }

    if ($action === 'delete' && !empty($_POST['name'])) {
        \Models\PostType::delete($_POST['name']);
        $message = 'Post type deleted!';
        $messageType = 'warning';
    }
}

// Get all post types
$postTypes = \Models\PostType::all();

$pageTitle = 'Post Types';
$currentPage = 'post-types';

ob_start();
?>

<?php if ($message): ?>
    <div class="notification is-<?= $messageType ?> is-light">
        <button class="delete" onclick="this.parentElement.remove()"></button>
        <?= htmlspecialchars($message) ?>
    </div>
<?php endif; ?>

<div class="columns">
    <div class="column is-8">
        <div class="admin-card">
            <div class="level">
                <div class="level-left">
                    <h2 class="card-header-title" style="border: none; padding: 0;">
                        <span class="icon mr-2"><i class="fas fa-cubes"></i></span>
                        Post Types
                    </h2>
                </div>
                <div class="level-right">
                    <button class="button is-primary"
                        onclick="document.getElementById('createModal').classList.add('is-active')">
                        <span class="icon"><i class="fas fa-plus"></i></span>
                        <span>New Post Type</span>
                    </button>
                </div>
            </div>

            <div class="table-container">
                <table class="table is-fullwidth is-hoverable">
                    <thead>
                        <tr>
                            <th>Icon</th>
                            <th>Name</th>
                            <th>Label</th>
                            <th>Posts</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($postTypes as $pt):
                            $postCount = \Models\PostType::getPostCount($pt['name']);
                            ?>
                            <tr>
                                <td>
                                    <span class="icon has-text-primary">
                                        <i class="<?= htmlspecialchars($pt['icon']) ?>"></i>
                                    </span>
                                </td>
                                <td>
                                    <code><?= htmlspecialchars($pt['name']) ?></code>
                                    <?php if ($pt['is_system']): ?>
                                        <span class="tag is-info is-light ml-2">System</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?= htmlspecialchars($pt['label_singular']) ?></strong>
                                    <br>
                                    <small class="has-text-grey"><?= htmlspecialchars($pt['label_plural']) ?></small>
                                </td>
                                <td>
                                    <span class="tag is-light"><?= $postCount ?></span>
                                </td>
                                <td>
                                    <div class="buttons are-small">
                                        <a href="/admin/custom-posts.php?type=<?= $pt['name'] ?>"
                                            class="button is-primary is-light">
                                            <span class="icon"><i class="fas fa-list"></i></span>
                                            <span>View</span>
                                        </a>
                                        <a href="/admin/custom-post-edit.php?type=<?= $pt['name'] ?>"
                                            class="button is-success is-light">
                                            <span class="icon"><i class="fas fa-plus"></i></span>
                                            <span>Add</span>
                                        </a>
                                        <?php if (!$pt['is_system']): ?>
                                            <form method="POST" style="display: inline;"
                                                onsubmit="return confirm('Delete this post type?')">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="csrf_token"
                                                    value="<?= \Core\Auth::generateCsrfToken() ?>">
                                                <input type="hidden" name="name" value="<?= $pt['name'] ?>">
                                                <button type="submit" class="button is-danger is-light">
                                                    <span class="icon"><i class="fas fa-trash"></i></span>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="column is-4">
        <div class="admin-card">
            <h3 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-info-circle"></i></span>
                About Post Types
            </h3>
            <div class="content">
                <p>Post types allow you to create different kinds of content beyond pages and blog posts.</p>

                <h4>Preset Types:</h4>
                <ul>
                    <li><strong>Product</strong> - E-commerce</li>
                    <li><strong>Property</strong> - Real Estate</li>
                    <li><strong>Portfolio</strong> - Agency/Freelancer</li>
                    <li><strong>Event</strong> - Events</li>
                    <li><strong>Team</strong> - Team members</li>
                </ul>

                <h4>Features:</h4>
                <ul>
                    <li>Custom fields per type</li>
                    <li>Categories & tags</li>
                    <li>SEO-friendly URLs</li>
                    <li>Archive pages</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Create Modal -->
<div class="modal" id="createModal">
    <div class="modal-background" onclick="this.parentElement.classList.remove('is-active')"></div>
    <div class="modal-card">
        <header class="modal-card-head">
            <p class="modal-card-title">Create New Post Type</p>
            <button class="delete" aria-label="close"
                onclick="this.closest('.modal').classList.remove('is-active')"></button>
        </header>
        <form method="POST">
            <input type="hidden" name="action" value="create">
            <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
            <section class="modal-card-body">
                <div class="field">
                    <label class="label">Name (slug) <span class="has-text-danger">*</span></label>
                    <div class="control">
                        <input type="text" name="name" class="input" pattern="[a-z0-9_]+" placeholder="product"
                            required>
                    </div>
                    <p class="help">Lowercase letters, numbers, underscores only</p>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label">Singular Label <span class="has-text-danger">*</span></label>
                            <div class="control">
                                <input type="text" name="label_singular" class="input" placeholder="Product" required>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label">Plural Label</label>
                            <div class="control">
                                <input type="text" name="label_plural" class="input" placeholder="Products">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label">Icon</label>
                            <div class="control has-icons-left">
                                <input type="text" name="icon" class="input" placeholder="fas fa-box"
                                    value="fas fa-file">
                                <span class="icon is-left"><i class="fas fa-icons"></i></span>
                            </div>
                            <p class="help"><a href="https://fontawesome.com/icons" target="_blank">Browse icons</a></p>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label">URL Prefix</label>
                            <div class="control">
                                <input type="text" name="slug_prefix" class="input" placeholder="products/">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="field">
                    <label class="checkbox">
                        <input type="checkbox" name="has_archive" checked>
                        Has archive page
                    </label>
                </div>
            </section>
            <footer class="modal-card-foot">
                <button type="submit" class="button is-primary">Create Post Type</button>
                <button type="button" class="button"
                    onclick="this.closest('.modal').classList.remove('is-active')">Cancel</button>
            </footer>
        </form>
    </div>
</div>

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