<?php

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

add_action( 'admin_init', 'tw_lem_set_install_timestamp_if_missing' );
add_action( 'admin_enqueue_scripts', 'tw_lem_enqueue_rating_popup_assets' );
add_action( 'admin_post_tw_lem_send_rating_feedback', 'tw_lem_handle_rating_feedback' );
add_action( 'admin_post_tw_lem_record_rating_popup_shown', 'tw_lem_handle_rating_popup_recorded' );

/**
 * Set or reset popup state on activation.
 */
function tw_lem_set_install_timestamp() {
    update_option( 'tw_lem_install_timestamp', time() );
    delete_option( 'tw_lem_rating_popup_last_dismissed' );
    delete_option( 'tw_lem_rating_popup_reviewed' );
}

/**
 * Set install timestamp if missing.
 */
function tw_lem_set_install_timestamp_if_missing() {
    if ( ! get_option( 'tw_lem_install_timestamp' ) ) {
        update_option( 'tw_lem_install_timestamp', time() );
    }
}

/**
 * Decide whether the rating popup should show.
 *
 * @return bool
 */
function tw_lem_should_show_rating_popup() {
    $install_timestamp = absint( get_option( 'tw_lem_install_timestamp', 0 ) );
    $reviewed          = get_option( 'tw_lem_rating_popup_reviewed', false );
    $last_dismissed    = absint( get_option( 'tw_lem_rating_popup_last_dismissed', 0 ) );
    $current_time      = time();
    $delay_seconds     = DAY_IN_SECONDS;
    $retry_seconds     = 10 * DAY_IN_SECONDS;
    $age               = $current_time - $install_timestamp;

    if ( $reviewed ) {
        return false;
    }

    if ( ! $install_timestamp ) {
        return false;
    }

    if ( $last_dismissed ) {
        $ready = ( $current_time - $last_dismissed ) >= $retry_seconds;
    } else {
        $ready = $age >= $delay_seconds;
    }

    return $ready;
}

/**
 * Enqueue rating popup scripts on plugin admin pages when ready.
 */
function tw_lem_enqueue_rating_popup_assets() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    global $pagenow;
    $is_plugin_screen = isset( $pagenow ) && 'plugins.php' === $pagenow;

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

    $is_tw_lem_admin_page = $page && strpos( $page, 'tw-lem' ) === 0;

    if ( $is_plugin_screen ) {
        $has_reviewed = get_option( 'tw_lem_rating_popup_reviewed', false );
        if ( $has_reviewed ) {
            return;
        }
    } else {
        if ( ! $is_tw_lem_admin_page ) {
            return;
        }

        $ready = tw_lem_should_show_rating_popup();
        if ( ! $ready ) {
            return;
        }
    }

    $js_file = TW_LEM_PLUGIN_DIR . 'assets/js/rating-popup.js';

    if ( ! file_exists( $js_file ) ) {
        return;
    }

    wp_enqueue_style(
        'tw-lem-rating-popup',
        TW_LEM_PLUGIN_URL . 'assets/css/rating-popup.css',
        array(),
        TW_LEM_PLUGIN_VERSION
    );

    wp_enqueue_script(
        'tw-lem-rating-popup',
        TW_LEM_PLUGIN_URL . 'assets/js/rating-popup.js',
        array( 'jquery' ),
        TW_LEM_PLUGIN_VERSION,
        true
    );

    $show_immediately = false;
    if ( ! $is_plugin_screen ) {
        $show_immediately = tw_lem_should_show_rating_popup();
    }

    wp_localize_script(
        'tw-lem-rating-popup',
        'tw_lem_rating_popup_vars',
        array(
            'ajaxUrl'                => admin_url( 'admin-post.php' ),
            'nonce'                  => wp_create_nonce( 'tw_lem_rating_popup_action' ),
            'feedbackNonce'          => wp_create_nonce( 'tw_lem_rating_feedback' ),
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            'sourcePage'             => isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '',
            'pluginBasename'         => TW_LEM_PLUGIN_BASENAME,
            'hasReviewed'            => (bool) get_option( 'tw_lem_rating_popup_reviewed', false ),
            'isPluginList'           => $is_plugin_screen,
            'showPopupImmediately'   => $show_immediately,
            'popupTitle'             => esc_html__( 'Rate Your Experience', 'tw-link-expiration-manager' ),
            'popupText'              => esc_html__( 'Please take a moment to rate the plugin and send feedback. This helps us improve the experience for everyone.', 'tw-link-expiration-manager' ),
            'deactivationPopupTitle' => esc_html__( 'Before You Deactivate', 'tw-link-expiration-manager' ),
            'deactivationPopupText'  => esc_html__( 'Before you go, please consider leaving a review. Or close this popup to continue deactivation.', 'tw-link-expiration-manager' ),
            'ratingLabel'            => esc_html__( 'Your Rating', 'tw-link-expiration-manager' ),
            'messageLabel'           => esc_html__( 'Write a Review (Optional)', 'tw-link-expiration-manager' ),
            'messagePlaceholder'     => esc_html__( 'Add any comments or suggestions here...', 'tw-link-expiration-manager' ),
            'consentLabel'           => esc_html__( 'I agree to send my review along with my site information (Site URL and admin email) to the plugin developer for feedback purposes.', 'tw-link-expiration-manager' ),
            'submitLabel'            => esc_html__( 'Submit Feedback', 'tw-link-expiration-manager' ),
            'closeLabel'             => esc_html__( 'Close', 'tw-link-expiration-manager' ),
            'ratingRequired'         => esc_html__( 'Please select a star rating before submitting.', 'tw-link-expiration-manager' ),
            'thankYouTitle'          => esc_html__( 'Thanks for your feedback!', 'tw-link-expiration-manager' ),
            'defaultError'           => esc_html__( 'Unable to submit feedback. Please try again.', 'tw-link-expiration-manager' ),
        )
    );
}

/**
 * Record rating popup events such as dismissals.
 */
function tw_lem_handle_rating_popup_recorded() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized access.', 'tw-link-expiration-manager' ) ) );
    }

    $nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'tw_lem_rating_popup_action' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Invalid request.', 'tw-link-expiration-manager' ) ) );
    }

    $event = isset( $_POST['event'] ) ? sanitize_text_field( wp_unslash( $_POST['event'] ) ) : '';
    if ( 'dismiss' === $event ) {
        update_option( 'tw_lem_rating_popup_last_dismissed', time() );
    }

    wp_send_json_success();
}

/**
 * Handle rating popup form submission.
 */
function tw_lem_handle_rating_feedback() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized access.', 'tw-link-expiration-manager' ) ) );
    }

    $nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'tw_lem_rating_feedback' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Invalid request.', 'tw-link-expiration-manager' ) ) );
    }

    $rating      = isset( $_POST['rating'] ) ? absint( wp_unslash( $_POST['rating'] ) ) : 0;
    $message     = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
    $source_page = isset( $_POST['source_page'] ) ? sanitize_text_field( wp_unslash( $_POST['source_page'] ) ) : '';

    if ( $rating < 1 || $rating > 5 ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Please select a rating between 1 and 5 stars.', 'tw-link-expiration-manager' ) ) );
    }

    update_option( 'tw_lem_rating_popup_reviewed', 1 );
    delete_option( 'tw_lem_rating_popup_last_dismissed' );

    $site_name    = get_bloginfo( 'name' );
    $site_url     = get_bloginfo( 'url' );
    $current_user = wp_get_current_user();
    $plugin_name  = tw_lem_get_plugin_name();

    $subject = sprintf(
        'New Rating Feedback Received via %s Plugin',
        $plugin_name
    );

    $body  = '<p>' . esc_html__( 'Dear TW Plugin Team,', 'tw-link-expiration-manager' ) . '</p>';
    $body .= '<p>' . esc_html__( 'We have received a new rating submission for', 'tw-link-expiration-manager' ) . ' <strong>' . esc_html( $plugin_name ) . '</strong>.</p>';
    $body .= '<ul style="list-style-type: disc; padding-left: 20px; margin: 0 0 14px">
        <li><strong>' . esc_html__( 'Site:', 'tw-link-expiration-manager' ) . '</strong> ' . esc_html( $site_name ) . ' (' . esc_url( $site_url ) . ')</li>
        <li><strong>' . esc_html__( 'Submitted By:', 'tw-link-expiration-manager' ) . '</strong> ' . esc_html( $current_user->display_name ) . ' (<a href="mailto:' . esc_attr( $current_user->user_email ) . '">' . esc_html( $current_user->user_email ) . '</a>)</li>
        <li><strong>' . esc_html__( 'Plugin Name:', 'tw-link-expiration-manager' ) . '</strong> ' . esc_html( $plugin_name ) . '</li>
        <li><strong>' . esc_html__( 'Rating:', 'tw-link-expiration-manager' ) . '</strong> ' . esc_html( $rating ) . ' / 5</li>';

    if ( $message ) {
        $body .= '<li><strong>' . esc_html__( 'Message:', 'tw-link-expiration-manager' ) . '</strong> ' . nl2br( esc_html( $message ) ) . '</li>';
    } else {
        $body .= '<li><strong>' . esc_html__( 'Message:', 'tw-link-expiration-manager' ) . '</strong> ' . esc_html__( 'No additional comments provided.', 'tw-link-expiration-manager' ) . '</li>';
    }

    $body .= '</ul>';
    $body .= '<p>' . esc_html__( 'Please review this feedback and take any necessary action as appropriate.', 'tw-link-expiration-manager' ) . '</p>';
    $body .= '<p>' . esc_html__( 'Thank you.', 'tw-link-expiration-manager' ) . '</p>';

    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        'Reply-To: ' . sanitize_email( $current_user->user_email ),
    );

    $support_email = 'pluginsupport@technologywisdom.com';
    $sent          = wp_mail( $support_email, $subject, $body, $headers );

    if ( ! $sent ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unable to send email. Please try again later.', 'tw-link-expiration-manager' ) ) );
    }

    wp_send_json_success( array( 'message' => esc_html__( 'Thank you for your feedback.', 'tw-link-expiration-manager' ) ) );
}

/**
 * Get the plugin name dynamically.
 */
function tw_lem_get_plugin_name() {
    if ( ! function_exists( 'get_plugins' ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $plugin_data = get_plugin_data( TW_LEM_PLUGIN_DIR . 'tw-link-expiration-manager.php' );

    if ( ! empty( $plugin_data['Name'] ) ) {
        return html_entity_decode( $plugin_data['Name'], ENT_QUOTES, 'UTF-8' );
    }

    return 'TW Link Expiration Manager';
}
