<?php

if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
   error_log( 'EWZ: Attempt to uninstall without WP_UNINSTALL_PLUGIN defined' );
   exit();
}
if ( ! current_user_can( 'activate_plugins' ) ){
   exit();
}

global $wpdb;

$prefix = $wpdb->prefix;

define( 'EWZ_LAYOUT_TABLE', $prefix . 'ewz_layout' );
define( 'EWZ_FIELD_TABLE', $prefix . 'ewz_field' );
define( 'EWZ_WEBFORM_TABLE', $prefix . 'ewz_webform' );
define( 'EWZ_ITEM_TABLE', $prefix . 'ewz_item' );

error_log( 'EWZ: ********  uninstalling EntryWizard *********' );

// the ewz_del_imgs_on_uninst option will be deleted, so save its value
$do_clean_imgs = get_option('ewz_del_imgs_on_uninst');

error_log( 'EWZ: deleting all entrywizard tables and data from database');

$layout_table = EWZ_LAYOUT_TABLE;
$field_table = EWZ_FIELD_TABLE;
$webform_table = EWZ_WEBFORM_TABLE;
$item_table = EWZ_ITEM_TABLE;


if ( $wpdb->get_var( "SHOW TABLES LIKE '$item_table'" ) == $item_table ) {           // no tainted data
    $wpdb->query( "DROP TABLE $item_table" );                                        // no tainted data
    if( $wpdb->last_error ){ throw new Exception("DB Error " . $wpdb->last_error ); }
}
if ( $wpdb->get_var( "SHOW TABLES LIKE '$field_table'" ) == $field_table ) {           // no tainted data
    $wpdb->query( "DROP TABLE $field_table" );                                        // no tainted data
    if( $wpdb->last_error ){ throw new Exception("DB Error " . $wpdb->last_error ); }
}
if ( $wpdb->get_var( "SHOW TABLES LIKE '$webform_table'" ) == $webform_table ) {           // no tainted data
    $wpdb->query( "DROP TABLE  $webform_table" );                                        // no tainted data
    if( $wpdb->last_error ){ throw new Exception("DB Error " . $wpdb->last_error ); }
}
if ( $wpdb->get_var( "SHOW TABLES LIKE '$layout_table'" ) == $layout_table ) {            // no tainted data
    $wpdb->query( "DROP TABLE $layout_table" );                                        // no tainted data
    if( $wpdb->last_error ){ throw new Exception("DB Error " . $wpdb->last_error ); }
}


$meta_rows = $wpdb->get_results( 'SELECT umeta_id, meta_key FROM ' . $wpdb->usermeta . " WHERE meta_key LIKE 'ewz_%'" ); //for deletion no tainted data
foreach ( $meta_rows as $meta_row ) {
    if( ( $meta_row->meta_key == 'ewz_itemsperpage' ) || ( strpos( $meta_row->meta_key, 'ewz_can_' ) === 0 ) ){
        delete_metadata_by_mid( 'user', $meta_row->umeta_id );
    }
}

// Dont rely on just 'ewz_' in case another plugin uses it
$options = $wpdb->get_col( 'SELECT option_name FROM ' . $wpdb->options . " WHERE option_name LIKE 'ewz_%'" ); //for deletion no tainted data

foreach ( $options as $option_name ) {
    $ewz_options = array(
                          'ewz_attach_img_comment',
                          'ewz_attach_img_size',
                          'ewz_attach_jpeg_qual',
                          'ewz_csv_ascii',
                          'ewz_cs_warn',
                          'ewz_curr_stored_txt',
                          'ewz_data_version',
                          'ewz_del_data_on_uninst',
                          'ewz_del_imgs_on_uninst',
                          'ewz_gen_ssheet_on_close',
                          'ewz_margin',
                          'ewz_show_auto_close',
                          'ewz_show_auto_open',
                          'ewz_show_title_if_closed',
                          'ewz_spec_char_replace',
                          'ewz_terminal_underscore',
                          'ewz_ss_usr_labels',
                          'ewz_upload_closed_txt',
                          'ewz_webform_alias',
                          'ewz_will_close_txt',
                          'ewz_will_open_txt',
                        );
    // also delete attachment options saved for individual webforms
    if( in_array( $option_name, $ewz_options ) || preg_match( '/^ewz_[0-9]+_/', $option_name ) ){
        delete_option( $option_name );
    }
}


// all ewz options now gone from db

if( $do_clean_imgs ){
    error_log( 'EWZ: deleting uploaded images');

    $updir_arr = wp_upload_dir();
    $ewzdir = $updir_arr['basedir'] . '/ewz_img_uploads';
    ewz_rrmdir( $ewzdir );
}

/**
 * Recursively remove a directory
 *
 * @param string $dir  the directory to be removed
 *
 * @return void
 */
function ewz_rrmdir( $dir ) {
    error_log( "EWZ: removing directory $dir" );
    if ( is_dir( $dir ) ) {
        $objects = scandir( $dir );
        foreach ( $objects as $object ) {
            if ( $object != "." && $object != ".." ) {
                if ( filetype( $dir . "/" . $object ) == "dir" ) {
                    ewz_rrmdir( $dir . "/" . $object );
                } else {
                    unlink( $dir . "/" . $object );
                }
            }
        }
        reset( $objects );
        rmdir( $dir );
    }
}
