<?php
/**
 * Maple Carts Uninstall
 *
 * Removes all plugin data when uninstalled.
 *
 * @package MapleCarts
 */

// Exit if accessed directly or not uninstalling.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

global $wpdb;

// Delete options.
delete_option( 'maple_carts_settings' );
delete_option( 'maple_carts_version' );

// Drop custom tables.
$tables = [
    $wpdb->prefix . 'maple_carts_email_log',
    $wpdb->prefix . 'maple_carts_emails',
    $wpdb->prefix . 'maple_carts',
];

foreach ( $tables as $table ) {
    $wpdb->query( "DROP TABLE IF EXISTS {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}

// Delete coupons created by this plugin.
$coupon_ids = $wpdb->get_col(
    "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_maple_carts_coupon' AND meta_value = '1'"
);

foreach ( $coupon_ids as $coupon_id ) {
    wp_delete_post( $coupon_id, true );
}

// Clear scheduled events.
wp_clear_scheduled_hook( 'maple_carts_send_emails' );
wp_clear_scheduled_hook( 'maple_carts_cleanup' );
