<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Custom Posts List
 */

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

$typeName = $_GET['type'] ?? '';
$typeName = \Core\Hook::applyFilters('admin_custom_post_type', $typeName);

if (!$typeName) {
    die('Post type not specified.');
}

$postType = \Models\PostType::get($typeName);
if (!$postType) {
    die('Post type not found.');
}

$message = null;
$messageType = 'success';

// Handle delete (POST only)
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
    $delId = (int) ($_POST['id'] ?? 0);
    // CSRF is handled globally by index.php
    if ($delId) {
        try {
            \Models\CustomPost::delete($delId);
            \Core\Cache::clear();
            header("Location: /admin/custom-posts.php?type=$typeName&deleted=1");
            exit;
        } catch (Exception $e) {
            $message = 'Error: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}

// Filter by status
$status = $_GET['status'] ?? null;
$search = $_GET['search'] ?? '';

// Get posts
if ($search) {
    $posts = \Models\CustomPost::search($typeName, $search);
} else {
    $posts = \Models\CustomPost::all($typeName, $status);
}

$pageTitle = $postType['label_plural'];
$currentPage = 'post-type-' . $typeName;

ob_start();
?>

<?php if ($message || isset($_GET['deleted'])): ?>
    <div class="notification is-<?= $messageType ?> is-light">
        <button class="delete" onclick="this.parentElement.remove()"></button>
        <?= $message ?: 'Post deleted successfully!' ?>
    </div>
<?php endif; ?>

<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="<?= htmlspecialchars($postType['icon']) ?>"></i></span>
                <?= htmlspecialchars($postType['label_plural']) ?>
                <span class="tag is-light ml-3"><?= count($posts) ?> items</span>
            </h2>
        </div>
        <div class="level-right">
            <a href="/admin/custom-post-edit.php?type=<?= $typeName ?>" class="button is-primary">
                <span class="icon"><i class="fas fa-plus"></i></span>
                <span>Add <?= htmlspecialchars($postType['label_singular']) ?></span>
            </a>
        </div>
    </div>

    <!-- Filters -->
    <div class="level mb-4">
        <div class="level-left">
            <div class="tabs is-small is-toggle">
                <ul>
                    <li class="<?= !$status ? 'is-active' : '' ?>">
                        <a href="?type=<?= $typeName ?>">All</a>
                    </li>
                    <li class="<?= $status === 'published' ? 'is-active' : '' ?>">
                        <a href="?type=<?= $typeName ?>&status=published">Published</a>
                    </li>
                    <li class="<?= $status === 'draft' ? 'is-active' : '' ?>">
                        <a href="?type=<?= $typeName ?>&status=draft">Drafts</a>
                    </li>
                </ul>
            </div>
        </div>
        <div class="level-right">
            <form method="GET" class="field has-addons">
                <input type="hidden" name="type" value="<?= $typeName ?>">
                <div class="control">
                    <input type="text" name="search" class="input is-small" placeholder="Search..."
                        value="<?= htmlspecialchars($search) ?>">
                </div>
                <div class="control">
                    <button type="submit" class="button is-small is-info">
                        <span class="icon"><i class="fas fa-search"></i></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <?php if (empty($posts)): ?>
        <div class="has-text-centered py-6">
            <span class="icon is-large has-text-grey-light">
                <i class="<?= htmlspecialchars($postType['icon']) ?> fa-3x"></i>
            </span>
            <p class="has-text-grey mt-4">No <?= strtolower($postType['label_plural']) ?> yet.</p>
            <a href="/admin/custom-post-edit.php?type=<?= $typeName ?>" class="button is-primary mt-3">
                <span class="icon"><i class="fas fa-plus"></i></span>
                <span>Add First <?= htmlspecialchars($postType['label_singular']) ?></span>
            </a>
        </div>
    <?php else: ?>
        <div class="table-container">
            <table class="table is-fullwidth is-hoverable">
                <thead>
                    <tr>
                        <th style="width: 50px;"></th>
                        <th>Title</th>
                        <?php
                        // Show first 2 custom fields as columns
                        $visibleFields = array_slice($postType['fields'] ?? [], 0, 2);
                        foreach ($visibleFields as $field):
                            ?>
                            <th><?= htmlspecialchars($field['label'] ?? $field['name']) ?></th>
                        <?php endforeach; ?>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($posts as $post): ?>
                        <tr>
                            <td>
                                <?php if ($post['thumbnail']): ?>
                                    <figure class="image is-48x48">
                                        <img src="<?= htmlspecialchars($post['thumbnail']) ?>"
                                            style="object-fit: cover; border-radius: 4px;">
                                    </figure>
                                <?php else: ?>
                                    <span class="icon is-large has-text-grey-lighter">
                                        <i class="<?= htmlspecialchars($postType['icon']) ?>"></i>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="/admin/custom-post-edit.php?type=<?= $typeName ?>&id=<?= $post['id'] ?>"
                                    class="has-text-weight-semibold">
                                    <?= htmlspecialchars($post['title']) ?>
                                </a>
                                <br>
                                <small class="has-text-grey">/<?= htmlspecialchars($post['slug']) ?></small>
                            </td>
                            <?php foreach ($visibleFields as $field):
                                $value = $post['fields_data'][$field['name']] ?? '';
                                ?>
                                <td>
                                    <?php if ($field['type'] === 'number' && $field['name'] === 'price'): ?>
                                        <strong>$<?= number_format((float) $value, 2) ?></strong>
                                    <?php else: ?>
                                        <?= htmlspecialchars(is_string($value) ? substr($value, 0, 50) : '') ?>
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>
                            <td>
                                <span class="tag is-<?= $post['status'] === 'published' ? 'success' : 'warning' ?>">
                                    <?= ucfirst($post['status']) ?>
                                </span>
                            </td>
                            <td>
                                <small><?= date('M j, Y', strtotime($post['created_at'])) ?></small>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="/admin/custom-post-edit.php?type=<?= $typeName ?>&id=<?= $post['id'] ?>"
                                        class="button is-small is-info is-light">
                                        <span class="icon"><i class="fas fa-edit"></i></span>
                                    </a>
                                    <a href="/<?= htmlspecialchars($post['slug']) ?>" target="_blank"
                                        class="button is-small is-success is-light">
                                        <span class="icon"><i class="fas fa-eye"></i></span>
                                    </a>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                                        <input type="hidden" name="id" value="<?= $post['id'] ?>">
                                        <button type="submit" class="button is-small is-danger is-light">
                                            <span class="icon"><i class="fas fa-trash"></i></span>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

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