<?php
/**
 * Deactivation feedback (Plugins screen) and api.maca.se reporting.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/maca-api.php';

/**
 * Allowed deactivation feedback reason keys (UI labels).
 *
 * @return array<string, string>
 */
function maca_menulist_deactivation_feedback_reasons() {
    return array(
        'missing_feature' => __('Missing a feature I need', 'maca-restu-pro'),
        'hard_to_use'     => __('Too difficult to set up or use', 'maca-restu-pro'),
        'bug'             => __('Something is broken or not working', 'maca-restu-pro'),
        'switching'       => __('Switching to another solution', 'maca-restu-pro'),
        'temporary'       => __('Only needed temporarily / testing', 'maca-restu-pro'),
        'other'           => __('Other', 'maca-restu-pro'),
    );
}

/**
 * English reason labels for API telemetry.
 *
 * @return array<string, string>
 */
function maca_menulist_deactivation_feedback_api_labels() {
    return array(
        'missing_feature' => 'Missing a feature I need',
        'hard_to_use'     => 'Too difficult to set up or use',
        'bug'             => 'Something is broken or not working',
        'switching'       => 'Switching to another solution',
        'temporary'       => 'Only needed temporarily / testing',
        'other'           => 'Other',
    );
}

/**
 * Handle AJAX deactivation report before redirect to deactivate URL.
 *
 * @return void
 */
function maca_menulist_handle_deactivation_feedback() {
    check_ajax_referer('maca_restu_deactivation_feedback', 'nonce');

    if (!current_user_can('activate_plugins')) {
        wp_send_json_error(array('message' => 'Forbidden'), 403);
    }

    $reasons = maca_menulist_deactivation_feedback_api_labels();
    $reason  = isset($_POST['reason']) ? sanitize_key(wp_unslash($_POST['reason'])) : '';
    $details = isset($_POST['details']) ? sanitize_textarea_field(wp_unslash($_POST['details'])) : '';
    $extra   = array();

    if ($reason !== '' && isset($reasons[$reason])) {
        $extra['reason']       = $reason;
        $extra['reason_label'] = $reasons[$reason];
        if ($details !== '') {
            $extra['details'] = $details;
        }
    }

    if (maca_restu_api_send_event('deactivated', $extra, true)) {
        maca_restu_api_mark_deactivated_reported();
    }

    wp_send_json_success();
}

add_action('wp_ajax_maca_restu_deactivation_feedback', 'maca_menulist_handle_deactivation_feedback');
