<?php


class SAVEAMSU_Bookmarks {

    public static function init() {
        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
        add_action( 'wp_ajax_saveamsu_toggle_bookmark', array( __CLASS__, 'ajax_toggle_bookmark' ) );
        add_action( 'wp_ajax_nopriv_saveamsu_toggle_bookmark', array( __CLASS__, 'ajax_login_required' ) );
    }

    /**
     * Get the bookmarks table name with a legacy fallback.
     */
    private static function get_table_name() {
        global $wpdb;

        $table_name      = $wpdb->prefix . 'saveamsu_bookmarks';
        $legacy_table    = $wpdb->prefix . 'ss_bookmarks';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $table_exists    = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $legacy_exists   = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $legacy_table ) );

        if ( $table_exists === $table_name ) {
            return $table_name;
        }

        return ( $legacy_exists === $legacy_table ) ? $legacy_table : $table_name;
    }

    /**
     * Load CSS + JS only on single posts + pages
     */
    public static function enqueue_assets() {

        if ( ! is_singular( array( 'post', 'page' ) ) ) {
            return;
        }

        wp_enqueue_style(
            'saveamsu-style',
            SAVEAMSU_PLUGIN_URL . 'assets/css/ss-style.css',
            array(),
            SAVEAMSU_PLUGIN_VERSION
        );

        wp_enqueue_script(
            'saveamsu-bookmark',
            SAVEAMSU_PLUGIN_URL . 'assets/js/ss-bookmark.js',
            array( 'jquery' ),
            SAVEAMSU_PLUGIN_VERSION,
            true
        );

        wp_localize_script(
            'saveamsu-bookmark',
            'saveamsuBookmark',
            array(
                'ajax_url'     => admin_url( 'admin-ajax.php' ),
                'nonce'        => wp_create_nonce( 'saveamsu_bookmark_nonce' ),
                'is_logged_in' => is_user_logged_in(),
            )
        );
    }

    /**
     * Error for non-logged-in users
     */
    public static function ajax_login_required() {
        wp_send_json_error(
            array(
                'message' => __( 'Please log in to save items.', 'save-summarize-ai-digest-for-saved-articles' ),
            ),
            401
        );
    }

    /**
     * AJAX: Toggle Save/Unsave
     */
    public static function ajax_toggle_bookmark() {

        check_ajax_referer( 'saveamsu_bookmark_nonce', 'nonce' );

        if ( ! is_user_logged_in() ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Please log in to save items.', 'save-summarize-ai-digest-for-saved-articles' ),
                ),
                401
            );
        }

        $user_id = get_current_user_id();
        $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;

        if ( ! $post_id || get_post_status( $post_id ) !== 'publish' ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Invalid post.', 'save-summarize-ai-digest-for-saved-articles' ),
                )
            );
        }

        // Allow both posts & pages (and any public post type)
        $type = get_post_type( $post_id );
        if ( ! in_array( $type, array( 'post', 'page' ), true ) ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Saving not supported for this content type.', 'save-summarize-ai-digest-for-saved-articles' ),
                )
            );
        }

        $bookmarked = self::is_bookmarked( $user_id, $post_id );

        if ( $bookmarked ) {
            self::remove( $user_id, $post_id );
            wp_send_json_success(
                array(
                    'status'  => 'removed',
                    'message' => __( 'Removed from saved items.', 'save-summarize-ai-digest-for-saved-articles' ),
                )
            );
        } else {
            self::add( $user_id, $post_id );
            wp_send_json_success(
                array(
                    'status'  => 'added',
                    'message' => __( 'Saved for later.', 'save-summarize-ai-digest-for-saved-articles' ),
                )
            );
        }
    }

    /**
     * Add a bookmark for a user
     */
    public static function add( $user_id, $post_id ) {
        global $wpdb;
        $table = self::get_table_name();

       // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->replace(
            $table,
            array(
                'user_id'    => $user_id,
                'post_id'    => $post_id,
                'created_at' => current_time( 'mysql' ),
            ), 
           
            array( '%d', '%d', '%s' )
        );

    }

    /**
     * Remove bookmark
     */
    public static function remove( $user_id, $post_id ) {
        global $wpdb;
        $table = self::get_table_name();

         // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete(
            $table,
            array(
                'user_id' => $user_id,
                'post_id' => $post_id,
            ),
            array( '%d', '%d' )
        );
    }

    /**
     * Check if saved
     */
    public static function is_bookmarked( $user_id, $post_id ) {
        global $wpdb;
        $table = self::get_table_name();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var(
            $wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND post_id = %d",
                $user_id,
                $post_id
            )
        );

        return ( $count > 0 );
    }

    /**
     * Get all bookmarks for user
     */
    public static function get_user_bookmarks( $user_id ) {
        global $wpdb;
        $table = self::get_table_name();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.DirectDatabaseQuery.NoCaching
        return $wpdb->get_col(
            $wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT post_id FROM {$table} WHERE user_id = %d ORDER BY created_at DESC",
                $user_id
            )
        );
    }
}
