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

class AIIO_Lifecycle {

    const PURGE_FLAG_OPTION = 'aiio_pending_data_purge';

    public static function init() {
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_plugins_screen']);
        add_action('wp_ajax_aiio_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(AIIO_OPTION);
        delete_option(AIIO_JOB_OPTION);
        delete_transient('aiio_last_scan');
        self::delete_post_meta_by_prefix('_aiio_');
        self::delete_transients_by_prefix('aiio_');
        self::remove_uploads_subdir('pewit-ai-image-optimizer-backups');
        self::unschedule_cron();
    }

    public static function unschedule_cron() {
        wp_clear_scheduled_hook('aiio_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 . '%'
        ));
    }

    private static function remove_uploads_subdir($folder) {
        $upload = wp_get_upload_dir();
        $dir = trailingslashit($upload['basedir']) . $folder;
        if (!is_dir($dir)) {
            return;
        }
        self::recursive_rmdir($dir);
    }

    private static function recursive_rmdir($dir) {
        $dir = trailingslashit($dir);
        $items = @scandir($dir);
        if (!is_array($items)) {
            return;
        }
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }
            $path = $dir . $item;
            if (is_dir($path)) {
                self::recursive_rmdir($path);
            } else {
                wp_delete_file($path);
            }
        }
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Recursive uploads dir cleanup on uninstall.
        @rmdir(rtrim($dir, '/'));
    }

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

    private static function js_config() {
        return [
            'pluginId'   => plugin_basename(AIIO_FILE),
            'pluginName' => 'Pewit AI Image Optimizer',
            'ajax'       => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('aiio_deactivate_purge'),
            'action'     => 'aiio_set_deactivation_purge',
            'i18n'       => [
                'title'       => __('Deactivate Pewit AI Image Optimizer', 'pewit-ai-image-optimizer'),
                'message'     => __('What should happen to plugin data in the database?', 'pewit-ai-image-optimizer'),
                'keep'        => __('Keep settings & data', 'pewit-ai-image-optimizer'),
                'keepHint'    => __('Keeps compression settings and scan cache.', 'pewit-ai-image-optimizer'),
                'purge'       => __('Remove all plugin data', 'pewit-ai-image-optimizer'),
                'purgeHint'   => __('Deletes settings, _aiio_ meta and plugin backup copies. Original image files and names stay.', 'pewit-ai-image-optimizer'),
                'cancel'      => __('Cancel', 'pewit-ai-image-optimizer'),
                'deleteTitle' => __('Delete Pewit AI Image Optimizer', 'pewit-ai-image-optimizer'),
            ],
        ];
    }

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