<?php
/**
 * Admin meta boxes for guide editing.
 *
 * @package BW_Onboarding_Guide
 */

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

class BW_Admin {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
        add_action( 'save_post_bw_guide', array( $this, 'save_meta' ), 10, 2 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        add_filter( 'manage_bw_guide_posts_columns', array( $this, 'custom_columns' ) );
        add_action( 'manage_bw_guide_posts_custom_column', array( $this, 'column_content' ), 10, 2 );
    }

    /**
     * Enqueue admin scripts and styles.
     */
    public function enqueue_admin_assets( $hook ) {
        global $post_type;
        if ( 'bw_guide' !== $post_type ) {
            return;
        }
        wp_enqueue_style( 'bw-admin-css', BW_ONBOARDING_URL . 'assets/css/bw-admin.css', array(), BW_ONBOARDING_VERSION );
        wp_enqueue_script( 'bw-admin-js', BW_ONBOARDING_URL . 'assets/js/bw-admin.js', array( 'jquery', 'jquery-ui-sortable' ), BW_ONBOARDING_VERSION, true );
    }

    /**
     * Register meta boxes.
     */
    public function add_meta_boxes() {
        add_meta_box(
            'bw_guide_settings',
            __( 'Guide Settings', 'bw-onboarding-guide' ),
            array( $this, 'render_settings_meta_box' ),
            'bw_guide',
            'normal',
            'high'
        );

        add_meta_box(
            'bw_guide_steps',
            __( 'Tour Steps', 'bw-onboarding-guide' ),
            array( $this, 'render_steps_meta_box' ),
            'bw_guide',
            'normal',
            'high'
        );
    }

    /**
     * Render Guide Settings meta box.
     */
    public function render_settings_meta_box( $post ) {
        wp_nonce_field( 'bw_guide_save', 'bw_guide_nonce' );

        $trigger_url = get_post_meta( $post->ID, '_bw_trigger_url', true );
        $show_to     = get_post_meta( $post->ID, '_bw_show_to', true ) ?: 'logged_in';
        $show_once   = get_post_meta( $post->ID, '_bw_show_once', true ) ?: '1';
        $auto_start  = get_post_meta( $post->ID, '_bw_auto_start', true ) ?: '1';
        ?>
        <div class="bw-settings-grid">
            <div class="bw-field">
                <label for="bw_trigger_url"><?php _e( 'Trigger URL', 'bw-onboarding-guide' ); ?></label>
                <input type="text" id="bw_trigger_url" name="bw_trigger_url" value="<?php echo esc_attr( $trigger_url ); ?>" placeholder="e.g. / or /forums/ (leave empty for all pages)" class="widefat">
                <p class="description"><?php _e( 'The page URL where this guide starts. Leave empty to trigger on any page. Use relative paths (e.g., <code>/</code> for homepage).', 'bw-onboarding-guide' ); ?></p>
            </div>

            <div class="bw-field-row">
                <div class="bw-field">
                    <label for="bw_show_to"><?php _e( 'Show To', 'bw-onboarding-guide' ); ?></label>
                    <select id="bw_show_to" name="bw_show_to">
                        <option value="logged_in" <?php selected( $show_to, 'logged_in' ); ?>><?php _e( 'Logged-in users only', 'bw-onboarding-guide' ); ?></option>
                        <option value="logged_out" <?php selected( $show_to, 'logged_out' ); ?>><?php _e( 'Logged-out users only', 'bw-onboarding-guide' ); ?></option>
                        <option value="all" <?php selected( $show_to, 'all' ); ?>><?php _e( 'All visitors', 'bw-onboarding-guide' ); ?></option>
                    </select>
                </div>

                <div class="bw-field">
                    <label>
                        <input type="checkbox" name="bw_show_once" value="1" <?php checked( $show_once, '1' ); ?>>
                        <?php _e( 'Show only once per user', 'bw-onboarding-guide' ); ?>
                    </label>
                    <p class="description"><?php _e( 'For logged-in users, uses user meta. For visitors, uses localStorage.', 'bw-onboarding-guide' ); ?></p>
                </div>

                <div class="bw-field">
                    <label>
                        <input type="checkbox" name="bw_auto_start" value="1" <?php checked( $auto_start, '1' ); ?>>
                        <?php _e( 'Auto-start on page load', 'bw-onboarding-guide' ); ?>
                    </label>
                    <p class="description"><?php _e( 'If unchecked, the guide can be triggered manually via shortcode or JS.', 'bw-onboarding-guide' ); ?></p>
                </div>
            </div>

            <div class="bw-field">
                <label><?php _e( 'Shortcode', 'bw-onboarding-guide' ); ?></label>
                <code class="bw-shortcode">[bw_onboarding_guide id="<?php echo $post->ID; ?>"]</code>
                <p class="description"><?php _e( 'Use this shortcode to place a "Start Tour" button on any page. Also available: <code>bwOnboarding.start(guideId)</code> in JavaScript.', 'bw-onboarding-guide' ); ?></p>
            </div>
        </div>
        <?php
    }

    /**
     * Render Tour Steps meta box.
     */
    public function render_steps_meta_box( $post ) {
        $steps = get_post_meta( $post->ID, '_bw_steps', true );
        if ( ! is_array( $steps ) || empty( $steps ) ) {
            $steps = array( $this->get_default_step() );
        }
        ?>
        <div id="bw-steps-container">
            <?php foreach ( $steps as $index => $step ) : ?>
                <?php $this->render_step_row( $index, $step ); ?>
            <?php endforeach; ?>
        </div>

        <div class="bw-steps-footer">
            <button type="button" class="button button-primary" id="bw-add-step">
                <span class="dashicons dashicons-plus-alt2"></span>
                <?php _e( 'Add Step', 'bw-onboarding-guide' ); ?>
            </button>
        </div>

        <!-- Hidden template for new steps -->
        <script type="text/html" id="bw-step-template">
            <?php $this->render_step_row( '__INDEX__', $this->get_default_step() ); ?>
        </script>
        <?php
    }

    /**
     * Render a single step row.
     */
    private function render_step_row( $index, $step ) {
        $step = wp_parse_args( $step, $this->get_default_step() );
        ?>
        <div class="bw-step-row" data-index="<?php echo esc_attr( $index ); ?>">
            <div class="bw-step-header">
                <span class="bw-step-drag dashicons dashicons-menu"></span>
                <span class="bw-step-number"><?php printf( __( 'Step %s', 'bw-onboarding-guide' ), '<span class="bw-step-num">' . ( is_numeric( $index ) ? $index + 1 : '#' ) . '</span>' ); ?></span>
                <span class="bw-step-title-preview"><?php echo esc_html( $step['title'] ?: __( '(untitled)', 'bw-onboarding-guide' ) ); ?></span>
                <span class="bw-step-type-badge"><?php echo $step['target_selector'] ? 'hotspot' : 'modal'; ?></span>
                <button type="button" class="bw-step-toggle" title="<?php _e( 'Expand/Collapse', 'bw-onboarding-guide' ); ?>">
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                </button>
                <button type="button" class="bw-step-delete" title="<?php _e( 'Delete Step', 'bw-onboarding-guide' ); ?>">
                    <span class="dashicons dashicons-trash"></span>
                </button>
            </div>

            <div class="bw-step-body">
                <div class="bw-field-row">
                    <div class="bw-field bw-field-wide">
                        <label><?php _e( 'Step Title', 'bw-onboarding-guide' ); ?></label>
                        <input type="text" name="bw_steps[<?php echo $index; ?>][title]" value="<?php echo esc_attr( $step['title'] ); ?>" placeholder="e.g. Welcome to our site!" class="widefat">
                    </div>
                </div>

                <div class="bw-field">
                    <label><?php _e( 'Content', 'bw-onboarding-guide' ); ?></label>
                    <textarea name="bw_steps[<?php echo $index; ?>][content]" rows="3" placeholder="Describe what this step shows the user..." class="widefat"><?php echo esc_textarea( $step['content'] ); ?></textarea>
                </div>

                <div class="bw-field-row">
                    <div class="bw-field">
                        <label><?php _e( 'CSS Selector', 'bw-onboarding-guide' ); ?></label>
                        <input type="text" name="bw_steps[<?php echo $index; ?>][target_selector]" value="<?php echo esc_attr( $step['target_selector'] ); ?>" placeholder="e.g. .site-header .menu-item-forums" class="widefat bw-mono">
                        <p class="description"><?php _e( 'Leave empty for a centered welcome modal (no highlight).', 'bw-onboarding-guide' ); ?></p>
                    </div>

                    <div class="bw-field">
                        <label><?php _e( 'Tooltip Position', 'bw-onboarding-guide' ); ?></label>
                        <select name="bw_steps[<?php echo $index; ?>][position]">
                            <option value="center" <?php selected( $step['position'], 'center' ); ?>><?php _e( 'Center (modal)', 'bw-onboarding-guide' ); ?></option>
                            <option value="top" <?php selected( $step['position'], 'top' ); ?>><?php _e( 'Top', 'bw-onboarding-guide' ); ?></option>
                            <option value="bottom" <?php selected( $step['position'], 'bottom' ); ?>><?php _e( 'Bottom', 'bw-onboarding-guide' ); ?></option>
                            <option value="left" <?php selected( $step['position'], 'left' ); ?>><?php _e( 'Left', 'bw-onboarding-guide' ); ?></option>
                            <option value="right" <?php selected( $step['position'], 'right' ); ?>><?php _e( 'Right', 'bw-onboarding-guide' ); ?></option>
                        </select>
                    </div>
                </div>

                <div class="bw-field-row">
                    <div class="bw-field">
                        <label><?php _e( 'Page URL (optional)', 'bw-onboarding-guide' ); ?></label>
                        <input type="text" name="bw_steps[<?php echo $index; ?>][url]" value="<?php echo esc_attr( $step['url'] ); ?>" placeholder="e.g. /forums/ (leave empty = stay on current page)" class="widefat bw-mono">
                        <p class="description"><?php _e( 'Navigate to this URL before showing this step. For multi-page tours.', 'bw-onboarding-guide' ); ?></p>
                    </div>

                    <div class="bw-field">
                        <label><?php _e( 'Button Label (optional)', 'bw-onboarding-guide' ); ?></label>
                        <input type="text" name="bw_steps[<?php echo $index; ?>][button_label]" value="<?php echo esc_attr( $step['button_label'] ); ?>" placeholder="Next" class="widefat">
                        <p class="description"><?php _e( 'Custom label for the "Next" button on this step.', 'bw-onboarding-guide' ); ?></p>
                    </div>
                </div>

                <div class="bw-field">
                    <label><?php _e( 'Tip Text (optional)', 'bw-onboarding-guide' ); ?></label>
                    <input type="text" name="bw_steps[<?php echo $index; ?>][tip]" value="<?php echo esc_attr( $step['tip'] ); ?>" placeholder="e.g. Tip: Hover over icons to see labels" class="widefat">
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Default step values.
     */
    private function get_default_step() {
        return array(
            'title'           => '',
            'content'         => '',
            'target_selector' => '',
            'position'        => 'center',
            'url'             => '',
            'button_label'    => '',
            'tip'             => '',
        );
    }

    /**
     * Save meta data.
     */
    public function save_meta( $post_id, $post ) {
        if ( ! isset( $_POST['bw_guide_nonce'] ) || ! wp_verify_nonce( $_POST['bw_guide_nonce'], 'bw_guide_save' ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Guide settings
        update_post_meta( $post_id, '_bw_trigger_url', sanitize_text_field( $_POST['bw_trigger_url'] ?? '' ) );
        update_post_meta( $post_id, '_bw_show_to', sanitize_text_field( $_POST['bw_show_to'] ?? 'logged_in' ) );
        update_post_meta( $post_id, '_bw_show_once', isset( $_POST['bw_show_once'] ) ? '1' : '0' );
        update_post_meta( $post_id, '_bw_auto_start', isset( $_POST['bw_auto_start'] ) ? '1' : '0' );

        // Steps
        $steps = array();
        if ( isset( $_POST['bw_steps'] ) && is_array( $_POST['bw_steps'] ) ) {
            foreach ( $_POST['bw_steps'] as $step ) {
                $steps[] = array(
                    'title'           => sanitize_text_field( $step['title'] ?? '' ),
                    'content'         => wp_kses_post( $step['content'] ?? '' ),
                    'target_selector' => sanitize_text_field( $step['target_selector'] ?? '' ),
                    'position'        => sanitize_text_field( $step['position'] ?? 'center' ),
                    'url'             => sanitize_text_field( $step['url'] ?? '' ),
                    'button_label'    => sanitize_text_field( $step['button_label'] ?? '' ),
                    'tip'             => sanitize_text_field( $step['tip'] ?? '' ),
                );
            }
        }
        update_post_meta( $post_id, '_bw_steps', $steps );
    }

    /**
     * Custom columns for guide list table.
     */
    public function custom_columns( $columns ) {
        $new = array();
        foreach ( $columns as $key => $label ) {
            $new[ $key ] = $label;
            if ( 'title' === $key ) {
                $new['bw_steps_count'] = __( 'Steps', 'bw-onboarding-guide' );
                $new['bw_trigger']     = __( 'Trigger URL', 'bw-onboarding-guide' );
                $new['bw_show_to']     = __( 'Audience', 'bw-onboarding-guide' );
            }
        }
        return $new;
    }

    /**
     * Column content.
     */
    public function column_content( $column, $post_id ) {
        switch ( $column ) {
            case 'bw_steps_count':
                $steps = get_post_meta( $post_id, '_bw_steps', true );
                echo is_array( $steps ) ? count( $steps ) : 0;
                break;
            case 'bw_trigger':
                $url = get_post_meta( $post_id, '_bw_trigger_url', true );
                echo $url ? '<code>' . esc_html( $url ) . '</code>' : '<em>' . __( 'Any page', 'bw-onboarding-guide' ) . '</em>';
                break;
            case 'bw_show_to':
                $show = get_post_meta( $post_id, '_bw_show_to', true );
                $labels = array(
                    'logged_in'  => __( 'Logged-in', 'bw-onboarding-guide' ),
                    'logged_out' => __( 'Logged-out', 'bw-onboarding-guide' ),
                    'all'        => __( 'Everyone', 'bw-onboarding-guide' ),
                );
                echo $labels[ $show ] ?? $show;
                break;
        }
    }
}
