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

class AISB_Lifecycle {

    const PURGE_FLAG_OPTION = 'aisb_pending_data_purge';

    public static function init() {
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_plugins_screen']);
        add_action('wp_ajax_aisb_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() {
        delete_option(AISB_OPTION);
        delete_option(AISB_JOB_OPTION);
        self::delete_post_meta_by_prefix('_aisb_');
        self::delete_transients_by_prefix('aisb_');
        self::unschedule_cron();
    }

    public static function unschedule_cron() {
        wp_clear_scheduled_hook('aisb_process_queue');
    }

    private static function delete_post_meta_by_prefix($prefix) {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query on core tables; values prepared, results not cacheable here.
        $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 -- Direct query on core tables; values prepared, results not cacheable here.
        $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('aisb-deactivate-prompt', AISB_URL . 'assets/css/deactivate-prompt.css', [], AISB_VERSION);
        wp_enqueue_script('aisb-deactivate-prompt', AISB_URL . 'assets/js/deactivate-prompt.js', ['jquery'], AISB_VERSION, true);
        wp_localize_script('aisb-deactivate-prompt', 'AISB_DeactivatePrompt', self::js_config());
    }

    private static function js_config() {
        return [
            'pluginId'   => plugin_basename(AISB_FILE),
            'pluginName' => 'Pewit AI Schema Builder',
            'ajax'       => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('aisb_deactivate_purge'),
            'action'     => 'aisb_set_deactivation_purge',
            'i18n'       => [
                'title'       => __('Deactivate Pewit AI Schema Builder', 'pewit-ai-schema-builder'),
                'message'     => __('What should happen to plugin data in the database?', 'pewit-ai-schema-builder'),
                'keep'        => __('Keep settings & data', 'pewit-ai-schema-builder'),
                'keepHint'    => __('Keeps saved JSON-LD in post meta until you remove it manually.', 'pewit-ai-schema-builder'),
                'purge'       => __('Remove all plugin data', 'pewit-ai-schema-builder'),
                'purgeHint'   => __('Deletes settings, jobs and _aisb_ schema meta. Post content and filenames stay.', 'pewit-ai-schema-builder'),
                'cancel'      => __('Cancel', 'pewit-ai-schema-builder'),
                'deleteTitle' => __('Delete Pewit AI Schema Builder', 'pewit-ai-schema-builder'),
            ],
        ];
    }

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