<?php
/**
 * Plugin Name: EarthPure Setup Wizard
 * Plugin URI:  https://earthpure.net
 * Description: Installatiewizard voor het EarthPure theme. Stel plugins, paginas, PayPal en instellingen in via een stapsgewijze wizard.
 * Version:     1.0.0
 * Author:      EarthPure
 * Text Domain: earthpure-wizard
 * License:     GPL v2 or later
 */

if ( ! defined( 'ABSPATH' ) ) exit;

define( 'EPW_VERSION', '1.0.0' );
define( 'EPW_DIR', plugin_dir_path( __FILE__ ) );
define( 'EPW_URL', plugin_dir_url( __FILE__ ) );

/* =============================================
   ADMIN MENU
   ============================================= */
add_action( 'admin_menu', 'epw_admin_menu' );
function epw_admin_menu() {
    add_menu_page(
        'EarthPure Setup',
        '🌿 EP Setup Wizard',
        'manage_options',
        'earthpure-wizard',
        'epw_wizard_page',
        'dashicons-superhero',
        2
    );
}

/* =============================================
   ENQUEUE WIZARD STYLES
   ============================================= */
add_action( 'admin_enqueue_scripts', 'epw_enqueue' );
function epw_enqueue( $hook ) {
    if ( strpos($hook, 'earthpure-wizard') === false ) return;
    wp_enqueue_style( 'epw-style', EPW_URL . 'wizard.css', [], EPW_VERSION );
    wp_enqueue_script( 'epw-script', EPW_URL . 'wizard.js', ['jquery'], EPW_VERSION, true );
    wp_localize_script( 'epw-script', 'epwData', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('epw_nonce'),
    ]);
}

/* =============================================
   WIZARD PAGE HTML
   ============================================= */
function epw_wizard_page() {
    $step    = intval( $_GET['step'] ?? 1 );
    $done    = get_option('epw_completed_steps', []);
    $total   = 5;
    $percent = round( (count($done) / $total) * 100 );
    ?>
    <div id="epw-wizard">
        <!-- Sidebar -->
        <div class="epw-sidebar">
            <div class="epw-logo">🌿 EarthPure</div>
            <p class="epw-tagline">Setup Wizard</p>
            <div class="epw-steps-list">
                <?php
                $steps = [
                    1 => ['🔌', 'Plugins installeren'],
                    2 => ['📄', "Pagina's aanmaken"],
                    3 => ['⚙️', 'Basis instellingen'],
                    4 => ['💳', 'PayPal koppelen'],
                    5 => ['🎉', 'Klaar!'],
                ];
                foreach ($steps as $num => [$icon, $label]) :
                    $class = 'epw-step-item';
                    if ($num === $step) $class .= ' active';
                    if (in_array($num, $done)) $class .= ' done';
                    ?>
                    <div class="<?php echo $class; ?>">
                        <span class="epw-step-num"><?php echo in_array($num, $done) ? '✓' : $num; ?></span>
                        <span><?php echo $icon . ' ' . $label; ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="epw-progress-wrap">
                <div class="epw-progress-bar" style="width:<?php echo $percent; ?>%"></div>
            </div>
            <p class="epw-progress-label"><?php echo $percent; ?>% voltooid</p>
        </div>

        <!-- Main Content -->
        <div class="epw-main">
            <?php
            switch ($step) {
                case 1: epw_step_plugins(); break;
                case 2: epw_step_pages(); break;
                case 3: epw_step_settings(); break;
                case 4: epw_step_paypal(); break;
                case 5: epw_step_done(); break;
                default: epw_step_plugins();
            }
            ?>
        </div>
    </div>
    <?php
}

/* =============================================
   STAP 1: Plugins installeren
   ============================================= */
function epw_step_plugins() {
    $plugins = [
        [
            'slug'        => 'earthpure-shop',
            'name'        => 'EarthPure Shop',
            'description' => 'De webshop plugin met producten, winkelwagen en PayPal.',
            'icon'        => '🛒',
            'bundled'     => true,
            'required'    => true,
        ],
        [
            'slug'        => 'woocommerce',
            'name'        => 'WooCommerce',
            'description' => 'Optioneel: grote webshop oplossing van Automattic.',
            'icon'        => '🏪',
            'bundled'     => false,
            'required'    => false,
        ],
        [
            'slug'        => 'contact-form-7',
            'name'        => 'Contact Form 7',
            'description' => 'Geavanceerde contactformulieren (optioneel, ingebouwd formulier werkt ook).',
            'icon'        => '📬',
            'bundled'     => false,
            'required'    => false,
        ],
    ];
    ?>
    <div class="epw-step-content">
        <h1>🔌 Stap 1: Plugins installeren</h1>
        <p class="epw-intro">De volgende plugins zijn aanbevolen voor jouw EarthPure webshop. De <strong>EarthPure Shop</strong> plugin zit al in je pakket en wordt automatisch geïnstalleerd.</p>

        <div class="epw-plugins-list">
            <?php foreach ($plugins as $plugin) :
                $active = is_plugin_active("{$plugin['slug']}/{$plugin['slug']}.php");
                ?>
                <div class="epw-plugin-card <?php echo $active ? 'installed' : ''; ?>">
                    <div class="epw-plugin-icon"><?php echo $plugin['icon']; ?></div>
                    <div class="epw-plugin-info">
                        <strong><?php echo esc_html($plugin['name']); ?></strong>
                        <?php if ($plugin['required']) : ?><span class="epw-badge">Vereist</span><?php endif; ?>
                        <?php if ($plugin['bundled']) : ?><span class="epw-badge epw-badge-blue">Inbegrepen</span><?php endif; ?>
                        <p><?php echo esc_html($plugin['description']); ?></p>
                    </div>
                    <div class="epw-plugin-action">
                        <?php if ($active) : ?>
                            <span class="epw-installed-badge">✅ Actief</span>
                        <?php elseif ($plugin['bundled']) : ?>
                            <button class="epw-btn epw-btn-primary epw-install-plugin"
                                    data-slug="<?php echo esc_attr($plugin['slug']); ?>">
                                Installeer & Activeer
                            </button>
                        <?php else : ?>
                            <button class="epw-btn epw-btn-secondary epw-install-wp-plugin"
                                    data-slug="<?php echo esc_attr($plugin['slug']); ?>">
                                Installeer via WordPress
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div id="epw-install-log" class="epw-log" style="display:none;"></div>

        <div class="epw-nav">
            <span></span>
            <a href="<?php echo admin_url('admin.php?page=earthpure-wizard&step=2'); ?>"
               class="epw-btn epw-btn-primary" id="epw-next-1">
                Volgende stap →
            </a>
        </div>
    </div>
    <?php
}

/* =============================================
   STAP 2: Pagina's aanmaken
   ============================================= */
function epw_step_pages() {
    ?>
    <div class="epw-step-content">
        <h1>📄 Stap 2: Pagina's aanmaken</h1>
        <p class="epw-intro">We maken automatisch de benodigde pagina's aan voor jouw webshop.</p>

        <div class="epw-pages-list" id="epw-pages-list">
            <?php
            $pages = [
                ['Home',       'Hoofdpagina van de shop', 'home'],
                ['Shop',       'Producten overzicht pagina', 'shop'],
                ['Over Ons',   'Informatie over EarthPure', 'about'],
                ['Contact',    'Contactformulier pagina', 'contact'],
                ['Privacybeleid', 'Privacybeleid pagina', 'privacy'],
                ['Voorwaarden',   'Algemene voorwaarden', 'terms'],
            ];
            foreach ($pages as [$title, $desc, $slug]) :
                $existing = get_page_by_path($slug);
                ?>
                <div class="epw-page-item" id="epw-page-<?php echo $slug; ?>">
                    <div class="epw-page-icon">📄</div>
                    <div class="epw-page-info">
                        <strong><?php echo esc_html($title); ?></strong>
                        <p><?php echo esc_html($desc); ?></p>
                    </div>
                    <div class="epw-page-status">
                        <?php if ($existing) : ?>
                            <span class="epw-installed-badge">✅ Bestaat al</span>
                        <?php else : ?>
                            <span class="epw-pending-badge">⏳ Nog aanmaken</span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="epw-nav">
            <a href="<?php echo admin_url('admin.php?page=earthpure-wizard&step=1'); ?>" class="epw-btn epw-btn-secondary">← Terug</a>
            <button class="epw-btn epw-btn-primary" id="epw-create-pages">📄 Maak pagina's aan & Verder →</button>
        </div>
    </div>
    <?php
}

/* =============================================
   STAP 3: Basis instellingen
   ============================================= */
function epw_step_settings() {
    if ( isset($_POST['epw_save_settings']) ) {
        check_admin_referer('epw_settings');
        update_option('blogname',        sanitize_text_field($_POST['site_title']));
        update_option('blogdescription', sanitize_text_field($_POST['site_tagline']));
        update_option('admin_email',     sanitize_email($_POST['admin_email']));
        update_option('ep_shop_email',   sanitize_email($_POST['admin_email']));
        // Sla stap op
        $done = get_option('epw_completed_steps', []);
        if (!in_array(3, $done)) { $done[] = 3; update_option('epw_completed_steps', $done); }
        wp_redirect( admin_url('admin.php?page=earthpure-wizard&step=4&saved=1') );
        exit;
    }
    ?>
    <div class="epw-step-content">
        <h1>⚙️ Stap 3: Basis instellingen</h1>
        <p class="epw-intro">Stel de basisinformatie van jouw webshop in.</p>

        <?php if (isset($_GET['saved'])) : ?>
            <div class="epw-notice epw-notice-success">✅ Instellingen opgeslagen!</div>
        <?php endif; ?>

        <form method="post" class="epw-settings-form">
            <?php wp_nonce_field('epw_settings'); ?>
            <div class="epw-field">
                <label>🏪 Naam van de webshop</label>
                <input type="text" name="site_title" value="<?php echo esc_attr(get_bloginfo('name')); ?>" required>
            </div>
            <div class="epw-field">
                <label>💬 Tagline / Ondertitel</label>
                <input type="text" name="site_tagline" value="<?php echo esc_attr(get_bloginfo('description')); ?>" placeholder="Duurzame producten voor een beter thuis">
            </div>
            <div class="epw-field">
                <label>📧 Admin e-mailadres</label>
                <input type="email" name="admin_email" value="<?php echo esc_attr(get_option('admin_email')); ?>" required>
                <span class="epw-hint">Hier ontvang je bestellingen en contactberichten.</span>
            </div>
            <div class="epw-nav">
                <a href="<?php echo admin_url('admin.php?page=earthpure-wizard&step=2'); ?>" class="epw-btn epw-btn-secondary">← Terug</a>
                <button type="submit" name="epw_save_settings" class="epw-btn epw-btn-primary">Opslaan & Verder →</button>
            </div>
        </form>
    </div>
    <?php
}

/* =============================================
   STAP 4: PayPal koppelen
   ============================================= */
function epw_step_paypal() {
    if ( isset($_POST['epw_save_paypal']) ) {
        check_admin_referer('epw_paypal');
        update_option('ep_paypal_client_id', sanitize_text_field($_POST['paypal_client_id']));
        update_option('ep_currency',         sanitize_text_field($_POST['currency']));
        $done = get_option('epw_completed_steps', []);
        if (!in_array(4, $done)) { $done[] = 4; update_option('epw_completed_steps', $done); }
        wp_redirect( admin_url('admin.php?page=earthpure-wizard&step=5') );
        exit;
    }
    ?>
    <div class="epw-step-content">
        <h1>💳 Stap 4: PayPal koppelen</h1>
        <p class="epw-intro">Koppel jouw PayPal account om betalingen te ontvangen. Je hebt hiervoor een <strong>PayPal Developer Client ID</strong> nodig.</p>

        <div class="epw-info-box">
            <h4>📋 Hoe krijg ik mijn PayPal Client ID?</h4>
            <ol>
                <li>Ga naar <a href="https://developer.paypal.com" target="_blank">developer.paypal.com</a></li>
                <li>Log in met je PayPal account</li>
                <li>Klik op <strong>Apps & Credentials</strong></li>
                <li>Maak een nieuwe app aan of kopieer de bestaande <strong>Client ID</strong></li>
                <li>Plak hem hieronder</li>
            </ol>
        </div>

        <form method="post" class="epw-settings-form">
            <?php wp_nonce_field('epw_paypal'); ?>
            <div class="epw-field">
                <label>🔑 PayPal Client ID</label>
                <input type="text" name="paypal_client_id" value="<?php echo esc_attr(get_option('ep_paypal_client_id','')); ?>"
                       placeholder="AYour-PayPal-Client-ID-Here..." style="font-family:monospace;">
                <span class="epw-hint">Je kunt dit later ook invullen via EP Bestellingen → Instellingen.</span>
            </div>
            <div class="epw-field">
                <label>💱 Valuta</label>
                <select name="currency">
                    <?php foreach (['USD'=>'USD - Dollar ($)', 'EUR'=>'EUR - Euro (€)', 'GBP'=>'GBP - Pond (£)', 'SRD'=>'SRD - Surinaamse Dollar'] as $k=>$v) : ?>
                        <option value="<?php echo $k; ?>" <?php selected(get_option('ep_currency','USD'), $k); ?>><?php echo $v; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="epw-nav">
                <a href="<?php echo admin_url('admin.php?page=earthpure-wizard&step=3'); ?>" class="epw-btn epw-btn-secondary">← Terug</a>
                <button type="submit" name="epw_save_paypal" class="epw-btn epw-btn-primary">Opslaan & Afronden →</button>
            </div>
        </form>
    </div>
    <?php
}

/* =============================================
   STAP 5: Klaar!
   ============================================= */
function epw_step_done() {
    // Markeer wizard als voltooid
    update_option('epw_show_wizard', '0');
    $done = get_option('epw_completed_steps', []);
    if (!in_array(5, $done)) { $done[] = 5; update_option('epw_completed_steps', $done); }
    ?>
    <div class="epw-step-content epw-done-step">
        <div class="epw-success-icon">🎉</div>
        <h1>Gefeliciteerd!</h1>
        <p class="epw-intro">Je EarthPure webshop is klaar om te gebruiken. Alles is ingesteld en je kunt nu beginnen met verkopen!</p>

        <div class="epw-done-cards">
            <a href="<?php echo admin_url('post-new.php?post_type=ep_product'); ?>" class="epw-done-card">
                <span class="epw-done-card-icon">📦</span>
                <strong>Producten toevoegen</strong>
                <p>Voeg je eerste product toe aan de webshop</p>
            </a>
            <a href="<?php echo home_url('/'); ?>" target="_blank" class="epw-done-card">
                <span class="epw-done-card-icon">👁️</span>
                <strong>Bekijk je site</strong>
                <p>Open de homepage en zie hoe alles eruitziet</p>
            </a>
            <a href="<?php echo admin_url('customize.php'); ?>" class="epw-done-card">
                <span class="epw-done-card-icon">🎨</span>
                <strong>Aanpassen</strong>
                <p>Logo, kleuren en teksten aanpassen</p>
            </a>
            <a href="<?php echo admin_url('admin.php?page=ep-orders'); ?>" class="epw-done-card">
                <span class="epw-done-card-icon">📋</span>
                <strong>Bestellingen</strong>
                <p>Bekijk en beheer inkomende bestellingen</p>
            </a>
        </div>

        <div class="epw-nav" style="justify-content:center;">
            <a href="<?php echo admin_url(); ?>" class="epw-btn epw-btn-primary" style="font-size:1.1rem;padding:16px 36px;">
                Naar het dashboard →
            </a>
        </div>
    </div>
    <?php
}

/* =============================================
   AJAX: Plugin installeren (bundled)
   ============================================= */
add_action( 'wp_ajax_epw_install_plugin', 'epw_install_plugin_handler' );
function epw_install_plugin_handler() {
    check_ajax_referer( 'epw_nonce', 'nonce' );
    if ( ! current_user_can('install_plugins') ) wp_send_json_error(['msg' => 'Geen rechten.']);

    $slug = sanitize_key( $_POST['slug'] );

    // Check of het een bundled plugin is (in wp-content/plugins of in het theme)
    $plugin_file = "$slug/$slug.php";
    if ( file_exists( WP_PLUGIN_DIR . "/$plugin_file" ) ) {
        activate_plugin( $plugin_file );
        wp_send_json_success(['msg' => 'Plugin geactiveerd!', 'status' => 'activated']);
    }

    // Probeer te installeren via WordPress plugin installer
    require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
    require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';

    $api = plugins_api( 'plugin_information', ['slug' => $slug, 'fields' => ['sections' => false]] );
    if ( is_wp_error($api) ) wp_send_json_error(['msg' => 'Plugin niet gevonden op WordPress.org']);

    $upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
    $result   = $upgrader->install( $api->download_link );

    if ( is_wp_error($result) ) wp_send_json_error(['msg' => $result->get_error_message()]);

    activate_plugin( $plugin_file );
    wp_send_json_success(['msg' => 'Plugin geïnstalleerd en geactiveerd!', 'status' => 'installed']);
}

/* =============================================
   AJAX: Pagina's aanmaken
   ============================================= */
add_action( 'wp_ajax_epw_create_pages', 'epw_create_pages_handler' );
function epw_create_pages_handler() {
    check_ajax_referer( 'epw_nonce', 'nonce' );
    if ( ! current_user_can('edit_pages') ) wp_send_json_error(['msg' => 'Geen rechten.']);

    $pages = [
        ['Home',            'home',    '[ep_products limit="6"]'],
        ['Shop',            'shop',    '[ep_products limit="12"]'],
        ['Over Ons',        'about',   '<h2>Over EarthPure</h2><p>Lorem ipsum...</p>'],
        ['Contact',         'contact', '[ep_contact]'],
        ['Privacybeleid',   'privacy', '<h2>Privacybeleid</h2><p>Voeg hier je privacybeleid in.</p>'],
        ['Voorwaarden',     'terms',   '<h2>Algemene Voorwaarden</h2><p>Voeg hier je voorwaarden in.</p>'],
    ];

    $created = [];
    foreach ( $pages as [$title, $slug, $content] ) {
        if ( ! get_page_by_path($slug) ) {
            $id = wp_insert_post([
                'post_title'   => $title,
                'post_name'    => $slug,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
            ]);
            if ( $slug === 'home' ) {
                update_option('show_on_front', 'page');
                update_option('page_on_front', $id);
            }
            $created[] = $title;
        }
    }

    $done = get_option('epw_completed_steps', []);
    if (!in_array(2, $done)) { $done[] = 2; update_option('epw_completed_steps', $done); }

    wp_send_json_success([
        'msg'     => count($created) . ' pagina\'s aangemaakt: ' . implode(', ', $created),
        'created' => $created,
    ]);
}
