<?php
/**
 * GGM Commerce Discounts Admin Tab
 *
 * @package GGM_Commerce
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Render the Discounts admin tab
 */
function ggmc_render_discounts_tab() {
    // Ensure discounts class is loaded.
    if ( ! class_exists( 'GGM_Commerce_Discounts' ) ) {
        require_once plugin_dir_path( __FILE__ ) . 'class-discounts.php';
    }

    $discounts_handler = GGM_Commerce_Discounts::get_instance();

    // Handle pagination.
    $page = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
    $per_page = 20;

    // Get filters.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $status_filter = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $type_filter = isset( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';

    $discounts_data = $discounts_handler->list_discounts( array(
        'page'     => $page,
        'per_page' => $per_page,
        'status'   => $status_filter,
        'type'     => $type_filter,
        'search'   => $search,
    ) );

    $nonce = wp_create_nonce( 'ggmc_discount_admin' );
    ?>
    <div class="wrap ggmc-discounts-admin">
        <?php GGM_Commerce_Admin::page_title( __( 'Discounts & Vouchers', 'ggm-commerce' ) ); ?>
        <div class="ggmc-discount-grid">
            <!-- Left Column: Discount List -->
            <div>
                <div class="ggmc-discount-section">
                    <h2>
                        <span class="dashicons dashicons-tag"></span>
                        <?php esc_html_e( 'Discounts & Vouchers', 'ggm-commerce' ); ?>
                    </h2>

                    <!-- Filters -->
                    <form class="ggmc-filters" method="get">
                        <input type="hidden" name="page" value="ggmc-settings">
                        <input type="hidden" name="tab" value="discounts">

                        <div class="ggmc-form-group">
                            <label for="discount-search"><?php esc_html_e( 'Search', 'ggm-commerce' ); ?></label>
                            <input type="text" id="discount-search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Code or name...', 'ggm-commerce' ); ?>">
                        </div>

                        <div class="ggmc-form-group">
                            <label for="discount-status"><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></label>
                            <select id="discount-status" name="status">
                                <option value=""><?php esc_html_e( 'All Statuses', 'ggm-commerce' ); ?></option>
                                <option value="active" <?php selected( $status_filter, 'active' ); ?>><?php esc_html_e( 'Active', 'ggm-commerce' ); ?></option>
                                <option value="inactive" <?php selected( $status_filter, 'inactive' ); ?>><?php esc_html_e( 'Inactive', 'ggm-commerce' ); ?></option>
                            </select>
                        </div>

                        <div class="ggmc-form-group">
                            <label for="discount-type"><?php esc_html_e( 'Type', 'ggm-commerce' ); ?></label>
                            <select id="discount-type" name="type">
                                <option value=""><?php esc_html_e( 'All Types', 'ggm-commerce' ); ?></option>
                                <option value="percentage" <?php selected( $type_filter, 'percentage' ); ?>><?php esc_html_e( 'Percentage', 'ggm-commerce' ); ?></option>
                                <option value="fixed_amount" <?php selected( $type_filter, 'fixed_amount' ); ?>><?php esc_html_e( 'Fixed Amount', 'ggm-commerce' ); ?></option>
                                <option value="voucher" <?php selected( $type_filter, 'voucher' ); ?>><?php esc_html_e( 'Voucher', 'ggm-commerce' ); ?></option>
                            </select>
                        </div>

                        <div class="ggmc-form-group">
                            <label>&nbsp;</label>
                            <button type="submit" class="button"><?php esc_html_e( 'Filter', 'ggm-commerce' ); ?></button>
                        </div>
                    </form>

                    <!-- Message Container -->
                    <div id="discount-message"></div>

                    <!-- Discounts Table -->
                    <table class="ggmc-discounts-table" id="discounts-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Code', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Name', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Type', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Value', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Usage', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ( empty( $discounts_data['discounts'] ) ) : ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 40px;">
                                        <?php esc_html_e( 'No discounts found. Create your first discount using the form on the right.', 'ggm-commerce' ); ?>
                                    </td>
                                </tr>
                            <?php else : ?>
                                <?php foreach ( $discounts_data['discounts'] as $discount ) : ?>
                                    <?php
                                    $type_label = '';
                                    $value_display = '';
                                    switch ( $discount->discount_type ) {
                                        case 'percentage':
                                            $type_label = __( 'Percentage', 'ggm-commerce' );
                                            $value_display = $discount->amount . '%';
                                            break;
                                        case 'fixed_amount':
                                            $type_label = __( 'Fixed', 'ggm-commerce' );
                                            $value_display = GGM_Commerce_Helpers::format_price( $discount->amount );
                                            break;
                                        case 'voucher':
                                            $type_label = __( 'Voucher', 'ggm-commerce' );
                                            $value_display = GGM_Commerce_Helpers::format_price( $discount->current_balance );
                                            break;
                                    }

                                    $status_class = 'ggmc-status-' . $discount->status;

                                    // Check if expired.
                                    if ( $discount->valid_to && strtotime( $discount->valid_to ) < time() ) {
                                        $status_class = 'ggmc-status-expired';
                                        $discount->status = 'expired';
                                    }
                                    ?>
                                    <tr data-discount-id="<?php echo esc_attr( $discount->id ); ?>">
                                        <td>
                                            <span class="ggmc-discount-code"><?php echo esc_html( $discount->code ); ?></span>
                                        </td>
                                        <td><?php echo esc_html( $discount->name ); ?></td>
                                        <td>
                                            <span class="ggmc-discount-type ggmc-type-<?php echo esc_attr( $discount->discount_type ); ?>">
                                                <?php echo esc_html( $type_label ); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php echo esc_html( $value_display ); ?>
                                            <?php if ( 'voucher' === $discount->discount_type && $discount->initial_value != $discount->current_balance ) : ?>
                                                <div class="ggmc-voucher-balance">
                                                    <?php
                                                    printf(
                                                        /* translators: %s: initial value */
                                                        esc_html__( 'of %s', 'ggm-commerce' ),
                                                        esc_html( GGM_Commerce_Helpers::format_price( $discount->initial_value ) )
                                                    );
                                                    ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="ggmc-usage-info">
                                                <?php
                                                if ( $discount->usage_limit ) {
                                                    printf(
                                                        '%d / %d',
                                                        intval( $discount->usage_count ),
                                                        intval( $discount->usage_limit )
                                                    );
                                                } else {
                                                    echo esc_html( $discount->usage_count );
                                                }
                                                ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="ggmc-status-badge <?php echo esc_attr( $status_class ); ?>">
                                                <?php echo esc_html( ucfirst( $discount->status ) ); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="ggmc-actions">
                                                <button type="button" class="button button-small edit-discount" data-id="<?php echo esc_attr( $discount->id ); ?>">
                                                    <?php esc_html_e( 'Edit', 'ggm-commerce' ); ?>
                                                </button>
                                                <button type="button" class="button button-small button-link-delete delete-discount" data-id="<?php echo esc_attr( $discount->id ); ?>">
                                                    <?php esc_html_e( 'Delete', 'ggm-commerce' ); ?>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <?php if ( $discounts_data['total_pages'] > 1 ) : ?>
                        <div class="ggmc-pagination">
                            <div class="ggmc-pagination-info">
                                <?php
                                printf(
                                    /* translators: 1: first item number, 2: last item number, 3: total items */
                                    esc_html__( 'Showing %1$d-%2$d of %3$d', 'ggm-commerce' ),
                                    intval( ( ( $page - 1 ) * $per_page ) + 1 ),
                                    intval( min( $page * $per_page, $discounts_data['total'] ) ),
                                    intval( $discounts_data['total'] )
                                );
                                ?>
                            </div>
                            <div class="ggmc-pagination-links">
                                <?php
                                $base_url = admin_url( 'admin.php?page=ggmc-settings&tab=discounts' );
                                if ( $status_filter ) {
                                    $base_url .= '&status=' . $status_filter;
                                }
                                if ( $type_filter ) {
                                    $base_url .= '&type=' . $type_filter;
                                }
                                if ( $search ) {
                                    $base_url .= '&s=' . urlencode( $search );
                                }

                                if ( $page > 1 ) {
                                    echo '<a href="' . esc_url( $base_url . '&paged=' . ( $page - 1 ) ) . '">&laquo;</a>';
                                }

                                for ( $i = 1; $i <= $discounts_data['total_pages']; $i++ ) {
                                    if ( $i === $page ) {
                                        echo '<span class="current">' . esc_html( $i ) . '</span>';
                                    } else {
                                        echo '<a href="' . esc_url( $base_url . '&paged=' . $i ) . '">' . esc_html( $i ) . '</a>';
                                    }
                                }

                                if ( $page < $discounts_data['total_pages'] ) {
                                    echo '<a href="' . esc_url( $base_url . '&paged=' . ( $page + 1 ) ) . '">&raquo;</a>';
                                }
                                ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Right Column: Create/Edit Form & Bulk Generator -->
            <div>
                <!-- Create Discount Form -->
                <div class="ggmc-discount-section">
                    <h2>
                        <span class="dashicons dashicons-plus-alt"></span>
                        <?php esc_html_e( 'Create Discount', 'ggm-commerce' ); ?>
                    </h2>

                    <form id="create-discount-form">
                        <input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">

                        <div class="ggmc-form-grid">
                            <div class="ggmc-form-group">
                                <label for="new-code"><?php esc_html_e( 'Code', 'ggm-commerce' ); ?> *</label>
                                <input type="text" id="new-code" name="code" required style="text-transform: uppercase;">
                                <span class="description"><?php esc_html_e( 'Unique discount code', 'ggm-commerce' ); ?></span>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-name"><?php esc_html_e( 'Name', 'ggm-commerce' ); ?> *</label>
                                <input type="text" id="new-name" name="name" required>
                                <span class="description"><?php esc_html_e( 'Internal name', 'ggm-commerce' ); ?></span>
                            </div>

                            <div class="ggmc-form-group full-width">
                                <label for="new-description"><?php esc_html_e( 'Description', 'ggm-commerce' ); ?></label>
                                <textarea id="new-description" name="description" rows="2"></textarea>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-type"><?php esc_html_e( 'Discount Type', 'ggm-commerce' ); ?></label>
                                <select id="new-type" name="discount_type">
                                    <option value="percentage"><?php esc_html_e( 'Percentage', 'ggm-commerce' ); ?></option>
                                    <option value="fixed_amount"><?php esc_html_e( 'Fixed Amount', 'ggm-commerce' ); ?></option>
                                    <option value="voucher"><?php esc_html_e( 'Voucher / Gift Card', 'ggm-commerce' ); ?></option>
                                </select>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-amount"><?php esc_html_e( 'Amount', 'ggm-commerce' ); ?> *</label>
                                <input type="number" id="new-amount" name="amount" step="0.01" min="0" required>
                                <span class="description" id="amount-hint"><?php esc_html_e( 'Percentage value (e.g., 10 for 10%)', 'ggm-commerce' ); ?></span>
                            </div>

                            <!-- Voucher-specific options -->
                            <div class="ggmc-type-fields voucher-fields">
                                <div class="ggmc-form-group">
                                    <label>
                                        <input type="checkbox" name="single_use_voucher" value="1">
                                        <?php esc_html_e( 'Single-use voucher', 'ggm-commerce' ); ?>
                                    </label>
                                    <span class="description"><?php esc_html_e( 'Entire balance used at once', 'ggm-commerce' ); ?></span>
                                </div>
                            </div>

                            <!-- Percentage-specific options -->
                            <div class="ggmc-type-fields percentage-fields active">
                                <div class="ggmc-form-group">
                                    <label for="new-max-discount"><?php esc_html_e( 'Maximum Discount', 'ggm-commerce' ); ?></label>
                                    <input type="number" id="new-max-discount" name="maximum_discount_amount" step="0.01" min="0">
                                    <span class="description"><?php esc_html_e( 'Cap the discount amount', 'ggm-commerce' ); ?></span>
                                </div>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-min-order"><?php esc_html_e( 'Minimum Order', 'ggm-commerce' ); ?></label>
                                <input type="number" id="new-min-order" name="minimum_order_amount" step="0.01" min="0">
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-usage-limit"><?php esc_html_e( 'Usage Limit', 'ggm-commerce' ); ?></label>
                                <input type="number" id="new-usage-limit" name="usage_limit" min="0">
                                <span class="description"><?php esc_html_e( 'Leave empty for unlimited', 'ggm-commerce' ); ?></span>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-user-limit"><?php esc_html_e( 'Per User Limit', 'ggm-commerce' ); ?></label>
                                <input type="number" id="new-user-limit" name="usage_limit_per_user" min="0">
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-valid-from"><?php esc_html_e( 'Valid From', 'ggm-commerce' ); ?></label>
                                <input type="datetime-local" id="new-valid-from" name="valid_from">
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-valid-to"><?php esc_html_e( 'Valid To', 'ggm-commerce' ); ?></label>
                                <input type="datetime-local" id="new-valid-to" name="valid_to">
                            </div>

                            <div class="ggmc-form-group">
                                <label>
                                    <input type="checkbox" name="free_shipping" value="1">
                                    <?php esc_html_e( 'Free shipping', 'ggm-commerce' ); ?>
                                </label>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="new-status"><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></label>
                                <select id="new-status" name="status">
                                    <option value="active"><?php esc_html_e( 'Active', 'ggm-commerce' ); ?></option>
                                    <option value="inactive"><?php esc_html_e( 'Inactive', 'ggm-commerce' ); ?></option>
                                </select>
                            </div>
                        </div>

                        <div style="margin-top: 20px;">
                            <button type="submit" class="button button-primary" id="create-discount-btn">
                                <?php esc_html_e( 'Create Discount', 'ggm-commerce' ); ?>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Bulk Voucher Generator -->
                <div class="ggmc-discount-section">
                    <h2>
                        <span class="dashicons dashicons-tickets"></span>
                        <?php esc_html_e( 'Bulk Voucher Generator', 'ggm-commerce' ); ?>
                    </h2>

                    <form id="bulk-generate-form">
                        <input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">

                        <div class="ggmc-form-grid">
                            <div class="ggmc-form-group">
                                <label for="bulk-count"><?php esc_html_e( 'Number of Vouchers', 'ggm-commerce' ); ?> *</label>
                                <input type="number" id="bulk-count" name="count" min="1" max="1000" value="10" required>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="bulk-value"><?php esc_html_e( 'Value Each', 'ggm-commerce' ); ?> *</label>
                                <input type="number" id="bulk-value" name="value" step="0.01" min="0.01" required>
                            </div>

                            <div class="ggmc-form-group">
                                <label for="bulk-prefix"><?php esc_html_e( 'Code Prefix', 'ggm-commerce' ); ?></label>
                                <input type="text" id="bulk-prefix" name="prefix" value="GIFT" style="text-transform: uppercase;">
                            </div>

                            <div class="ggmc-form-group">
                                <label for="bulk-expiry"><?php esc_html_e( 'Expiry Date', 'ggm-commerce' ); ?></label>
                                <input type="date" id="bulk-expiry" name="expiry_date">
                            </div>

                            <div class="ggmc-form-group full-width">
                                <label>
                                    <input type="checkbox" name="single_use" value="1">
                                    <?php esc_html_e( 'Single-use vouchers (entire balance used at once)', 'ggm-commerce' ); ?>
                                </label>
                            </div>
                        </div>

                        <div style="margin-top: 20px;">
                            <button type="submit" class="button button-primary" id="bulk-generate-btn">
                                <?php esc_html_e( 'Generate Vouchers', 'ggm-commerce' ); ?>
                            </button>
                        </div>
                    </form>

                    <div id="bulk-result" style="display: none; margin-top: 15px;"></div>
                </div>
            </div>
        </div>

        <!-- Edit Modal -->
        <div class="ggmc-modal" id="edit-modal" style="display: none;">
            <div class="ggmc-modal-content">
                <div class="ggmc-modal-header">
                    <h3><?php esc_html_e( 'Edit Discount', 'ggm-commerce' ); ?></h3>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <form id="edit-discount-form">
                    <input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">
                    <input type="hidden" name="discount_id" id="edit-discount-id">

                    <div class="ggmc-modal-body">
                    <div class="ggmc-form-grid">
                        <div class="ggmc-form-group">
                            <label for="edit-code"><?php esc_html_e( 'Code', 'ggm-commerce' ); ?></label>
                            <input type="text" id="edit-code" disabled>
                            <span class="description"><?php esc_html_e( 'Code cannot be changed', 'ggm-commerce' ); ?></span>
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-name"><?php esc_html_e( 'Name', 'ggm-commerce' ); ?> *</label>
                            <input type="text" id="edit-name" name="name" required>
                        </div>

                        <div class="ggmc-form-group full-width">
                            <label for="edit-description"><?php esc_html_e( 'Description', 'ggm-commerce' ); ?></label>
                            <textarea id="edit-description" name="description" rows="2"></textarea>
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-amount"><?php esc_html_e( 'Amount', 'ggm-commerce' ); ?> *</label>
                            <input type="number" id="edit-amount" name="amount" step="0.01" min="0" required>
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-min-order"><?php esc_html_e( 'Minimum Order', 'ggm-commerce' ); ?></label>
                            <input type="number" id="edit-min-order" name="minimum_order_amount" step="0.01" min="0">
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-usage-limit"><?php esc_html_e( 'Usage Limit', 'ggm-commerce' ); ?></label>
                            <input type="number" id="edit-usage-limit" name="usage_limit" min="0">
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-user-limit"><?php esc_html_e( 'Per User Limit', 'ggm-commerce' ); ?></label>
                            <input type="number" id="edit-user-limit" name="usage_limit_per_user" min="0">
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-valid-from"><?php esc_html_e( 'Valid From', 'ggm-commerce' ); ?></label>
                            <input type="datetime-local" id="edit-valid-from" name="valid_from">
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-valid-to"><?php esc_html_e( 'Valid To', 'ggm-commerce' ); ?></label>
                            <input type="datetime-local" id="edit-valid-to" name="valid_to">
                        </div>

                        <div class="ggmc-form-group">
                            <label>
                                <input type="checkbox" id="edit-free-shipping" name="free_shipping" value="1">
                                <?php esc_html_e( 'Free shipping', 'ggm-commerce' ); ?>
                            </label>
                        </div>

                        <div class="ggmc-form-group">
                            <label for="edit-status"><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></label>
                            <select id="edit-status" name="status">
                                <option value="active"><?php esc_html_e( 'Active', 'ggm-commerce' ); ?></option>
                                <option value="inactive"><?php esc_html_e( 'Inactive', 'ggm-commerce' ); ?></option>
                            </select>
                        </div>
                    </div>
                    </div>

                    <div class="ggmc-modal-footer">
                        <button type="submit" class="button button-primary" id="update-discount-btn">
                            <?php esc_html_e( 'Update Discount', 'ggm-commerce' ); ?>
                        </button>
                        <button type="button" class="button ggmc-modal-close">
                            <?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <script>
        (function($) {
            'use strict';

            var nonce = '<?php echo esc_js( $nonce ); ?>';

            // Type change handler
            $('#new-type').on('change', function() {
                var type = $(this).val();
                $('.ggmc-type-fields').removeClass('active');

                if (type === 'voucher') {
                    $('.voucher-fields').addClass('active');
                    $('#amount-hint').text('<?php echo esc_js( __( 'Voucher value', 'ggm-commerce' ) ); ?>');
                } else if (type === 'percentage') {
                    $('.percentage-fields').addClass('active');
                    $('#amount-hint').text('<?php echo esc_js( __( 'Percentage value (e.g., 10 for 10%)', 'ggm-commerce' ) ); ?>');
                } else {
                    $('#amount-hint').text('<?php echo esc_js( __( 'Fixed discount amount', 'ggm-commerce' ) ); ?>');
                }
            });

            // Create discount
            $('#create-discount-form').on('submit', function(e) {
                e.preventDefault();

                var $btn = $('#create-discount-btn');
                var $form = $(this);

                $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Creating...', 'ggm-commerce' ) ); ?>');

                var formData = {
                    action: 'ggmc_create_discount',
                    nonce: nonce,
                    discount: {}
                };

                $form.find('input, select, textarea').each(function() {
                    var $input = $(this);
                    var name = $input.attr('name');
                    if (!name || name === 'nonce') return;

                    if ($input.is(':checkbox')) {
                        formData.discount[name] = $input.is(':checked') ? 1 : 0;
                    } else {
                        formData.discount[name] = $input.val();
                    }
                });

                $.post(ajaxurl, formData, function(response) {
                    if (response.success) {
                        showMessage('success', response.data.message || '<?php echo esc_js( __( 'Discount created successfully.', 'ggm-commerce' ) ); ?>');
                        $form[0].reset();
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        showMessage('error', response.data.error || response.data.message || '<?php echo esc_js( __( 'Failed to create discount.', 'ggm-commerce' ) ); ?>');
                    }
                }).fail(function() {
                    showMessage('error', '<?php echo esc_js( __( 'Request failed. Please try again.', 'ggm-commerce' ) ); ?>');
                }).always(function() {
                    $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Create Discount', 'ggm-commerce' ) ); ?>');
                });
            });

            // Bulk generate vouchers
            $('#bulk-generate-form').on('submit', function(e) {
                e.preventDefault();

                var $btn = $('#bulk-generate-btn');
                var $form = $(this);
                var $result = $('#bulk-result');

                $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Generating...', 'ggm-commerce' ) ); ?>');

                $.post(ajaxurl, {
                    action: 'ggmc_bulk_generate_vouchers',
                    nonce: nonce,
                    count: $('#bulk-count').val(),
                    value: $('#bulk-value').val(),
                    prefix: $('#bulk-prefix').val(),
                    expiry_date: $('#bulk-expiry').val(),
                    single_use: $form.find('input[name="single_use"]').is(':checked') ? 1 : 0
                }, function(response) {
                    if (response.success && response.data.generated) {
                        var codesHtml = '<div class="ggmc-message ggmc-message-success">' + response.data.message + '</div>';
                        codesHtml += '<p><strong><?php echo esc_js( __( 'Generated Codes:', 'ggm-commerce' ) ); ?></strong></p>';
                        codesHtml += '<div class="ggmc-voucher-codes-list">';
                        response.data.generated.forEach(function(code) {
                            codesHtml += '<code>' + code + '</code>';
                        });
                        codesHtml += '</div>';
                        codesHtml += '<button type="button" class="button" style="margin-top: 10px;" onclick="navigator.clipboard.writeText(\'' + response.data.generated.join('\\n') + '\'); alert(\'<?php echo esc_js( __( 'Codes copied to clipboard!', 'ggm-commerce' ) ); ?>\');"><?php echo esc_js( __( 'Copy All Codes', 'ggm-commerce' ) ); ?></button>';

                        $result.html(codesHtml).show();
                    } else {
                        $result.html('<div class="ggmc-message ggmc-message-error">' + (response.data.error || '<?php echo esc_js( __( 'Failed to generate vouchers.', 'ggm-commerce' ) ); ?>') + '</div>').show();
                    }
                }).fail(function() {
                    $result.html('<div class="ggmc-message ggmc-message-error"><?php echo esc_js( __( 'Request failed. Please try again.', 'ggm-commerce' ) ); ?></div>').show();
                }).always(function() {
                    $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Generate Vouchers', 'ggm-commerce' ) ); ?>');
                });
            });

            // Edit discount
            $(document).on('click', '.edit-discount', function() {
                var discountId = $(this).data('id');
                var $row = $(this).closest('tr');
                var $modal = $('#edit-modal');

                // For now, populate from row data - in production would fetch via AJAX
                $modal.find('#edit-discount-id').val(discountId);
                $modal.fadeIn(200);

                // Fetch full discount data
                $.post(ajaxurl, {
                    action: 'ggmc_get_discount',
                    nonce: nonce,
                    discount_id: discountId
                }, function(response) {
                    if (response.success && response.data) {
                        var d = response.data;
                        $('#edit-code').val(d.code);
                        $('#edit-name').val(d.name);
                        $('#edit-description').val(d.description);
                        $('#edit-amount').val(d.amount);
                        $('#edit-min-order').val(d.minimum_order_amount);
                        $('#edit-usage-limit').val(d.usage_limit);
                        $('#edit-user-limit').val(d.usage_limit_per_user);
                        $('#edit-valid-from').val(d.valid_from ? d.valid_from.replace(' ', 'T').slice(0, 16) : '');
                        $('#edit-valid-to').val(d.valid_to ? d.valid_to.replace(' ', 'T').slice(0, 16) : '');
                        $('#edit-free-shipping').prop('checked', d.free_shipping == 1);
                        $('#edit-status').val(d.status);
                    }
                });
            });

            // Update discount
            $('#edit-discount-form').on('submit', function(e) {
                e.preventDefault();

                var $btn = $('#update-discount-btn');
                var $form = $(this);

                $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Updating...', 'ggm-commerce' ) ); ?>');

                var formData = {
                    action: 'ggmc_update_discount',
                    nonce: nonce,
                    discount_id: $('#edit-discount-id').val(),
                    discount: {}
                };

                $form.find('input:not([type="hidden"]):not(:disabled), select, textarea').each(function() {
                    var $input = $(this);
                    var name = $input.attr('name');
                    if (!name || name === 'nonce' || name === 'discount_id') return;

                    if ($input.is(':checkbox')) {
                        formData.discount[name] = $input.is(':checked') ? 1 : 0;
                    } else {
                        formData.discount[name] = $input.val();
                    }
                });

                $.post(ajaxurl, formData, function(response) {
                    if (response.success) {
                        showMessage('success', response.data.message || '<?php echo esc_js( __( 'Discount updated successfully.', 'ggm-commerce' ) ); ?>');
                        $('#edit-modal').fadeOut(200);
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        showMessage('error', response.data.error || response.data.message || '<?php echo esc_js( __( 'Failed to update discount.', 'ggm-commerce' ) ); ?>');
                    }
                }).fail(function() {
                    showMessage('error', '<?php echo esc_js( __( 'Request failed. Please try again.', 'ggm-commerce' ) ); ?>');
                }).always(function() {
                    $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Update Discount', 'ggm-commerce' ) ); ?>');
                });
            });

            // Delete discount
            $(document).on('click', '.delete-discount', function() {
                if (!confirm('<?php echo esc_js( __( 'Are you sure you want to delete this discount?', 'ggm-commerce' ) ); ?>')) {
                    return;
                }

                var discountId = $(this).data('id');
                var $row = $(this).closest('tr');

                $row.addClass('ggmc-loading');

                $.post(ajaxurl, {
                    action: 'ggmc_delete_discount',
                    nonce: nonce,
                    discount_id: discountId
                }, function(response) {
                    if (response.success) {
                        $row.fadeOut(300, function() {
                            $(this).remove();
                        });
                        showMessage('success', response.data.message || '<?php echo esc_js( __( 'Discount deleted.', 'ggm-commerce' ) ); ?>');
                    } else {
                        $row.removeClass('ggmc-loading');
                        showMessage('error', response.data.error || '<?php echo esc_js( __( 'Failed to delete discount.', 'ggm-commerce' ) ); ?>');
                    }
                }).fail(function() {
                    $row.removeClass('ggmc-loading');
                    showMessage('error', '<?php echo esc_js( __( 'Request failed.', 'ggm-commerce' ) ); ?>');
                });
            });

            // Close modal
            $(document).on('click', '.ggmc-modal-close', function() {
                $(this).closest('.ggmc-modal').fadeOut(200);
            });

            $(document).on('click', '.ggmc-modal', function(e) {
                if ($(e.target).hasClass('ggmc-modal')) {
                    $(this).fadeOut(200);
                }
            });

            // Helper function
            function showMessage(type, message) {
                var $container = $('#discount-message');
                $container.html('<div class="ggmc-message ggmc-message-' + type + '">' + message + '</div>');
                setTimeout(function() {
                    $container.find('.ggmc-message').fadeOut(300, function() {
                        $(this).remove();
                    });
                }, 5000);
            }

        })(jQuery);
        </script>
    </div>
    <?php
}
