<?php
/**
 * Admin interface for Maple Carts.
 *
 * @package MapleCarts
 */

defined( 'ABSPATH' ) || exit;

/**
 * Admin class.
 */
class Maple_Carts_Admin {

    /**
     * Single instance.
     *
     * @var Maple_Carts_Admin
     */
    private static $instance = null;

    /**
     * Get instance.
     *
     * @return Maple_Carts_Admin
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'admin_menu', [ $this, 'add_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
        add_action( 'admin_init', [ $this, 'handle_actions' ] );
        
        // AJAX handlers.
        add_action( 'wp_ajax_maple_carts_delete_cart', [ $this, 'ajax_delete_cart' ] );
        add_action( 'wp_ajax_maple_carts_save_template', [ $this, 'ajax_save_template' ] );
        add_action( 'wp_ajax_maple_carts_delete_template', [ $this, 'ajax_delete_template' ] );
        add_action( 'wp_ajax_maple_carts_toggle_template', [ $this, 'ajax_toggle_template' ] );
    }

    /**
     * Add admin menu.
     */
    public function add_menu() {
        add_menu_page(
            __( 'Maple Carts', 'maple-carts' ),
            __( 'Maple Carts', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts',
            [ $this, 'render_dashboard' ],
            'dashicons-cart',
            56
        );

        add_submenu_page(
            'maple-carts',
            __( 'Dashboard', 'maple-carts' ),
            __( 'Dashboard', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts',
            [ $this, 'render_dashboard' ]
        );

        add_submenu_page(
            'maple-carts',
            __( 'Abandoned Carts', 'maple-carts' ),
            __( 'Abandoned Carts', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts-abandoned',
            [ $this, 'render_abandoned_carts' ]
        );

        add_submenu_page(
            'maple-carts',
            __( 'Recovered Carts', 'maple-carts' ),
            __( 'Recovered Carts', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts-recovered',
            [ $this, 'render_recovered_carts' ]
        );

        add_submenu_page(
            'maple-carts',
            __( 'Email Templates', 'maple-carts' ),
            __( 'Email Templates', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts-emails',
            [ $this, 'render_email_templates' ]
        );

        add_submenu_page(
            'maple-carts',
            __( 'Settings', 'maple-carts' ),
            __( 'Settings', 'maple-carts' ),
            'manage_woocommerce',
            'maple-carts-settings',
            [ $this, 'render_settings' ]
        );
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_scripts( $hook ) {
        if ( strpos( $hook, 'maple-carts' ) === false ) {
            return;
        }

        wp_enqueue_style(
            'maple-carts-admin',
            MAPLE_CARTS_URL . 'assets/css/admin.css',
            [],
            MAPLE_CARTS_VERSION
        );

        wp_enqueue_script(
            'maple-carts-admin',
            MAPLE_CARTS_URL . 'assets/js/admin.js',
            [ 'jquery' ],
            MAPLE_CARTS_VERSION,
            true
        );

        wp_localize_script( 'maple-carts-admin', 'mapleCartsAdmin', [
            'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            'nonce'          => wp_create_nonce( 'maple_carts_admin' ),
            'confirmDelete'  => __( 'Are you sure you want to delete this?', 'maple-carts' ),
            'saving'         => __( 'Saving...', 'maple-carts' ),
            'saved'          => __( 'Saved!', 'maple-carts' ),
        ] );

        // Enqueue WP editor for email templates.
        if ( strpos( $hook, 'maple-carts-emails' ) !== false ) {
            wp_enqueue_editor();
        }
    }

    /**
     * Handle form actions.
     */
    public function handle_actions() {
        // Save settings.
        if ( isset( $_POST['maple_carts_save_settings'] ) && check_admin_referer( 'maple_carts_settings' ) ) {
            $this->save_settings();
        }
    }

    /**
     * Save settings.
     */
    private function save_settings() {
        $settings = [
            'enabled'           => isset( $_POST['enabled'] ) ? 'yes' : 'no',
            'cart_cutoff_time'  => absint( $_POST['cart_cutoff_time'] ?? 15 ),
            'delete_after_days' => absint( $_POST['delete_after_days'] ?? 90 ),
            'email_mode'        => isset( $_POST['email_mode'] ) && 'mailjet' === $_POST['email_mode'] ? 'mailjet' : 'builtin',
            'mailjet_api_key'   => sanitize_text_field( wp_unslash( $_POST['mailjet_api_key'] ?? '' ) ),
            'mailjet_secret_key'=> sanitize_text_field( wp_unslash( $_POST['mailjet_secret_key'] ?? '' ) ),
            'from_name'         => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? '' ) ),
            'from_email'        => sanitize_email( wp_unslash( $_POST['from_email'] ?? '' ) ),
            'reply_to'          => sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) ),
            'notify_admin'      => isset( $_POST['notify_admin'] ) ? 'yes' : 'no',
            'admin_email'       => sanitize_email( wp_unslash( $_POST['admin_email'] ?? '' ) ),
            'require_consent'   => isset( $_POST['require_consent'] ) ? 'yes' : 'no',
            'consent_text'      => sanitize_text_field( wp_unslash( $_POST['consent_text'] ?? '' ) ),
            'show_delete_link'  => isset( $_POST['show_delete_link'] ) ? 'yes' : 'no',
            'gdpr_notice'       => sanitize_textarea_field( wp_unslash( $_POST['gdpr_notice'] ?? '' ) ),
            'exclude_roles'     => isset( $_POST['exclude_roles'] ) ? array_map( 'sanitize_text_field', $_POST['exclude_roles'] ) : [],
        ];

        update_option( 'maple_carts_settings', $settings );

        add_settings_error( 'maple_carts', 'settings_saved', __( 'Settings saved.', 'maple-carts' ), 'success' );
    }

    /**
     * Render dashboard page.
     */
    public function render_dashboard() {
        $period = isset( $_GET['period'] ) ? sanitize_text_field( wp_unslash( $_GET['period'] ) ) : '30days';
        $stats  = Maple_Carts_DB::get_stats( $period );
        ?>
        <div class="wrap maple-carts-wrap">
            <h1><?php esc_html_e( 'Maple Carts Dashboard', 'maple-carts' ); ?></h1>

            <div class="maple-carts-period-selector">
                <a href="<?php echo esc_url( add_query_arg( 'period', '7days' ) ); ?>" 
                   class="<?php echo '7days' === $period ? 'active' : ''; ?>">
                    <?php esc_html_e( 'Last 7 Days', 'maple-carts' ); ?>
                </a>
                <a href="<?php echo esc_url( add_query_arg( 'period', '30days' ) ); ?>"
                   class="<?php echo '30days' === $period ? 'active' : ''; ?>">
                    <?php esc_html_e( 'Last 30 Days', 'maple-carts' ); ?>
                </a>
                <a href="<?php echo esc_url( add_query_arg( 'period', 'all' ) ); ?>"
                   class="<?php echo 'all' === $period ? 'active' : ''; ?>">
                    <?php esc_html_e( 'All Time', 'maple-carts' ); ?>
                </a>
            </div>

            <div class="maple-carts-stats-grid">
                <div class="maple-carts-stat-box">
                    <span class="stat-number"><?php echo esc_html( $stats['abandoned'] ); ?></span>
                    <span class="stat-label"><?php esc_html_e( 'Abandoned Carts', 'maple-carts' ); ?></span>
                    <span class="stat-value"><?php echo wc_price( $stats['abandoned_value'] ); ?></span>
                </div>

                <div class="maple-carts-stat-box stat-success">
                    <span class="stat-number"><?php echo esc_html( $stats['recovered'] ); ?></span>
                    <span class="stat-label"><?php esc_html_e( 'Recovered', 'maple-carts' ); ?></span>
                    <span class="stat-value"><?php echo wc_price( $stats['recovered_value'] ); ?></span>
                </div>

                <div class="maple-carts-stat-box">
                    <span class="stat-number"><?php echo esc_html( $stats['recovery_rate'] ); ?>%</span>
                    <span class="stat-label"><?php esc_html_e( 'Recovery Rate', 'maple-carts' ); ?></span>
                </div>

                <div class="maple-carts-stat-box stat-muted">
                    <span class="stat-number"><?php echo esc_html( $stats['lost'] ); ?></span>
                    <span class="stat-label"><?php esc_html_e( 'Lost Carts', 'maple-carts' ); ?></span>
                </div>
            </div>

            <div class="maple-carts-quick-links">
                <h2><?php esc_html_e( 'Quick Links', 'maple-carts' ); ?></h2>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=maple-carts-abandoned' ) ); ?>" class="button">
                    <?php esc_html_e( 'View Abandoned Carts', 'maple-carts' ); ?>
                </a>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=maple-carts-emails' ) ); ?>" class="button">
                    <?php esc_html_e( 'Email Templates', 'maple-carts' ); ?>
                </a>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=maple-carts-settings' ) ); ?>" class="button">
                    <?php esc_html_e( 'Settings', 'maple-carts' ); ?>
                </a>
            </div>
        </div>
        <?php
    }

    /**
     * Render abandoned carts page.
     */
    public function render_abandoned_carts() {
        $this->render_carts_table( 'abandoned', __( 'Abandoned Carts', 'maple-carts' ) );
    }

    /**
     * Render recovered carts page.
     */
    public function render_recovered_carts() {
        $this->render_carts_table( 'recovered', __( 'Recovered Carts', 'maple-carts' ) );
    }

    /**
     * Render carts table.
     *
     * @param string $status Page status.
     * @param string $title  Page title.
     */
    private function render_carts_table( $status, $title ) {
        $page    = isset( $_GET['paged'] ) ? max( 1, absint( $_GET['paged'] ) ) : 1;
        $limit   = 20;
        $offset  = ( $page - 1 ) * $limit;
        $carts   = Maple_Carts_DB::get_carts_by_status( $status, $limit, $offset );
        $total   = Maple_Carts_DB::count_carts_by_status( $status );
        $pages   = ceil( $total / $limit );
        ?>
        <div class="wrap maple-carts-wrap">
            <h1><?php echo esc_html( $title ); ?></h1>

            <?php if ( empty( $carts ) ) : ?>
                <p><?php esc_html_e( 'No carts found.', 'maple-carts' ); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Email', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Customer', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Cart Total', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Products', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Date', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'maple-carts' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $carts as $cart ) : 
                            $cart_contents = maybe_unserialize( $cart->cart_contents );
                            $product_count = is_array( $cart_contents ) ? count( $cart_contents ) : 0;
                        ?>
                            <tr data-cart-id="<?php echo esc_attr( $cart->id ); ?>">
                                <td>
                                    <strong><?php echo esc_html( $cart->email ); ?></strong>
                                    <?php if ( $cart->unsubscribed ) : ?>
                                        <span class="maple-carts-badge badge-muted"><?php esc_html_e( 'Unsubscribed', 'maple-carts' ); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html( $cart->customer_name ?: '—' ); ?></td>
                                <td><?php echo wc_price( $cart->cart_total, [ 'currency' => $cart->currency ] ); ?></td>
                                <td>
                                    <?php 
                                    printf(
                                        /* translators: %d: number of products */
                                        esc_html( _n( '%d product', '%d products', $product_count, 'maple-carts' ) ),
                                        $product_count
                                    );
                                    ?>
                                    <button type="button" class="button-link maple-carts-view-products" data-cart="<?php echo esc_attr( wp_json_encode( $cart_contents ) ); ?>">
                                        <?php esc_html_e( 'View', 'maple-carts' ); ?>
                                    </button>
                                </td>
                                <td>
                                    <?php 
                                    $date = 'recovered' === $status && $cart->recovered_at 
                                        ? $cart->recovered_at 
                                        : ( $cart->abandoned_at ?: $cart->created_at );
                                    echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $date ) ) );
                                    ?>
                                </td>
                                <td>
                                    <button type="button" class="button-link maple-carts-delete-cart" data-id="<?php echo esc_attr( $cart->id ); ?>">
                                        <?php esc_html_e( 'Delete', 'maple-carts' ); ?>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if ( $pages > 1 ) : ?>
                    <div class="tablenav bottom">
                        <div class="tablenav-pages">
                            <?php
                            echo paginate_links( [
                                'base'      => add_query_arg( 'paged', '%#%' ),
                                'format'    => '',
                                'prev_text' => '&laquo;',
                                'next_text' => '&raquo;',
                                'total'     => $pages,
                                'current'   => $page,
                            ] );
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Products modal -->
        <div id="maple-carts-products-modal" class="maple-carts-modal" style="display:none;">
            <div class="maple-carts-modal-content">
                <span class="maple-carts-modal-close">&times;</span>
                <h3><?php esc_html_e( 'Cart Contents', 'maple-carts' ); ?></h3>
                <div id="maple-carts-products-list"></div>
            </div>
        </div>
        <?php
    }

    /**
     * Render email templates page.
     */
    public function render_email_templates() {
        $templates = Maple_Carts_DB::get_email_templates();
        $editing   = isset( $_GET['edit'] ) ? absint( $_GET['edit'] ) : 0;
        $template  = $editing ? Maple_Carts_DB::get_email_template( $editing ) : null;
        ?>
        <div class="wrap maple-carts-wrap">
            <h1>
                <?php esc_html_e( 'Email Templates', 'maple-carts' ); ?>
                <a href="<?php echo esc_url( add_query_arg( 'edit', 'new' ) ); ?>" class="page-title-action">
                    <?php esc_html_e( 'Add New', 'maple-carts' ); ?>
                </a>
            </h1>

            <?php if ( $editing || isset( $_GET['edit'] ) ) : ?>
                <!-- Template Editor -->
                <div class="maple-carts-template-editor">
                    <form id="maple-carts-template-form">
                        <input type="hidden" name="id" value="<?php echo esc_attr( $template ? $template->id : '' ); ?>">
                        
                        <table class="form-table">
                            <tr>
                                <th><label for="template-name"><?php esc_html_e( 'Template Name', 'maple-carts' ); ?></label></th>
                                <td>
                                    <input type="text" id="template-name" name="name" class="regular-text" 
                                           value="<?php echo esc_attr( $template ? $template->name : '' ); ?>" required>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="template-subject"><?php esc_html_e( 'Email Subject', 'maple-carts' ); ?></label></th>
                                <td>
                                    <input type="text" id="template-subject" name="subject" class="large-text" 
                                           value="<?php echo esc_attr( $template ? $template->subject : '' ); ?>" required>
                                    <p class="description"><?php esc_html_e( 'Available: {{customer_name}}, {{cart_total}}, {{coupon_code}}, {{coupon_amount}}', 'maple-carts' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="template-body"><?php esc_html_e( 'Email Body', 'maple-carts' ); ?></label></th>
                                <td>
                                    <?php 
                                    wp_editor( 
                                        $template ? $template->body : '', 
                                        'template-body', 
                                        [
                                            'textarea_name' => 'body',
                                            'textarea_rows' => 15,
                                            'media_buttons' => false,
                                        ]
                                    ); 
                                    ?>
                                    <p class="description">
                                        <?php esc_html_e( 'Available placeholders:', 'maple-carts' ); ?><br>
                                        <code>{{customer_name}}</code>, <code>{{customer_email}}</code>, <code>{{cart_contents}}</code>, <code>{{cart_total}}</code>, <code>{{product_names}}</code>, <code>{{recovery_url}}</code>, <code>{{coupon_code}}</code>, <code>{{coupon_amount}}</code>, <code>{{coupon_expires}}</code>, <code>{{site_name}}</code>, <code>{{unsubscribe_link}}</code>, <code>{{delete_data_link}}</code>
                                    </p>
                                </td>
                            </tr>
                            <tr>
                                <th><label><?php esc_html_e( 'Send After', 'maple-carts' ); ?></label></th>
                                <td>
                                    <input type="number" name="delay_value" min="1" class="small-text" 
                                           value="<?php echo esc_attr( $template ? $template->delay_value : 1 ); ?>">
                                    <select name="delay_unit">
                                        <option value="minutes" <?php selected( $template && $template->delay_unit, 'minutes' ); ?>><?php esc_html_e( 'Minutes', 'maple-carts' ); ?></option>
                                        <option value="hours" <?php selected( ! $template || $template->delay_unit === 'hours', true ); ?>><?php esc_html_e( 'Hours', 'maple-carts' ); ?></option>
                                        <option value="days" <?php selected( $template && $template->delay_unit, 'days' ); ?>><?php esc_html_e( 'Days', 'maple-carts' ); ?></option>
                                    </select>
                                    <p class="description"><?php esc_html_e( 'Time after cart is abandoned before sending this email.', 'maple-carts' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th><label><?php esc_html_e( 'Include Coupon', 'maple-carts' ); ?></label></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="include_coupon" value="1" 
                                               <?php checked( $template && $template->include_coupon ); ?>>
                                        <?php esc_html_e( 'Generate a unique coupon code for this email', 'maple-carts' ); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr class="coupon-settings" <?php echo ( ! $template || ! $template->include_coupon ) ? 'style="display:none;"' : ''; ?>>
                                <th><label><?php esc_html_e( 'Coupon Type', 'maple-carts' ); ?></label></th>
                                <td>
                                    <select name="coupon_type">
                                        <option value="percent" <?php selected( ! $template || $template->coupon_type === 'percent', true ); ?>><?php esc_html_e( 'Percentage Discount', 'maple-carts' ); ?></option>
                                        <option value="fixed_cart" <?php selected( $template && $template->coupon_type, 'fixed_cart' ); ?>><?php esc_html_e( 'Fixed Cart Discount', 'maple-carts' ); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr class="coupon-settings" <?php echo ( ! $template || ! $template->include_coupon ) ? 'style="display:none;"' : ''; ?>>
                                <th><label><?php esc_html_e( 'Coupon Amount', 'maple-carts' ); ?></label></th>
                                <td>
                                    <input type="number" name="coupon_amount" min="0" step="0.01" class="small-text" 
                                           value="<?php echo esc_attr( $template ? $template->coupon_amount : 10 ); ?>">
                                </td>
                            </tr>
                            <tr class="coupon-settings" <?php echo ( ! $template || ! $template->include_coupon ) ? 'style="display:none;"' : ''; ?>>
                                <th><label><?php esc_html_e( 'Coupon Expires', 'maple-carts' ); ?></label></th>
                                <td>
                                    <input type="number" name="coupon_expires_days" min="0" class="small-text" 
                                           value="<?php echo esc_attr( $template ? $template->coupon_expires_days : 7 ); ?>">
                                    <?php esc_html_e( 'days after email is sent (0 = no expiry)', 'maple-carts' ); ?>
                                </td>
                            </tr>
                            <tr>
                                <th><label><?php esc_html_e( 'Status', 'maple-carts' ); ?></label></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="is_active" value="1" 
                                               <?php checked( $template && $template->is_active ); ?>>
                                        <?php esc_html_e( 'Active', 'maple-carts' ); ?>
                                    </label>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save Template', 'maple-carts' ); ?></button>
                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=maple-carts-emails' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'maple-carts' ); ?></a>
                            <button type="button" class="button maple-carts-preview-email"><?php esc_html_e( 'Preview', 'maple-carts' ); ?></button>
                            <button type="button" class="button maple-carts-test-email"><?php esc_html_e( 'Send Test Email', 'maple-carts' ); ?></button>
                        </p>
                    </form>
                </div>

            <?php else : ?>
                <!-- Templates List -->
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Name', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Subject', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Send After', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Coupon', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'maple-carts' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'maple-carts' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ( empty( $templates ) ) : ?>
                            <tr>
                                <td colspan="6"><?php esc_html_e( 'No email templates found.', 'maple-carts' ); ?></td>
                            </tr>
                        <?php else : ?>
                            <?php foreach ( $templates as $tmpl ) : ?>
                                <tr>
                                    <td><strong><?php echo esc_html( $tmpl->name ); ?></strong></td>
                                    <td><?php echo esc_html( $tmpl->subject ); ?></td>
                                    <td><?php echo esc_html( $tmpl->delay_value . ' ' . $tmpl->delay_unit ); ?></td>
                                    <td>
                                        <?php if ( $tmpl->include_coupon ) : ?>
                                            <?php 
                                            echo $tmpl->coupon_type === 'percent' 
                                                ? esc_html( $tmpl->coupon_amount . '%' )
                                                : wc_price( $tmpl->coupon_amount );
                                            ?>
                                        <?php else : ?>
                                            —
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="maple-carts-toggle-template button-link" 
                                                data-id="<?php echo esc_attr( $tmpl->id ); ?>"
                                                data-active="<?php echo esc_attr( $tmpl->is_active ); ?>">
                                            <?php if ( $tmpl->is_active ) : ?>
                                                <span class="maple-carts-badge badge-success"><?php esc_html_e( 'Active', 'maple-carts' ); ?></span>
                                            <?php else : ?>
                                                <span class="maple-carts-badge badge-muted"><?php esc_html_e( 'Inactive', 'maple-carts' ); ?></span>
                                            <?php endif; ?>
                                        </button>
                                    </td>
                                    <td>
                                        <a href="<?php echo esc_url( add_query_arg( 'edit', $tmpl->id ) ); ?>" class="button-link">
                                            <?php esc_html_e( 'Edit', 'maple-carts' ); ?>
                                        </a>
                                        |
                                        <button type="button" class="button-link maple-carts-delete-template" data-id="<?php echo esc_attr( $tmpl->id ); ?>">
                                            <?php esc_html_e( 'Delete', 'maple-carts' ); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Preview modal -->
        <div id="maple-carts-preview-modal" class="maple-carts-modal" style="display:none;">
            <div class="maple-carts-modal-content maple-carts-modal-large">
                <span class="maple-carts-modal-close">&times;</span>
                <h3><?php esc_html_e( 'Email Preview', 'maple-carts' ); ?></h3>
                <div class="maple-carts-preview-subject"></div>
                <iframe id="maple-carts-preview-frame" style="width:100%;height:500px;border:1px solid #ddd;"></iframe>
            </div>
        </div>

        <!-- Test email modal -->
        <div id="maple-carts-test-modal" class="maple-carts-modal" style="display:none;">
            <div class="maple-carts-modal-content">
                <span class="maple-carts-modal-close">&times;</span>
                <h3><?php esc_html_e( 'Send Test Email', 'maple-carts' ); ?></h3>
                <p>
                    <label for="test-email-address"><?php esc_html_e( 'Send to:', 'maple-carts' ); ?></label>
                    <input type="email" id="test-email-address" class="regular-text" 
                           value="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
                </p>
                <p>
                    <button type="button" class="button button-primary maple-carts-send-test">
                        <?php esc_html_e( 'Send Test', 'maple-carts' ); ?>
                    </button>
                </p>
                <div class="maple-carts-test-result"></div>
            </div>
        </div>
        <?php
    }

    /**
     * Render settings page.
     */
    public function render_settings() {
        settings_errors( 'maple_carts' );
        ?>
        <div class="wrap maple-carts-wrap">
            <h1><?php esc_html_e( 'Maple Carts Settings', 'maple-carts' ); ?></h1>

            <form method="post" action="">
                <?php wp_nonce_field( 'maple_carts_settings' ); ?>

                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e( 'Enable Cart Tracking', 'maple-carts' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="enabled" value="yes" 
                                       <?php checked( Maple_Carts::get_option( 'enabled', 'yes' ), 'yes' ); ?>>
                                <?php esc_html_e( 'Track abandoned carts and send recovery emails', 'maple-carts' ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="cart_cutoff_time"><?php esc_html_e( 'Cart Cutoff Time', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="number" id="cart_cutoff_time" name="cart_cutoff_time" min="5" class="small-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'cart_cutoff_time', 15 ) ); ?>">
                            <?php esc_html_e( 'minutes', 'maple-carts' ); ?>
                            <p class="description"><?php esc_html_e( 'Time after last activity before a cart is considered abandoned.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="delete_after_days"><?php esc_html_e( 'Data Retention', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="number" id="delete_after_days" name="delete_after_days" min="7" class="small-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'delete_after_days', 90 ) ); ?>">
                            <?php esc_html_e( 'days', 'maple-carts' ); ?>
                            <p class="description"><?php esc_html_e( 'Automatically delete cart data older than this.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                </table>

                <h2><?php esc_html_e( 'Email Settings', 'maple-carts' ); ?></h2>
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e( 'Email Mode', 'maple-carts' ); ?></th>
                        <td>
                            <fieldset>
                                <label>
                                    <input type="radio" name="email_mode" value="builtin" 
                                           <?php checked( Maple_Carts::get_option( 'email_mode', 'builtin' ), 'builtin' ); ?>>
                                    <?php esc_html_e( 'Built-in Emails', 'maple-carts' ); ?>
                                    <span class="description"><?php esc_html_e( '— Send timed emails directly via WordPress/SMTP', 'maple-carts' ); ?></span>
                                </label>
                                <br><br>
                                <label>
                                    <input type="radio" name="email_mode" value="mailjet" 
                                           <?php checked( Maple_Carts::get_option( 'email_mode', 'builtin' ), 'mailjet' ); ?>>
                                    <?php esc_html_e( 'Mailjet Sync', 'maple-carts' ); ?>
                                    <span class="description"><?php esc_html_e( '— Sync cart data to Mailjet for use in automations', 'maple-carts' ); ?></span>
                                </label>
                            </fieldset>
                        </td>
                    </tr>
                </table>

                <!-- Mailjet Settings (shown when mailjet mode selected) -->
                <div id="mailjet-settings" style="<?php echo 'mailjet' !== Maple_Carts::get_option( 'email_mode', 'builtin' ) ? 'display:none;' : ''; ?>">
                    <h3><?php esc_html_e( 'Mailjet Configuration', 'maple-carts' ); ?></h3>
                    <p class="description">
                        <?php 
                        printf(
                            /* translators: %s: link to Mailjet */
                            esc_html__( 'Get your API credentials from %s', 'maple-carts' ),
                            '<a href="https://app.mailjet.com/account/apikeys" target="_blank">Mailjet API Keys</a>'
                        );
                        ?>
                    </p>
                    <table class="form-table">
                        <tr>
                            <th><label for="mailjet_api_key"><?php esc_html_e( 'API Key', 'maple-carts' ); ?></label></th>
                            <td>
                                <input type="text" id="mailjet_api_key" name="mailjet_api_key" class="regular-text"
                                       value="<?php echo esc_attr( Maple_Carts::get_option( 'mailjet_api_key', '' ) ); ?>"
                                       autocomplete="off">
                            </td>
                        </tr>
                        <tr>
                            <th><label for="mailjet_secret_key"><?php esc_html_e( 'Secret Key', 'maple-carts' ); ?></label></th>
                            <td>
                                <input type="password" id="mailjet_secret_key" name="mailjet_secret_key" class="regular-text"
                                       value="<?php echo esc_attr( Maple_Carts::get_option( 'mailjet_secret_key', '' ) ); ?>"
                                       autocomplete="off">
                            </td>
                        </tr>
                        <tr>
                            <th><?php esc_html_e( 'Connection', 'maple-carts' ); ?></th>
                            <td>
                                <button type="button" class="button" id="test-mailjet-connection">
                                    <?php esc_html_e( 'Test Connection', 'maple-carts' ); ?>
                                </button>
                                <button type="button" class="button" id="setup-mailjet-properties">
                                    <?php esc_html_e( 'Setup Contact Properties', 'maple-carts' ); ?>
                                </button>
                                <span id="mailjet-status" style="margin-left:10px;"></span>
                            </td>
                        </tr>
                        <tr>
                            <th><?php esc_html_e( 'Contact Properties', 'maple-carts' ); ?></th>
                            <td>
                                <p class="description"><?php esc_html_e( 'These properties will be synced to Mailjet for each abandoned cart:', 'maple-carts' ); ?></p>
                                <ul style="list-style:disc;margin-left:20px;margin-top:10px;">
                                    <?php foreach ( Maple_Carts_Mailjet::instance()->get_available_properties() as $prop => $desc ) : ?>
                                        <li><code><?php echo esc_html( $prop ); ?></code> — <?php echo esc_html( $desc ); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                                <p class="description" style="margin-top:10px;">
                                    <?php esc_html_e( 'Use these in Mailjet automation conditions, e.g.:', 'maple-carts' ); ?>
                                    <code>maple_has_abandoned_cart equals true</code>
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Built-in Email Settings (shown when builtin mode selected) -->
                <div id="builtin-email-settings" style="<?php echo 'mailjet' === Maple_Carts::get_option( 'email_mode', 'builtin' ) ? 'display:none;' : ''; ?>">
                <h3><?php esc_html_e( 'Email Configuration', 'maple-carts' ); ?></h3>
                <table class="form-table">
                    <tr>
                        <th><label for="from_name"><?php esc_html_e( 'From Name', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="text" id="from_name" name="from_name" class="regular-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'from_name', get_bloginfo( 'name' ) ) ); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th><label for="from_email"><?php esc_html_e( 'From Email', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="email" id="from_email" name="from_email" class="regular-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'from_email', get_option( 'admin_email' ) ) ); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th><label for="reply_to"><?php esc_html_e( 'Reply-To Email', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="email" id="reply_to" name="reply_to" class="regular-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'reply_to', get_option( 'admin_email' ) ) ); ?>">
                        </td>
                    </tr>
                </table>

                <h2><?php esc_html_e( 'Notifications', 'maple-carts' ); ?></h2>
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e( 'Recovery Notifications', 'maple-carts' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="notify_admin" value="yes" 
                                       <?php checked( Maple_Carts::get_option( 'notify_admin', 'yes' ), 'yes' ); ?>>
                                <?php esc_html_e( 'Email admin when an abandoned cart is recovered', 'maple-carts' ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="admin_email"><?php esc_html_e( 'Admin Email', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="email" id="admin_email" name="admin_email" class="regular-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'admin_email', get_option( 'admin_email' ) ) ); ?>">
                        </td>
                    </tr>
                </table>
                </div><!-- /builtin-email-settings -->

                <h2><?php esc_html_e( 'Privacy', 'maple-carts' ); ?></h2>
                <p class="description">
                    <?php 
                    printf(
                        /* translators: %s: link to privacy policy page */
                        esc_html__( 'Maple Carts integrates with WordPress Privacy Tools. Suggested privacy policy text has been added to your %s.', 'maple-carts' ),
                        '<a href="' . esc_url( admin_url( 'options-privacy.php' ) ) . '">' . esc_html__( 'Privacy Settings', 'maple-carts' ) . '</a>'
                    );
                    ?>
                </p>
                <table class="form-table">
                    <tr>
                        <th><?php esc_html_e( 'Require Consent', 'maple-carts' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="require_consent" value="yes" 
                                       <?php checked( Maple_Carts::get_option( 'require_consent', 'no' ), 'yes' ); ?>>
                                <?php esc_html_e( 'Show consent checkbox on checkout (recommended for GDPR)', 'maple-carts' ); ?>
                            </label>
                            <p class="description"><?php esc_html_e( 'When enabled, cart tracking only occurs if the customer explicitly consents.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="consent_text"><?php esc_html_e( 'Consent Checkbox Text', 'maple-carts' ); ?></label></th>
                        <td>
                            <input type="text" id="consent_text" name="consent_text" class="large-text"
                                   value="<?php echo esc_attr( Maple_Carts::get_option( 'consent_text', __( 'I agree to receive cart reminder emails if I don\'t complete my purchase.', 'maple-carts' ) ) ); ?>">
                        </td>
                    </tr>
                    <tr>
                        <th><?php esc_html_e( 'Delete Data Link', 'maple-carts' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="show_delete_link" value="yes" 
                                       <?php checked( Maple_Carts::get_option( 'show_delete_link', 'no' ), 'yes' ); ?>>
                                <?php esc_html_e( 'Include "Delete my data" link in emails (required for GDPR/EU)', 'maple-carts' ); ?>
                            </label>
                            <p class="description"><?php esc_html_e( 'When enabled, adds a one-click data deletion link to all recovery emails. Enable this if you have customers in the EU.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="gdpr_notice"><?php esc_html_e( 'GDPR Notice', 'maple-carts' ); ?></label></th>
                        <td>
                            <textarea id="gdpr_notice" name="gdpr_notice" class="large-text" rows="3"><?php echo esc_textarea( Maple_Carts::get_option( 'gdpr_notice', '' ) ); ?></textarea>
                            <p class="description"><?php esc_html_e( 'Optional notice displayed on checkout about cart data collection. Leave empty to disable.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label><?php esc_html_e( 'Exclude User Roles', 'maple-carts' ); ?></label></th>
                        <td>
                            <?php 
                            $exclude_roles = Maple_Carts::get_option( 'exclude_roles', [] );
                            foreach ( wp_roles()->roles as $role_key => $role ) : 
                            ?>
                                <label style="display:block;margin-bottom:5px;">
                                    <input type="checkbox" name="exclude_roles[]" value="<?php echo esc_attr( $role_key ); ?>"
                                           <?php checked( in_array( $role_key, $exclude_roles, true ) ); ?>>
                                    <?php echo esc_html( $role['name'] ); ?>
                                </label>
                            <?php endforeach; ?>
                            <p class="description"><?php esc_html_e( 'Do not track carts for users with these roles.', 'maple-carts' ); ?></p>
                        </td>
                    </tr>
                </table>

                <p class="submit">
                    <input type="submit" name="maple_carts_save_settings" class="button button-primary" 
                           value="<?php esc_attr_e( 'Save Settings', 'maple-carts' ); ?>">
                </p>
            </form>
        </div>
        <?php
    }

    /**
     * AJAX: Delete cart.
     */
    public function ajax_delete_cart() {
        check_ajax_referer( 'maple_carts_admin', 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $cart_id = isset( $_POST['cart_id'] ) ? absint( $_POST['cart_id'] ) : 0;

        if ( ! $cart_id ) {
            wp_send_json_error( 'Invalid cart ID' );
        }

        if ( Maple_Carts_DB::delete_cart( $cart_id ) ) {
            wp_send_json_success();
        } else {
            wp_send_json_error( 'Failed to delete cart' );
        }
    }

    /**
     * AJAX: Save template.
     */
    public function ajax_save_template() {
        check_ajax_referer( 'maple_carts_admin', 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        // Validate enum values.
        $delay_unit = sanitize_text_field( wp_unslash( $_POST['delay_unit'] ?? 'hours' ) );
        if ( ! in_array( $delay_unit, [ 'minutes', 'hours', 'days' ], true ) ) {
            $delay_unit = 'hours';
        }

        $coupon_type = sanitize_text_field( wp_unslash( $_POST['coupon_type'] ?? 'percent' ) );
        if ( ! in_array( $coupon_type, [ 'percent', 'fixed_cart' ], true ) ) {
            $coupon_type = 'percent';
        }

        $data = [
            'name'               => sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ),
            'subject'            => sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) ),
            'body'               => wp_kses_post( wp_unslash( $_POST['body'] ?? '' ) ),
            'delay_value'        => absint( $_POST['delay_value'] ?? 1 ),
            'delay_unit'         => $delay_unit,
            'is_active'          => isset( $_POST['is_active'] ) ? 1 : 0,
            'include_coupon'     => isset( $_POST['include_coupon'] ) ? 1 : 0,
            'coupon_type'        => $coupon_type,
            'coupon_amount'      => floatval( $_POST['coupon_amount'] ?? 10 ),
            'coupon_expires_days'=> absint( $_POST['coupon_expires_days'] ?? 7 ),
        ];

        if ( ! empty( $_POST['id'] ) ) {
            $data['id'] = absint( $_POST['id'] );
        }

        $id = Maple_Carts_DB::save_email_template( $data );

        if ( $id ) {
            wp_send_json_success( [ 'id' => $id ] );
        } else {
            wp_send_json_error( 'Failed to save template' );
        }
    }

    /**
     * AJAX: Delete template.
     */
    public function ajax_delete_template() {
        check_ajax_referer( 'maple_carts_admin', 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0;

        if ( ! $id ) {
            wp_send_json_error( 'Invalid template ID' );
        }

        if ( Maple_Carts_DB::delete_email_template( $id ) ) {
            wp_send_json_success();
        } else {
            wp_send_json_error( 'Failed to delete template' );
        }
    }

    /**
     * AJAX: Toggle template active status.
     */
    public function ajax_toggle_template() {
        check_ajax_referer( 'maple_carts_admin', 'nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $id     = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0;
        $active = isset( $_POST['active'] ) ? absint( $_POST['active'] ) : 0;

        if ( ! $id ) {
            wp_send_json_error( 'Invalid template ID' );
        }

        global $wpdb;
        $result = $wpdb->update(
            $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE,
            [ 'is_active' => $active ? 0 : 1 ],
            [ 'id' => $id ]
        );

        if ( false !== $result ) {
            wp_send_json_success( [ 'is_active' => $active ? 0 : 1 ] );
        } else {
            wp_send_json_error( 'Failed to update template' );
        }
    }
}
