<?php
/**
 * Fired during plugin deactivation.
 *
 * @package Inqyra
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

/**
 * Plugin deactivator class.
 */
class Inqyra_Deactivator {

    /**
     * Runs during plugin deactivation.
     *
     * Note: We don't delete tables or data on deactivation.
     * Data is only removed on uninstall (see uninstall.php).
     */
    public static function deactivate() {
        // Clear scheduled cron events
        self::clear_cron_events();

        // Clear transients
        self::clear_transients();

        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Clear all scheduled cron events.
     */
    private static function clear_cron_events() {
        // Remove embedding processing event
        $timestamp = wp_next_scheduled('inqyra_process_embeddings');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'inqyra_process_embeddings');
        }

        // Remove conversation archiving event
        $timestamp = wp_next_scheduled('inqyra_archive_conversations');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'inqyra_archive_conversations');
        }
    }

    /**
     * Clear all plugin transients.
     */
    private static function clear_transients() {
        global $wpdb;

        // Delete all transients starting with 'inqyra_'
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table from $wpdb->options, LIKE patterns are hardcoded.
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM %i WHERE option_name LIKE %s OR option_name LIKE %s",
                $wpdb->options,
                '_transient_inqyra_%',
                '_transient_timeout_inqyra_%'
            )
        );
    }
}
