<?php

namespace GriffinForms;

require_once __DIR__ . '/traits/singleton.php';
require_once __DIR__ . '/traits/maybedecode.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/settings.php';

class Uninstall
{
    /**
     * Drop custom database tables created by GriffinForms.
     */
    public function dropTables() {
        global $wpdb;
        $config = \GriffinForms\Config::getInstance();
        $tables = $config->getTables();

        foreach ($tables as $table) {
            if (strpos($table, $wpdb->prefix . 'griffinforms_') === 0) {
                $wpdb->query($wpdb->prepare("DROP TABLE IF EXISTS %i", $table));
            }
        }
    }

    /**
     * Delete options and settings from wp_options.
     */
    public function deleteOptions() {
        $settings = \GriffinForms\Settings::getInstance();
        foreach ($settings->getAllOptionNames() as $option_name) {
            delete_option($option_name);
        }
    }

    /**
     * Delete migration and backfill markers that are not registered in Settings
     * but must be cleared so a reinstall on the same database starts clean.
     */
    public function deleteMarkers() {
        delete_option('griffinforms_db_migrations_version');
        delete_option('griffinforms_lifetime_submission_count_backfilled');
        delete_option('griffinforms_form_element_form_id_backfilled');
        delete_option('griffinforms_form_element_form_id_backfill_last_id');
        delete_option('griffinforms_submission_history_backfilled');
    }

    /**
     * Entry point to run all uninstall routines.
     */
    public function run() {
        $settings = \GriffinForms\Settings::getInstance();
        $should_delete = $settings->getOption('delete_data_on_uninstall');

        if (!empty($should_delete)) {
            $this->dropTables();
            $this->deleteOptions();
            $this->deleteMarkers();
        }
    }
}

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

// Run the uninstall process
(new Uninstall())->run();