<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

// Top-level "GiftCard Studio" wp-admin settings page - global gift card defaults
// that apply across every form/design (as opposed to per-field settings,
// which live on the blocks/Elementor widgets themselves).
class CGC_Admin_Settings {

    const OPTION_GROUP = 'cgc_settings';
    const OPTION_NAME = 'cgc_settings';

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'register_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
    }

    public function register_menu() {
        add_menu_page(
            __( 'GiftCard Studio', 'gift-card-studio' ),
            __( 'GiftCard Studio', 'gift-card-studio' ),
            'manage_options',
            'giftcard-studio-settings',
            array( $this, 'render_settings_page' ),
            'dashicons-tickets-alt',
            26
        );

        // Without this, once the "cgc-design" post type attaches itself as
        // a submenu here (show_in_menu => 'giftcard-studio-settings', see
        // class-cgc-post-type.php), WordPress auto-generates its OWN first
        // submenu item to keep the top-level page reachable - but it labels
        // that item after the top-level menu_title ("GiftCard Studio" again,
        // confusingly duplicated) rather than something meaningful.
        // Registering a submenu page with the SAME slug as the parent is
        // the standard way to claim that first slot explicitly instead.
        add_submenu_page(
            'giftcard-studio-settings',
            __( 'GiftCard Studio Settings', 'gift-card-studio' ),
            __( 'Settings', 'gift-card-studio' ),
            'manage_options',
            'giftcard-studio-settings',
            array( $this, 'render_settings_page' )
        );
    }

    // Reused by class-cgc-rest-api.php's add_to_cart() instead of the
    // previous hardcoded "+3 days".
    public static function get_coupon_expiration_days() {
        $settings = get_option( self::OPTION_NAME, array() );
        $days = isset( $settings['coupon_expiration_days'] ) ? (int) $settings['coupon_expiration_days'] : 3;

        return $days > 0 ? $days : 3;
    }

    // Server-side floor for a plain "Amount" field's price (pills or a
    // custom typed amount) - class-cgc-rest-api.php's add_to_cart() only
    // ever receives the client's submitted amount value, not a reference
    // back to which page/field configuration produced it, so it can't
    // cross-check against that specific field's configured pill options.
    // This is the defense-in-depth backstop that closes the "submit
    // amount=0.01 directly to the REST endpoint" underpayment path
    // regardless of what the field's own UI would have allowed.
    public static function get_minimum_amount() {
        $settings = get_option( self::OPTION_NAME, array() );
        $minimum = isset( $settings['minimum_amount'] ) ? (float) $settings['minimum_amount'] : 1.0;

        return $minimum > 0 ? $minimum : 1.0;
    }

    // Site-wide fallback currency, sitting between a field's own per-field
    // currencySymbol override (highest priority) and the WooCommerce
    // store's own currency (final fallback) - see
    // CGC_Blocks::render_amount_field_markup() and
    // CGC_Elementor_Field::content_template() for the full 3-tier chain.
    // Empty string means "no site-wide override configured".
    public static function get_default_currency_symbol() {
        $settings = get_option( self::OPTION_NAME, array() );
        return trim( $settings['default_currency_symbol'] ?? '' );
    }

    public function register_settings() {
        register_setting( self::OPTION_GROUP, self::OPTION_NAME, array( $this, 'sanitize_settings' ) );

        add_settings_section(
            'cgc_defaults_section',
            __( 'Gift Card Defaults', 'gift-card-studio' ),
            null,
            'giftcard-studio-settings'
        );

        add_settings_field(
            'default_currency_symbol',
            __( 'Default Currency Symbol', 'gift-card-studio' ),
            array( $this, 'render_default_currency_field' ),
            'giftcard-studio-settings',
            'cgc_defaults_section'
        );

        add_settings_field(
            'coupon_expiration_days',
            __( 'Coupon Expiration (days after purchase)', 'gift-card-studio' ),
            array( $this, 'render_coupon_expiration_field' ),
            'giftcard-studio-settings',
            'cgc_defaults_section'
        );

        add_settings_field(
            'minimum_amount',
            __( 'Minimum Gift Card Amount', 'gift-card-studio' ),
            array( $this, 'render_minimum_amount_field' ),
            'giftcard-studio-settings',
            'cgc_defaults_section'
        );
    }

    public function sanitize_settings( $input ) {
        return array(
            'default_currency_symbol' => sanitize_text_field( $input['default_currency_symbol'] ?? '' ),
            'coupon_expiration_days' => max( 1, absint( $input['coupon_expiration_days'] ?? 3 ) ),
            'minimum_amount' => max( 0.01, (float) ( $input['minimum_amount'] ?? 1 ) ),
        );
    }

    public function render_default_currency_field() {
        $store_symbol = function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '$';
        ?>
        <input
            type="text"
            size="4"
            name="<?php echo esc_attr( self::OPTION_NAME ); ?>[default_currency_symbol]"
            value="<?php echo esc_attr( self::get_default_currency_symbol() ); ?>"
            placeholder="<?php echo esc_attr( $store_symbol ); ?>"
        />
        <p class="description">
            <?php
            printf(
                /* translators: %s is the store's own WooCommerce currency symbol. */
                esc_html__( 'Used for every Amount field that doesn\'t set its own currency. Leave empty to use the store\'s own currency (currently "%s").', 'gift-card-studio' ),
                esc_html( $store_symbol )
            );
            ?>
        </p>
        <?php
    }

    public function render_coupon_expiration_field() {
        $is_pro = cgc_is_pro_active();
        ?>
        <input
            type="number"
            min="1"
            name="<?php echo esc_attr( self::OPTION_NAME ); ?>[coupon_expiration_days]"
            value="<?php echo esc_attr( self::get_coupon_expiration_days() ); ?>"
            <?php disabled( ! $is_pro ); ?>
        />
        <p class="description">
            <?php if ( $is_pro ) : ?>
                <?php esc_html_e( 'How many days after purchase a generated coupon code stays valid.', 'gift-card-studio' ); ?>
            <?php else : ?>
                <?php esc_html_e( 'Requires GiftCard Studio Pro - real coupon code generation is a Pro feature.', 'gift-card-studio' ); ?>
                <a href="<?php echo esc_url( CGC_UPGRADE_URL ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade now', 'gift-card-studio' ); ?></a>
            <?php endif; ?>
        </p>
        <?php
    }

    public function render_minimum_amount_field() {
        ?>
        <input
            type="number"
            min="0.01"
            step="0.01"
            name="<?php echo esc_attr( self::OPTION_NAME ); ?>[minimum_amount]"
            value="<?php echo esc_attr( self::get_minimum_amount() ); ?>"
        />
        <p class="description">
            <?php esc_html_e( 'The lowest amount accepted for a plain "Amount" field (pills or a custom typed amount), enforced when the order is placed - independent of whatever pill values are configured on the field itself.', 'gift-card-studio' ); ?>
        </p>
        <?php
    }

    public function render_overview_section() {
        $is_pro = cgc_is_pro_active();
        ?>
        <div class="card" style="max-width:800px;margin-bottom:20px;padding:1px 20px;">
            <h2><?php esc_html_e( 'Overview', 'gift-card-studio' ); ?></h2>
            <p>
                <?php esc_html_e( 'GiftCard Studio lets customers design and buy personalized gift cards on your WooCommerce store: they pick a design, fill in an amount/message/recipient details, and check out like any other product.', 'gift-card-studio' ); ?>
            </p>
            <p>
                <strong><?php esc_html_e( 'Plan:', 'gift-card-studio' ); ?></strong>
                <?php if ( $is_pro ) : ?>
                    <span style="color:#008a20;"><?php esc_html_e( 'Pro (active)', 'gift-card-studio' ); ?></span>
                <?php else : ?>
                    <span><?php esc_html_e( 'Free', 'gift-card-studio' ); ?></span>
                    &mdash;
                    <a href="<?php echo esc_url( CGC_UPGRADE_URL ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade to Pro', 'gift-card-studio' ); ?></a>
                <?php endif; ?>
            </p>
        </div>
        <?php
    }

    public function render_instructions_section() {
        ?>
        <div class="card" style="max-width:800px;margin-bottom:20px;padding:1px 20px;">
            <h2><?php esc_html_e( 'Instructions', 'gift-card-studio' ); ?></h2>
            <ol>
                <li><?php esc_html_e( 'Design a gift card template under GiftCard Studio → Designs, or start from one of the built-in starter templates in the design editor.', 'gift-card-studio' ); ?></li>
                <li>
                    <?php esc_html_e( 'Add the form to a page: in the block editor, insert the "Gift Card Form" block. In Elementor, drag in the "Gift Card Form" widget (requires GiftCard Studio Pro).', 'gift-card-studio' ); ?>
                </li>
                <li><?php esc_html_e( 'Add/arrange fields (amount, message, recipient emails, products, etc.) as children of the form - each field has its own settings panel.', 'gift-card-studio' ); ?></li>
                <li><?php esc_html_e( 'Configure the defaults below, then publish the page. Purchases go through WooCommerce checkout like any other product.', 'gift-card-studio' ); ?></li>
            </ol>
        </div>
        <?php
    }

    public function render_settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'GiftCard Studio Settings', 'gift-card-studio' ); ?></h1>
            <?php
            $this->render_overview_section();
            $this->render_instructions_section();
            ?>
            <form method="post" action="options.php">
                <?php
                settings_fields( self::OPTION_GROUP );
                do_settings_sections( 'giftcard-studio-settings' );
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }
}

new CGC_Admin_Settings();
