<?php
/**
 * Theme Deactivation Feedback Modal
 *
 * Shows a feedback modal when user switches away from MediHealth theme.
 *
 * @package MediHealth WordPress theme
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Enqueue deactivation feedback scripts and styles
 */
function medihealth_deactivation_feedback_scripts( $hook ) {
    // Only load on themes page.
    if ( 'themes.php' !== $hook ) {
        return;
    }

    // Only load if MediHealth is the active theme.
    $current_theme = wp_get_theme();
    if ( 'MediHealth' !== $current_theme->get( 'Name' ) && 'medihealth' !== $current_theme->get_template() ) {
        return;
    }

    // Only load for users who can switch themes.
    if ( ! current_user_can( 'switch_themes' ) ) {
        return;
    }

    // Enqueue CSS.
    wp_enqueue_style(
        'medihealth-deactivation-feedback',
        get_template_directory_uri() . '/css/deactivation-feedback.css',
        array(),
        wp_get_theme()->get( 'Version' )
    );

    // Enqueue JS.
    wp_enqueue_script(
        'medihealth-deactivation-feedback',
        get_template_directory_uri() . '/js/deactivation-feedback.js',
        array( 'jquery' ),
        wp_get_theme()->get( 'Version' ),
        true
    );

    // Localize script.
    wp_localize_script(
        'medihealth-deactivation-feedback',
        'medihealthDeactivation',
        array(
            'nonce'     => wp_create_nonce( 'medihealth_deactivation_feedback' ),
            'ajaxurl'   => admin_url( 'admin-ajax.php' ),
            'themeName' => 'MediHealth',
        )
    );
}
add_action( 'admin_enqueue_scripts', 'medihealth_deactivation_feedback_scripts' );

/**
 * Output the deactivation feedback modal HTML
 */
function medihealth_deactivation_feedback_modal() {
    // Only on themes page.
    $screen = get_current_screen();
    if ( ! $screen || 'themes' !== $screen->id ) {
        return;
    }

    // Only if MediHealth is active.
    $current_theme = wp_get_theme();
    if ( 'MediHealth' !== $current_theme->get( 'Name' ) && 'medihealth' !== $current_theme->get_template() ) {
        return;
    }

    // Only for users who can switch themes.
    if ( ! current_user_can( 'switch_themes' ) ) {
        return;
    }
    ?>
    <div id="medihealth-deactivation-modal" class="medihealth-modal-overlay" style="display: none;">
        <div class="medihealth-modal">
            <button type="button" class="medihealth-modal-close" aria-label="<?php esc_attr_e( 'Close', 'medihealth' ); ?>">&times;</button>
            
            <div class="medihealth-modal-header">
                <h2><?php esc_html_e( 'Quick Feedback', 'medihealth' ); ?></h2>
                <p><?php esc_html_e( 'We\'re sorry to see you go! Could you please share why you\'re switching themes?', 'medihealth' ); ?></p>
            </div>
            
            <form id="medihealth-deactivation-form" class="medihealth-modal-body">
                <div class="medihealth-feedback-options">
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="found_better">
                        <span><?php esc_html_e( 'I found a better theme', 'medihealth' ); ?></span>
                    </label>
                    
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="missing_features">
                        <span><?php esc_html_e( 'The theme is missing features I need', 'medihealth' ); ?></span>
                    </label>
                    
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="hard_to_customize">
                        <span><?php esc_html_e( 'The theme is difficult to customize', 'medihealth' ); ?></span>
                    </label>
                    
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="technical_issues">
                        <span><?php esc_html_e( 'I\'m experiencing technical issues', 'medihealth' ); ?></span>
                    </label>
                    
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="temporary">
                        <span><?php esc_html_e( 'Temporary deactivation, I\'ll be back', 'medihealth' ); ?></span>
                    </label>
                    
                    <label class="medihealth-feedback-option">
                        <input type="radio" name="deactivation_reason" value="other">
                        <span><?php esc_html_e( 'Other', 'medihealth' ); ?></span>
                    </label>
                </div>
                
                <div class="medihealth-feedback-details" style="display: none;">
                    <label for="medihealth-feedback-text"><?php esc_html_e( 'Please share more details (optional):', 'medihealth' ); ?></label>
                    <textarea id="medihealth-feedback-text" name="feedback_text" rows="3" placeholder="<?php esc_attr_e( 'What features are missing? What issues did you face?', 'medihealth' ); ?>"></textarea>
                </div>
                
                <input type="hidden" id="medihealth-new-theme-url" name="new_theme_url" value="">
            </form>
            
            <div class="medihealth-modal-footer">
                <p class="medihealth-feedback-note">
                    <?php 
                    printf(
                        /* translators: %s: developer email address */
                        esc_html__( 'Note: If feedback submission fails, please email us directly at %s', 'medihealth' ),
                        '<a href="mailto:support@awplife.com">support@awplife.com</a>'
                    );
                    ?>
                </p>
                <div class="medihealth-modal-buttons">
                    <button type="button" class="button medihealth-skip-btn"><?php esc_html_e( 'Skip & Deactivate', 'medihealth' ); ?></button>
                    <button type="button" class="button button-primary medihealth-submit-btn"><?php esc_html_e( 'Submit & Deactivate', 'medihealth' ); ?></button>
                </div>
            </div>
        </div>
    </div>
    <?php
}
add_action( 'admin_footer', 'medihealth_deactivation_feedback_modal' );

/**
 * AJAX handler for deactivation feedback submission
 */
function medihealth_submit_deactivation_feedback() {
    // Verify nonce.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'medihealth_deactivation_feedback' ) ) {
        wp_send_json_error( 'Security check failed' );
    }

    // Check capability.
    if ( ! current_user_can( 'switch_themes' ) ) {
        wp_send_json_error( 'Unauthorized' );
    }

    // Get feedback data.
    $reason       = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';
    $feedback     = isset( $_POST['feedback'] ) ? sanitize_textarea_field( wp_unslash( $_POST['feedback'] ) ) : '';
    $site_url     = home_url();
    $wp_version   = get_bloginfo( 'version' );
    $theme_version = wp_get_theme()->get( 'Version' );

    // Map reason codes to readable text.
    $reason_labels = array(
        'found_better'      => 'Found a better theme',
        'missing_features'  => 'Missing features needed',
        'hard_to_customize' => 'Difficult to customize',
        'technical_issues'  => 'Technical issues',
        'temporary'         => 'Temporary deactivation',
        'other'             => 'Other reason',
    );

    $reason_text = isset( $reason_labels[ $reason ] ) ? $reason_labels[ $reason ] : $reason;

    // Prepare email content.
    $to      = 'support@awplife.com';
    $subject = 'MediHealth Theme Deactivation Feedback';
    
    $message = "A user has deactivated the MediHealth theme.\n\n";
    $message .= "=== Deactivation Details ===\n\n";
    $message .= "Reason: {$reason_text}\n";
    
    if ( ! empty( $feedback ) ) {
        $message .= "Additional Feedback: {$feedback}\n";
    }
    
    $message .= "\n=== Site Information ===\n\n";
    $message .= "Site URL: {$site_url}\n";
    $message .= "WordPress Version: {$wp_version}\n";
    $message .= "Theme Version: {$theme_version}\n";
    $message .= "Date/Time: " . current_time( 'mysql' ) . "\n";

    $headers = array( 'Content-Type: text/plain; charset=UTF-8' );
    
    // Send email to theme author
    $sent = wp_mail( $to, $subject, $message, $headers );

    // Always return success so user can proceed with deactivation
    wp_send_json_success( array( 'message' => 'Thank you for your feedback!' ) );
}
add_action( 'wp_ajax_medihealth_deactivation_feedback', 'medihealth_submit_deactivation_feedback' );
