<?php
/**
 * SocialPilot MetaBox Handler
 *
 * @package SocialPilot
 * @subpackage MetaBox
 * @since 1.0.0
 */

/**
 * Class to handle post meta box functionality
 */
class SocialPilot_MetaBox {

    /**
     * Instance of this class
     *
     * @since 1.0.0
     * @var object
     */
    private static $instance = null;

    /**
     * Get singleton instance
     *
     * @since 1.0.0
     * @return SocialPilot_MetaBox
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     *
     * @since 1.0.0
     */
    private function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    }

    /**
     * Add meta box to supported post types
     *
     * @since 1.0.0
     * @return void
     */
    public function add_meta_box() {
        $options = get_option( 'socialpilot_options', array() );
        $enabled_post_types = isset( $options['enabled_post_types'] ) ? 
            $options['enabled_post_types'] : array( 'post' );

        foreach ( $enabled_post_types as $post_type ) {
            add_meta_box(
                'socialpilot_meta_box',
                __( 'SocialPilot', 'socialpilot-wp' ),
                array( $this, 'render_meta_box' ),
                $post_type,
                'normal',
                'high'
            );
        }
    }

    /**
     * Render meta box content
     *
     * @since 1.0.0
     * @param WP_Post $post Current post object.
     * @return void
     */
    public function render_meta_box($post) {
        wp_nonce_field('socialpilot_meta_box', 'socialpilot_meta_box_nonce');
    
        // Get default values from post
        $post_title = get_the_title($post->ID);
        $post_excerpt = has_excerpt($post->ID) ? get_the_excerpt($post->ID) : wp_trim_words($post->post_content, 55);
        $featured_image_id = get_post_thumbnail_id($post->ID);
        $featured_image_url = $featured_image_id ? wp_get_attachment_image_url($featured_image_id, 'full') : '';
        ?>
        <div class="socialpilot-metabox">
            <!-- Left Column -->
            <div class="socialpilot-left-column">
                <!-- Post Type Selection -->
                <div class="socialpilot-field">
                    <label><?php esc_html_e('Post Type', 'socialpilot-wp'); ?></label>
                    <div class="post-type-radio">
                        <label>
                            <input type="radio" name="socialpilot_post_type" value="text" checked>
                            <?php esc_html_e('Text Post', 'socialpilot-wp'); ?>
                        </label>
                        <label>
                            <input type="radio" name="socialpilot_post_type" value="image">
                            <?php esc_html_e('Image Post', 'socialpilot-wp'); ?>
                        </label>
                        <label>
                            <input type="radio" name="socialpilot_post_type" value="article">
                            <?php esc_html_e('Article Post', 'socialpilot-wp'); ?>
                        </label>
                    </div>
                </div>
    
                <!-- Caption Field -->
                <div class="socialpilot-field border-bottom mb-0">
                    <label for="socialpilot_caption">
                        <?php esc_html_e('Post Caption', 'socialpilot-wp'); ?>
                    </label>
                    <textarea id="socialpilot_caption" name="socialpilot_caption" rows="7"></textarea>
                    <button type="button" class="button button-secondary" id="generate_caption">
                        <?php esc_html_e('Generate Caption', 'socialpilot-wp'); ?>
                    </button>
                </div>
    
               
    
                <!-- Image Post Fields -->
                <div id="image_post_fields" class="post-type-fields" style="display: none;">
                    <div class="socialpilot-field">
                        <label><?php esc_html_e('Upload Images', 'socialpilot-wp'); ?></label>
                        <div id="socialpilot_media_preview" class="media-preview-grid"></div>
                        <button type="button" class="button button-secondary" id="add_media">
                            <span class="dashicons dashicons-plus"></span> 
                            <?php esc_html_e('Add Media', 'socialpilot-wp'); ?>
                        </button>
                    </div>
                </div>
    
                <!-- Article Post Fields -->
                <div id="article_post_fields" class="post-type-fields" style="display: none;">
                    <div class="socialpilot-field">
                        <label for="article_title">
                            <?php esc_html_e('Article Title', 'socialpilot-wp'); ?>
                        </label>
                        <input type="text" 
                               id="article_title" 
                               name="article_title" 
                               value="<?php echo esc_attr($post_title); ?>" 
                               placeholder="<?php esc_attr_e('Default: Post Title', 'socialpilot-wp'); ?>">
                    </div>
    
                    <div class="socialpilot-field">
                        <label for="article_description">
                            <?php esc_html_e('Short Description', 'socialpilot-wp'); ?>
                        </label>
                        <textarea id="article_description" 
                                  name="article_description" 
                                  rows="7"
                                  placeholder="<?php esc_attr_e('Default: Post Excerpt', 'socialpilot-wp'); ?>"><?php echo esc_textarea($post_excerpt); ?></textarea>
                    </div>
    
                    <div class="socialpilot-field">
                        <label><?php esc_html_e('Featured Image', 'socialpilot-wp'); ?></label>
                        <div id="article_thumbnail_preview" class="thumbnail-preview">
                            <?php if ($featured_image_url) : ?>
                                <div class="thumbnail-container">
                                    <img src="<?php echo esc_url($featured_image_url); ?>" 
                                         alt="<?php esc_attr_e('Article thumbnail', 'socialpilot-wp'); ?>">
                                    <button type="button" class="remove-thumbnail">×</button>
                                </div>
                            <?php endif; ?>
                        </div>
                        <input type="hidden" 
                               id="article_thumbnail_id" 
                               name="article_thumbnail_id" 
                               value="<?php echo esc_attr($featured_image_id); ?>">
                        <button type="button" class="button button-secondary" id="add_thumbnail">
                            <span class="dashicons dashicons-format-image"></span> 
                            <?php esc_html_e('Select Thumbnail', 'socialpilot-wp'); ?>
                        </button>
                    </div>
                </div>
     <!-- Schedule Time -->
    
                <!-- Schedule Post Button -->
                 
                <div class="schedule-post-container">
                     <div class="socialpilot-field">
                    <label for="socialpilot_schedule_time">
                        <?php esc_html_e('Schedule Time', 'socialpilot-wp'); ?>
                    </label>
                    <input type="datetime-local" 
                           id="socialpilot_schedule_time" 
                           name="socialpilot_schedule_time">
                </div>
                    <button type="button" class="button button-primary" id="schedule_post">
                        <?php esc_html_e('Schedule Post', 'socialpilot-wp'); ?>
                    </button>
                </div>
                 <!-- Messages - Spans both columns -->
            <div id="socialpilot_messages"></div>
            </div>
    
            <!-- Right Column - Account Selection -->
            <div class="socialpilot-right-column">
                <div class="socialpilot-field">
                    <label class="right-bar-label"><?php esc_html_e('Social Media Accounts', 'socialpilot-wp'); ?></label>
                    <div id="socialpilot_accounts" class="accounts-list">
                        <p class="loading-accounts">
                            <?php esc_html_e('Loading accounts...', 'socialpilot-wp'); ?>
                        </p>
                    </div>
                </div>
            </div>
    
           
        </div>
        <?php
    }

    /**
     * Enqueue required assets
     *
     * @since 1.0.0
     * @param string $hook Current admin page.
     * @return void
     */
    public function enqueue_assets( $hook ) {
        if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
            return;
        }

        // Enqueue WordPress media scripts
        wp_enqueue_media();

        // Enqueue our styles
        wp_enqueue_style(
            'socialpilot-meta-box',
            SOCIALPILOT_PLUGIN_URL . 'assets/css/meta-box.css',
            array(),
            SOCIALPILOT_VERSION
        );

        // Enqueue our scripts
        wp_enqueue_script(
            'socialpilot-meta-box',
            SOCIALPILOT_PLUGIN_URL . 'assets/js/meta-box.js',
            array( 'jquery', 'wp-util', 'media-upload' ),
            SOCIALPILOT_VERSION,
            true
        );

        // Get post data for JavaScript
        $post_id = get_the_ID();
        $post_url = '';

        if ( $post_id ) {
            $post = get_post( $post_id );
            if ( $post ) {
                $post_url = 'publish' === $post->post_status ? 
                    get_permalink( $post_id ) : get_preview_post_link( $post );
            }
        }

        // Localize script
        wp_localize_script(
            'socialpilot-meta-box',
            'socialpilotData',
            array(
                'ajaxurl'   => admin_url( 'admin-ajax.php' ),
                'nonce'     => wp_create_nonce( 'socialpilot_nonce' ),
                'postUrl'   => $post_url,
                'strings'   => array(
                    'generateCaption' => __( 'Generate Caption', 'socialpilot-wp' ),
                    'generating'      => __( 'Generating...', 'socialpilot-wp' ),
                    'schedulePost'    => __( 'Schedule Post', 'socialpilot-wp' ),
                    'scheduling'      => __( 'Scheduling...', 'socialpilot-wp' ),
                ),
            )
        );
    }
}