<?php
/**
 * Metabox for classic editor
 */

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

class BW_Expiry_Metabox {

    private static $instance = null;
    private $meta_key = '_bw_expiry_date';

    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_box' ) );
        add_action( 'save_post', array( $this, 'save_meta_box' ), 10, 2 );

        // Add to publish box for classic editor
        add_action( 'post_submitbox_misc_actions', array( $this, 'add_to_publish_box' ) );

        // Remove metabox from block editor (we use Gutenberg panel instead)
        add_action( 'enqueue_block_editor_assets', array( $this, 'remove_metabox_for_gutenberg' ) );
    }

    /**
     * Add meta box (for classic editor)
     */
    public function add_meta_box() {
        $options = get_option( 'bw_expiry_settings', array() );
        $enabled_types = isset( $options['post_types'] ) ? $options['post_types'] : array( 'post' );

        foreach ( $enabled_types as $post_type ) {
            // Check if this post type uses block editor
            if ( $this->post_type_uses_block_editor( $post_type ) ) {
                continue; // Skip - Gutenberg panel will handle this
            }

            add_meta_box(
                'bw_expiry_metabox',
                __( 'Post Expiry', 'bw-expiry-post' ),
                array( $this, 'render_meta_box' ),
                $post_type,
                'side',
                'high'
            );
        }
    }

    /**
     * Remove metabox when in Gutenberg
     */
    public function remove_metabox_for_gutenberg() {
        $options = get_option( 'bw_expiry_settings', array() );
        $enabled_types = isset( $options['post_types'] ) ? $options['post_types'] : array( 'post' );

        foreach ( $enabled_types as $post_type ) {
            remove_meta_box( 'bw_expiry_metabox', $post_type, 'side' );
        }
    }

    /**
     * Check if a post type uses the block editor
     */
    private function post_type_uses_block_editor( $post_type ) {
        if ( function_exists( 'use_block_editor_for_post_type' ) ) {
            return use_block_editor_for_post_type( $post_type );
        }
        return false;
    }

    /**
     * Render meta box content
     */
    public function render_meta_box( $post ) {
        wp_nonce_field( 'bw_expiry_save', 'bw_expiry_nonce' );

        $expiry_date = get_post_meta( $post->ID, $this->meta_key, true );

        // Determine if "never expires" is set (no date = never expires)
        $never_expires = empty( $expiry_date );

        // Format date for datetime-local input
        $formatted_date = '';
        if ( ! empty( $expiry_date ) ) {
            $timestamp = strtotime( $expiry_date );
            if ( $timestamp ) {
                $formatted_date = date( 'Y-m-d\TH:i', $timestamp );
            }
        }
        ?>
        <div class="bw-expiry-metabox-content">
            <div class="bw-expiry-toggle-wrap">
                <label class="bw-expiry-never-toggle">
                    <input
                        type="checkbox"
                        id="bw_expiry_never"
                        name="bw_expiry_never"
                        value="1"
                        <?php checked( $never_expires ); ?>
                    >
                    <strong><?php esc_html_e( 'Never expires', 'bw-expiry-post' ); ?></strong>
                </label>
                <p id="bw-expiry-never-status" class="bw-expiry-status-note <?php echo $never_expires ? '' : 'hidden'; ?>">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php esc_html_e( 'This post will remain published indefinitely.', 'bw-expiry-post' ); ?>
                </p>
            </div>

            <div id="bw-expiry-date-wrap" class="<?php echo $never_expires ? 'hidden' : ''; ?>">
                <p>
                    <label for="bw_expiry_date">
                        <strong><?php esc_html_e( 'Expiry Date & Time:', 'bw-expiry-post' ); ?></strong>
                    </label>
                </p>
                <p>
                    <input
                        type="datetime-local"
                        id="bw_expiry_date"
                        name="bw_expiry_date"
                        value="<?php echo esc_attr( $formatted_date ); ?>"
                        class="widefat"
                    >
                </p>
                <p class="description">
                    <?php esc_html_e( 'Post will be set to Draft when this date is reached.', 'bw-expiry-post' ); ?>
                </p>
            </div>

            <?php
            // Show status if post has been expired
            $was_expired = get_post_meta( $post->ID, '_bw_expired', true );
            if ( $was_expired ) :
            ?>
                <p class="bw-expiry-status expired">
                    <span class="dashicons dashicons-warning"></span>
                    <?php esc_html_e( 'This post was automatically unpublished due to expiry.', 'bw-expiry-post' ); ?>
                </p>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Add expiry field to publish box (classic editor)
     */
    public function add_to_publish_box( $post ) {
        // Check if this post type is enabled
        $plugin = BW_Expiry_Post::get_instance();
        if ( ! $plugin->is_post_type_enabled( $post->post_type ) ) {
            return;
        }

        $expiry_date = get_post_meta( $post->ID, $this->meta_key, true );

        // Format for display
        $display_date = '';
        if ( ! empty( $expiry_date ) ) {
            $timestamp = strtotime( $expiry_date );
            if ( $timestamp ) {
                $display_date = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp );
            }
        }
        ?>
        <div class="misc-pub-section bw-expiry-publish-section">
            <span class="dashicons dashicons-calendar-alt"></span>
            <?php esc_html_e( 'Expires:', 'bw-expiry-post' ); ?>
            <strong>
                <span id="bw-expiry-display">
                    <?php echo ! empty( $display_date ) ? esc_html( $display_date ) : esc_html__( 'Never', 'bw-expiry-post' ); ?>
                </span>
            </strong>
            <a href="#bw_expiry_metabox" class="edit-expiry hide-if-no-js">
                <span aria-hidden="true"><?php esc_html_e( 'Edit', 'bw-expiry-post' ); ?></span>
            </a>
        </div>
        <?php
    }

    /**
     * Save meta box data
     */
    public function save_meta_box( $post_id, $post ) {
        // Check nonce
        if ( ! isset( $_POST['bw_expiry_nonce'] ) || ! wp_verify_nonce( $_POST['bw_expiry_nonce'], 'bw_expiry_save' ) ) {
            return;
        }

        // Check autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Check if post type is enabled
        $plugin = BW_Expiry_Post::get_instance();
        if ( ! $plugin->is_post_type_enabled( $post->post_type ) ) {
            return;
        }

        // Check if "never expires" is checked
        $never_expires = isset( $_POST['bw_expiry_never'] ) && $_POST['bw_expiry_never'] === '1';

        if ( $never_expires ) {
            // Remove expiry date
            delete_post_meta( $post_id, $this->meta_key );
            delete_post_meta( $post_id, '_bw_expired' );
        } elseif ( isset( $_POST['bw_expiry_date'] ) && ! empty( $_POST['bw_expiry_date'] ) ) {
            // Save expiry date
            $expiry_date = sanitize_text_field( $_POST['bw_expiry_date'] );

            // Convert from datetime-local format to MySQL datetime
            $timestamp = strtotime( $expiry_date );
            if ( $timestamp ) {
                $mysql_date = date( 'Y-m-d H:i:s', $timestamp );
                update_post_meta( $post_id, $this->meta_key, $mysql_date );

                // Clear the expired flag if republishing
                delete_post_meta( $post_id, '_bw_expired' );
            }
        }
    }
}
