<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Custom Post Editor
 * Create/edit custom post entries
 */

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

// Get post type
$typeName = $_GET['type'] ?? '';
if (!$typeName) {
    header('Location: /admin/post-types.php');
    exit;
}

// Database and Models are already initialized by index.php or parent scripts.
$postType = \Models\PostType::get($typeName);
if (!$postType) {
    header('Location: /admin/post-types.php');
    exit;
}

// Ensure tables exist
\Models\PostType::createTables();

// Get taxonomies for this type
$taxonomies = \Models\Taxonomy::forPostType($typeName);

// Get existing post if editing
$postId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$post = $postId ? \Models\CustomPost::find($postId) : null;

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

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    
    if (empty($title)) {
        $message = 'Title is required!';
        $messageType = 'danger';
    } else {
        // Generate slug if empty
        if (empty($slug)) {
            $slug = $postType['slug_prefix'] . \Models\CustomPost::generateSlug($title, $postId);
        }
        
        // Collect custom fields
        $fieldsData = [];
        foreach ($postType['fields'] as $field) {
            $fieldName = $field['name'];
            if (isset($_POST['fields'][$fieldName])) {
                $fieldsData[$fieldName] = $_POST['fields'][$fieldName];
            }
        }
        
        $data = [
            'post_type' => $typeName,
            'title' => $title,
            'slug' => $slug,
            'content' => $_POST['content'] ?? '',
            'excerpt' => $_POST['excerpt'] ?? '',
            'thumbnail' => $_POST['thumbnail'] ?? '',
            'fields_data' => $fieldsData,
            'status' => $_POST['status'] ?? 'draft'
        ];
        
        try {
            if ($postId) {
                \Models\CustomPost::update($postId, $data);
                $message = $postType['label_singular'] . ' updated successfully!';
            } else {
                $postId = \Models\CustomPost::create($data);
                $message = $postType['label_singular'] . ' created successfully!';
            }
            
            // Clear cache
            \Core\Cache::clear();

            $messageType = 'success';
            
            // Handle taxonomy terms
            foreach ($taxonomies as $tax) {
                $termIds = $_POST['tax_' . $tax['name']] ?? [];
                if (is_array($termIds)) {
                    \Models\CustomPost::setTerms($postId, $termIds);
                }
            }
            
            // Reload post
            $post = \Models\CustomPost::find($postId);
            
        } catch (Exception $e) {
            $message = 'Error: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}

$pageTitle = ($postId ? 'Edit' : 'New') . ' ' . $postType['label_singular'];
$currentPage = 'post-type-' . $typeName;

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; ?>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
    <div class="level mb-4">
        <div class="level-left">
            <a href="/admin/custom-posts.php?type=<?= $typeName ?>" class="button is-light">
                <span class="icon"><i class="fas fa-arrow-left"></i></span>
                <span>Back to <?= htmlspecialchars($postType['label_plural']) ?></span>
            </a>
        </div>
        <div class="level-right">
            <div class="buttons">
                <button type="submit" name="status" value="draft" class="button is-warning">
                    <span class="icon"><i class="fas fa-save"></i></span>
                    <span>Save Draft</span>
                </button>
                <button type="submit" name="status" value="published" class="button is-primary">
                    <span class="icon"><i class="fas fa-check"></i></span>
                    <span>Publish</span>
                </button>
            </div>
        </div>
    </div>
    
    <div class="columns">
        <!-- Main Content -->
        <div class="column is-8">
            <div class="admin-card">
                <div class="field">
                    <label class="label">Title <span class="has-text-danger">*</span></label>
                    <div class="control">
                        <input type="text" name="title" class="input is-medium" 
                               value="<?= htmlspecialchars($post['title'] ?? '') ?>" 
                               placeholder="Enter title" required>
                    </div>
                </div>
                
                <div class="field">
                    <label class="label">Slug</label>
                    <div class="control has-icons-left">
                        <input type="text" name="slug" class="input" 
                               value="<?= htmlspecialchars($post['slug'] ?? '') ?>" 
                               placeholder="<?= $postType['slug_prefix'] ?>auto-generated">
                        <span class="icon is-left"><i class="fas fa-link"></i></span>
                    </div>
                    <p class="help">Leave empty to auto-generate from title</p>
                </div>
                
                <?php if (in_array('content', $postType['supports'])): ?>
                <div class="field">
                    <label class="label">Content</label>
                    <div class="control">
                        <textarea name="content" class="textarea" rows="10" 
                                  placeholder="Write content here..."><?= htmlspecialchars($post['content'] ?? '') ?></textarea>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if (in_array('excerpt', $postType['supports'])): ?>
                <div class="field">
                    <label class="label">Excerpt</label>
                    <div class="control">
                        <textarea name="excerpt" class="textarea" rows="3" 
                                  placeholder="Short description..."><?= htmlspecialchars($post['excerpt'] ?? '') ?></textarea>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Custom Fields -->
            <?php if (!empty($postType['fields'])): ?>
            <div class="admin-card">
                <h3 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-sliders-h"></i></span>
                    <?= htmlspecialchars($postType['label_singular']) ?> Details
                </h3>
                
                <?php foreach ($postType['fields'] as $field): 
                    $fieldValue = $post['fields_data'][$field['name']] ?? '';
                ?>
                <div class="field mb-4">
                    <label class="label">
                        <?= htmlspecialchars($field['label'] ?? $field['name']) ?>
                        <?php if (!empty($field['required'])): ?>
                        <span class="has-text-danger">*</span>
                        <?php endif; ?>
                    </label>
                    <div class="control">
                        <?php switch ($field['type']): 
                            case 'text': ?>
                            <input type="text" name="fields[<?= $field['name'] ?>]" class="input"
                                   value="<?= htmlspecialchars($fieldValue) ?>"
                                   placeholder="<?= htmlspecialchars($field['placeholder'] ?? '') ?>"
                                   <?= !empty($field['required']) ? 'required' : '' ?>>
                            <?php break; ?>
                            
                            <?php case 'textarea': ?>
                            <textarea name="fields[<?= $field['name'] ?>]" class="textarea" rows="3"
                                      placeholder="<?= htmlspecialchars($field['placeholder'] ?? '') ?>"><?= htmlspecialchars($fieldValue) ?></textarea>
                            <?php break; ?>
                            
                            <?php case 'number': ?>
                            <input type="number" name="fields[<?= $field['name'] ?>]" class="input"
                                   value="<?= htmlspecialchars($fieldValue) ?>"
                                   step="any"
                                   <?= !empty($field['required']) ? 'required' : '' ?>>
                            <?php break; ?>
                            
                            <?php case 'email': ?>
                            <input type="email" name="fields[<?= $field['name'] ?>]" class="input"
                                   value="<?= htmlspecialchars($fieldValue) ?>">
                            <?php break; ?>
                            
                            <?php case 'url': ?>
                            <input type="url" name="fields[<?= $field['name'] ?>]" class="input"
                                   value="<?= htmlspecialchars($fieldValue) ?>"
                                   placeholder="https://...">
                            <?php break; ?>
                            
                            <?php case 'select': ?>
                            <div class="select is-fullwidth">
                                <select name="fields[<?= $field['name'] ?>]">
                                    <option value="">-- Select --</option>
                                    <?php foreach ($field['options'] ?? [] as $opt): 
                                        $optValue = is_array($opt) ? $opt['value'] : $opt;
                                        $optLabel = is_array($opt) ? $opt['label'] : $opt;
                                    ?>
                                    <option value="<?= htmlspecialchars($optValue) ?>" 
                                            <?= $fieldValue === $optValue ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($optLabel) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php break; ?>
                            
                            <?php case 'media': ?>
                            <div class="field has-addons">
                                <div class="control is-expanded">
                                    <input type="text" name="fields[<?= $field['name'] ?>]" class="input"
                                           value="<?= htmlspecialchars($fieldValue) ?>"
                                           placeholder="Image URL">
                                </div>
                                <div class="control">
                                    <button type="button" class="button is-info" onclick="this.previousElementSibling.querySelector('input').value = prompt('Enter image URL:') || ''">
                                        <span class="icon"><i class="fas fa-image"></i></span>
                                    </button>
                                </div>
                            </div>
                            <?php break; ?>
                            
                            <?php default: ?>
                            <input type="text" name="fields[<?= $field['name'] ?>]" class="input"
                                   value="<?= htmlspecialchars(is_string($fieldValue) ? $fieldValue : json_encode($fieldValue)) ?>">
                        <?php endswitch; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Sidebar -->
        <div class="column is-4">
            <!-- Status -->
            <div class="admin-card">
                <h3 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-cog"></i></span>
                    Status
                </h3>
                <?php 
                $currentStatus = $post['status'] ?? 'draft';
                ?>
                <div class="field">
                    <label class="label">Current Status</label>
                    <div class="control">
                        <?php if ($currentStatus === 'published'): ?>
                        <span class="tag is-success is-medium">Published</span>
                        <?php else: ?>
                        <span class="tag is-warning is-medium">Draft</span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($post): ?>
                <div class="field">
                    <label class="label">Created</label>
                    <p><?= date('M j, Y H:i', strtotime($post['created_at'])) ?></p>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Thumbnail -->
            <?php if (in_array('thumbnail', $postType['supports'])): ?>
            <div class="admin-card">
                <h3 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-image"></i></span>
                    Featured Image
                </h3>
                <div class="field">
                    <div class="control">
                        <input type="text" name="thumbnail" id="thumbnailInput" class="input mb-2"
                               value="<?= htmlspecialchars($post['thumbnail'] ?? '') ?>"
                               placeholder="Image URL">
                    </div>
                    <div id="thumbnailPreview" class="mt-2">
                        <?php if (!empty($post['thumbnail'])): ?>
                        <figure class="image is-16by9">
                            <img src="<?= htmlspecialchars($post['thumbnail']) ?>" style="object-fit: cover; border-radius: 4px;">
                        </figure>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Taxonomies -->
            <?php foreach ($taxonomies as $tax): 
                $terms = \Models\Taxonomy::getTerms($tax['name']);
                $postTerms = $post ? \Models\CustomPost::getTerms($post['id']) : [];
                $postTermIds = array_column($postTerms, 'id');
            ?>
            <div class="admin-card">
                <h3 class="card-header-title">
                    <span class="icon mr-2"><i class="fas fa-tags"></i></span>
                    <?= htmlspecialchars($tax['label']) ?>
                </h3>
                <?php if (empty($terms)): ?>
                <p class="has-text-grey is-size-7">No terms yet.</p>
                <?php else: ?>
                <div style="max-height: 200px; overflow-y: auto;">
                    <?php foreach ($terms as $term): ?>
                    <label class="checkbox is-block mb-2">
                        <input type="checkbox" name="tax_<?= $tax['name'] ?>[]" 
                               value="<?= $term['id'] ?>"
                               <?= in_array($term['id'], $postTermIds) ? 'checked' : '' ?>>
                        <?= htmlspecialchars($term['name']) ?>
                        <span class="tag is-light is-small ml-1"><?= $term['count'] ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</form>

<script>
// Thumbnail preview
document.getElementById('thumbnailInput')?.addEventListener('input', function() {
    const preview = document.getElementById('thumbnailPreview');
    if (this.value) {
        preview.innerHTML = '<figure class="image is-16by9"><img src="' + this.value + '" style="object-fit: cover; border-radius: 4px;"></figure>';
    } else {
        preview.innerHTML = '';
    }
});
</script>

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