<?php

/**
 * TrackSharp Wizard
 *
 * Handles the setup wizard page.
 *
 * @package TrackSharp
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class TrackSharp_Wizard {
    /** @var TrackSharp_GA4 */
    private $ga4;

    /** @var TrackSharp_Meta|null */
    private $meta;

    /**
     * @param TrackSharp_GA4       $ga4  GA4 client.
     * @param TrackSharp_Meta|null $meta Meta client (premium build only).
     */
    public function __construct( TrackSharp_GA4 $ga4, ?object $meta ) {
        $this->ga4 = $ga4;
        $this->meta = $meta;
    }

    /**
     * Render the wizard page.
     */
    public function render() {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Step is just pagination, not a form action
        $step = ( isset( $_GET['step'] ) ? max( 1, (int) $_GET['step'] ) : 1 );
        $step = min( $step, 5 );
        $action_url = admin_url( 'admin.php?page=tracksharp-setup&step=' . $step );
        $has_wc = class_exists( 'WooCommerce' );
        $has_consent_api = function_exists( 'wp_has_consent' );
        // Handle saves (only relevant when premium code is present).
        if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer( 'ws_wizard_step' ) ) {
            if ( $step === 2 ) {
                update_option( 'tracksharp_ga4_measurement_id', sanitize_text_field( wp_unslash( $_POST['ga4_measurement_id'] ?? '' ) ) );
                update_option( 'tracksharp_ga4_api_secret', sanitize_text_field( wp_unslash( $_POST['ga4_api_secret'] ?? '' ) ) );
                wp_safe_redirect( admin_url( 'admin.php?page=tracksharp-setup&step=3' ) );
                exit;
            }
            // Premium-only block is stripped from the free build by Freemius.
            if ( function_exists( 'tracksharp_fs' ) ) {
                $fs = tracksharp_fs();
                if ( is_object( $fs ) && method_exists( $fs, 'is__premium_only' ) && $fs->is__premium_only() ) {
                    if ( $has_wc && TrackSharp_Features::is_pro_active() && $step === 3 ) {
                        update_option( 'tracksharp_meta_pixel_id', sanitize_text_field( wp_unslash( $_POST['meta_pixel_id'] ?? '' ) ) );
                        update_option( 'tracksharp_meta_access_token', sanitize_text_field( wp_unslash( $_POST['meta_access_token'] ?? '' ) ) );
                        update_option( 'tracksharp_meta_test_event_code', sanitize_text_field( wp_unslash( $_POST['meta_test_event_code'] ?? '' ) ) );
                        wp_safe_redirect( admin_url( 'admin.php?page=tracksharp-setup&step=4' ) );
                        exit;
                    }
                }
            }
        }
        $ga_mid = trim( get_option( 'tracksharp_ga4_measurement_id', '' ) );
        $ga_sec = trim( get_option( 'tracksharp_ga4_api_secret', '' ) );
        $px_id = trim( get_option( 'tracksharp_meta_pixel_id', '' ) );
        $px_tok = trim( get_option( 'tracksharp_meta_access_token', '' ) );
        $px_test = trim( get_option( 'tracksharp_meta_test_event_code', '' ) );
        $ga_test = $meta_test = null;
        if ( $step === 4 && isset( $_GET['run_tests'] ) ) {
            $ga_test = $this->run_ga4_test( $ga_mid, $ga_sec );
            // Premium-only call is stripped from the free build by Freemius.
            if ( function_exists( 'tracksharp_fs' ) ) {
                $fs = tracksharp_fs();
                if ( is_object( $fs ) && method_exists( $fs, 'is__premium_only' ) && $fs->is__premium_only() ) {
                    if ( $has_wc && TrackSharp_Features::is_pro_active() ) {
                        $meta_test = $this->run_meta_test__premium_only( $px_id, $px_tok, $px_test );
                    }
                }
            }
        }
        $wizard_steps = [
            1 => 'Check',
            2 => 'GA4',
            3 => 'Meta',
            4 => 'Test',
            5 => 'Google Ads',
        ];
        $this->render_page(
            $step,
            $action_url,
            $wizard_steps,
            $has_wc,
            $has_consent_api,
            $ga_mid,
            $ga_sec,
            $px_id,
            $px_tok,
            $px_test,
            $ga_test,
            $meta_test
        );
    }

    private function render_page(
        $step,
        $action_url,
        $wizard_steps,
        $has_wc,
        $has_consent_api,
        $ga_mid,
        $ga_sec,
        $px_id,
        $px_tok,
        $px_test,
        $ga_test,
        $meta_test
    ) {
        ?>
        <div class="wrap tracksharp-admin">
            <div class="ws-card">
                <div class="ws-card-header">
                    <div>
                        <h1>TrackSharp Setup Wizard</h1>
                        <p>Complete the steps to activate server-to-server tracking.</p>
                    </div>
                    <div class="ws-toolbar">
                        <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-audit' ) );
        ?>">Dashboard</a>
                        <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-events' ) );
        ?>">Event Log</a>
                    </div>
                </div>
                <div class="ws-steps">
                    <?php 
        foreach ( $wizard_steps as $num => $label ) {
            ?>
                        <?php 
            $step_state = ( $step === $num ? 'active' : (( $step > $num ? 'done' : '' )) );
            $step_class = trim( 'ws-step ' . $step_state );
            ?>
                        <span class="<?php 
            echo esc_attr( $step_class );
            ?>">
                            <span class="num"><?php 
            echo (int) $num;
            ?></span>
                            <?php 
            echo esc_html( $label );
            ?>
                        </span>
                    <?php 
        }
        ?>
                </div>
            </div>

            <?php 
        $this->render_step(
            $step,
            $action_url,
            $has_wc,
            $has_consent_api,
            $ga_mid,
            $ga_sec,
            $px_id,
            $px_tok,
            $px_test,
            $ga_test,
            $meta_test
        );
        ?>
        </div>
        <?php 
    }

    private function render_step(
        $step,
        $action_url,
        $has_wc,
        $has_consent_api,
        $ga_mid,
        $ga_sec,
        $px_id,
        $px_tok,
        $px_test,
        $ga_test,
        $meta_test
    ) {
        if ( !$has_wc && $step > 1 ) {
            $this->render_requires_woocommerce();
            return;
        }
        switch ( $step ) {
            case 1:
                $this->render_step_1( $has_wc, $has_consent_api );
                break;
            case 2:
                $this->render_step_2( $action_url, $ga_mid, $ga_sec );
                break;
            case 3:
                $this->render_step_3(
                    $action_url,
                    $px_id,
                    $px_tok,
                    $px_test
                );
                break;
            case 4:
                $this->render_step_4( $ga_test, $meta_test );
                break;
            case 5:
                $this->render_step_5();
                break;
        }
    }

    private function render_step_1( $has_wc, $has_consent_api ) {
        ?>
        <div class="ws-card">
            <h2>Checklist</h2>
            <p class="ws-desc">We check if your store is ready for server events.</p>
            <ul class="ws-checklist">
                <li>
                    <span>WooCommerce</span>
                    <span class="ws-status <?php 
        echo ( $has_wc ? 'ws-status-ok' : 'ws-status-bad' );
        ?>">
                        <?php 
        echo ( $has_wc ? 'Ready' : 'Missing' );
        ?>
                    </span>
                </li>
                <li>
                    <span>WP Consent API (recommended)</span>
                    <span class="ws-status <?php 
        echo ( $has_consent_api ? 'ws-status-ok' : 'ws-status-warn' );
        ?>">
                        <?php 
        echo ( $has_consent_api ? 'Active' : 'Not found' );
        ?>
                    </span>
                </li>
            </ul>
            <div class="ws-action-row">
                <a class="button button-primary" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=2' ) );
        ?>">Continue</a>
            </div>
        </div>
        <?php 
    }

    private function render_requires_woocommerce() {
        ?>
        <div class="ws-card">
            <h2>WooCommerce required</h2>
            <p class="ws-desc">TrackSharp is built for WooCommerce stores. Install and activate WooCommerce to continue the setup wizard.</p>
            <div class="ws-action-row">
                <a class="button button-primary" href="<?php 
        echo esc_url( admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ) );
        ?>">Install WooCommerce</a>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=1' ) );
        ?>">Back to Step 1</a>
            </div>
        </div>
        <?php 
    }

    private function render_step_2( $action_url, $ga_mid, $ga_sec ) {
        ?>
        <form class="ws-card" method="post" action="<?php 
        echo esc_url( $action_url );
        ?>">
            <?php 
        wp_nonce_field( 'ws_wizard_step' );
        ?>
            <h2>Google Analytics 4</h2>
            <p class="ws-desc">Fill in your web data stream details.</p>
            <div class="ws-field">
                <label for="ga4_measurement_id">Measurement ID</label>
                <input type="text" id="ga4_measurement_id" name="ga4_measurement_id" class="regular-text" placeholder="G-XXXXXXX" value="<?php 
        echo esc_attr( $ga_mid );
        ?>">
                <p class="ws-desc">Admin → Data Streams → Web → <em>Measurement ID</em>.</p>
            </div>
            <div class="ws-field">
                <label for="ga4_api_secret">API Secret</label>
                <input type="text" id="ga4_api_secret" name="ga4_api_secret" class="regular-text" value="<?php 
        echo esc_attr( $ga_sec );
        ?>">
                <p class="ws-desc">Data Streams → <em>Measurement Protocol API secrets</em> → Create.</p>
            </div>
            <div class="ws-action-row">
                <button class="button button-primary">Save &amp; continue</button>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=3' ) );
        ?>">Skip</a>
            </div>
        </form>
        <?php 
    }

    private function render_step_3(
        $action_url,
        $px_id,
        $px_tok,
        $px_test
    ) {
        if ( TrackSharp_Features::is_meta_available() ) {
            // Premium-only call is stripped from the free build by Freemius.
            if ( function_exists( 'tracksharp_fs' ) ) {
                $fs = tracksharp_fs();
                if ( is_object( $fs ) && method_exists( $fs, 'is__premium_only' ) && $fs->is__premium_only() && TrackSharp_Features::is_pro_active() ) {
                    $this->render_step_3_form__premium_only(
                        $action_url,
                        $px_id,
                        $px_tok,
                        $px_test
                    );
                    return;
                }
            }
        }
        $upgrade_url = TrackSharp_Features::get_upgrade_url();
        ?>
        <div class="ws-card">
            <h2>Meta (Conversions API) <?php 
        echo wp_kses_post( TrackSharp_Features::render_pro_badge() );
        ?></h2>
            <p class="ws-desc">Meta Conversions API setup is available in TrackSharp Pro.</p>
            <div class="ws-action-row">
                <a href="<?php 
        echo esc_url( $upgrade_url );
        ?>" class="button button-primary" style="background:#158a5f;border-color:#127a54;">View Pro Plans</a>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=4' ) );
        ?>">Continue</a>
            </div>
        </div>
        <?php 
    }

    private function render_step_4( $ga_test, $meta_test ) {
        ?>
        <div class="ws-card">
            <h2>Send Test Events</h2>
            <p class="ws-desc">We send a small test purchase to GA4 (and Meta when available).</p>
            <div class="ws-action-row">
                <a class="button button-primary" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=4&run_tests=1' ) );
        ?>">Run Tests</a>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-setup&step=5' ) );
        ?>">Step 5: Google Ads <?php 
        echo wp_kses_post( ( TrackSharp_Features::is_google_ads_available() ? '' : TrackSharp_Features::render_pro_badge() ) );
        ?></a>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-audit' ) );
        ?>">Go to Dashboard</a>
            </div>

            <?php 
        if ( $ga_test !== null || $meta_test !== null ) {
            ?>
                <div class="ws-test-pills">
                    <?php 
            echo wp_kses_post( $this->render_test_badge( 'GA4', $ga_test ) );
            ?>
                    <?php 
            if ( TrackSharp_Features::is_meta_available() ) {
                ?>
                        <?php 
                echo wp_kses_post( $this->render_test_badge( 'Meta', $meta_test ) );
                ?>
                    <?php 
            }
            ?>
                </div>
            <?php 
        }
        ?>

            <p class="ws-desc"><strong>Tip:</strong> After this, place a test order and follow along live in the event log.</p>
        </div>
        <?php 
    }

    private function render_step_5() {
        if ( TrackSharp_Features::is_google_ads_available() ) {
            // Premium-only call is stripped from the free build by Freemius.
            if ( function_exists( 'tracksharp_fs' ) ) {
                $fs = tracksharp_fs();
                if ( is_object( $fs ) && method_exists( $fs, 'is__premium_only' ) && $fs->is__premium_only() && TrackSharp_Features::is_pro_active() ) {
                    $this->render_step_5__premium_only();
                    return;
                }
            }
        }
        $upgrade_url = TrackSharp_Features::get_upgrade_url();
        ?>
        <div class="ws-card">
            <h2>Google Ads via GA4 <?php 
        echo wp_kses_post( TrackSharp_Features::render_pro_badge() );
        ?></h2>
            <p class="ws-desc">Google Ads attribution (gclid, gbraid, wbraid) is available in TrackSharp Pro.</p>
            <div class="ws-action-row">
                <a href="<?php 
        echo esc_url( $upgrade_url );
        ?>" class="button button-primary" style="background:#158a5f;border-color:#127a54;">View Pro Plans</a>
                <a class="button" href="<?php 
        echo esc_url( admin_url( 'admin.php?page=tracksharp-audit' ) );
        ?>">Go to Dashboard</a>
            </div>
        </div>
        <?php 
    }

    private function run_ga4_test( $ga_mid, $ga_sec ) {
        if ( !$ga_mid || !$ga_sec ) {
            return null;
        }
        $items = [[
            'item_id'   => '123',
            'item_name' => 'Wizard Test',
            'price'     => 1.23,
            'quantity'  => 1,
        ]];
        $currency = ( function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'EUR' );
        return $this->ga4->send( [
            'client_id' => time() . '.' . wp_rand( 1000000000, 2147483647 ),
            'events'    => [[
                'name'   => 'purchase',
                'params' => [
                    'transaction_id'       => 'ws_wizard_' . time(),
                    'currency'             => $currency,
                    'value'                => 1.23,
                    'items'                => $items,
                    'event_id'             => 'ws_wizard_' . wp_generate_uuid4(),
                    'engagement_time_msec' => 1,
                    'debug_mode'           => 1,
                ],
            ]],
        ] );
    }

    private function render_test_badge( string $label, ?array $result ) : string {
        if ( $result === null ) {
            return '<div class="ws-test-pill"><span class="dashicons dashicons-minus"></span><div><strong>' . esc_html( $label ) . '</strong><br>Not configured</div></div>';
        }
        $ok = !empty( $result['ok'] );
        $class = ( $ok ? 'ws-ok' : 'ws-fail' );
        $icon = ( $ok ? 'dashicons-yes-alt' : 'dashicons-no-alt' );
        $message = ( $ok ? 'Success' : $result['reason'] ?? $result['error'] ?? 'Error' );
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Used for debug output in admin wizard
        $details = '<details><summary>Details</summary><pre>' . esc_html( print_r( $result, true ) ) . '</pre></details>';
        return '<div class="ws-test-pill ' . esc_attr( $class ) . '"><span class="dashicons ' . esc_attr( $icon ) . '"></span><div><strong>' . esc_html( $label ) . '</strong><br>' . esc_html( $message ) . '</div>' . $details . '</div>';
    }

    private function get_client_ip() : string {
        foreach ( [
            'HTTP_CF_CONNECTING_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR'
        ] as $k ) {
            if ( !empty( $_SERVER[$k] ) ) {
                $iplist = explode( ',', sanitize_text_field( wp_unslash( $_SERVER[$k] ) ) );
                return trim( $iplist[0] );
            }
        }
        return '';
    }

}
