<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * @package LolaCoreForBricks
 */

declare(strict_types=1);

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

global $wpdb;

if (class_exists(\LolaCoreForBricks\Index\IndexSchema::class)) {
    \LolaCoreForBricks\Index\IndexSchema::drop();
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Uninstall must purge prefixed options and transients directly.
$lolacore_for_bricks_option_rows = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
        $wpdb->esc_like('lolacore_bricks_') . '%'
    )
);

if (is_array($lolacore_for_bricks_option_rows)) {
    foreach ($lolacore_for_bricks_option_rows as $lolacore_for_bricks_option_name) {
        delete_option((string) $lolacore_for_bricks_option_name);
    }
}

$lolacore_for_bricks_transient_rows = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        $wpdb->esc_like('_transient_lolacore_bricks_') . '%',
        $wpdb->esc_like('_transient_timeout_lolacore_bricks_') . '%'
    )
);

if (is_array($lolacore_for_bricks_transient_rows)) {
    foreach ($lolacore_for_bricks_transient_rows as $lolacore_for_bricks_transient_name) {
        $lolacore_for_bricks_transient_key = (string) $lolacore_for_bricks_transient_name;
        if (str_starts_with($lolacore_for_bricks_transient_key, '_transient_timeout_')) {
            continue;
        }

        $lolacore_for_bricks_transient_option = str_replace('_transient_', '', $lolacore_for_bricks_transient_key);
        delete_transient($lolacore_for_bricks_transient_option);
    }
}
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
