<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
function freshenup_awaiting_moderation_count() {
    global $wpdb;
    freshenup_cleanup_orphaned_flags();
    // Get count of pending AI revisions
    // No user-supplied variables in this query; table names are from $wpdb.
    $pending_count = $wpdb->get_var( 
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->prepare( "SELECT COUNT(DISTINCT r.post_parent) \r\n             FROM {$wpdb->posts} r \r\n             JOIN {$wpdb->postmeta} pm ON r.post_parent = pm.post_id \r\n                AND pm.meta_key = %s\r\n             WHERE r.post_type = %s", 'freshenup_awaiting_moderation', 'revision' )
     );
    return $pending_count;
}

function freshenup_admin_menu() {
    $pending_count = freshenup_awaiting_moderation_count();
    wp_cache_set( 'freshenup_pending_count', $pending_count );
    // Main menu with count
    $menu_title = esc_html__( 'Freshenup', 'freshenup' );
    if ( $pending_count > 0 ) {
        $menu_title .= sprintf( ' <span class="update-plugins count-%d"><span class="plugin-count">%d</span></span>', $pending_count, $pending_count );
    }
    // Main menu page
    add_menu_page(
        esc_html__( 'Freshenup dashboard', 'freshenup' ),
        // Page title
        $menu_title,
        // Menu title
        'manage_options',
        // Capability
        'freshenup',
        // Menu slug
        'freshenup_settings_page',
        // Function to display the dashboard page
        'data:image/svg+xml;base64,' . base64_encode( freshenup_sanitize_svg( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#a7aaad"><path d="M20.4 3.6C18.3 1.35 15.3 0 12 0 5.4 0 0 5.4 0 12s5.4 12 12 12c5.55 0 10.2-3.9 11.55-9h-3.15c-1.2 3.45-4.5 6-8.4 6-4.95 0-9-4.05-9-9s4.05-9 9-9c2.55 0 4.65 1.05 6.3 2.7L13.5 10.5h10.5V0l-3.6 3.6Z"/></svg>' ) )
    );
    // Additional submenu page for settings that matches the main menu
    add_submenu_page(
        'freshenup',
        // Parent slug, matching the main menu slug
        esc_html__( 'Freshenup Settings', 'freshenup' ),
        // Page title
        esc_html__( 'Settings', 'freshenup' ),
        // Menu title
        'manage_options',
        // Capability
        'freshenup',
        // Menu slug, same as main menu to actually link to the main menu item
        'freshenup_settings_page'
    );
    // Additional submenu page for prompt
    $prompt_page_title = esc_html__( 'Freshenup Prompt', 'freshenup' );
    $prompt_menu_title = esc_html__( 'Prompt', 'freshenup' );
    add_submenu_page(
        'freshenup',
        $prompt_page_title,
        $prompt_menu_title,
        'manage_options',
        'freshenup_prompt',
        'freshenup_prompt_page'
    );
    // AI Review submenu with count
    $review_title = esc_html__( 'Awaiting approval', 'freshenup' );
    if ( $pending_count > 0 ) {
        $review_title .= sprintf( ' <span class="update-plugins count-%d"><span class="plugin-count">%d</span></span>', $pending_count, $pending_count );
    }
    add_submenu_page(
        'freshenup',
        esc_html__( 'Awaiting approval', 'freshenup' ),
        $review_title,
        'manage_options',
        'freshenup_review',
        'freshenup_review_page'
    );
    // Approved submenu page
    add_submenu_page(
        'freshenup',
        // Parent slug, matching the main menu slug
        esc_html__( 'Freshenup Latest Approved Posts', 'freshenup' ),
        // Page title
        esc_html__( 'Approved', 'freshenup' ),
        // Menu title
        'manage_options',
        // Capability
        'freshenup_approved',
        // Menu slug
        'freshenup_approved_page'
    );
}

function freshenup_print_update_notice_if_needed() {
    if ( !current_user_can( 'update_plugins' ) ) {
        return;
    }
    $plugin_slug = 'freshenup-pro/freshenup.php';
    // Adjust path if necessary
    $update_plugins = get_site_transient( 'update_plugins' );
    if ( isset( $update_plugins->response[$plugin_slug] ) ) {
        $update_url = self_admin_url( 'update.php?action=upgrade-plugin&plugin=' . urlencode( $plugin_slug ) );
        $nonce = wp_nonce_url( $update_url, 'upgrade-plugin_' . $plugin_slug );
        echo '<div style="background: #fff3cd; border-left: 4px solid #ffeeba; padding: 12px; margin: 20px auto">';
        echo '<strong>' . esc_html__( 'FreshenUp:', 'freshenup' ) . '</strong> ' . esc_html__( 'A new version is available.', 'freshenup' ) . ' <a href="' . esc_url( $nonce ) . '">' . esc_html__( 'Click here to update', 'freshenup' ) . '</a>.';
        echo '</div>';
    }
}

function freshenup_send_feedback_to_server(
    $post_id,
    $revision_id,
    $feedback,
    $comment,
    $action_clicked
) {
    if ( !empty( $post_id ) ) {
        $api_key = freshenup_get_api_key();
        $plugin_version = ( defined( 'FRESHENUP_VERSION' ) ? FRESHENUP_VERSION : '' );
        // Prepare the data, ensuring all values are set
        $data = [
            'call'              => 'freshenup_feedback',
            'post_id'           => $post_id,
            'revision_id'       => $revision_id,
            'feedback'          => $feedback,
            'comment'           => $comment,
            'action_clicked'    => $action_clicked,
            'license_id'        => '',
            'install_id'        => '',
            'site_private_key'  => '',
            'url'               => '',
            'wp_url'            => get_site_url(),
            'trialtf'           => false,
            'plugin_version'    => $plugin_version,
            'encrypted_api_key' => ( $api_key ? freshenup_encrypt_for_transit( $api_key ) : '' ),
        ];
        // Safely get Freemius data
        if ( function_exists( 'freshenup_fs' ) ) {
            $fs = freshenup_fs();
            if ( $fs ) {
                $license = $fs->_get_license();
                $site = $fs->get_site();
                if ( $license ) {
                    $data['license_id'] = $license->id;
                }
                if ( $site ) {
                    $data['install_id'] = $site->id;
                    $data['site_private_key'] = $site->secret_key;
                    $data['url'] = $site->url;
                }
            }
        }
        if ( freshenup_fs()->is_trial() ) {
            $data['trialtf'] = true;
        }
        // API url
        $api_url = 'https://freshenup.io/api_connect.php';
        // Make the API call
        $response = wp_remote_post( $api_url, array(
            'method'      => 'POST',
            'timeout'     => 5,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking'    => false,
            'headers'     => array(
                'Content-Type'         => 'application/json',
                'X-Freshenup-Site-Key' => freshenup_get_or_generate_site_key(),
            ),
            'body'        => wp_json_encode( $data ),
            'cookies'     => array(),
        ) );
    }
}

add_action( 'admin_post_freshenup_process_feedback', 'freshenup_handle_feedback' );
function freshenup_handle_feedback() {
    if ( !isset( $_POST['post_id'], $_POST['revision_id'], $_POST['_wpnonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'freshenup_feedback_' . intval( $_POST['revision_id'] ) ) ) {
        wp_die( esc_html__( 'Invalid request', 'freshenup' ) );
    }
    $post_id = intval( $_POST['post_id'] );
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        wp_die( esc_html__( 'You do not have permission to moderate this post.', 'freshenup' ) );
    }
    $revision_id = intval( $_POST['revision_id'] );
    $update_published_date = ( isset( $_POST['update_published_date'] ) ? intval( $_POST['update_published_date'] ) : 0 );
    $feedback = ( isset( $_POST['feedback'] ) ? sanitize_text_field( wp_unslash( $_POST['feedback'] ) ) : '' );
    $comment = ( isset( $_POST['comment'] ) ? wp_kses_post( wp_unslash( $_POST['comment'] ) ) : '' );
    $action_clicked = ( isset( $_POST['action_clicked'] ) ? sanitize_text_field( wp_unslash( $_POST['action_clicked'] ) ) : 'unknown' );
    // Save shared feedback
    freshenup_send_feedback_to_server(
        $post_id,
        $revision_id,
        $feedback,
        $comment,
        $action_clicked
    );
    // Route by button
    if ( $action_clicked === 'approve' ) {
        do_action( "freshenup_feedback_approve", [
            'post_id'               => $post_id,
            'revision_id'           => $revision_id,
            'update_published_date' => $update_published_date,
        ] );
    } elseif ( $action_clicked === 'reject' ) {
        // Handle rejection logic
        do_action( "freshenup_feedback_reject", [
            'post_id'     => $post_id,
            'revision_id' => $revision_id,
        ] );
    } elseif ( $action_clicked === 'edit' ) {
        // Redirect to post editor
        $edit_url = admin_url( "post.php?action=edit&post={$post_id}&revision_id={$revision_id}" );
        wp_safe_redirect( esc_url_raw( $edit_url ) );
    } else {
        wp_safe_redirect( admin_url( 'admin.php?page=freshenup_review' ) );
    }
    exit;
}

add_action( 'freshenup_feedback_approve', 'freshenup_handle_approve_revision' );
add_action( 'freshenup_feedback_reject', 'freshenup_handle_reject_revision' );
function freshenup_cleanup_orphaned_flags() {
    global $wpdb;
    // Find all posts with the meta flag
    $posts_with_meta = $wpdb->get_col( 
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->prepare( "SELECT post_id \r\n             FROM {$wpdb->postmeta}\r\n             WHERE meta_key = %s", 'freshenup_awaiting_moderation' )
     );
    if ( empty( $posts_with_meta ) ) {
        //echo "No products with awaiting_moderation flag found.<br>";
        return;
    }
    $cleaned = 0;
    $kept = 0;
    foreach ( $posts_with_meta as $product_id ) {
        // Check if this product has ANY revisions
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Cleanup query, caching not beneficial
        $has_revisions = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) \r\n                 FROM {$wpdb->posts} \r\n                 WHERE post_parent = %d \r\n                 AND post_type = 'revision'", $product_id ) );
        if ( $has_revisions == 0 ) {
            // No revisions - delete the meta
            delete_post_meta( $product_id, 'freshenup_awaiting_moderation' );
            //echo "Cleaned flag from product $product_id (no revisions)<br>";
            $cleaned++;
        } else {
            $kept++;
        }
    }
    /*echo "<br><strong>Summary:</strong><br>";
      echo "Cleaned: $cleaned<br>";
      echo "Kept: $kept<br>";*/
}

// Review page content
function freshenup_review_page() {
    global $wpdb;
    ?>
    
    <div class="wrap freshenup_settings_form revisions-diff">
        <h1><?php 
    echo esc_html__( 'Awaiting approval', 'freshenup' );
    ?></h1>
        
        <?php 
    freshenup_print_update_notice_if_needed();
    ?>
        <div class="notice notice-info freshenup-prompt-tips">
            <p><strong><?php 
    echo esc_html__( 'Tips for Moderating', 'freshenup' );
    ?></strong></p>
                <ul class="freshenup-tips">
                    <li><?php 
    echo esc_html__( 'Clicking Approve will accept the Freshened up version and make it live for your users.', 'freshenup' );
    ?></li>
                    <li><?php 
    echo esc_html__( 'Clicking Manual Edit will take you to the WordPress editor loading the Freshened up version, and you will be able to make modifications. Upon saving those changes with the Update button in the editor, it becomes the live article and approved.', 'freshenup' );
    ?></li>
                    <li><?php 
    echo esc_html__( 'Clicking Reject deletes the Freshened up version, your article remains as the original. We are working on a new feature to offer a do-over.', 'freshenup' );
    ?></li>
                    <li><?php 
    echo esc_html__( 'Beta: Delete new sections directly from this page, clicking on the X while hovering, and then hit Approve with changes button. If you want to make more changes, hit the Manual edit button.', 'freshenup' );
    ?></li>
                    <li><?php 
    echo esc_html__( 'Beta: Enter your feedback with the thumbs up/down and writing down a comment, regardless of which option you choose. Once a good amount is collected, your feedback will be used in our prompt sequence.', 'freshenup' );
    ?></li>
                </ul>
        </div>
        <?php 
    freshenup_cleanup_orphaned_flags();
    // Get AI revisions
    $revisions = $wpdb->get_results( 
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->prepare(
            "SELECT r.* \r\n                 FROM {$wpdb->posts} r \r\n                 JOIN {$wpdb->postmeta} pm ON r.post_parent = pm.post_id \r\n                    AND pm.meta_key = %s\r\n                 WHERE r.post_type = %s\r\n                 AND r.ID = (\r\n                     SELECT MAX(r2.ID)\r\n                     FROM {$wpdb->posts} r2\r\n                     WHERE r2.post_parent = r.post_parent\r\n                     AND r2.post_type = %s\r\n                 )\r\n                 ORDER BY r.post_date DESC",
            'freshenup_awaiting_moderation',
            'revision',
            'revision'
        )
     );
    if ( !empty( $revisions ) ) {
        libxml_use_internal_errors( true );
        // suppress warnings
        foreach ( $revisions as $revision ) {
            $changes = get_post_meta( $revision->post_parent, 'freshenup_summary_changes', true );
            $spent = get_post_meta( $revision->post_parent, 'freshenup_spent', true );
            $old_content = get_post_meta( $revision->post_parent, 'freshenup_previous_content', true );
            $new_content = get_post_meta( $revision->post_parent, 'freshenup_new_content', true );
            echo '<div class="freshenup-post">';
            freshenup_side_by_side_comparison(
                $revision->post_parent,
                $changes,
                $spent,
                $old_content,
                $new_content
            );
            ?>
    
<form class="freshenup_feedback-form" method="POST" action="<?php 
            echo esc_url( admin_url( 'admin-post.php' ) );
            ?>">
<?php 
            echo '<p style="padding-left:0;  margin-bottom: 5px;">' . esc_html__( 'Leave feedback to improve your future posts (optional):', 'freshenup' ) . '</p>';
            ?>
  <input type="hidden" name="action" value="freshenup_process_feedback">
  <input type="hidden" name="post_id" value="<?php 
            echo esc_attr( $revision->post_parent );
            ?>">
  <input type="hidden" name="revision_id" value="<?php 
            echo esc_attr( $revision->ID );
            ?>">
  <?php 
            wp_nonce_field( 'freshenup_feedback_' . $revision->ID );
            ?>

  <div class="thumbs-options">
    <label class="thumb-label">
      <input type="radio" name="feedback" value="up" />
      <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor"
        class="freshenup-feedback-thumbs bi-hand-thumbs-up" viewBox="0 0 16 16">
        <path d="M8.864.046C7.908-.193 7.02.53 6.956 1.466c-.072 1.051-.23 2.016-.428 2.59-.125.36-.479 1.013-1.04 1.639-.557.623-1.282 1.178-2.131 1.41C2.685 7.288 2 7.87 2 8.72v4.001c0 .845.682 1.464 1.448 1.545 1.07.114 1.564.415 2.068.723l.048.03c.272.165.578.348.97.484.397.136.861.217 1.466.217h3.5c.937 0 1.599-.477 1.934-1.064a1.86 1.86 0 0 0 .254-.912c0-.152-.023-.312-.077-.464.201-.263.38-.578.488-.901.11-.33.172-.762.004-1.149.069-.13.12-.269.159-.403.077-.27.113-.568.113-.857 0-.288-.036-.585-.113-.856a2 2 0 0 0-.138-.362 1.9 1.9 0 0 0 .234-1.734c-.206-.592-.682-1.1-1.2-1.272-.847-.282-1.803-.276-2.516-.211a10 10 0 0 0-.443.05 9.4 9.4 0 0 0-.062-4.509A1.38 1.38 0 0 0 9.125.111zM11.5 14.721H8c-.51 0-.863-.069-1.14-.164-.281-.097-.506-.228-.776-.393l-.04-.024c-.555-.339-1.198-.731-2.49-.868-.333-.036-.554-.29-.554-.55V8.72c0-.254.226-.543.62-.65 1.095-.3 1.977-.996 2.614-1.708.635-.71 1.064-1.475 1.238-1.978.243-.7.407-1.768.482-2.85.025-.362.36-.594.667-.518l.262.066c.16.04.258.143.288.255a8.34 8.34 0 0 1-.145 4.725.5.5 0 0 0 .595.644l.003-.001.014-.003.058-.014a9 9 0 0 1 1.036-.157c.663-.06 1.457-.054 2.11.164.175.058.45.3.57.65.107.308.087.67-.266 1.022l-.353.353.353.354c.043.043.105.141.154.315.048.167.075.37.075.581 0 .212-.027.414-.075.582-.05.174-.111.272-.154.315l-.353.353.353.354c.047.047.109.177.005.488a2.2 2.2 0 0 1-.505.805l-.353.353.353.354c.006.005.041.05.041.17a.9.9 0 0 1-.121.416c-.165.288-.503.56-1.066.56z"/>
      </svg>
    </label>

    <label class="thumb-label">
      <input type="radio" name="feedback" value="down" />
      <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor"
        class="freshenup-feedback-thumbs bi-hand-thumbs-down" viewBox="0 0 16 16">
        <path d="M8.864 15.674c-.956.24-1.843-.484-1.908-1.42-.072-1.05-.23-2.015-.428-2.59-.125-.36-.479-1.012-1.04-1.638-.557-.624-1.282-1.179-2.131-1.41C2.685 8.432 2 7.85 2 7V3c0-.845.682-1.464 1.448-1.546 1.07-.113 1.564-.415 2.068-.723l.048-.029c.272-.166.578-.349.97-.484C6.931.08 7.395 0 8 0h3.5c.937 0 1.599.478 1.934 1.064.164.287.254.607.254.913 0 .152-.023.312-.077.464.201.262.38.577.488.9.11.33.172.762.004 1.15.069.13.12.268.159.403.077.27.113.567.113.856s-.036.586-.113.856c-.035.12-.08.244-.138.363.394.571.418 1.2.234 1.733-.206.592-.682 1.1-1.2 1.272-.847.283-1.803.276-2.516.211a10 10 0 0 1-.443-.05 9.36 9.36 0 0 1-.062 4.51c-.138.508-.55.848-1.012.964zM11.5 1H8c-.51 0-.863.068-1.14.163-.281.097-.506.229-.776.393l-.04.025c-.555.338-1.198.73-2.49.868-.333.035-.554.29-.554.55V7c0 .255.226.543.62.65 1.095.3 1.977.997 2.614 1.709.635.71 1.064 1.475 1.238 1.977.243.7.407 1.768.482 2.85.025.362.36.595.667.518l.262-.065c.16-.04.258-.144.288-.255a8.34 8.34 0 0 0-.145-4.726.5.5 0 0 1 .595-.643h.003l.014.004.058.013a9 9 0 0 0 1.036.157c.663.06 1.457.054 2.11-.163.175-.059.45-.301.57-.651.107-.308.087-.67-.266-1.021L12.793 7l.353-.354c.043-.042.105-.14.154-.315.048-.167.075-.37.075-.581s-.027-.414-.075-.581c-.05-.174-.111-.273-.154-.315l-.353-.354.353-.354c.047-.047.109-.176.005-.488a2.2 2.2 0 0 0-.505-.804l-.353-.354.353-.354c.006-.005.041-.05.041-.17a.9.9 0 0 0-.121-.415C12.4 1.272 12.063 1 11.5 1"/>
      </svg>
    </label>
  </div>

<textarea name="comment" placeholder="<?php 
            echo esc_html__( 'Optional feedback...', 'freshenup' );
            ?>" style="display: block;max-width: 100%;width: 400px;height: 50px;margin-bottom: 20px;"></textarea>

<p style="padding-left:0;  margin-bottom: 30px;"><input type="checkbox" id="update_published_date" name="update_published_date" value="1" /><label for="update_published_date"><?php 
            echo esc_html__( 'Update Post Published Date', 'freshenup' );
            ?></label></p>
      
<button class="freshenup_approve button" type="submit" name="action_clicked" value="approve"><?php 
            echo esc_html__( 'Approve', 'freshenup' );
            ?></button>
<button class="freshenup_edit button" type="submit" name="action_clicked" value="edit"><?php 
            echo esc_html__( 'Manual Edit', 'freshenup' );
            ?></button>
<button class="freshenup_reject button" type="submit" name="action_clicked" value="reject"><?php 
            echo esc_html__( 'Reject', 'freshenup' );
            ?></button>

</form>
</div>

<br /><br />
<hr />           
                        
        <?php 
        }
    } else {
        echo '<p>' . esc_html__( 'No freshenup updates awaiting moderation right now.', 'freshenup' ) . '</p>';
        $next_prompt_scheduled = freshenup_get_next_freshenup_hook_occurrence();
        echo '<p><strong>' . esc_html__( 'Next post scheduled for FreshenUp on: ', 'freshenup' ) . '</strong>' . esc_html( $next_prompt_scheduled ) . '</p>';
    }
    ?>

    </div>
    <?php 
}

// Handle approve action
function freshenup_handle_approve_revision(  $data  ) {
    // Check permissions
    if ( !current_user_can( 'edit_posts' ) ) {
        wp_die( esc_html__( 'You do not have permission to edit posts.', 'freshenup' ) );
    }
    // Verify revision_id exist
    if ( empty( $data['revision_id'] ) ) {
        wp_die( esc_html__( 'Invalid request', 'freshenup' ) );
    }
    $revision_id = intval( $data['revision_id'] );
    $update_published_date = intval( $data['update_published_date'] );
    $revision = get_post( $revision_id );
    // Ensure the revision exists and is valid
    if ( !$revision || $revision->post_type !== 'revision' ) {
        wp_die( esc_html__( 'Invalid revision.', 'freshenup' ) );
    }
    // Additional permission check for this specific post
    if ( !current_user_can( 'edit_post', $revision->post_parent ) ) {
        wp_die( esc_html__( 'You do not have permission to edit this post.', 'freshenup' ) );
    }
    // Start with revision content
    //$content = $revision->post_content;
    $content = get_post_meta( $revision->post_parent, 'freshenup_new_content', true );
    // Step 1: Remove full sections the user chose to delete
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in freshenup_handle_feedback()
    if ( !empty( $_POST['freshenup_deleted_ids'] ) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in freshenup_handle_feedback()
        $deleted_ids = json_decode( sanitize_text_field( wp_unslash( $_POST['freshenup_deleted_ids'] ) ), true );
        if ( is_array( $deleted_ids ) ) {
            $deleted_ids = array_map( 'sanitize_text_field', $deleted_ids );
            // Delete from the post_content
            //$content = freshenup_delete_sections_by_id($content, $deleted_ids);
            // Delete from the post_meta freshenup_new_content, so the user sees under Approved what really made it into the post
            // Get post_content in freshenup_new_content post_meta
            // Delete sections
            $content = freshenup_delete_sections_by_id( $content, $deleted_ids );
            //$content = $post_meta_content;
            // Update post_meta
            update_post_meta( $revision->post_parent, 'freshenup_new_content', $content );
        }
    }
    // Step 2: Always strip remaining wrapper comments
    $cleaned_content = freshenup_strip_all_freshenup_wrappers( $content );
    // Save the cleaned content
    $updated_post = [
        'ID'                => $revision->post_parent,
        'post_content'      => $cleaned_content,
        'post_modified'     => current_time( 'mysql' ),
        'post_modified_gmt' => current_time( 'mysql', true ),
    ];
    // Check if the update_published_date checkbox is checked
    if ( isset( $update_published_date ) && $update_published_date == '1' ) {
        $updated_post['post_date'] = current_time( 'mysql' );
        $updated_post['post_date_gmt'] = current_time( 'mysql', true );
    }
    wp_update_post( $updated_post );
    // Remove the awaiting moderation flag
    delete_post_meta( $revision->post_parent, 'freshenup_awaiting_moderation' );
    // Stores the approval of the update
    update_post_meta( $revision->post_parent, 'freshenup_approved', time() );
    // Redirect back with success message
    wp_safe_redirect( esc_url_raw( add_query_arg( 'approved', '1', admin_url( 'admin.php?page=freshenup_review' ) ) ) );
    exit;
}

// Register the action
//add_action('admin_post_freshenup_approve_revision', 'freshenup_handle_approve_revision');
// Handle reject action
function freshenup_handle_reject_revision(  $data  ) {
    // Check permissions
    if ( !current_user_can( 'edit_posts' ) ) {
        wp_die( esc_html__( 'You do not have permission to edit posts.', 'freshenup' ) );
    }
    // Verify nonce and revision_id exist
    if ( !isset( $data['revision_id'] ) ) {
        wp_die( esc_html__( 'Invalid request', 'freshenup' ) );
    }
    $revision_id = intval( $data['revision_id'] );
    $revision = get_post( $revision_id );
    // Additional permission check for this specific post
    if ( !current_user_can( 'edit_post', $revision->post_parent ) ) {
        wp_die( esc_html__( 'You do not have permission to edit this post.', 'freshenup' ) );
    }
    if ( $revision ) {
        // Delete the revision
        wp_delete_post_revision( $revision_id );
        // Remove the awaiting moderation flag
        delete_post_meta( $revision->post_parent, 'freshenup_awaiting_moderation' );
        // Redirect back with message
        wp_safe_redirect( esc_url_raw( add_query_arg( 'rejected', '1', admin_url( 'admin.php?page=freshenup_review' ) ) ) );
        exit;
    }
}

//add_action('admin_post_freshenup_reject_revision', 'freshenup_handle_reject_revision');
function freshenup_admin_notices() {
    $screen = get_current_screen();
    if ( $screen->id !== 'posts_page_freshenup-review' ) {
        return;
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only query parameter after redirect
    if ( isset( $_GET['approved'] ) ) {
        ?>
        <div class="notice notice-success is-dismissible">
            <p><?php 
        esc_html_e( 'AI revision approved and applied successfully.', 'freshenup' );
        ?></p>
        </div>
        <?php 
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only query parameter after redirect
    if ( isset( $_GET['rejected'] ) ) {
        ?>
        <div class="notice notice-info is-dismissible">
            <p><?php 
        esc_html_e( 'AI revision rejected and removed.', 'freshenup' );
        ?></p>
        </div>
        <?php 
    }
}

add_action( 'admin_notices', 'freshenup_admin_notices' );
function freshenup_add_revision_field() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for hidden field
    if ( isset( $_GET['revision_id'] ) ) {
        ?>
        <input type="hidden" name="freshenup_revision_edit" value="<?php 
        echo esc_attr( intval( $_GET['revision_id'] ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        ?>">
        <input type="hidden" name="freshenup_revision_flag" value="true">
        <?php 
    }
}

add_action( 'admin_init', 'freshenup_load_revision_content' );
// hook into revision save if we are reviewing a freshenedup post
add_action(
    'save_post',
    'freshenup_handle_revision_save',
    10,
    2
);
// Extract highlights for the annotations API, to display in block editors
function freshenup_extract_highlights(  $html, &$highlights = array()  ) {
    static $i = 0;
    return preg_replace_callback( '/<!--\\s*freshenup:start\\b([^>]*)-->(.*?)<!--\\s*\\/?\\s*freshenup:end\\s*-->/is', function ( $m ) use(&$highlights, &$i) {
        // if id="foo" or id=foo comes we use it; otherwise we create one
        if ( preg_match( '/\\bid\\s*=\\s*("?)([^\\s">]+)\\1/i', $m[1], $idM ) ) {
            $base_id = $idM[2];
        } else {
            $base_id = 'freshenup-' . ++$i;
        }
        $inner_html = trim( $m[2] );
        // if parse_blocks does not exist, we treat the entire fragment as a unique block
        $blocks = ( function_exists( 'parse_blocks' ) ? parse_blocks( $inner_html ) : array(array(
            'innerHTML'   => $inner_html,
            'innerBlocks' => array(),
        )) );
        foreach ( $blocks as $block ) {
            // Saltar bloques contenedores.
            if ( !empty( $block['innerBlocks'] ) ) {
                continue;
            }
            $raw = ( isset( $block['innerHTML'] ) ? $block['innerHTML'] : '' );
            $text = wp_strip_all_tags( $raw );
            if ( $text !== '' ) {
                $highlights[] = array(
                    'id'      => $base_id . '-' . count( $highlights ),
                    'snippet' => mb_substr( $text, 0, 40 ),
                );
            }
        }
        // Return the clean content (without the FreshenUp comments).
        return $inner_html;
    }, $html );
}

function freshenup_load_revision_content() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameters for admin page display
    if ( !isset( $_GET['revision_id'] ) || !isset( $_GET['action'] ) || $_GET['action'] !== 'edit' ) {
        return;
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $revision_id = intval( $_GET['revision_id'] );
    $revision = get_post( $revision_id );
    // Check if the revision exists
    if ( !$revision || 'revision' !== $revision->post_type ) {
        return;
    }
    // For block editor
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $post_id = ( isset( $_GET['post'] ) ? intval( $_GET['post'] ) : 0 );
    $post_type = get_post_type( $post_id );
    $new_content = get_post_meta( $revision->post_parent, 'freshenup_new_content', true );
    if ( use_block_editor_for_post_type( $post_type ) ) {
        // Add the block editor notice
        add_action( 'enqueue_block_editor_assets', function () {
            wp_enqueue_script(
                'freshenup-editor-notice',
                plugin_dir_url( __FILE__ ) . 'js/freshenup-editor-notice.js',
                array('wp-dom-ready', 'wp-data'),
                FRESHENUP_VERSION,
                true
            );
            wp_localize_script( 'freshenup-editor-notice', 'freshenupEditorNotice', array(
                'text' => __( 'You are editing a Freshened up revision. New content is highlighted visually for review, but the highlighting will disappear after saving. Click Save to apply these changes to the post.', 'freshenup' ),
            ) );
        } );
        add_action( 'enqueue_block_editor_assets', function () {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for editor assets
            $revision_id = ( isset( $_GET['revision_id'] ) ? (int) $_GET['revision_id'] : 0 );
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $revision = ( $revision_id ? get_post( (int) $revision_id ) : null );
            if ( !$revision || !in_array( $revision->post_type, array('revision'), true ) ) {
                return;
                // nothing to do
            }
            $new_content = get_post_meta( $revision->post_parent, 'freshenup_new_content', true );
            $highlights = [];
            $clean_html = freshenup_extract_highlights( $new_content, $highlights );
            // Register / enqueue JS
            wp_register_script(
                'freshenup-editor',
                plugins_url( 'js/freshenup-editor.js', __FILE__ ),
                ['wp-blocks', 'wp-data', 'wp-annotations'],
                filemtime( __DIR__ . '/js/freshenup-editor.js' ),
                true
            );
            // Inline data for JS
            wp_add_inline_script( 'freshenup-editor', 'window.FRESHENUP_REVISION_HTML = ' . wp_json_encode( $clean_html ) . ';' . 'window.FRESHENUP_HIGHLIGHTS   = ' . wp_json_encode( $highlights ) . ';', 'before' );
            wp_enqueue_script( 'freshenup-editor' );
            // Simple yellow background for annotated blocks
            wp_add_inline_style( 'wp-block-library', '.is-annotated-by-freshenup{background:#cff5d5;}' );
        } );
    } else {
        add_filter( 'content_edit_pre', 'freshenup_load_revision_content_filter' );
        add_action( 'admin_notices', 'freshenup_revision_edit_notice' );
    }
    add_action( 'edit_form_after_title', 'freshenup_add_revision_field' );
}

add_filter( 'mce_css', function ( $styles ) {
    $url = plugin_dir_url( __FILE__ ) . 'css/freshenup-editor.css';
    return ( $styles ? $styles . ',' . $url : $url );
} );
add_action( 'enqueue_block_editor_assets', function () {
    wp_enqueue_style(
        'freshenup-editor-styles',
        plugin_dir_url( __FILE__ ) . 'css/freshenup-editor.css',
        array(),
        FRESHENUP_VERSION
    );
} );
function freshenup_load_revision_content_filter(  $content  ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for content filter
    if ( !isset( $_GET['revision_id'] ) ) {
        return $content;
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $revision_id = intval( $_GET['revision_id'] );
    $revision = get_post( $revision_id );
    $new_content = get_post_meta( $revision->post_parent, 'freshenup_new_content', true );
    if ( $revision && 'revision' === $revision->post_type ) {
        if ( strpos( $new_content, "<!-- freshenup:start" ) !== false ) {
            //$raw_content = $new_content;
            $new_content = freshenup_highlight_inserted_content( $new_content );
            //$new_content_cleaned = wpautop($highlighted); // apply to surrounding content only
        }
        return $new_content;
    }
    return $content;
}

function freshenup_revision_edit_notice() {
    ?>
    <div class="notice notice-info">
        <p><?php 
    echo esc_html__( 'You are editing a Freshened up revision. New content is highlighted visually for review, but the highlighting will disappear after saving. Click Save to apply these changes to the post.', 'freshenup' );
    ?></p>
    </div>
    <?php 
}

function freshenup_handle_revision_save(  $post_id, $post  ) {
    // Prevent double firing
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // Check if we're saving a freshenup revision edit
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress core save_post action
    if ( !isset( $_POST['freshenup_revision_edit'] ) || !isset( $_POST['freshenup_revision_flag'] ) ) {
        return;
    }
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    // Only update if Classic editor is used (Gutenberg already cleaned it via wp_insert_post_data)
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress core save_post action
    if ( !empty( $_POST['content'] ) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Content sanitized via wp_kses_post below
        $raw = wp_unslash( $_POST['content'] );
        $data = [
            'post_content' => $raw,
        ];
        $data = freshenup_clean_post_on_manual_edit( $data, [] );
        $cleaned = wp_kses_post( wp_unslash( $data['post_content'] ) );
        remove_action( 'save_post', 'freshenup_handle_revision_save', 10 );
        wp_update_post( [
            'ID'           => $post_id,
            'post_content' => $cleaned,
        ] );
        add_action(
            'save_post',
            'freshenup_handle_revision_save',
            10,
            2
        );
    }
    delete_post_meta( $post_id, 'freshenup_awaiting_moderation' );
    if ( $post->post_parent != 0 ) {
        delete_post_meta( $post->post_parent, 'freshenup_awaiting_moderation' );
    }
}

add_filter(
    'wp_insert_post_data',
    'freshenup_clean_post_on_manual_edit',
    10,
    2
);
function freshenup_clean_post_on_manual_edit(  $data, $postarr  ) {
    $content = wp_unslash( $data['post_content'] );
    if ( strpos( $content, "freshenup" ) !== false ) {
        $content = freshenup_strip_all_freshenup_wrappers( $content );
        $content = preg_replace( '/<div\\s+class=["\']freshenup-highlight["\'][^>]*>(.*?)<\\/div>/is', '$1', $content );
        $content = preg_replace( '/<span\\s+class=["\']freshenup-highlight["\'][^>]*>(.*?)<\\/span>/is', '$1', $content );
        $data['post_content'] = wp_slash( $content );
    }
    return $data;
}

add_action( 'admin_enqueue_scripts', function ( $hook ) {
    // Only load on your custom plugin page
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking page parameter for script enqueue
    if ( isset( $_GET['page'] ) && sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'freshenup_review' ) {
        wp_enqueue_script(
            'freshenup-delete-highlight',
            plugin_dir_url( __FILE__ ) . 'js/freshenup_delete_ai_section.js',
            // adjust path
            array(),
            FRESHENUP_VERSION,
            true
        );
    }
} );
// Function to highlight changes based on freshenup:start and freshenup:end
function freshenup_highlight_inserted_content(  $html  ) {
    static $i = 0;
    return preg_replace_callback( '/<!--\\s*freshenup:start\\b([^>]*)-->(.*?)<!--\\s*\\/?\\s*freshenup:end\\s*-->/is', function ( $m ) use(&$i) {
        // Extract id="..." or id=...
        if ( preg_match( '/\\bid\\s*=\\s*("?)([^\\s">]+)\\1/i', $m[1], $idM ) ) {
            $id = $idM[2];
        } else {
            $id = 'freshenup-' . ++$i;
        }
        $content = trim( $m[2] );
        // Detect at least one block-level end-tag
        $is_block = preg_match( '#</\\s*(?:p|h[1-6]|ul|ol|li|div|section|article|table|blockquote)[^>]*>#i', $content );
        return ( $is_block ? "<div class='freshenup-highlight' data-freshenup-id=\"{$id}\">\n{$content}\n</div>" : " <span class='freshenup-highlight' data-freshenup-id=\"{$id}\">{$content}</span>" );
    }, $html );
}

function freshenup_double_break_after_start(  $html  ) {
    /*
     *  (<!-- freshenup:start ... -->)   capture the whole opening comment
     *  (\r?\n)                         capture exactly ONE newline
     *  ([^\r\n])                       the first non-newline char of content
     *
     *  The (?![\r\n]) in the pattern makes sure we match only the single-newline
     *  case; if two newlines are already there, the look-ahead fails and
     *  nothing is changed.
     */
    $pattern = '/(<!--\\s*freshenup:start\\b[^>]*-->)(\\r?\\n)([^\\r\\n])/i';
    return preg_replace_callback( $pattern, function ( $m ) {
        // keep the comment + original newline, add one more, then the content
        return $m[1] . $m[2] . "\n" . $m[3];
    }, $html );
}

// Deletes freshenup:start and freshenup:end sections when deleted by user at Awaiting approval
function freshenup_delete_sections_by_id(  $content, $deleted_ids = []  ) {
    foreach ( $deleted_ids as $id ) {
        $pattern = '/(?:\\s*\\n){0,2}<!--\\s*freshenup:start\\s+id=' . preg_quote( $id, '/' ) . '\\s*-->(.*?)<!--\\s*\\/?\\s*freshenup:end\\s*-->(?:\\s*\\n){0,2}/is';
        $content = preg_replace( $pattern, '', $content );
    }
    // After deleting, reduce 3+ newlines to max 2
    $content = preg_replace( "/\n{3,}/", "\n\n", $content );
    return $content;
}

// Deletes freshenup:start and freshenup:end comment tags before updating the post
function freshenup_strip_all_freshenup_wrappers(  $content  ) {
    // Strip just the wrapper comments, not the inner content
    $content = preg_replace( '/<!--\\s*freshenup:start\\s+id=.*?-->\\s*\\n?/i', '', $content );
    $content = preg_replace( '/\\s*\\n?<!--\\s*\\/?\\s*freshenup:end\\s*-->/i', '', $content );
    return $content;
}

// Function to highlight changes if freshenup:start and freshenup:end not present
function freshenup_compare_and_highlight_paragraphs(  $original, $modified  ) {
    $normalize = function ( $text ) {
        $text = wp_strip_all_tags( $text );
        $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
        // Decode HTML entities
        // Normalize straight/curly quotes and apostrophes to plain equivalents
        // Normalize straight/curly quotes and apostrophes to plain equivalents
        $text = str_replace( 
            [
                "‘",
                "’",
                "“",
                "”",
                "′",
                "`",
                "´"
            ],
            // curly/special quote variants
            [
                "'",
                "'",
                '"',
                '"',
                "'",
                "'",
                "'"
            ],
            // normalize to straight
            $text
         );
        $text = str_replace( " ", ' ', $text );
        return $text;
    };
    $clean_original = $normalize( $original );
    $clean_modified = $normalize( $modified );
    // Split into paragraphs first
    $orig_blocks = explode( PHP_EOL, $clean_original );
    $mod_blocks = explode( PHP_EOL, $clean_modified );
    $new_content = [];
    foreach ( $mod_blocks as $i => $block ) {
        $block = trim( $block );
        if ( empty( $block ) ) {
            continue;
        }
        // Find corresponding block in original
        $corresponding_block = ( isset( $orig_blocks[$i] ) ? $orig_blocks[$i] : '' );
        // If blocks are different, analyze chunks
        if ( $block !== $corresponding_block ) {
            // Split into chunks by punctuation but preserve it
            $chunks = preg_split(
                '/([,.:;?!-])(?=\\s)/',
                $block,
                -1,
                PREG_SPLIT_DELIM_CAPTURE
            );
            $orig_chunks = ( $corresponding_block ? preg_split(
                '/([,.:;?!-])(?=\\s)/',
                $corresponding_block,
                -1,
                PREG_SPLIT_DELIM_CAPTURE
            ) : [] );
            $current_chunk = '';
            for ($j = 0; $j < count( $chunks ); $j += 2) {
                // Combine chunk with its punctuation
                $chunk = trim( $chunks[$j] ) . (( isset( $chunks[$j + 1] ) ? $chunks[$j + 1] : '' ));
                $trimmedChunk = trim( $chunk );
                if ( empty( $trimmedChunk ) ) {
                    continue;
                }
                // Check if this chunk exists in corresponding section
                $chunk_found = false;
                foreach ( $orig_chunks as $k => $orig_chunk ) {
                    similar_text( $chunk, $orig_chunk, $similarity );
                    if ( $similarity > 80 ) {
                        $chunk_found = true;
                        break;
                    }
                }
                if ( !$chunk_found && strpos( $clean_original, $chunk ) === false ) {
                    $new_content[] = $chunk;
                }
            }
        }
    }
    // Highlight new content in the HTML version
    $output = $modified;
    $missing_matches = 0;
    $original_output = $output;
    foreach ( $new_content as $text ) {
        if ( strlen( trim( $text ) ) > 3 ) {
            // Avoid highlighting very short segments
            // First attempt: direct match with optional trailing whitespace
            $temp_output = preg_replace(
                '/(' . preg_quote( $text, '/' ) . ')(\\s+)?/',
                "<span style='background-color: #cff5d5;'>\$1\$2</span>",
                $output,
                1,
                $count
            );
            // Check if preg_replace succeeded
            if ( $temp_output !== null && $temp_output !== false ) {
                $output = $temp_output;
            } else {
                $count = 0;
                // Force fallback
            }
            if ( $count === 0 ) {
                // Strip trailing punctuation and control characters
                $text_stripped = rtrim( $text, ',;.:!?-' );
                // Second attempt: match without punctuation
                $temp_output = preg_replace(
                    '/' . preg_quote( $text_stripped, '/' ) . '/',
                    "<span style='background-color: #cff5d5;'>\$0</span>",
                    $output,
                    1,
                    $count
                );
                // Check result
                if ( $temp_output !== null && $temp_output !== false ) {
                    $output = $temp_output;
                } else {
                    $count = 0;
                }
                if ( empty( $output ) ) {
                    // Restore from backup
                    $output = $original_output;
                }
            }
            if ( $count === 0 ) {
                // Third attempt: allow inline tags between words
                $words = preg_split( '/\\s+/', $text_stripped );
                if ( count( $words ) > 1 ) {
                    $pattern = '/' . implode( '\\s*(?:<[^>]+>)?\\s*', array_map( 'preg_quote', $words ) ) . '/i';
                    $temp_output = preg_replace(
                        $pattern,
                        "<span style='background-color: #cff5d5;'>\$0</span>",
                        $output,
                        1,
                        $count
                    );
                    if ( $temp_output !== null && $temp_output !== false ) {
                        $output = $temp_output;
                    } else {
                        $count = 0;
                    }
                }
            }
            if ( $count === 0 ) {
                // Fourth attempt: match by first and last word
                $words = preg_split( '/\\s+/', $text_stripped );
                if ( count( $words ) >= 2 ) {
                    $first = preg_quote( $words[0], '/' );
                    $last = preg_quote( $words[count( $words ) - 1], '/' );
                    // This pattern is risky - the (?:.*?) can match too much
                    $pattern = '/' . $first . '(?:.,;*?)(?:<[^>]+>)*' . $last . '/ui';
                    $temp_output = preg_replace(
                        $pattern,
                        "<span style='background-color: #cff5d5;'>\$0</span>",
                        $output,
                        1,
                        $count
                    );
                    if ( $temp_output !== null && $temp_output !== false && $temp_output !== '' ) {
                        // Extra check: make sure we didn't match too much
                        if ( strlen( $temp_output ) <= strlen( $output ) * 1.5 ) {
                            // Sanity check
                            $output = $temp_output;
                        } else {
                            $count = 0;
                        }
                    } else {
                        $count = 0;
                    }
                }
            }
            // Final fallback: str_replace
            if ( $count === 0 ) {
                $stripped_output = wp_strip_all_tags( $original_output );
                if ( strpos( $stripped_output, $text_stripped ) !== false ) {
                    $highlighted = "<span style='background-color: #cff5d5;'>{$text_stripped}</span>";
                    $temp_output = str_replace( $text_stripped, $highlighted, $output );
                    if ( $temp_output !== false && $temp_output !== '' ) {
                        $output = $temp_output;
                    } else {
                    }
                } else {
                }
            }
            // Final safety check: if $output is empty but shouldn't be, restore original
            if ( empty( $output ) && !empty( $original_output ) ) {
                $output = $original_output;
            }
            if ( $count === 0 ) {
                $missing_matches++;
            }
        }
    }
    // Extend span highlight when stopped by tag in preg_replace
    // Store the original content before processing for comparison
    // Extend span highlight when stopped by tag in preg_replace
    $output = preg_replace_callback( '#(<span[^>]*>)(.*?)(</span>)(.*?)([\\.:!?])(?=\\s*(?:</?[^>]*>)*\\s*(?:$|<|[\\r\\n]))#isu', function ( $matches ) use($clean_original, $normalize) {
        // Only process spans with the specific background color
        if ( strpos( $matches[1], 'background-color: #cff5d5' ) !== false ) {
            // Extract the content that would be added
            $content_to_add = wp_strip_all_tags( $matches[4] . $matches[5] );
            $normalized_content_to_add = $normalize( $content_to_add );
            // Check if this content exists in the original unprocessed content
            $normalized_original = $clean_original;
            // If the content to add was in the original but NOT highlighted, extend the span
            if ( !str_contains( $normalized_original, $normalized_content_to_add ) ) {
                return $matches[1] . $matches[2] . $matches[4] . $matches[5] . $matches[3];
            }
        }
        // Return unchanged
        return $matches[0];
    }, $output );
    if ( strpos( $output, "<!-- wp:paragraph" ) === false ) {
        $output = wpautop( $output );
    }
    return trim( $output );
}

function freshenup_settings_page() {
    ?>
    <div class="wrap freshenup_settings_form">
        <h2 class="freshenup_settings_title"><?php 
    echo esc_html__( 'Freshenup settings', 'freshenup' );
    ?></h2>
        
        <!-- Begin Form -->
        <form method="post" action="options.php">
            <?php 
    settings_fields( 'freshenup_options' );
    // Unified option group
    do_settings_sections( 'freshenup_options' );
    // Display all sections
    submit_button( esc_html__( 'Save Changes', 'freshenup' ) );
    ?>
        </form>
    </div>
    <?php 
}

function freshenup_ajax_run_scheduled_action() {
    check_ajax_referer( 'freshenup_run_scheduled_action', 'nonce' );
    if ( !current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Insufficient permissions' );
    }
    $hook = ( isset( $_POST['hook'] ) ? sanitize_text_field( wp_unslash( $_POST['hook'] ) ) : '' );
    $prompt_id = ( isset( $_POST['prompt_id'] ) ? intval( $_POST['prompt_id'] ) : 0 );
    $execution_number = ( isset( $_POST['execution_number'] ) ? intval( $_POST['execution_number'] ) : 0 );
    // Run the action with the specific prompt_id and execution_number arguments
    as_enqueue_async_action( $hook, array(
        'prompt_id'        => $prompt_id,
        'execution_number' => $execution_number,
    ) );
    // Store metadata about this update
    update_option( 'freshenup_manual_ran_' . $prompt_id, time() );
    wp_send_json_success( 'Action scheduled successfully' );
}

add_action( 'wp_ajax_freshenup_run_scheduled_action', 'freshenup_ajax_run_scheduled_action' );
function freshenup_prompt_page() {
    ?>
    <?php 
    $prompt_header_title = esc_html__( 'Freshenup Prompt', 'freshenup' );
    ?>
    <div class="wrap freshenup_settings_form">
        <h2 class="freshenup_settings_title"><?php 
    echo $prompt_header_title;
    ?></h2>
        
        <!-- Begin Form -->
        <form method="post" id="form_prompt" action="options.php">
            <?php 
    settings_fields( 'freshenup_prompts' );
    // Unified option group
    do_settings_sections( 'freshenup_prompts' );
    // Display all sections
    submit_button( esc_html__( 'Save Changes', 'freshenup' ) );
    ?>
        </form>
    </div>
    <?php 
}

function freshenup_approved_page() {
    global $wpdb;
    ?>
    <div class="wrap freshenup_settings_form revisions-diff">
        <h2 class="freshenup_settings_title"><?php 
    echo esc_html__( 'Freshenup approved', 'freshenup' );
    ?></h2>
        <?php 
    // Get count of pending Freshenup revisions
    $pending_count = wp_cache_get( 'freshenup_pending_count' );
    if ( $pending_count > 0 ) {
        $pending_text = sprintf( 
            /* Translators: %d is the number of posts awaiting moderation. */
            esc_html( _n(
                'You have %d post awaiting moderation',
                'You have %d posts awaiting moderation',
                $pending_count,
                'freshenup'
            ) ),
            $pending_count
         );
        echo '<h3><a href="' . esc_url( admin_url( 'admin.php?page=freshenup_review' ) ) . '">';
        echo esc_html( $pending_text );
        // Already sanitized via esc_html(_n(...)) but escape late.
        echo '</a></h3>';
    }
    ?>

<h2 class="freshenup_settings_title subtitle"><?php 
    echo esc_html__( 'Latest posts freshened up', 'freshenup' );
    ?></h2>


        <?php 
    // Query to get the last 10 summaries from postmeta
    $like_previous = $wpdb->esc_like( 'freshenup_previous_content' ) . '%';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Complex meta query not feasible with WP_Query
    $edits = $wpdb->get_results( $wpdb->prepare(
        "\r\n    SELECT \r\n        post_id,\r\n        MAX(CASE WHEN meta_key = 'freshenup_summary_changes' THEN meta_value END) as changes,\r\n        MAX(CASE WHEN meta_key = 'freshenup_spent' THEN meta_value END) as spent,\r\n        MAX(CASE WHEN meta_key = 'freshenup_new_content' THEN meta_value END) as new_content,\r\n        MAX(CASE WHEN meta_key LIKE %s THEN meta_value END) as old_content\r\n    FROM {$wpdb->postmeta} pm\r\n    WHERE meta_key LIKE %s\r\n    AND EXISTS (\r\n        SELECT 1 FROM {$wpdb->postmeta}\r\n        WHERE post_id = pm.post_id\r\n        AND meta_key = 'freshenup_summary_changes'\r\n    )\r\n    AND NOT EXISTS (\r\n        SELECT 1 FROM {$wpdb->postmeta}\r\n        WHERE post_id = pm.post_id\r\n        AND meta_key = 'freshenup_awaiting_moderation'\r\n    )\r\n    GROUP BY post_id\r\n    ORDER BY MAX(meta_id) DESC\r\n    LIMIT %d\r\n",
        $like_previous,
        'freshenup_%',
        10
    ) );
    if ( !empty( $edits ) ) {
        libxml_use_internal_errors( true );
        // suppress warnings
        // Loop through the summaries and display them
        foreach ( $edits as $edit ) {
            freshenup_side_by_side_comparison(
                $edit->post_id,
                $edit->changes,
                $edit->spent,
                $edit->old_content,
                $edit->new_content
            );
            echo '<hr>';
        }
    } else {
        echo '<p>' . esc_html__( 'No freshened up posts yet.', 'freshenup' ) . ' ';
        $prompt = get_option( 'freshenup_prompts', array() );
        if ( empty( $prompt ) ) {
            echo '<a href="' . esc_url( admin_url( 'admin.php?page=freshenup_prompt' ) ) . '">';
            echo esc_html__( 'Set up your prompt to start.', 'freshenup' );
            echo '</a>';
        }
        echo '</p>';
    }
    ?>
    </div>    
        
    <?php 
}

function freshenup_side_by_side_comparison(
    $post_id,
    $changes,
    $spent,
    $old_content,
    $new_content
) {
    $post = get_post( $post_id );
    // Retrieve the post object based on post_id
    $link = get_permalink( $post_id );
    $author_name = get_the_author_meta( 'display_name', $post->post_author );
    $modified_date = get_post_meta( $post_id, 'freshenup_old_content_date', true );
    $formatted_last_update = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $modified_date ) );
    echo '<freshenup-summary class="freshenup_settings_form">
<h2 style="padding: 25px 25px 10px 25px;margin:0"><a href="' . esc_url( $link ) . '">' . esc_html( $post->post_title ) . '</a></h2>

<p style="padding:0 25px 10px 25px;margin:0"><strong>' . esc_html__( 'Author', 'freshenup' ) . '</strong> ' . esc_html( $author_name ) . '</p>

<p style="padding:0 25px 10px 25px;margin:0"><strong>' . esc_html__( 'Last updated (before this freshenup) on', 'freshenup' ) . '</strong> ' . esc_html( $formatted_last_update ) . '</p>';
    echo '<p style="padding: 0 25px;margin:0"><strong>' . esc_html__( 'What was updated', 'freshenup' ) . '</strong></p>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Content sanitized via wp_kses_post()
    echo '<div class="summary_changes">' . wpautop( wp_kses_post( $changes ) ) . '</div>';
    echo '<p style="padding: 0 25px;margin:0"><strong>' . esc_html__( 'API cost:', 'freshenup' ) . '</strong> $';
    $formatted_spent = ( is_numeric( $spent ) ? round( $spent, 3 ) : $spent );
    echo esc_html( $formatted_spent );
    echo '</p>';
    echo '<comparison-container class="wp-list-table widefat fixed bookmarks" style="padding-left:0;display:flex;gap:40px">';
    // Clean mismatched closing tags
    $old_content_for_cleaning = new DOMDocument();
    $old_content_for_cleaning->loadHTML( mb_convert_encoding( wpautop( $old_content ), 'HTML-ENTITIES', 'UTF-8' ) );
    $old_content_cleaned = $old_content_for_cleaning->saveHTML( $old_content_for_cleaning->getElementsByTagName( 'body' )->item( 0 ) );
    $old_content_cleaned = preg_replace( '/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/mi', '', $old_content_cleaned );
    if ( !empty( $new_content ) && strpos( $new_content, "<!-- freshenup:start" ) !== false ) {
        //$new_content_cleaned = freshenup_highlight_inserted_content($new_content);
        $raw_content = $new_content;
        $done_autop = false;
        if ( strpos( $new_content, "<!-- wp:paragraph" ) === false && strpos( $new_content, "</p>" ) === false ) {
            $done_autop = true;
            $raw_content = freshenup_double_break_after_start( $raw_content );
            $raw_content = wpautop( $raw_content );
        }
        $highlighted = freshenup_highlight_inserted_content( $raw_content );
        $new_content_cleaned = $highlighted;
        // apply to surrounding content only
        if ( strpos( $new_content, "<!-- wp:paragraph" ) === false && !$done_autop ) {
            $new_content_cleaned = wpautop( $new_content_cleaned );
        }
    } elseif ( !empty( $new_content ) ) {
        $new_content_for_cleaning = new DOMDocument();
        $new_content_for_cleaning->loadHTML( mb_convert_encoding( freshenup_compare_and_highlight_paragraphs( $old_content, $new_content ), 'HTML-ENTITIES', 'UTF-8' ) );
        $new_content_cleaned = $new_content_for_cleaning->saveHTML( $new_content_for_cleaning->getElementsByTagName( 'body' )->item( 0 ) );
    }
    $new_content_cleaned = preg_replace( '/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/mi', '', $new_content_cleaned );
    echo '<side-panel style="padding:25px;width:49%"><h2>Original</h2>' . wp_kses_post( $old_content_cleaned ) . '</side-panel>
    <side-panel style="padding:25px;width:49%"><h2>Freshened up</h2>';
    //echo '<div class="freshenup-post">';
    echo wp_kses_post( $new_content_cleaned );
    //echo '</div>';
    echo '</side-panel>
    </comparison-container>';
    echo '</freshenup-summary>';
    libxml_clear_errors();
}

// Ensure this hooks into the admin_menu
add_action( 'admin_menu', 'freshenup_admin_menu' );
function freshenup_sanitize_svg(  $svg  ) {
    $allowed_tags = array(
        'svg'  => array(
            'xmlns'   => array(),
            'viewbox' => array(),
            'fill'    => array(),
        ),
        'path' => array(
            'd' => array(),
        ),
    );
    return wp_kses( $svg, $allowed_tags );
}
