<?php
if (!defined('ABSPATH')) exit;

class AIVT_Lifecycle {

    const PURGE_FLAG_OPTION = 'aivt_pending_data_purge';

    public static function init() {
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_plugins_screen']);
        add_action('wp_ajax_aivt_set_deactivation_purge', [__CLASS__, 'ajax_set_purge_flag']);
    }

    public static function on_deactivate() {
        self::unschedule_cron();
        if (get_option(self::PURGE_FLAG_OPTION)) {
            self::purge_all_data();
            delete_option(self::PURGE_FLAG_OPTION);
        }
    }

    public static function on_uninstall() {
        if (get_option(self::PURGE_FLAG_OPTION)) {
            self::purge_all_data();
            delete_option(self::PURGE_FLAG_OPTION);
        }
    }

    public static function purge_all_data() {
        self::delete_options_by_prefix('aivt_');
        self::delete_post_meta_by_prefix('_aivt_');
        self::delete_transients_by_prefix('aivt_');
        self::unschedule_cron();
    }

    private static function delete_options_by_prefix($prefix) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off cleanup of all plugin options; value prepared, results not cacheable.
        $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $wpdb->esc_like($prefix) . '%'
        ));
    }

    public static function unschedule_cron() {
        wp_clear_scheduled_hook('aivt_process_queue');
        wp_clear_scheduled_hook('aivt_prompt_monitor');
    }

    private static function delete_post_meta_by_prefix($prefix) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off uninstall cleanup; values prepared, results not cacheable.
        $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
            $wpdb->esc_like($prefix) . '%'
        ));
    }

    private static function delete_transients_by_prefix($prefix) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off uninstall cleanup; values prepared, results not cacheable.
        $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
            '_transient_' . $prefix . '%',
            '_transient_timeout_' . $prefix . '%'
        ));
    }

    public static function enqueue_plugins_screen($hook) {
        if ($hook !== 'plugins.php') {
            return;
        }
        wp_enqueue_style('aivt-deactivate-prompt', AIVT_URL . 'assets/css/deactivate-prompt.css', [], AIVT_VERSION);
        wp_enqueue_script('aivt-deactivate-prompt', AIVT_URL . 'assets/js/deactivate-prompt.js', ['jquery'], AIVT_VERSION, true);
        wp_localize_script('aivt-deactivate-prompt', 'AIVT_DeactivatePrompt', self::js_config());
    }

    private static function js_config() {
        return [
            'pluginId'   => plugin_basename(AIVT_FILE),
            'pluginName' => 'Pewit GEO Analysis Tool',
            'ajax'       => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('aivt_deactivate_purge'),
            'action'     => 'aivt_set_deactivation_purge',
            'i18n'       => [
                'title'       => __('Deactivate GEO Analysis Tool', 'pewit-geo-analysis-tool'),
                'message'     => __('What should happen to plugin data in the database?', 'pewit-geo-analysis-tool'),
                'keep'        => __('Keep settings & data', 'pewit-geo-analysis-tool'),
                'keepHint'    => __('Keeps saved analyses in post meta until you remove them manually.', 'pewit-geo-analysis-tool'),
                'purge'       => __('Remove all plugin data', 'pewit-geo-analysis-tool'),
                'purgeHint'   => __('Deletes settings, jobs and _aivt_ analysis meta. Post content stays.', 'pewit-geo-analysis-tool'),
                'cancel'      => __('Cancel', 'pewit-geo-analysis-tool'),
                'deleteTitle' => __('Delete GEO Analysis Tool', 'pewit-geo-analysis-tool'),
            ],
        ];
    }

    public static function ajax_set_purge_flag() {
        check_ajax_referer('aivt_deactivate_purge', 'nonce');
        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-geo-analysis-tool')], 403);
        }
        update_option(self::PURGE_FLAG_OPTION, 1, false);
        wp_send_json_success();
    }
}
