<?php
/**
 * CPT Builder Edit Page Template
 * Modern form design matching Switchboard design system
 *
 * @package Switchboard
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

// Get CPT data if editing
$is_edit = !empty($_GET['cpt']);
$cpt_slug = $is_edit ? sanitize_key($_GET['cpt']) : '';
$cpt_data = [];

if ($is_edit) {
    $cpts = get_option('switchboard_custom_post_types', []);
    foreach ($cpts as $cpt) {
        if ($cpt['slug'] === $cpt_slug) {
            $cpt_data = $cpt;
            break;
        }
    }

    if (empty($cpt_data)) {
        wp_die(esc_html__('Custom post type not found.', 'wpswitchboard'));
    }
}

// Set defaults
$defaults = [
    'name' => '',
    'plural_name' => '',
    'slug' => '',
    'menu_icon' => 'dashicons-admin-post',
    'menu_position' => 5,
    'rewrite_slug' => '',
    'supports' => ['title', 'editor', 'thumbnail'],
    'public' => true,
    'show_in_rest' => true,
    'has_archive' => true,
    'hierarchical' => false,
];

$cpt_data = wp_parse_args($cpt_data, $defaults);
?>

<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="cpt-form" class="sb-module-cpt-form">
    <?php wp_nonce_field('cpt_builder_save', 'cpt_builder_nonce'); ?>
    <input type="hidden" name="action" value="cpt_builder_save">
    <input type="hidden" name="is_edit" value="<?php echo $is_edit ? '1' : '0'; ?>">
    <?php if ($is_edit): ?>
        <input type="hidden" name="original_slug" value="<?php echo esc_attr($cpt_slug); ?>">
    <?php endif; ?>

    <!-- 2-Column Layout: Left (big) for Basic Info + Options, Right (small) for Features -->
    <div class="sb-module-form-layout">
        <!-- Left Column: Basic Information + Post Type Options -->
        <div class="sb-module-form-left">
            <!-- Basic Information -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Basic Information', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Core settings for your custom post type', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-grid">
                        <div class="sb-module-form-group">
                            <label for="cpt_name" class="sb-module-form-label">
                                <?php esc_html_e('Singular Name', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="cpt_name" id="cpt_name" value="<?php echo esc_attr($cpt_data['name']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Product, Event, Team Member', 'wpswitchboard'); ?>" required>
                            <p class="sb-module-form-help"><?php esc_html_e('The singular name for your post type', 'wpswitchboard'); ?></p>
                        </div>

                        <div class="sb-module-form-group">
                            <label for="cpt_plural_name" class="sb-module-form-label">
                                <?php esc_html_e('Plural Name', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="cpt_plural_name" id="cpt_plural_name" value="<?php echo esc_attr($cpt_data['plural_name']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Products, Events, Team Members', 'wpswitchboard'); ?>" required>
                            <p class="sb-module-form-help"><?php esc_html_e('The plural form of the name', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <div class="sb-module-form-grid">
                        <div class="sb-module-form-group">
                            <label for="cpt_slug" class="sb-module-form-label">
                                <?php esc_html_e('Slug', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="cpt_slug" id="cpt_slug" value="<?php echo esc_attr($cpt_data['slug']); ?>" class="sb-module-input" <?php echo $is_edit ? 'readonly' : ''; ?> placeholder="<?php esc_attr_e('e.g., product, event', 'wpswitchboard'); ?>" required pattern="[a-z0-9_-]+">
                            <p class="sb-module-form-help">
                                <?php echo $is_edit ?
                                    esc_html__('Cannot be changed after creation', 'wpswitchboard') :
                                    esc_html__('URL-friendly identifier (auto-generated from name)', 'wpswitchboard');
                                ?>
                            </p>
                        </div>

                        <div class="sb-module-form-group">
                            <label for="cpt_menu_icon" class="sb-module-form-label"><?php esc_html_e('Menu Icon', 'wpswitchboard'); ?></label>
                            <select name="cpt_menu_icon" id="cpt_menu_icon" class="sb-module-select">
                                <option value="dashicons-admin-post" <?php selected($cpt_data['menu_icon'], 'dashicons-admin-post'); ?>>Post</option>
                                <option value="dashicons-book" <?php selected($cpt_data['menu_icon'], 'dashicons-book'); ?>>Book</option>
                                <option value="dashicons-portfolio" <?php selected($cpt_data['menu_icon'], 'dashicons-portfolio'); ?>>Portfolio</option>
                                <option value="dashicons-products" <?php selected($cpt_data['menu_icon'], 'dashicons-products'); ?>>Product</option>
                                <option value="dashicons-calendar" <?php selected($cpt_data['menu_icon'], 'dashicons-calendar'); ?>>Event</option>
                                <option value="dashicons-location" <?php selected($cpt_data['menu_icon'], 'dashicons-location'); ?>>Location</option>
                                <option value="dashicons-groups" <?php selected($cpt_data['menu_icon'], 'dashicons-groups'); ?>>Team</option>
                                <option value="dashicons-star-filled" <?php selected($cpt_data['menu_icon'], 'dashicons-star-filled'); ?>>Featured</option>
                                <option value="dashicons-video-alt3" <?php selected($cpt_data['menu_icon'], 'dashicons-video-alt3'); ?>>Video</option>
                                <option value="dashicons-images-alt2" <?php selected($cpt_data['menu_icon'], 'dashicons-images-alt2'); ?>>Gallery</option>
                            </select>
                            <p class="sb-module-form-help"><?php esc_html_e('Icon shown in admin menu', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <div class="sb-module-form-grid">
                        <div class="sb-module-form-group">
                            <label for="cpt_menu_position" class="sb-module-form-label"><?php esc_html_e('Menu Position', 'wpswitchboard'); ?></label>
                            <input type="number" name="cpt_menu_position" id="cpt_menu_position" value="<?php echo esc_attr($cpt_data['menu_position']); ?>" class="sb-module-input" min="1" max="100">
                            <p class="sb-module-form-help"><?php esc_html_e('Position in admin menu (5 = below Posts, 20 = below Pages)', 'wpswitchboard'); ?></p>
                        </div>

                        <div class="sb-module-form-group">
                            <label for="cpt_rewrite_slug" class="sb-module-form-label"><?php esc_html_e('Rewrite Slug (Optional)', 'wpswitchboard'); ?></label>
                            <input type="text" name="cpt_rewrite_slug" id="cpt_rewrite_slug" value="<?php echo esc_attr($cpt_data['rewrite_slug']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('Leave empty to use main slug', 'wpswitchboard'); ?>" pattern="[a-z0-9_-]*">
                            <p class="sb-module-form-help"><?php esc_html_e('Custom URL slug (optional)', 'wpswitchboard'); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Post Type Options -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Post Type Options', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Configure behavior and visibility settings', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-options-grid">
                        <label class="sb-module-option-item">
                            <input type="checkbox" name="cpt_public" value="1" <?php checked($cpt_data['public']); ?>>
                            <div>
                                <strong><?php esc_html_e('Public', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Make this post type publicly queryable on the frontend', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="cpt_show_in_rest" value="1" <?php checked($cpt_data['show_in_rest']); ?>>
                            <div>
                                <strong><?php esc_html_e('Show in REST API', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Required for Gutenberg block editor support', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="cpt_has_archive" value="1" <?php checked($cpt_data['has_archive']); ?>>
                            <div>
                                <strong><?php esc_html_e('Has Archive', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Enable archive page for this post type', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="cpt_hierarchical" value="1" <?php checked($cpt_data['hierarchical']); ?>>
                            <div>
                                <strong><?php esc_html_e('Hierarchical', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Like pages (supports parent/child relationships)', 'wpswitchboard'); ?></span>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column: Supported Features -->
        <div class="sb-module-form-right">
            <div class="sb-module-card">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Supported Features', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Select which features this post type supports', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-checkbox-grid" style="grid-template-columns: 1fr;">
                        <?php
                        $support_options = [
                            'title' => __('Title', 'wpswitchboard'),
                            'editor' => __('Editor', 'wpswitchboard'),
                            'thumbnail' => __('Featured Image', 'wpswitchboard'),
                            'excerpt' => __('Excerpt', 'wpswitchboard'),
                            'comments' => __('Comments', 'wpswitchboard'),
                            'custom-fields' => __('Custom Fields', 'wpswitchboard'),
                            'author' => __('Author', 'wpswitchboard'),
                            'revisions' => __('Revisions', 'wpswitchboard'),
                            'page-attributes' => __('Page Attributes', 'wpswitchboard'),
                        ];
                        foreach ($support_options as $value => $label):
                            $checked = in_array($value, $cpt_data['supports']);
                        ?>
                            <label class="sb-module-checkbox-item">
                                <input type="checkbox" name="cpt_supports[]" value="<?php echo esc_attr($value); ?>" <?php checked($checked); ?>>
                                <span><?php echo esc_html($label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Actions (Full Width) -->
    <div class="sb-module-form-actions">
        <div class="sb-module-form-actions-left">
            <?php if ($is_edit): ?>
                <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['action' => 'delete', 'cpt' => $cpt_slug], admin_url('admin.php?page=cpt-builder')), 'delete_cpt_' . $cpt_slug)); ?>" class="sb-module-button sb-module-button-danger sb-module-button-sm" onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this custom post type? This will remove the configuration but not delete any existing posts.', 'wpswitchboard'); ?>');">
                    <?php esc_html_e('Delete', 'wpswitchboard'); ?>
                </a>
            <?php endif; ?>
        </div>
        <div class="sb-module-form-actions-right">
            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm cpt-cancel-btn">
                <?php esc_html_e('Cancel', 'wpswitchboard'); ?>
            </button>
            <button type="submit" name="save" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                <?php echo $is_edit ? esc_html__('Update Post Type', 'wpswitchboard') : esc_html__('Create Post Type', 'wpswitchboard'); ?>
            </button>
        </div>
    </div>
</form>

<script>
jQuery(document).ready(function($) {
    // Auto-generate slug from name (only when creating new)
    <?php if (!$is_edit): ?>
    // Track if user has manually edited the plural field
    var pluralManuallyEdited = false;
    var lastAutoPlural = '';

    $('#cpt_plural_name').on('input', function() {
        // If user types something different from what we auto-generated, mark as manually edited
        if ($(this).val() !== lastAutoPlural) {
            pluralManuallyEdited = true;
        }
    });

    $('#cpt_name').on('input', function() {
        var name = $(this).val();
        var slug = name.toLowerCase()
            .replace(/[^a-z0-9]+/g, '_')
            .replace(/^_|_$/g, '');
        $('#cpt_slug').val(slug);

        // Auto-generate plural only if user hasn't manually edited it
        if (!pluralManuallyEdited) {
            var plural = singularToPlural(name);
            lastAutoPlural = plural;
            $('#cpt_plural_name').val(plural);
        }
    });

    // Convert singular to plural with common English rules
    function singularToPlural(word) {
        if (!word) return '';

        // Common irregular plurals
        var irregulars = {
            'person': 'People',
            'child': 'Children',
            'man': 'Men',
            'woman': 'Women',
            'foot': 'Feet',
            'tooth': 'Teeth',
            'goose': 'Geese',
            'mouse': 'Mice',
            'ox': 'Oxen',
            'leaf': 'Leaves',
            'life': 'Lives',
            'knife': 'Knives',
            'wife': 'Wives',
            'half': 'Halves',
            'self': 'Selves',
            'calf': 'Calves',
            'loaf': 'Loaves',
            'potato': 'Potatoes',
            'tomato': 'Tomatoes',
            'hero': 'Heroes',
            'echo': 'Echoes',
            'cargo': 'Cargoes',
            'analysis': 'Analyses',
            'basis': 'Bases',
            'crisis': 'Crises',
            'diagnosis': 'Diagnoses',
            'thesis': 'Theses',
            'datum': 'Data',
            'medium': 'Media',
            'curriculum': 'Curricula',
            'memorandum': 'Memoranda',
            'criterion': 'Criteria',
            'phenomenon': 'Phenomena'
        };

        var lowerWord = word.toLowerCase();
        if (irregulars[lowerWord]) {
            // Preserve original capitalization
            if (word[0] === word[0].toUpperCase()) {
                return irregulars[lowerWord].charAt(0).toUpperCase() + irregulars[lowerWord].slice(1);
            }
            return irregulars[lowerWord];
        }

        // Words ending in -f or -fe -> -ves
        if (word.match(/[^aeiou]fe?$/i)) {
            return word.replace(/fe?$/i, 'ves');
        }

        // Words ending in consonant + y -> -ies
        if (word.match(/[^aeiou]y$/i)) {
            return word.replace(/y$/i, 'ies');
        }

        // Words ending in -s, -ss, -sh, -ch, -x, -z -> -es
        if (word.match(/(s|ss|sh|ch|x|z)$/i)) {
            return word + 'es';
        }

        // Words ending in -o (after consonant) -> -es (common cases)
        if (word.match(/[^aeiou]o$/i)) {
            return word + 'es';
        }

        // Default: add -s
        return word + 's';
    }
    <?php endif; ?>
});
</script>
