<?php

class SAVEAMSU_Metabox {

    public static function init() {
        add_action( 'add_meta_boxes', [ __CLASS__, 'add_metabox' ] );
        add_action( 'save_post', [ __CLASS__, 'save' ] );
    }

    /**
     * Retrieve the saved items page ID with legacy fallback.
     */
    private static function get_saved_page_id() {
        $saved_page_id = get_option( 'saveamsu_saved_page_id', null );

        if ( null === $saved_page_id ) {
            $legacy_saved_page_id = get_option( 'ss_saved_page_id', null );
            if ( null !== $legacy_saved_page_id ) {
                update_option( 'saveamsu_saved_page_id', $legacy_saved_page_id );
                $saved_page_id = $legacy_saved_page_id;
            }
        }

        return $saved_page_id;
    }

    /**
     * Get the enable meta value, migrating the legacy key if needed.
     */
    public static function get_enable_meta( $post_id ) {
        $enabled = get_post_meta( $post_id, '_saveamsu_enable_save', true );

        if ( '' === $enabled ) {
            $enabled = get_post_meta( $post_id, '_ss_enable_save', true );
            if ( '' !== $enabled ) {
                update_post_meta( $post_id, '_saveamsu_enable_save', $enabled );
                delete_post_meta( $post_id, '_ss_enable_save' );
            }
        }

        return $enabled;
    }

    /**
     * Add the Enable checkbox to Posts + Pages
     */
    public static function add_metabox() {

        $saved_page_id = self::get_saved_page_id();

        add_meta_box(
            'saveamsu_enable_save',
            'Save & Summarize',
            [ __CLASS__, 'render_metabox' ],
            ['post', 'page'], 
            'side',
            'high'
        );

        // Remove box for the Saved Items page
        if ( $saved_page_id ) {
            remove_meta_box( 'saveamsu_enable_save', 'page', 'side' );
        }
    }

    /**
     * Render the checkbox
     */
    public static function render_metabox( $post ) {

        // Security nonce
        wp_nonce_field( 'saveamsu_enable_save_action', 'saveamsu_enable_save_nonce' );

        $enabled = self::get_enable_meta( $post->ID );
        ?>

        <label style="font-weight:600;display:block;margin-bottom:8px;">
            <input type="checkbox"
                   name="saveamsu_enable_save"
                   value="1"
                   <?php checked( $enabled, '1' ); ?> />
            <?php esc_html_e( 'Allow users to save this page', 'save-summarize-ai-digest-for-saved-articles' ); ?>
        </label>

        <?php
    }

    /**
     * Save checkbox value
     */
    public static function save( $post_id ) {

        $saved_page_id = self::get_saved_page_id();

        // Skip autosave
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
      
        if ($post_id == $saved_page_id) {
            return; // Do not save meta for this page
        }

        // Validate nonce
        if (
            ! isset( $_POST['saveamsu_enable_save_nonce'] ) ||
            ! wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_POST['saveamsu_enable_save_nonce'] ) ),
                'saveamsu_enable_save_action'
            )
        ) {
            return;
        }

        // Permission check
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Save or remove meta
        if ( isset( $_POST['saveamsu_enable_save'] ) ) {
            update_post_meta( $post_id, '_saveamsu_enable_save', '1' );
            delete_post_meta( $post_id, '_ss_enable_save' );
        } else {
            delete_post_meta( $post_id, '_saveamsu_enable_save' );
            delete_post_meta( $post_id, '_ss_enable_save' );
        }
    }
}
