<?php

namespace GriffinForms;

/**
 * Handles installation tasks for the GriffinForms plugin,
 * including table creation, initial data setup, and post-activation redirection.
 */
class Install
{
    /**
     * Performs plugin installation tasks on activation.
     *
     * @return void
     */
    public function install()
    {
        try {
            // Set up required database tables
            $db = new Db();
            $db->setupTables();

            // Add default plugin data
            $install_data = new InstallData();
            $install_data->addData();

            // Prepare reusable preview page for frontend iframe previews.
            try {
                $preview_page = \GriffinForms\Includes\Onboarding\PreviewPage::getInstance();
                $preview_page->ensurePage();
            } catch (\Throwable $ignored) {
                // Preview page creation is best-effort and must never block activation.
            }

            // Set flag for redirecting after activation
            add_option('griffinforms_activation_redirect', true);
        } catch (\Throwable $e) {
            // Surface failure in PHP error log and native log (if available)
            if (function_exists('error_log')) {
                error_log('GriffinForms install error: ' . $e->getMessage());
            }
            if (class_exists('\\GriffinForms\\Log')) {
                try {
                    $log = \GriffinForms\Log::getInstance();
                    $log->add('error', 'install', 0, 0, 'Install failed: ' . $e->getMessage(), 'install');
                } catch (\Throwable $ignored) {
                    // Never block activation with secondary failures
                }
            }
        }
    }

    /**
     * Redirects user to GriffinForms landing page after plugin activation.
     *
     * @return void
     */
    public function redirectOnActivation()
    {
        if (get_option('griffinforms_activation_redirect')) {
            delete_option('griffinforms_activation_redirect');

            // Avoid redirect on multi-plugin activation
            if (!isset($_GET['activate-multi'])) {
                $eligibility = \GriffinForms\Includes\Onboarding\Eligibility::getInstance();
                $feature_flags = \GriffinForms\Includes\Onboarding\FeatureFlags::getInstance();
                $redirect_url = $feature_flags->getFormsPageUrl();

                if ($eligibility->shouldRedirectToOnboarding()) {
                    $redirect_url = $feature_flags->getOnboardingPageUrl([
                        'entry_source' => 'activation_redirect',
                    ]);
                }

                wp_safe_redirect($redirect_url);
                exit;
            }
        }
    }
}
