<?php
/**
 * WP Social Buffer Admin Interface
 *
 * @package MKM_DSPB_Bridge
 * @version 2.0.2
 */

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

if ( ! class_exists( 'MKM_DSPB_Admin' ) ) {
    class MKM_DSPB_Admin {

    private $api;

    public function __construct( $api ) {
        $this->api = $api;

        add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
    }

    public function enqueue_admin_assets( $hook ) {
        if ( 'toplevel_page_mkmdigital-social-publisher-bridge' !== $hook ) {
            return;
        }

        wp_enqueue_script(
            'mkm-dspb-admin-settings',
            MKM_DSPB_URL . 'admin/js/admin-settings.js',
            array( 'jquery' ),
            MKM_DSPB_VERSION,
            true
        );
    }

    /**
     * Add settings sub-menu under Settings
     */
    public function add_menu_page() {
        add_menu_page(
            __( 'MKM Digital Social Publisher Bridge to Buffer Settings', 'mkmdigital-social-publisher-bridge' ),
            __( 'WP Social Buffer', 'mkmdigital-social-publisher-bridge' ),
            'manage_options',
            'mkmdigital-social-publisher-bridge',
            array( $this, 'render_settings_page' ),
            'dashicons-share',
            80
        );
    }

    /**
     * Register option fields
     */
    public function register_settings() {
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_token', 'sanitize_text_field' );
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_publish_mode', 'sanitize_text_field' );
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_shortener_provider', 'sanitize_text_field' );
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_template', 'sanitize_textarea_field' );
        
        // Custom arrays sanitization
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_default_channels', array(
            'sanitize_callback' => array( $this, 'sanitize_array_fields' )
        ) );
        register_setting( 'mkm_dspb_settings', 'mkm_dspb_post_types', array(
            'sanitize_callback' => array( $this, 'sanitize_array_fields' )
        ) );
    }

    public function sanitize_array_fields( $input ) {
        if ( ! is_array( $input ) ) {
            return array();
        }
        return array_map( 'sanitize_text_field', $input );
    }

    /**
     * Render settings page template
     */
    public function render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Process Sync Request
        if ( isset( $_POST['mkm_dspb_sync'] ) && check_admin_referer( 'mkm_dspb_sync_action', 'mkm_dspb_sync_nonce' ) ) {
            $token = get_option( 'mkm_dspb_token' );
            if ( ! empty( $token ) ) {
                $channels = $this->api->fetch_channels( $token );
                if ( is_wp_error( $channels ) ) {
                    add_settings_error(
                        'mkm_dspb_settings',
                        'sync_error',
                        /* translators: %s: Error message from Buffer API */
                        sprintf( __( 'Sync Error: %s', 'mkmdigital-social-publisher-bridge' ), $channels->get_error_message() ),
                        'error'
                    );
                } else {
                    update_option( 'mkm_dspb_profiles', $channels );
                    add_settings_error(
                        'mkm_dspb_settings',
                        'sync_success',
                        /* translators: %d: Number of synchronized channels */
                        sprintf( __( 'Successfully synced %d social channels from Buffer.', 'mkmdigital-social-publisher-bridge' ), count( $channels ) ),
                        'updated'
                    );
                }
            } else {
                add_settings_error(
                    'mkm_dspb_settings',
                    'sync_empty_token',
                    __( 'Please save your Buffer Access Token before syncing.', 'mkmdigital-social-publisher-bridge' ),
                    'error'
                );
            }
        }

        // Read options
        $token                  = get_option( 'mkm_dspb_token', '' );
        $publish_mode           = get_option( 'mkm_dspb_publish_mode', 'addToQueue' );
        $shortener_provider     = get_option( 'mkm_dspb_shortener_provider', 'none' );
        $template               = get_option( 'mkm_dspb_template', "{title}\n\n{excerpt}\n\n{link}" );
        $default_channels       = get_option( 'mkm_dspb_default_channels', array() );
        $post_types             = get_option( 'mkm_dspb_post_types', array( 'post' ) );
        $profiles               = get_option( 'mkm_dspb_profiles', array() );

        // Get all public post types
        $all_post_types = get_post_types( array( 'public' => true ), 'objects' );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'MKM Digital Social Publisher Bridge to Buffer Settings', 'mkmdigital-social-publisher-bridge' ); ?></h1>
            <p><?php esc_html_e( 'Directly bridge your WordPress posts and events to your social channels using Buffer.', 'mkmdigital-social-publisher-bridge' ); ?></p>
            
            <?php settings_errors(); ?>

            <div class="metabox-holder" style="display: flex; gap: 20px; flex-wrap: wrap; margin-top: 20px;">
                
                <!-- Main Settings Form -->
                <div style="flex: 2; min-width: 300px;">
                    <div class="postbox" style="padding: 15px;">
                        <h2 class="hndle" style="padding: 0; margin-bottom: 20px; border: none; font-size: 1.3em;">
                            <?php esc_html_e( 'Configuration', 'mkmdigital-social-publisher-bridge' ); ?>
                        </h2>
                        
                        <form method="post" action="options.php">
                            <?php settings_fields( 'mkm_dspb_settings' ); ?>
                            
                            <table class="form-table" role="presentation">
                                <tbody>
                                    <!-- Buffer Token -->
                                    <tr>
                                        <th scope="row"><label for="mkm_dspb_token"><?php esc_html_e( 'Buffer Access Token', 'mkmdigital-social-publisher-bridge' ); ?></label></th>
                                        <td>
                                            <input name="mkm_dspb_token" type="password" id="mkm_dspb_token" value="<?php echo esc_attr( $token ); ?>" class="regular-text" autocomplete="off" />
                                            <p class="description"><?php esc_html_e( 'Generate this token from your Buffer Account (Settings -> API).', 'mkmdigital-social-publisher-bridge' ); ?></p>
                                        </td>
                                    </tr>

                                    <!-- Default Publish Mode -->
                                    <tr>
                                        <th scope="row"><?php esc_html_e( 'Publishing Mode', 'mkmdigital-social-publisher-bridge' ); ?></th>
                                        <td>
                                            <fieldset>
                                                <label>
                                                    <input type="radio" name="mkm_dspb_publish_mode" value="addToQueue" <?php checked( $publish_mode, 'addToQueue' ); ?> />
                                                    <span><strong><?php esc_html_e( 'Add to Queue', 'mkmdigital-social-publisher-bridge' ); ?></strong> (<?php esc_html_e( 'Follows Buffer posting schedule', 'mkmdigital-social-publisher-bridge' ); ?>)</span>
                                                </label><br/><br/>
                                                <label>
                                                    <input type="radio" name="mkm_dspb_publish_mode" value="shareNow" <?php checked( $publish_mode, 'shareNow' ); ?> />
                                                    <span><strong><?php esc_html_e( 'Share Now', 'mkmdigital-social-publisher-bridge' ); ?></strong> (<?php esc_html_e( 'Publishes immediately on social channels', 'mkmdigital-social-publisher-bridge' ); ?>)</span>
                                                </label>
                                            </fieldset>
                                        </td>
                                    </tr>

                                    <!-- Trigger Post Types -->
                                    <tr>
                                        <th scope="row"><?php esc_html_e( 'Auto-Publish Post Types', 'mkmdigital-social-publisher-bridge' ); ?></th>
                                        <td>
                                            <fieldset>
                                                <?php foreach ( $all_post_types as $pt_slug => $pt_obj ) : ?>
                                                    <label>
                                                        <input type="checkbox" name="mkm_dspb_post_types[]" value="<?php echo esc_attr( $pt_slug ); ?>" <?php checked( in_array( $pt_slug, $post_types ) ); ?> />
                                                        <span><?php echo esc_html( $pt_obj->label ); ?> (<code><?php echo esc_html( $pt_slug ); ?></code>)</span>
                                                    </label><br/>
                                                <?php endforeach; ?>
                                                <p class="description"><?php esc_html_e( 'Select which post types should trigger an update when published.', 'mkmdigital-social-publisher-bridge' ); ?></p>
                                            </fieldset>
                                        </td>
                                    </tr>

                                    <!-- Shortener Provider -->
                                    <tr>
                                        <th scope="row"><label for="mkm_dspb_shortener_provider"><?php esc_html_e( 'URL Shortener Provider', 'mkmdigital-social-publisher-bridge' ); ?></label></th>
                                        <td>
                                            <select name="mkm_dspb_shortener_provider" id="mkm_dspb_shortener_provider">
                                                <option value="none" <?php selected( $shortener_provider, 'none' ); ?>><?php esc_html_e( 'Disabled (Use full canonical permalink)', 'mkmdigital-social-publisher-bridge' ); ?></option>
                                                <option value="tinyurl" <?php selected( $shortener_provider, 'tinyurl' ); ?>><?php esc_html_e( 'TinyURL (Free, automatic instant shortening)', 'mkmdigital-social-publisher-bridge' ); ?></option>
                                                <option value="wp_shortlink" <?php selected( $shortener_provider, 'wp_shortlink' ); ?>><?php esc_html_e( 'WordPress Native Shortlink (?p=1234 or active shortlink plugin)', 'mkmdigital-social-publisher-bridge' ); ?></option>
                                            </select>
                                            <p class="description">
                                                <?php esc_html_e( 'Choose how URLs are shortened. Shortening automatically applies to Twitter/X (and whenever {shortlink} is used), while Facebook, Instagram, and LinkedIn use full canonical URLs for brand recognition.', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <span style="color: #0c4a6e; font-weight: 500;">💡 <strong><?php esc_html_e( 'Tip:', 'mkmdigital-social-publisher-bridge' ); ?></strong> <?php esc_html_e( 'You can also enable automatic buff.ly / bit.ly shortening in your Buffer.com account under Settings -> Channels -> Link Shortening.', 'mkmdigital-social-publisher-bridge' ); ?></span>
                                            </p>
                                        </td>
                                    </tr>

                                    <!-- Post Content Template -->
                                    <tr>
                                        <th scope="row"><label for="mkm_dspb_template"><?php esc_html_e( 'Social Post Template', 'mkmdigital-social-publisher-bridge' ); ?></label></th>
                                        <td>
                                            <textarea name="mkm_dspb_template" id="mkm_dspb_template" rows="8" cols="50" class="large-text" style="font-family: monospace;"><?php echo esc_textarea( $template ); ?></textarea>
                                            <p class="description">
                                                <strong><?php esc_html_e( 'Available tags:', 'mkmdigital-social-publisher-bridge' ); ?></strong><br/>
                                                <code>{title}</code> - <?php esc_html_e( 'Post Title', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <code>{excerpt}</code> - <?php esc_html_e( 'Post Excerpt / short description', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <code>{link}</code> - <?php esc_html_e( 'Post Permalink', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <code>{shortlink}</code> - <?php esc_html_e( 'Short URL (TinyURL or WP shortlink)', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <code>{yoast_desc}</code> - <?php esc_html_e( 'Yoast SEO meta description (if installed)', 'mkmdigital-social-publisher-bridge' ); ?><br/>
                                                <code>{aioseo_desc}</code> - <?php esc_html_e( 'All in One SEO description (if installed)', 'mkmdigital-social-publisher-bridge' ); ?>
                                            </p>
                                        </td>
                                    </tr>


                                    <!-- Default Channel Checklist -->
                                    <tr>
                                        <th scope="row"><?php esc_html_e( 'Default Target Channels', 'mkmdigital-social-publisher-bridge' ); ?></th>
                                        <td>
                                            <fieldset>
                                                <?php if ( empty( $profiles ) ) : ?>
                                                    <p class="description" style="color: #d63638;"><?php esc_html_e( 'No social channels found. Please save token and click "Sync Channels" on the right panel.', 'mkmdigital-social-publisher-bridge' ); ?></p>
                                                <?php else : ?>
                                                    <?php foreach ( $profiles as $key => $profile ) : ?>
                                                        <label>
                                                            <input type="checkbox" name="mkm_dspb_default_channels[]" class="mkm-dspb-default-channel-cb" value="<?php echo esc_attr( $key ); ?>" <?php checked( in_array( $key, $default_channels ) ); ?> />
                                                            <strong><?php echo esc_html( ucfirst( $profile['service'] ) ); ?></strong>: <?php echo esc_html( $profile['name'] ); ?>
                                                        </label><br/>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </fieldset>
                                        </td>
                                    </tr>

                                </tbody>
                            </table>
                            <?php submit_button( __( 'Save Settings', 'mkmdigital-social-publisher-bridge' ) ); ?>
                        </form>
                    </div>
                </div>

                <!-- Side Panel for Synchronization -->
                <div style="flex: 1; min-width: 250px;">
                    <div class="postbox" style="padding: 15px;">
                        <h2 class="hndle" style="padding: 0; margin-bottom: 20px; border: none; font-size: 1.3em;">
                            <?php esc_html_e( 'Sync Channels', 'mkmdigital-social-publisher-bridge' ); ?>
                        </h2>
                        <p><?php esc_html_e( 'Use this panel to pull the latest channels configured in your Buffer account.', 'mkmdigital-social-publisher-bridge' ); ?></p>
                        
                        <form method="post" action="">
                            <?php wp_nonce_field( 'mkm_dspb_sync_action', 'mkm_dspb_sync_nonce' ); ?>
                            <input type="submit" name="mkm_dspb_sync" class="button button-secondary" value="<?php esc_attr_e( 'Sync Buffer Channels', 'mkmdigital-social-publisher-bridge' ); ?>" />
                        </form>

                        <?php if ( ! empty( $profiles ) ) : ?>
                            <h3 style="margin-top: 25px; margin-bottom: 10px; font-size: 1em; font-weight: 600; border-bottom: 1px solid #eee; padding-bottom: 5px;">
                                <?php esc_html_e( 'Currently Synced Channels:', 'mkmdigital-social-publisher-bridge' ); ?>
                            </h3>
                            <ul style="margin: 0; padding-left: 15px; list-style-type: disc;">
                                <?php foreach ( $profiles as $profile ) : ?>
                                    <li>
                                        <strong><?php echo esc_html( ucfirst( $profile['service'] ) ); ?></strong>: <?php echo esc_html( $profile['name'] ); ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>
        <?php
    }
    }
}
