<?php
/**
 * Uninstall script for Bookaro.
 * Removes all database tables, options, transients and user meta
 * created by the plugin.
 */

defined( 'ABSPATH' ) || exit;

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

// Respect data retention setting (default: keep data).
$bookaro_settings = get_option( 'bookaro_settings', [] );
$bookaro_delete_data = ! empty( $bookaro_settings['delete_data_on_uninstall'] );

global $wpdb;

// Clear scheduled events.
wp_clear_scheduled_hook( 'bookaro_auto_complete' );
wp_clear_scheduled_hook( 'bookaro_send_reminder' );
wp_clear_scheduled_hook( 'bookaro_send_review_invite' );
wp_clear_scheduled_hook( 'bookaro_notification_log_cleanup' );
wp_clear_scheduled_hook( 'bookaro_logfile_cleanup' );

// Remove transients created by the plugin.
$bookaro_option_like  = '_transient_bookaro_%';
$bookaro_timeout_like = '_transient_timeout_bookaro_%';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$bookaro_transients = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        $bookaro_option_like,
        $bookaro_timeout_like
    )
);
foreach ( $bookaro_transients as $bookaro_transient ) {
    $bookaro_name = preg_replace( '/^_transient_(timeout_)?/', '', $bookaro_transient );
    delete_transient( $bookaro_name );
}

// Clear per-user cached availability transients.
$bookaro_users = get_users( [ 'fields' => 'ids' ] );
foreach ( $bookaro_users as $bookaro_uid ) {
    delete_transient( 'bookaro_avail_weekly_' . $bookaro_uid );
    delete_transient( 'bookaro_timeslots_' . $bookaro_uid );
    delete_transient( 'bookaro_exceptions_' . $bookaro_uid );
}

// Respect data retention setting (default: keep data).
if ( ! $bookaro_delete_data ) {
    return;
}

// Tables created by the plugin.
$bookaro_tables = [
    $wpdb->prefix . 'bookaro_bookings',
    $wpdb->prefix . 'bookaro_provider_availability',
    $wpdb->prefix . 'bookaro_provider_timeslots',
    $wpdb->prefix . 'bookaro_provider_exceptions',
    $wpdb->prefix . 'bookaro_notification_logs',
];
foreach ( $bookaro_tables as $bookaro_table ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $wpdb->query( "DROP TABLE IF EXISTS {$bookaro_table}" );
}

// Remove Bookaro post types and their meta.
$bookaro_post_types = [
    'bookaro_provider',
    'bookaro_service',
];
foreach ( $bookaro_post_types as $bookaro_post_type ) {
    $bookaro_posts = get_posts( [
        'post_type'      => $bookaro_post_type,
        'post_status'    => 'any',
        'posts_per_page' => -1,
        'fields'         => 'ids',
    ] );
    foreach ( $bookaro_posts as $bookaro_post_id ) {
        wp_delete_post( $bookaro_post_id, true );
    }
}
$bookaro_post_meta_keys = [
    'bookaro_provider_email',
    'bookaro_provider_phone',
    'bookaro_service_label',
    'bookaro_service_description',
    'bookaro_service_price',
    'bookaro_service_duration',
    'bookaro_service_duration_minutes',
    'bookaro_service_listing_id',
    'bookaro_service_owner_type',
    'bookaro_service_provider_id',
    'bookaro_service_scope',
    'bookaro_service_shared',
    'bookaro_service_is_shared',
];
foreach ( $bookaro_post_meta_keys as $bookaro_meta_key ) {
    delete_post_meta_by_key( $bookaro_meta_key );
}

// Plugin options.
$bookaro_option_keys = [
    'bookaro_settings',
    'bookaro_status',
    'bookaro_review_settings',
    'bookaro_version',
    'bookaro_db_version',
    'bookaro_services_cache_version',
    'bookaro_review_invite_delay',
    'bookaro_review_invite_subject',
    'bookaro_review_invite_body',
];
foreach ( $bookaro_option_keys as $bookaro_key ) {
    delete_option( $bookaro_key );
    delete_site_option( $bookaro_key );
}

// Remove Bookaro capabilities from roles that may have been granted access.
$bookaro_caps = [
    'bookaro_provider',
    'bookaro_customer',
];
if ( function_exists( 'wp_roles' ) ) {
    $bookaro_roles = wp_roles();
    if ( $bookaro_roles && is_array( $bookaro_roles->roles ) ) {
        foreach ( array_keys( $bookaro_roles->roles ) as $bookaro_role_key ) {
            $bookaro_role = $bookaro_roles->get_role( $bookaro_role_key );
            if ( ! $bookaro_role ) {
                continue;
            }
            foreach ( $bookaro_caps as $bookaro_cap ) {
                if ( $bookaro_role->has_cap( $bookaro_cap ) ) {
                    $bookaro_role->remove_cap( $bookaro_cap );
                }
            }
        }
    }
}

// Remove plugin-created roles.
if ( function_exists( 'remove_role' ) ) {
    remove_role( 'bookaro_provider' );
    remove_role( 'bookaro_customer' );
}

// Delete user meta for all users (Lite-only keys).
$bookaro_meta_keys = [
    'bookaro_slots_per_interval',
    'bookaro_viewed_exceptions',
];
foreach ( $bookaro_users as $bookaro_uid ) {
    foreach ( $bookaro_meta_keys as $bookaro_meta_key ) {
        delete_user_meta( $bookaro_uid, $bookaro_meta_key );
    }
}
