<?php
declare(strict_types=1);

namespace EHxMe\PostTypes;

use EHxMe\Classes\View;
use EHxMe\Helpers\Helper;
use EHxMe\Services\Request;
use EHxMe\Services\Response;
use EHxMe\Services\Validator;

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

class FormPostType
{
    public Response $response;
    public Validator $validator;

    public function __construct() 
    {
        // Initialize dependencies
        $this->response  = new Response();
        $this->validator = new Validator();

        // Register custom post type
        add_action('init', [$this, 'createPostType']);

        // Handle post saving
        add_action('save_post', [$this, 'savePost'], 10, 2);

        // AJAX handlers
        add_action('wp_ajax_ehxme_add_field_modal', [$this, 'addFieldModal']);
        add_action('wp_ajax_ehxme_custom_field_modal', [$this, 'customFieldModal']);
        add_action('wp_ajax_ehxme_render_input_field', [$this, 'renderInputField']);

        // Customize admin columns
        $this->customize_admin_columns();

        // Disable Gutenberg and Classic Editor for 'ehxme-form'
        $this->disable_editors();

        // Remove unnecessary meta boxes
        $this->remove_meta_boxes();

        // Customize "Add New" post title and placeholder
        $this->customize_post_ui();
    }
    
    /**
     * Register the custom post type 'ehxme-form'
     */
    public function createPostType()
    {
        register_post_type('ehxme-form', [
            'label' => esc_html__("Forms", 'ehx-members'),
            'description' => esc_html__("Forms", 'ehx-members'),
            'labels' => [
                'label' => esc_html__('Forms', 'ehx-members'),
                'singular_name' => esc_html__('Form', 'ehx-members'),
                'menu_name'     => esc_html__('EHx Forms', 'ehx-members'),
                'all_items'     => esc_html__('All Forms', 'ehx-members'),
                'add_new'       => esc_html__('Add New', 'ehx-members'),
                'add_new_item'  => esc_html__('Add New Form', 'ehx-members'),
                'edit_item'     => esc_html__('Edit Form', 'ehx-members'),
                'new_item'      => esc_html__('New Form', 'ehx-members'),
                'view_item'     => esc_html__('View Form', 'ehx-members'),
                'search_items'  => esc_html__('Search Forms', 'ehx-members'),
                'not_found'     => esc_html__('No forms found', 'ehx-members'),
                'not_found_in_trash' => esc_html__('No forms found in Trash', 'ehx-members')
            ],
            'public' => true,
            'supports' => ['title', 'editor', 'thumbnail'],
            'hierarchical' => false,
            'show_ui' => true,
            'show_in_menu' => false,
            'menu_position' => 5,
            'menu_in_admin_bar' => true,
            'menu_in_nav_menus' => true,
            'can_export' => false,
            'has_archive' => false,
            'exclude_from_search' => false,
            'publicly_queryable' => true,
            'show_in_rest' => true,
            'menu_icon' => 'dashicons-images-alt2',
            'register_meta_box_cb' => [$this, 'addMetaBoxes'],
        ]);         
    }
    
    public function formCptColumns($columns)
    {
        $new_columns = array(
            '_ehx_mode' => __('Type', 'ehx-members'),
            'ehx_form_default' => __('Default', 'ehx-members'),
            'shortcode' => __('Shortcode', 'ehx-members'),
        );
        return array_merge($columns, $new_columns);
    }

    public function formCustomColumns($column, $post_id)
    {
        $ehx_form = get_post_meta($post_id, 'ehx_form', true);

        switch ($column) {
            case '_ehx_mode':
                echo esc_html(ucfirst($ehx_form['_ehx_mode'] ?? ''));
                break;
            case 'shortcode':
                echo '[ehxmember form_id="'.esc_attr($post_id).'"]';
                break;
            case 'ehx_form_default':
                echo esc_html__('No', 'ehx-members');
                break;
            default:
                echo esc_html($ehx_campaign[$column] ?? '');
                break;
        }
    }

    public function formSortableColumns($columns)
    {
        $columns['ehx_form_type'] = 'ehx_form_type';
        $columns['ehx_form_default'] = 'ehx_form_default';
        $columns['ehx_form_shortcode'] = 'ehx_form_shortcode';

        return $columns;
    }

    /**
     * Customize admin columns for 'ehxme-form' post type.
     */
    protected function customize_admin_columns()
    {
        add_filter('manage_ehxme-form_posts_columns', [$this, 'formCptColumns']);
        add_action('manage_ehxme-form_posts_custom_column', [$this, 'formCustomColumns'], 10, 2);
        add_filter('manage_edit-ehxme-form_sortable_columns', [$this, 'formSortableColumns']);
    }

    /**
     * Disable Gutenberg and Classic Editor for 'ehxme-form' post type.
     */
    protected function disable_editors()
    {
        // Disable Gutenberg editor
        add_filter('use_block_editor_for_post_type', [$this, 'disableGutenbergForEhxForm'], 10, 2);

        // Remove Classic Editor support
        add_action('admin_head', [$this, 'removeClassicEditorSupport']);
        add_action('addMetaBoxes', [$this, 'removeEditorSupportOnScreen'], 100);
    }

    /**
     * Remove unnecessary meta boxes for 'ehxme-form' post type.
     */
    protected function remove_meta_boxes()
    {
        add_action('do_meta_boxes', [$this, 'removeUnnecessaryMetaBoxes']);
    }

    /**
     * Customize "Add New" post title and placeholder for 'ehxme-form' post type.
     */
    protected function customize_post_ui()
    {
        add_filter('gettext', [$this, 'customizeAddNewPostTitle'], 10, 3);
        add_filter('enter_title_here', [$this, 'customizeTitlePlaceholder'], 10, 2);
    }

    /**
     * Disable Gutenberg editor for 'ehxme-form' post type.
     */
    public function disableGutenbergForEhxForm($enabled, $post_type)
    {
        return $post_type === 'ehxme-form' ? false : $enabled;
    }

    /**
     * Remove Classic Editor support for 'ehxme-form' post type.
     */
    public function removeClassicEditorSupport()
    {
        $screen = get_current_screen();
        
        if ($screen && $screen->post_type === 'ehxme-form') {
            remove_post_type_support('ehxme-form', 'editor');
        }
    }

    /**
     * Remove editor support on the 'ehxme-form' screen.
     */
    public function removeEditorSupportOnScreen()
    {
        if ($screen = get_current_screen()) {
            if ($screen->id === 'ehxme-form') {
                remove_post_type_support($screen->id, 'editor');
            }
        }
    }

    /**
     * Remove unnecessary meta boxes for 'ehxme-form' post type.
     */
    public function removeUnnecessaryMetaBoxes()
    {
        $meta_boxes_to_remove = [
            'generate_layout_options_meta_box' => 'side',
            'categorydiv' => 'side',
            'tagsdiv-post_tag' => 'side',
            'postimagediv' => 'side',
            'submitdiv' => 'side',
            'slugdiv' => 'normal',
        ];

        foreach ($meta_boxes_to_remove as $meta_box => $context) {
            remove_meta_box($meta_box, 'ehxme-form', $context);
        }
    }

    /**
     * Customize "Add New" post title for 'ehxme-form' post type.
     */
    public function customizeAddNewPostTitle($translated_text, $text, $domain)
    {
        if (is_admin() && get_post_type() === 'ehxme-form' && $text === 'Add New Post') {
            return esc_html__('Add New Form', 'ehx-members');
        }
        return $translated_text;
    }

    /**
     * Customize placeholder for title field in 'ehxme-form' post type.
     */
    public function customizeTitlePlaceholder($placeholder, $post)
    {
        return $post->post_type === 'ehxme-form' ? esc_html__('e.g. New Registration Form', 'ehx-members') : $placeholder;
    }

    /**
     * Register meta boxes for the 'ehxme-form' post type.
     */
    public function addMetaBoxes()
    {
        $meta_boxes = [
            [
                'id' => 'ehx_form_type_meta_box',
                'title' => esc_html__('Select Form Type', 'ehx-members'),
                'context' => 'normal',
                'priority' => 'high',
                'view' => 'admin/inc/form-type.php',
            ],
            [
                'id' => 'ehx_form_builder_meta_box',
                'title' => esc_html__('Form Builder', 'ehx-members'),
                'context' => 'normal',
                'priority' => 'high',
                'view' => 'admin/inc/form-builder.php',
            ],
            [
                'id' => 'ehx_form_create_meta_box',
                'title' => esc_html__('Create', 'ehx-members'),
                'context' => 'side',
                'priority' => 'high',
                'view' => 'admin/inc/form-create.php',
            ],
            [
                'id' => 'ehx_form_shortcode_meta_box',
                'title' => esc_html__('Shortcode', 'ehx-members'),
                'context' => 'side',
                'priority' => 'high',
                'view' => 'admin/inc/form-shortcode.php',
            ],
            [
                'id' => 'ehx_form_membership_meta_box',
                'title' => esc_html__('Membership', 'ehx-members'),
                'context' => 'side',
                'priority' => 'high',
                'view' => 'admin/inc/form-membership.php',
                'fields' => true,
            ],
            [
                'id' => 'ehx_form_customize_meta_box',
                'title' => esc_html__('Customize this form', 'ehx-members'),
                'context' => 'side',
                'priority' => 'high',
                'view' => 'admin/inc/form-customize.php',
                'fields' => true,
            ],
            [
                'id' => 'ehx_form_privacy_meta_box',
                'title' => esc_html__('Privacy Policy', 'ehx-members'),
                'context' => 'side',
                'priority' => 'high',
                'view' => 'admin/inc/form-privacy.php',
                'fields' => true,
            ],
            [
                'id' => 'ehx_form_options_meta_box',
                'title' => esc_html__('Options', 'ehx-members'),
                'context' => 'side',
                'priority' => 'default',
                'view' => 'admin/inc/form-options.php',
                'fields' => true,
            ],
        ];

        foreach ($meta_boxes as $meta_box) {
            add_meta_box(
                $meta_box['id'],
                $meta_box['title'],
                [$this, 'metaBox'],
                'ehxme-form',
                $meta_box['context'],
                $meta_box['priority'],
                array_filter([
                    'view' => $meta_box['view'],
                    'fields' => $meta_box['fields'] ?? false,
                ])
            );
        }
    }

    /**
     * add inner meta boxes
     */
    public function metaBox($post, $callback_args)
    {
        $args = array_map('esc_html', $callback_args['args']);

        $fields = isset($args['fields']) && $args['fields']  ? Helper::customize() : null;

        require_once EHXME_PLUGIN_DIR . "views/{$args['view']}";
    }

    /**
     * add add field modal
     */
    public function addFieldModal()
    {
        $this->validator->validate_ajax_nonce();
        
        $buttons = Helper::fieldButtons();

        $content = View::render('admin/inc/add-field-modal', ['buttons' => $buttons], true);

        return $this->response->success(data: ['html' => $content]);
    }

    /**
     * add inner meta boxes
     */
    public function customFieldModal()
    {
        $this->validator->validate_ajax_nonce();

        $fields = Helper::fields();

        // Validate and sanitize input
        $validated = (new Request)->input('validated', []);

        $content = View::render('admin/inc/custom-field-modal', ['validated' => $validated, 'fields' => $fields], true);

        return $this->response->success(data: ['html' => $content]);
    }
    
    /**
     * Render Input Field
     *
     * @return void
     */
    public function renderInputField()
    {
        $this->validator->validate_ajax_nonce(); 

        $this->validator->validate([
            '_title' => 'required|string',
            '_type' => 'required|string|max:50',
            '_metakey' => 'required|string|max:50',
            '_label' => 'required|string',
            '_help' => 'nullable|string|max:50',
            '_placeholder' => 'nullable|string',
            '_default' => 'nullable|string|max:50',
            '_height' => 'nullable|string|max:50',
            '_max_words' => 'nullable|string|max:50',
            '_public' => 'nullable|string|max:50',
            '_options' => 'nullable|string',
            '_upload_help_text' => 'nullable|string',
            '_validate' => 'nullable|string|max:255',
            '_allowed_types' => 'nullable|array',
            '_column' => 'required|string|max:50',
            '_max_size' => 'nullable|numeric|max:50',
            // '_min_chars' => 'string|max:50',
            '_visibility' => 'string|max:50',
            // '_max_chars' => 'string|max:50',
            '_force_good_pass' => 'nullable|string',
            '_force_confirm_pass' => 'nullable|string',
            '_label_confirm_pass' => 'nullable|string|max:255',
            '_required' => 'nullable|string',
        ], false);

        $validated = $this->validator->validated();

        $request = new Request();

        $metakey  = $request->input('_metakey');
        $edit_key = $request->input('edit_key');

        $validated['_metakey'] = strtolower(str_replace([' ', '-'], '_', $metakey));

        $content = View::render('admin/inc/input-field', ['validated' => $validated], true);

        return $this->response->success(data: [
            'html' => $content,
            'edit_key' => $edit_key
        ]);
    }

    /**
     * Save post metadata for 'ehxme-form' post type.
     *
     * @param int|string $post_id Post ID.
     */
    public function savePost($post_id)
    {
        // Verify nonce for our custom fields
        if (!isset($_POST[Helper::NONCE_NAME]) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST[Helper::NONCE_NAME])), Helper::NONCE_NAME)) {
            return;
        }

        // Prevent auto-saves
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        $request = new Request();

        // Ensure the request is for an 'ehx-form' post type
        if ($request->input('post_type') !== 'ehxme-form') {
            return;
        }

        // Ensure the user has permission to edit the post
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Only proceed if it's an edit post action
        if ($request->input('action') !== 'editpost') {
            return;
        }

        // List of meta fields to update
        $fields = ['_ehx_custom_field', 'ehx_form'];
        
        foreach ($fields as $field) {
            $new_value = $request->input($field);
            
            $old_value = get_post_meta($post_id, $field, true);
            
            // Update only if the value has changed
            if ($new_value !== $old_value) {
                update_post_meta($post_id, $field, $new_value);
            }
        }
    }
    
    /**
     * ehx custom fields
     *
     * @param  mixed $fields
     */
    public static function ehxCustomFields($fields, $validated)
    {
        ?>
            <?php foreach ($fields as $field): ?>
                <?php 
                    $value = isset($validated[$field->name]) ? $validated[$field->name] : null; 
                    $_type = $validated['_type'] ?? 'text';
                    $is_multiple = isset($field->is_multiple) && $field->is_multiple ? true : false;
                    $is_metakey = $field->name == '_metakey' && isset($validated[esc_attr($field->name)]);
                ?>
                <div style="display: <?php echo empty($field->condition) || in_array($_type, $field->condition) ? 'block':'none' ?>">
                    <label for="<?php echo esc_attr($field->name) ?>">
                        <?php echo esc_html($field->label) ?>
                        <span class="ehx_tooltip dashicons dashicons-editor-help" title="<?php echo $is_metakey ? esc_html__('The meta key cannot be changed for duplicated fields or when editing an existing field. If you require a different meta key please create a new field.', 'ehx-members') : esc_html($field->tooltip) ?>"></span>
                    </label>

                    <?php if($field->type == 'select'): ?>
                        <select 
                            name="<?php echo esc_attr($field->name); ?><?php echo $is_multiple ? '[]':''; ?>" 
                            id="<?php echo esc_attr($field->name); ?>" 
                            <?php echo $is_multiple ? 'multiple':''; ?>
                        >
                            <?php foreach($field->options as $key => $option): ?>
                                <option 
                                    value="<?php echo esc_html($key); ?>" 
                                    <?php
                                        if (empty($value)) {
                                            if (gettype($field->value) === 'array') {
                                                selected(true, in_array($key, $field->value));
                                            } 
                                            else {
                                                selected($key, $field->value);
                                            } 
                                        } 
                                        else {
                                            if (gettype($field->value) === 'array' && gettype(json_decode($value)) === 'array') {
                                                selected(true, in_array($key, json_decode($value)));
                                            } 
                                            else {
                                                selected($key, $value);
                                            }
                                        }
                                    ?>
                                ><?php echo esc_html($option) ?></option>
                            <?php endforeach ?>
                        </select>
                    <?php elseif($field->type == 'textarea'): ?>
                        <textarea 
                            name="<?php echo esc_attr($field->name) ?><?php echo $is_multiple ? '[]':''; ?>" 
                            id="<?php echo esc_attr($field->name) ?>" 
                            placeholder="<?php echo esc_html($field->placeholder ?? '') ?>"
                        ><?php echo esc_html($value ?? $field->value) ?></textarea>
                    <?php else: ?>
                        <input
                            type="<?php echo esc_attr($field->type) ?><?php echo $is_multiple ? '[]':''; ?>" 
                            name="<?php echo esc_attr($field->name) ?>" 
                            id="<?php echo esc_attr($field->name) ?>" 
                            value="<?php echo in_array($field->type, ['checkbox','radio']) ? esc_html($field->value) : esc_html($value); ?>" 
                            placeholder="<?php echo esc_html($field->placeholder ?? '') ?>" 
                            <?php 
                                wp_readonly(true, $is_metakey);
                                if (in_array($field->type, ['checkbox','radio'])) {
                                    checked($field->value, $value);
                                }
                            ?>
                        >
                    <?php endif ?>

                    <small class="invalid-feedback" id="invalid_<?php echo esc_attr($field->name) ?>" style="display: block;"></small>
                </div>
            <?php endforeach ?>
        <?php
    }
}