<?php
namespace Pay4AllForMypos\Backend;

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

/**
 * Visual step-by-step guide showing the merchant how to obtain their
 * Configuration Pack (test then production) from the myPOS Developer /
 * Merchant portal, plus a "payment methods" tab explaining which methods
 * to enable on the myPOS side.
 *
 * Screenshots live under `assets/img/<lang>/<prefix>_<n>.png` with the
 * following naming :
 *
 *   - `pack_test_1.png … pack_test_N.png`  -> "Pack test" tab
 *   - `pack_prod_1.png … pack_prod_N.png`  -> "Pack production" tab
 *   - `pay_1.png … pay_N.png`              -> "Payment methods" tab
 *
 * When the folder doesn't exist yet (Batch 2 ships with no images), the
 * tabs simply render a friendly "screenshots unavailable" notice - the
 * layout and navigation remain fully functional.
 */
final class KeysGuidePage {

    const SLUG = 'pay4all-for-mypos-guide';

    /** @var string[] Locales that ship translated screenshots - extend as new folders appear. */
    private const SHIPPED_LANGS = [ 'fr', 'en', 'de', 'it' ];

    /**
     * URL to the guide page. The `?tab=` argument is preserved for
     * back-compat with older wizard links but ignored - the page now
     * renders a single Production Pack view.
     */
    public static function url( string $tab = 'prod' ) : string {
        unset( $tab );
        return add_query_arg( [ 'page' => self::SLUG ], admin_url( 'admin.php' ) );
    }

    /**
     * Back-compat entry point for external docs / bookmarks.
     */
    public static function render_prod() : void { self::render(); }

    public static function render( ?string $forced_tab = null ) : void {
        unset( $forced_tab );
        $cap = ( defined( 'PAY4ALL_FOR_MYPOS_WC_ACTIVE' ) && PAY4ALL_FOR_MYPOS_WC_ACTIVE ) ? 'manage_woocommerce' : 'manage_options';
        if ( ! current_user_can( $cap ) ) {
            return;
        }
        ?>
        <div class="wrap pay4all-for-mypos">
            <h1><?php esc_html_e( 'myPOS help', 'pay4all-for-mypos' ); ?></h1>
            <?php self::render_pack_tab( 'prod' ); ?>
        </div>
        <?php
    }

    /**
     * Renders the Test / Production Pack tab. Files are named
     * `pack_test_<n>.png` / `pack_prod_<n>.png` so a rename of a single
     * prefix doesn't ripple into the other tab's discovery logic.
     */
    private static function render_pack_tab( string $tab ) : void {
        $is_prod = $tab === 'prod';
        $prefix  = $is_prod ? 'pack_prod' : 'pack_test';
        $lang    = self::current_lang();
        $img_dir = PAY4ALL_FOR_MYPOS_PLUGIN_PATH . '/assets/img/' . $lang . '/';
        $img_url = PAY4ALL_FOR_MYPOS_PLUGIN_URL  . 'assets/img/'  . $lang . '/';
        $screens = self::collect_screenshots( $img_dir, $prefix );

        $settings_url      = admin_url( 'admin.php?page=' . WizardPage::SLUG );
        $mypos_portal_url  = $is_prod ? 'https://www.mypos.com/en/login' : 'https://developers.mypos.com/en/dashboard';
        $accent            = $is_prod ? '#22c55e' : '#f59e0b';
        $bg_soft           = '#f0fdf4';
        $bg_left           = '#22c55e';
        ?>
        <div style="display:flex;align-items:center;gap:10px;margin:20px 0 10px;">
            <span style="background:<?php echo esc_attr( $accent ); ?>;color:#fff;font-size:11px;padding:3px 10px;border-radius:10px;text-transform:uppercase;letter-spacing:.03em;font-weight:700;">
                <?php echo esc_html( $is_prod ? __( 'Production', 'pay4all-for-mypos' ) : __( 'Test', 'pay4all-for-mypos' ) ); ?>
            </span>
            <span style="color:#3c434a;font-size:13px;">
                <?php
                echo esc_html(
                    $is_prod
                        ? __( 'Real cash-in - requires an active myPOS merchant account.', 'pay4all-for-mypos' )
                        : __( 'Payment simulation - no real amount is charged.', 'pay4all-for-mypos' )
                );
                ?>
            </span>
        </div>

        <!-- ============ Before you start ============ -->
        <div style="background:<?php echo esc_attr( $bg_soft ); ?>;border-left:4px solid <?php echo esc_attr( $bg_left ); ?>;padding:16px 20px;border-radius:4px;margin:8px 0 24px;max-width:820px;">
            <p style="margin:0 0 8px;font-weight:700;font-size:14px;color:#1d2327;">
                <?php esc_html_e( 'Before you start', 'pay4all-for-mypos' ); ?>
            </p>
            <p style="margin:0 0 8px;color:#1d2327;line-height:1.55;">
                <?php
                printf(
                    wp_kses(
                        /* translators: %s: link to the myPOS portal. */
                        __( 'Log in to %s. Test Packs are issued instantly from the developer portal ; Production Packs require an approved myPOS merchant account with a verified IBAN.', 'pay4all-for-mypos' ),
                        [ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ] ]
                    ),
                    '<a href="' . esc_url( $mypos_portal_url ) . '" target="_blank" rel="noopener noreferrer"><strong>' . esc_html( $mypos_portal_url ) . '</strong></a>'
                );
                ?>
            </p>
            <?php if ( ! $is_prod ) : ?>
                <p style="margin:0;color:#3c434a;font-size:13px;">
                    <?php esc_html_e( 'The test Pack lets you simulate payments without collecting real money. Ideal for validating your integration end-to-end.', 'pay4all-for-mypos' ); ?>
                </p>
            <?php else : ?>
                <p style="margin:0;color:#3c434a;font-size:13px;">
                    <?php esc_html_e( 'The production Pack is used to accept real payments. Keep it strictly confidential - it contains your merchant private key.', 'pay4all-for-mypos' ); ?>
                </p>
            <?php endif; ?>
        </div>

        <h2 style="margin-top:0;">
            <?php
            echo esc_html(
                $is_prod
                    ? __( 'How to retrieve your Production Pack', 'pay4all-for-mypos' )
                    : __( 'How to retrieve your Test Pack', 'pay4all-for-mypos' )
            );
            ?>
        </h2>

        <p class="description" style="max-width:820px;">
            <?php
            printf(
                wp_kses(
                    /* translators: %s: link to the Pay4All for myPOS settings page. */
                    __( 'Follow the visual steps below, then paste the Pack into %s.', 'pay4all-for-mypos' ),
                    [ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ], 'strong' => [] ]
                ),
                '<a href="' . esc_url( $settings_url ) . '"><strong>' . esc_html__( 'Pay4All myPOS -> Settings', 'pay4all-for-mypos' ) . '</strong></a>'
            );
            ?>
        </p>

        <?php if ( empty( $screens ) ) : ?>
            <div class="notice notice-warning" style="margin:16px 0;padding:16px;max-width:820px;">
                <p><strong><?php esc_html_e( 'Screenshots unavailable for your language.', 'pay4all-for-mypos' ); ?></strong></p>
                <p>
                    <?php
                    printf(
                        wp_kses(
                            /* translators: 1: image prefix (e.g. pack_test), 2: expected image folder path. */
                            __( 'No file %1$s_1.png found in %2$s.', 'pay4all-for-mypos' ),
                            [ 'code' => [] ]
                        ),
                        esc_html( $prefix ),
                        '<code>' . esc_html( 'assets/img/' . $lang . '/' ) . '</code>'
                    );
                    ?>
                </p>
            </div>
        <?php else : ?>
            <div style="max-width:820px;">
                <?php foreach ( $screens as $n => $file ) :
                    $alt = sprintf(
                        /* translators: 1: tab name (Test / Production), 2: step number. */
                        __( 'Step %2$d - retrieve the %1$s Pack in the myPOS portal', 'pay4all-for-mypos' ),
                        $is_prod ? __( 'Production', 'pay4all-for-mypos' ) : __( 'Test', 'pay4all-for-mypos' ),
                        $n
                    );
                    ?>
                    <div style="margin-bottom:24px;">
                        <img src="<?php echo esc_url( $img_url . $file ); ?>"
                             alt="<?php echo esc_attr( $alt ); ?>"
                             style="max-width:100%;height:auto;border:1px solid #dcdcde;border-radius:6px;box-shadow:0 1px 3px rgba(0,0,0,.08);">
                    </div>
                <?php endforeach; ?>
            </div>

            <p style="margin-top:24px;">
                <a href="<?php echo esc_url( $settings_url ); ?>" class="button button-primary">
                    <?php esc_html_e( 'I have my Pack, go to Settings', 'pay4all-for-mypos' ); ?>
                </a>
            </p>
        <?php endif; ?>
        <?php
    }

    /**
     * Two-letter locale segment for the current admin user, but only if we
     * ship screenshots for that language. Falls back to French.
     */
    private static function current_lang() : string {
        $locale = function_exists( 'determine_locale' ) ? determine_locale() : get_locale();
        $code   = strtolower( substr( (string) $locale, 0, 2 ) );
        return in_array( $code, self::SHIPPED_LANGS, true ) ? $code : 'fr';
    }

    /**
     * Discovers screenshot files on disk. Files matching `<prefix>_<n>.png`
     * are indexed by step number so the render loop stays declarative.
     *
     * @return array<int,string> Sorted step number -> filename.
     */
    private static function collect_screenshots( string $dir, string $prefix ) : array {
        if ( ! is_dir( $dir ) ) { return []; }

        $files = glob( $dir . $prefix . '_*.png' );
        if ( ! is_array( $files ) ) { return []; }

        $steps = [];
        foreach ( $files as $path ) {
            $name = basename( $path );
            if ( preg_match( '/^' . preg_quote( $prefix, '/' ) . '_(\d+)\.png$/', $name, $m ) ) {
                $steps[ (int) $m[1] ] = $name;
            }
        }
        ksort( $steps );
        return $steps;
    }
}
