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

// If uninstall not called from WordPress, then exit.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Load plugin file for access to constants
require_once plugin_dir_path(__FILE__) . 'spai-contact-form.php';

// Load database handler
require_once SPAI_CONTACT_FORM_PLUGIN_DIR . 'includes/core/class-spai-db-handler.php';

// Initialize database handler
$db_handler = new SPAI_DB_Handler();

// Drop plugin tables
$db_handler->drop_tables();

// Delete plugin options
delete_option('spai_contact_form_version');
delete_option('spai_contact_form_settings');
delete_option('spai_contact_form_monday_settings');
delete_option('spai_contact_form_salespartner_settings');
delete_option('spai_contact_form_forms');
delete_option('spai_contact_form_field_mappings');

// Delete user meta
delete_metadata('user', 0, 'spai_contact_form_preferences', '', true);

// Remove uploaded files directory
$upload_dir = wp_upload_dir();
$spai_upload_dir = $upload_dir['basedir'] . '/' . SPAI_CONTACT_FORM_UPLOAD_DIR;

if (file_exists($spai_upload_dir)) {
    spai_rmdir_recursive($spai_upload_dir);
}

/**
 * Recursively remove directory
 */
function spai_rmdir_recursive($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (is_dir($dir . "/" . $object)) {
                    spai_rmdir_recursive($dir . "/" . $object);
                } else {
                    unlink($dir . "/" . $object);
                }
            }
        }
        rmdir($dir);
    }
}
