<?php
/**
 * Name: Custom Field Groups
 * Description: Create custom field groups for post types with drag-and-drop builder supporting text, textarea, select, checkbox, and other field types for flexible content
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Product Specifications",
 *     "description": "Add fields for dimensions, weight, material, and care instructions to WooCommerce products without complex plugins."
 *   },
 *   {
 *     "title": "Recipe Cards",
 *     "description": "Create custom fields for ingredients, cook time, serving size, and nutritional info on food blog recipe posts."
 *   },
 *   {
 *     "title": "Real Estate Data",
 *     "description": "Build fields for bedrooms, bathrooms, square footage, lot size, and year built for property listing post type."
 *   }
 * ]
 * Added: 2025-09-10
 * Tags: custom-fields, meta, post-types, forms, frontend
 * WhereToFind: {
 *   "location": "Switchboard → Custom Field Groups",
 *   "url": "admin.php?page=custom-field-groups",
 *   "instructions": "Manage custom field groups and assign them to post types. Fields appear in the post editor.",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardCustomFieldGroups {

    public function __construct() {
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        add_action('save_post', [$this, 'save_meta_boxes']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('wp_ajax_switchboard_save_field_group', [$this, 'ajax_save_field_group']);
        add_action('wp_ajax_switchboard_delete_field_group', [$this, 'ajax_delete_field_group']);
        add_shortcode('switchboard_form', [$this, 'render_frontend_form']);

        // Add admin menu for standalone page
        add_action('admin_menu', [$this, 'add_admin_menu']);
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            'Custom Field Groups',
            'Custom Field Groups',
            'manage_options',
            'custom-field-groups',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Render admin page
     */
    public function render_admin_page() {
        $admin_file = plugin_dir_path(__FILE__) . '../../assets/custom-field-groups/admin.php';
        if (file_exists($admin_file)) {
            include $admin_file;
        }
    }
    
    public function enqueue_admin_scripts($hook) {
        // Check if we're on the custom field groups admin page
        $is_cfg_page = (
            (isset($_GET['page']) && $_GET['page'] === 'custom-field-groups') ||
            strpos($hook, 'custom-field-groups') !== false
        );

        if ($is_cfg_page) {
            // Enqueue the main Switchboard admin CSS
            if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
                wp_enqueue_style(
                    'switchboard-admin',
                    SWITCHBOARD_URL . 'switchboard-admin.css',
                    [],
                    SWITCHBOARD_VERSION
                );
            }
            // Ensure jQuery is loaded
            wp_enqueue_script('jquery');
            return;
        }

        // Only load on post edit screens
        if (!in_array($hook, ['post.php', 'post-new.php'])) {
            return;
        }

        // Check if this post type has field groups
        global $post;
        if (!$post) return;

        $groups = $this->get_field_groups();
        $has_image_field = false;

        foreach ($groups as $group) {
            if (in_array($post->post_type, $group['post_types'])) {
                foreach ($group['fields'] as $field) {
                    if ($field['type'] === 'image') {
                        $has_image_field = true;
                        break 2;
                    }
                }
            }
        }

        if ($has_image_field) {
            wp_enqueue_media();
        }
    }
    
    private function get_field_groups() {
        return get_option('switchboard_field_groups', []);
    }
    
    public function ajax_save_field_group() {
        check_ajax_referer('field_groups', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
        }

        $group_id = sanitize_key($_POST['group_id']);
        $title = sanitize_text_field($_POST['title']);
        $post_types = isset($_POST['post_types']) ? array_map('sanitize_key', $_POST['post_types']) : [];
        $fields = isset($_POST['fields']) ? json_decode(wp_unslash($_POST['fields']), true) : [];

        $groups = $this->get_field_groups();
        $groups[$group_id] = [
            'title' => $title,
            'post_types' => $post_types,
            'fields' => $fields
        ];

        update_option('switchboard_field_groups', $groups);
        wp_send_json_success();
    }

    public function ajax_delete_field_group() {
        check_ajax_referer('field_groups', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
        }

        $group_id = sanitize_key($_POST['group_id']);
        $groups = $this->get_field_groups();
        unset($groups[$group_id]);
        update_option('switchboard_field_groups', $groups);

        wp_send_json_success();
    }
    
    public function add_meta_boxes() {
        $groups = $this->get_field_groups();
        
        foreach ($groups as $group_id => $group) {
            foreach ($group['post_types'] as $post_type) {
                add_meta_box(
                    'switchboard_' . $group_id,
                    esc_html($group['title']) . ' <span class="switchboard-badge">SWITCHBOARD</span>',
                    [$this, 'render_meta_box'],
                    $post_type,
                    'normal',
                    'default',
                    ['group_id' => $group_id, 'fields' => $group['fields']]
                );
            }
        }
    }
    
    public function render_meta_box($post, $metabox) {
        $fields = $metabox['args']['fields'];
        wp_nonce_field('switchboard_field_group', 'switchboard_field_group_nonce');

        echo '<table class="form-table"><tbody>';
        foreach ($fields as $field) {
            $value = get_post_meta($post->ID, $field['key'], true);
            $required = $field['required'] ? 'required' : '';
            $required_mark = $field['required'] ? ' <span style="color:#d63638;">*</span>' : '';

            echo '<tr>';
            echo '<th scope="row"><label for="' . esc_attr($field['key']) . '">' . esc_html($field['label']) . $required_mark . '</label></th>';
            echo '<td>';

            switch ($field['type']) {
                case 'text':
                case 'url':
                case 'email':
                    echo '<input type="' . esc_attr($field['type']) . '" id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" value="' . esc_attr($value) . '" placeholder="' . esc_attr($field['placeholder']) . '" class="regular-text" ' . $required . '>';
                    break;

                case 'textarea':
                    echo '<textarea id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" rows="4" placeholder="' . esc_attr($field['placeholder']) . '" class="large-text" ' . $required . '>' . esc_textarea($value) . '</textarea>';
                    break;

                case 'number':
                    echo '<input type="number" id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" value="' . esc_attr($value) . '" placeholder="' . esc_attr($field['placeholder']) . '" class="small-text" ' . $required . '>';
                    break;

                case 'date':
                    echo '<input type="date" id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" value="' . esc_attr($value) . '" ' . $required . '>';
                    break;

                case 'select':
                    $options = isset($field['options']) ? explode("\n", $field['options']) : [];
                    echo '<select id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" ' . $required . '>';
                    echo '<option value="">' . esc_html__('Select...', 'wpswitchboard') . '</option>';
                    foreach ($options as $option) {
                        $option = trim($option);
                        if ($option) {
                            echo '<option value="' . esc_attr($option) . '" ' . selected($value, $option, false) . '>' . esc_html($option) . '</option>';
                        }
                    }
                    echo '</select>';
                    break;

                case 'checkbox':
                    echo '<label>';
                    echo '<input type="checkbox" id="' . esc_attr($field['key']) . '" name="' . esc_attr($field['key']) . '" value="yes" ' . checked($value, 'yes', false) . '>';
                    echo ' ' . esc_html__('Yes', 'wpswitchboard');
                    echo '</label>';
                    break;

                case 'image':
                    if ($value) {
                        echo '<div style="margin-bottom:10px;"><img src="' . esc_url(wp_get_attachment_url($value)) . '" style="max-width:150px;height:auto;border-radius:4px;"></div>';
                    }
                    echo '<input type="hidden" name="' . esc_attr($field['key']) . '" value="' . esc_attr($value) . '" class="image-field-value">';
                    echo '<button type="button" class="button upload-image-btn">' . esc_html__('Select Image', 'wpswitchboard') . '</button>';
                    if ($value) {
                        echo ' <button type="button" class="button remove-image-btn">' . esc_html__('Remove', 'wpswitchboard') . '</button>';
                    }
                    break;
            }

            echo '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';

        // Image upload script
        ?>
        <script>
        jQuery(document).ready(function($) {
            $('.upload-image-btn').on('click', function(e) {
                e.preventDefault();
                const btn = $(this);
                const input = btn.siblings('.image-field-value');

                const frame = wp.media({
                    title: '<?php echo esc_js(__('Select Image', 'wpswitchboard')); ?>',
                    button: { text: '<?php echo esc_js(__('Use Image', 'wpswitchboard')); ?>' },
                    multiple: false
                });

                frame.on('select', function() {
                    const attachment = frame.state().get('selection').first().toJSON();
                    input.val(attachment.id);
                    btn.before('<div style="margin-bottom:10px;"><img src="' + attachment.url + '" style="max-width:150px;height:auto;border-radius:4px;"></div>');
                    btn.after(' <button type="button" class="button remove-image-btn"><?php echo esc_js(__('Remove', 'wpswitchboard')); ?></button>');
                });

                frame.open();
            });

            $(document).on('click', '.remove-image-btn', function() {
                $(this).siblings('.image-field-value').val('');
                $(this).siblings('img').remove();
                $(this).remove();
            });
        });
        </script>
        <?php
    }
    
    public function save_meta_boxes($post_id) {
        if (!isset($_POST['switchboard_field_group_nonce']) || !wp_verify_nonce($_POST['switchboard_field_group_nonce'], 'switchboard_field_group')) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        $groups = $this->get_field_groups();
        foreach ($groups as $group) {
            // Only process if this post type is assigned to this group
            if (!in_array(get_post_type($post_id), $group['post_types'])) {
                continue;
            }
            
            foreach ($group['fields'] as $field) {
                $field_key = $field['key'];
                
                if (isset($_POST[$field_key])) {
                    $value = $_POST[$field_key];
                    
                    // Sanitize based on field type
                    switch ($field['type']) {
                        case 'email':
                            $value = sanitize_email($value);
                            break;
                        case 'url':
                            $value = esc_url_raw($value);
                            break;
                        case 'textarea':
                            $value = sanitize_textarea_field($value);
                            break;
                        case 'number':
                            $value = floatval($value);
                            break;
                        case 'image':
                            $value = absint($value);
                            break;
                        case 'checkbox':
                            $value = $value === 'yes' ? 'yes' : 'no';
                            break;
                        default:
                            $value = sanitize_text_field($value);
                    }
                    
                    update_post_meta($post_id, $field_key, $value);
                } else {
                    // For checkboxes, if not set, it means unchecked
                    if ($field['type'] === 'checkbox') {
                        update_post_meta($post_id, $field_key, 'no');
                    } else {
                        delete_post_meta($post_id, $field_key);
                    }
                }
            }
        }
    }

    public function render_frontend_form($atts) {
        // Frontend form implementation - placeholder for now
        return '<p>Frontend form coming soon...</p>';
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_field_groups',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

// Add AJAX handler for getting field group
add_action('wp_ajax_switchboard_get_field_group', function() {
    check_ajax_referer('field_groups', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
    }

    $group_id = sanitize_key($_POST['group_id']);
    $groups = get_option('switchboard_field_groups', []);

    if (isset($groups[$group_id])) {
        wp_send_json_success($groups[$group_id]);
    } else {
        wp_send_json_error(esc_html__('Group not found', 'wpswitchboard'));
    }
});

$switchboard_instance = new SwitchboardCustomFieldGroups();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
