<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Admin Pages Management
 */

// Auth and Database are already handled by index.php or parent scripts in modern setup.
// But we keep basic check if accessed directly (though .htaccess prevents this).
if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;
$successMessage = null;
$errorMessage = null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    file_put_contents(__DIR__ . '/debug_post_all.log', date('Y-m-d H:i:s') . " - POST Data: " . print_r($_POST, true) . "\n", FILE_APPEND);

    if (isset($_POST['action']) && $_POST['action'] === 'save') {
        $data = [
            'title' => $_POST['title'],
            'slug' => $_POST['slug'],
            'content' => $_POST['content'],
            'status' => $_POST['status'],
            'template' => $_POST['template'] ?? 'standard'
        ];

        try {
            if (isset($_POST['page_id']) && $_POST['page_id']) {
                $oldPage = \Models\Page::find($_POST['page_id']);
                \Models\Revision::create([
                    'object_id' => $_POST['page_id'],
                    'object_type' => 'page',
                    'content' => $oldPage['content']
                ]);
                \Models\Page::update($_POST['page_id'], $data);
                $pageId = $_POST['page_id'];
                $successMessage = 'Page updated successfully!';
            } else {
                $pageId = \Models\Page::create($data);
                $successMessage = 'Page created successfully!';
            }

            // Save Meta
            if (isset($_POST['meta_key']) && isset($_POST['meta_value'])) {
                \Models\Meta::set($pageId, 'page', $_POST['meta_key'], $_POST['meta_value']);
            }

            \Core\Cache::clear();
            header('Location: /admin/pages.php?success=1');
            exit;
        } catch (Exception $e) {
            $errorMessage = 'Error: ' . $e->getMessage();
        }
    }
}

// Deletion logic moved into POST block or handled separately via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $delId = $_POST['page_id'] ?? 0;
    try {
        \Models\Page::delete($delId);
        \Core\Cache::clear();
        header('Location: /admin/pages.php?deleted=1');
        exit;
    } catch (Exception $e) {
        $errorMessage = 'Deletion Error: ' . $e->getMessage();
    }
}

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

// Page settings
$pageTitle = ($action === 'create') ? 'Create Page' : (($action === 'edit') ? 'Edit Page' : 'Pages');
$currentPage = 'pages';

// Header actions
$headerActions = '<a href="/admin/pages.php?action=create" class="button is-primary">
    <span class="icon"><i class="fas fa-plus"></i></span>
    <span>New Page</span>
</a>';

// Start content buffer
ob_start();

if ($action === 'create' || $action === 'edit'):
    $page = $id ? \Models\Page::find($id) : ['title' => '', 'slug' => '', 'content' => '', 'status' => 'draft'];
    $meta_value = $id ? \Models\Meta::get($id, 'page', 'subtitle') : '';
    ?>

    <div class="admin-card">
        <h2 class="card-header-title">
            <?= $action === 'create' ? 'Create New Page' : 'Edit: ' . htmlspecialchars($page['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="page_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" type="text" name="title" value="<?= htmlspecialchars($page['title']) ?>"
                                placeholder="Page Title" required>
                        </div>
                    </div>

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

                    <div class="field">
                        <label class="label">
                            Content
                            <span class="tag is-info is-light ml-2">Shortcodes Supported</span>
                        </label>
                        <div class="control">
                            <textarea class="textarea" name="content" rows="15"
                                placeholder="Page content with [component:name] shortcodes..."><?= htmlspecialchars($page['content']) ?></textarea>
                        </div>
                        <p class="help">
                            Use shortcodes like: <code>[component:hero title="..." subtitle="..."]</code>
                        </p>
                    </div>
                </div>

                <div class="column is-4">
                    <!-- Sidebar -->
                    <div class="box">
                        <h3 class="title is-6 mb-4">Publish</h3>

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

                        <div class="field">
                            <label class="label">Template</label>
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select name="template">
                                        <option value="standard" <?= ($page['template'] ?? 'standard') === 'standard' ? 'selected' : '' ?>>Standard Theme</option>
                                        <option value="blank" <?= ($page['template'] ?? '') === 'blank' ? 'selected' : '' ?>>
                                            Blank (Visual Builder)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="field">
                            <label class="label">Subtitle (Meta)</label>
                            <div class="control">
                                <input type="hidden" name="meta_key" value="subtitle">
                                <input class="input" type="text" name="meta_value"
                                    value="<?= htmlspecialchars($meta_value ?? '') ?>" placeholder="Optional subtitle">
                            </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 Page</span>
                            </button>
                        </div>

                        <?php if ($id): ?>
                            <div class="buttons">
                                <a href="/<?= htmlspecialchars($page['slug']) ?>" target="_blank"
                                    class="button is-light is-fullwidth">
                                    <span class="icon"><i class="fas fa-external-link-alt"></i></span>
                                    <span>View Page</span>
                                </a>
                                <?php if (($page['template'] ?? '') === 'blank'): ?>
                                    <a href="/admin/builder.php?id=<?= $id ?>" class="button is-info is-fullwidth">
                                        <span class="icon"><i class="fas fa-magic"></i></span>
                                        <span>Edit with Visual Builder</span>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Component Browser -->
                    <div class="box">
                        <h3 class="title is-6 mb-4">
                            <span class="icon"><i class="fas fa-puzzle-piece"></i></span>
                            Available Components
                        </h3>
                        <div class="content is-small">
                            <ul>
                                <li><code>hero</code> - Hero section</li>
                                <li><code>features</code> - Feature grid</li>
                                <li><code>team</code> - Team members</li>
                                <li><code>contact_form</code> - Contact form</li>
                                <li><code>showcase</code> - Showcase</li>
                            </ul>
                        </div>
                        <a href="/admin/components.php" class="button is-small is-light is-fullwidth">
                            Manage Components
                        </a>
                    </div>
                </div>
            </div>

            <hr>
        </form>

        <div class="level">
            <div class="level-left">
                <a href="/admin/pages.php" class="button is-light">
                    <span class="icon"><i class="fas fa-arrow-left"></i></span>
                    <span>Back to Pages</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 page?')">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="page_id" value="<?= $id ?>">
                        <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                        <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: ?>

    <!-- Pages List -->
    <div class="admin-card">
        <div class="table-container">
            <table class="table is-fullwidth admin-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>Status</th>
                        <th width="150">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (\Models\Page::all() as $p): ?>
                        <tr>
                            <td>
                                <strong><?= htmlspecialchars($p['title']) ?></strong>
                            </td>
                            <td>
                                <code>/<?= htmlspecialchars($p['slug']) ?></code>
                            </td>
                            <td>
                                <span class="status-badge is-<?= $p['status'] ?>">
                                    <?= ucfirst($p['status']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="/admin/pages.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 page?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="page_id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                                        <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>
    </div>

<?php endif; ?>

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