<?php

defined( "ABSPATH" ) || exit;
class Chit_Admin_Settings {
    public function __construct() {
        add_action( "admin_post_chit_save_settings", [$this, "handle_post"] );
    }

    public function enqueue_assets() : void {
        wp_register_script(
            "chit-format-preview",
            plugins_url( "assets/js/format-preview.js", CHIT_FILE ),
            [],
            CHIT_VERSION,
            true
        );
        wp_localize_script( "chit-format-preview", "chitFormatPreview", [
            "alphabet"  => Chit_Codes::ALPHABET,
            "maxLength" => Chit_Codes::MAX_CODE_LENGTH,
            "tooLong"   => __( "This format produces %1\$d-character codes — the maximum is %2\$d. Shorten the prefix or the code length.", "chit-download-codes-for-woocommerce" ),
        ] );
        wp_enqueue_script( "chit-format-preview" );
    }

    public function render() : void {
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        $format = Chit_Codes::get_format();
        echo '<div class="wrap">';
        echo "<h1>" . esc_html__( "Chit Settings", "chit-download-codes-for-woocommerce" ) . "</h1>";
        if ( isset( $_GET["saved"] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( "Settings saved.", "chit-download-codes-for-woocommerce" ) . "</p></div>";
        }
        if ( isset( $_GET["error"] ) && sanitize_key( $_GET["error"] ) === "format" ) {
            echo '<div class="notice notice-error is-dismissible"><p>' . sprintf( 
                /* translators: %d: maximum code length in characters */
                esc_html__( "Settings not saved: that format produces codes longer than %d characters. Shorten the prefix or the code length.", "chit-download-codes-for-woocommerce" ),
                (int) Chit_Codes::MAX_CODE_LENGTH
             ) . "</p></div>";
        }
        ?>
        <form method="post" action="<?php 
        echo esc_url( admin_url( "admin-post.php" ) );
        ?>">
            <input type="hidden" name="action" value="chit_save_settings">
            <?php 
        wp_nonce_field( "chit_save_settings" );
        ?>

            <h2><?php 
        esc_html_e( "Code format", "chit-download-codes-for-woocommerce" );
        ?></h2>
            <table class="form-table"><tbody>
                <tr>
                    <th><label for="chit-prefix"><?php 
        esc_html_e( "Prefix", "chit-download-codes-for-woocommerce" );
        ?></label></th>
                    <td>
                        <input
                            type="text"
                            id="chit-prefix"
                            name="chit_prefix"
                            value="<?php 
        echo esc_attr( $format["prefix"] );
        ?>"
                            class="regular-text"
                            maxlength="<?php 
        echo esc_attr( 
            // Room for the shortest body (2 groups of 4
            // plus their separator) and the prefix dash.
            Chit_Codes::MAX_CODE_LENGTH - Chit_Codes::MIN_RANDOM_LENGTH - 2
         );
        ?>"
                            style="text-transform: uppercase;"
                            autocomplete="off"
                        >
                        <p class="description">
                            <?php 
        esc_html_e( "Letters and numbers. A dash is added after the prefix automatically (ACME becomes ACME-XXXX-XXXX). Leave blank for no prefix.", "chit-download-codes-for-woocommerce" );
        ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th><label for="chit-groups"><?php 
        esc_html_e( "Code body", "chit-download-codes-for-woocommerce" );
        ?></label></th>
                    <td>
                        <select id="chit-groups" name="chit_groups">
                            <?php 
        foreach ( Chit_Codes::GROUP_COUNTS as $count ) {
            ?>
                                <option value="<?php 
            echo esc_attr( $count );
            ?>" <?php 
            selected( $format["groups"], $count );
            ?>>
                                    <?php 
            echo esc_html( sprintf( 
                /* translators: %d: number of character groups in a code */
                _n(
                    "%d group",
                    "%d groups",
                    $count,
                    "chit-download-codes-for-woocommerce"
                ),
                $count
             ) );
            ?>
                                </option>
                            <?php 
        }
        ?>
                        </select>
                        <label for="chit-group-size" class="screen-reader-text"><?php 
        esc_html_e( "Characters per group", "chit-download-codes-for-woocommerce" );
        ?></label>
                        <select id="chit-group-size" name="chit_group_size">
                            <?php 
        foreach ( Chit_Codes::GROUP_SIZES as $size ) {
            ?>
                                <option value="<?php 
            echo esc_attr( $size );
            ?>" <?php 
            selected( $format["group_size"], $size );
            ?>>
                                    <?php 
            echo esc_html( sprintf( 
                /* translators: %d: characters per group */
                __( "of %d characters", "chit-download-codes-for-woocommerce" ),
                $size
             ) );
            ?>
                                </option>
                            <?php 
        }
        ?>
                        </select>
                        <p class="description">
                            <?php 
        esc_html_e( "The random part of the code, split with dashes so it's easy to read off a print. More characters are harder to guess.", "chit-download-codes-for-woocommerce" );
        ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th><?php 
        esc_html_e( "Preview", "chit-download-codes-for-woocommerce" );
        ?></th>
                    <td>
                        <code id="chit-format-preview" style="font-size: 1.3em; padding: 0.35em 0.6em;"><?php 
        echo esc_html( Chit_Codes::generate_code() );
        ?></code>
                        <p
                            id="chit-format-warning"
                            style="color: #d63638; display: none; font-weight: 600;"
                        ></p>
                        <p class="description">
                            <?php 
        esc_html_e( "Changing the format only affects codes generated from now on. Codes you have already issued keep working exactly as printed.", "chit-download-codes-for-woocommerce" );
        ?>
                        </p>
                    </td>
                </tr>
            </tbody></table>

            <h2><?php 
        esc_html_e( "Redemption", "chit-download-codes-for-woocommerce" );
        ?></h2>
            <table class="form-table"><tbody>
                <tr>
                    <th><?php 
        esc_html_e( "Guest redemption", "chit-download-codes-for-woocommerce" );
        ?></th>
                    <td>
                        <label for="chit-allow-guest">
                            <input
                                type="checkbox"
                                id="chit-allow-guest"
                                name="chit_allow_guest"
                                value="1"
                                <?php 
        checked( get_option( "chit_allow_guest_redemption" ) );
        ?>
                            >
                            <?php 
        esc_html_e( "Allow redemption without an account", "chit-download-codes-for-woocommerce" );
        ?>
                        </label>
                        <p class="description">
                            <?php 
        esc_html_e( "Off (default): customers must log in to redeem, and their downloads appear under My Account. On: anyone can redeem by entering their email address; the download links are shown on screen and emailed to them, but won't be listed under My Account unless they were logged in.", "chit-download-codes-for-woocommerce" );
        ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th><?php 
        esc_html_e( "Order total", "chit-download-codes-for-woocommerce" );
        ?></th>
                    <td>
                        <label for="chit-catalog-price">
                            <input
                                type="checkbox"
                                id="chit-catalog-price"
                                name="chit_catalog_price"
                                value="1"
                                <?php 
        checked( get_option( "chit_redemption_catalog_price" ) );
        ?>
                            >
                            <?php 
        esc_html_e( "Record the product's catalog price on redemption orders", "chit-download-codes-for-woocommerce" );
        ?>
                        </label>
                        <p class="description">
                            <?php 
        esc_html_e( "Off (default): redemption orders are created with a zero total, since the customer already paid in person. On: the order books the product's current catalog price — useful if WooCommerce is your only sales record, but note this counts revenue WooCommerce never processed and can double-count sales you also record elsewhere.", "chit-download-codes-for-woocommerce" );
        ?>
                        </p>
                    </td>
                </tr>
            </tbody></table>

            <?php 
        ?>

            <?php 
        submit_button( esc_html__( "Save Settings", "chit-download-codes-for-woocommerce" ) );
        ?>
        </form>
        <?php 
        echo "</div>";
    }

    public function handle_post() : void {
        check_admin_referer( "chit_save_settings" );
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        $format = Chit_Codes::sanitize_format( [
            "prefix"     => sanitize_text_field( wp_unslash( $_POST["chit_prefix"] ?? "" ) ),
            "group_size" => absint( $_POST["chit_group_size"] ?? 0 ),
            "groups"     => absint( $_POST["chit_groups"] ?? 0 ),
        ] );
        if ( Chit_Codes::format_length( $format ) > Chit_Codes::MAX_CODE_LENGTH ) {
            wp_safe_redirect( add_query_arg( [
                "page"  => "chit-settings",
                "error" => "format",
            ], admin_url( "admin.php" ) ) );
            exit;
        }
        update_option( "chit_code_format", $format );
        update_option( "chit_redemption_catalog_price", !empty( $_POST["chit_catalog_price"] ) );
        update_option( "chit_allow_guest_redemption", !empty( $_POST["chit_allow_guest"] ) );
        wp_safe_redirect( add_query_arg( [
            "page"  => "chit-settings",
            "saved" => "1",
        ], admin_url( "admin.php" ) ) );
        exit;
    }

}
