<?php
/**
 * Email Admin Settings
 *
 * Handles admin UI for email template management
 *
 * @package GGM_Commerce
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

/**
 * Email Admin Settings Class
 */
class GGM_Commerce_Email_Admin_Settings {

    /**
     * Instance
     *
     * @var GGM_Commerce_Email_Admin_Settings
     */
    private static $instance = null;

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

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'wp_ajax_ggmc_get_email_template', array( $this, 'ajax_get_template' ) );
        add_action( 'wp_ajax_ggmc_save_email_template', array( $this, 'ajax_save_template' ) );
        add_action( 'wp_ajax_ggmc_preview_email', array( $this, 'ajax_preview_email' ) );
        add_action( 'wp_ajax_ggmc_send_test_email', array( $this, 'ajax_send_test_email' ) );
        add_action( 'wp_ajax_ggmc_reset_email_template', array( $this, 'ajax_reset_template' ) );
        add_action( 'wp_ajax_ggmc_toggle_email', array( $this, 'ajax_toggle_email' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    }

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

        $plugin_url = plugin_dir_url( dirname( dirname( __FILE__ ) ) );

        wp_enqueue_editor();
        wp_enqueue_script(
            'ggmc-email-admin',
            $plugin_url . 'assets/js/email-admin.js',
            array( 'jquery', 'wp-util' ),
            '1.0.0',
            true
        );

        wp_localize_script( 'ggmc-email-admin', 'ggmcEmailAdmin', array(
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'ggmc_email_admin' ),
            'strings' => array(
                'saving'        => __( 'Saving...', 'ggm-commerce' ),
                'saved'         => __( 'Saved!', 'ggm-commerce' ),
                'error'         => __( 'Error saving template', 'ggm-commerce' ),
                'sending'       => __( 'Sending...', 'ggm-commerce' ),
                'sent'          => __( 'Test email sent!', 'ggm-commerce' ),
                'sendError'     => __( 'Failed to send test email', 'ggm-commerce' ),
                'resetting'     => __( 'Resetting...', 'ggm-commerce' ),
                'resetComplete' => __( 'Template reset to default', 'ggm-commerce' ),
                'confirmReset'  => __( 'Are you sure you want to reset this template to default? Any customizations will be lost.', 'ggm-commerce' ),
            ),
        ) );
    }

    /**
     * Render the email templates management UI
     */
    public function render_email_templates_ui() {
        $email_manager = ggm_commerce_emails();
        $emails        = $email_manager->get_email_types();

        // Get saved templates from database.
        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_email_templates';
        $saved_templates = $wpdb->get_results(
            "SELECT email_type, enabled FROM {$table_name}",
            OBJECT_K
        );
        ?>
        <div class="ggmc-email-templates-wrap">
            <h2><?php esc_html_e( 'Email Notifications', 'ggm-commerce' ); ?></h2>
            <p class="description"><?php esc_html_e( 'Configure automated emails sent to customers and administrators.', 'ggm-commerce' ); ?></p>

            <table class="ggmc-email-list widefat">
                <thead>
                    <tr>
                        <th class="ggmc-email-status"><?php esc_html_e( 'Enabled', 'ggm-commerce' ); ?></th>
                        <th class="ggmc-email-name"><?php esc_html_e( 'Email', 'ggm-commerce' ); ?></th>
                        <th class="ggmc-email-recipient"><?php esc_html_e( 'Recipient', 'ggm-commerce' ); ?></th>
                        <th class="ggmc-email-actions"><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $emails as $email_id => $email ) :
                        $is_enabled = isset( $saved_templates[ $email_id ] )
                            ? (bool) $saved_templates[ $email_id ]->enabled
                            : true;
                        $recipient_type = $email->get_recipient_type();
                    ?>
                    <tr data-email-id="<?php echo esc_attr( $email_id ); ?>">
                        <td class="ggmc-email-status">
                            <label class="ggmc-toggle">
                                <input type="checkbox"
                                       class="ggmc-email-toggle"
                                       data-email-id="<?php echo esc_attr( $email_id ); ?>"
                                       <?php checked( $is_enabled ); ?>>
                                <span class="ggmc-toggle-slider"></span>
                            </label>
                        </td>
                        <td class="ggmc-email-name">
                            <strong><?php echo esc_html( $email->get_title() ); ?></strong>
                            <p class="description"><?php echo esc_html( $email->get_description() ); ?></p>
                        </td>
                        <td class="ggmc-email-recipient">
                            <?php if ( $recipient_type === 'admin' ) : ?>
                                <span class="ggmc-badge ggmc-badge-admin"><?php esc_html_e( 'Admin', 'ggm-commerce' ); ?></span>
                            <?php else : ?>
                                <span class="ggmc-badge ggmc-badge-customer"><?php esc_html_e( 'Customer', 'ggm-commerce' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="ggmc-email-actions">
                            <button type="button"
                                    class="button ggmc-configure-email"
                                    data-email-id="<?php echo esc_attr( $email_id ); ?>">
                                <span class="dashicons dashicons-edit"></span>
                                <?php esc_html_e( 'Configure', 'ggm-commerce' ); ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Email Editor Modal -->
        <div id="ggmc-email-editor-modal" class="ggmc-modal" style="display: none;">
            <div class="ggmc-modal-content">
                <div class="ggmc-modal-header">
                    <h2 id="ggmc-modal-title"><?php esc_html_e( 'Configure Email Template', 'ggm-commerce' ); ?></h2>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <form id="ggmc-email-template-form">
                        <input type="hidden" id="ggmc-email-type" name="email_type" value="">

                        <div class="ggmc-form-row">
                            <label for="ggmc-email-subject"><?php esc_html_e( 'Subject Line', 'ggm-commerce' ); ?></label>
                            <input type="text" id="ggmc-email-subject" name="subject" class="regular-text" style="width: 100%;">
                            <p class="description"><?php esc_html_e( 'Use placeholders like {order_number}, {customer_name}', 'ggm-commerce' ); ?></p>
                        </div>

                        <div class="ggmc-form-row">
                            <label for="ggmc-email-heading"><?php esc_html_e( 'Email Heading', 'ggm-commerce' ); ?></label>
                            <input type="text" id="ggmc-email-heading" name="heading" class="regular-text" style="width: 100%;">
                        </div>

                        <div class="ggmc-form-row">
                            <label for="ggmc-email-content"><?php esc_html_e( 'Email Content', 'ggm-commerce' ); ?></label>
                            <?php
                            wp_editor( '', 'ggmc-email-content', array(
                                'textarea_name' => 'content',
                                'textarea_rows' => 15,
                                'media_buttons' => false,
                                'teeny'         => false,
                                'quicktags'     => true,
                            ) );
                            ?>
                        </div>

                        <div class="ggmc-form-row">
                            <label for="ggmc-additional-recipients"><?php esc_html_e( 'Additional Recipients', 'ggm-commerce' ); ?></label>
                            <input type="text" id="ggmc-additional-recipients" name="additional_recipients" class="regular-text" style="width: 100%;">
                            <p class="description"><?php esc_html_e( 'Comma-separated email addresses to receive a copy', 'ggm-commerce' ); ?></p>
                        </div>

                        <div class="ggmc-placeholders-reference">
                            <h4><?php esc_html_e( 'Available Placeholders', 'ggm-commerce' ); ?></h4>
                            <div class="ggmc-placeholders-list" id="ggmc-placeholders-list">
                                <!-- Populated by JavaScript -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="ggmc-modal-footer">
                    <div class="ggmc-modal-footer-left">
                        <button type="button" class="button" id="ggmc-reset-template">
                            <span class="dashicons dashicons-image-rotate"></span>
                            <?php esc_html_e( 'Reset to Default', 'ggm-commerce' ); ?>
                        </button>
                    </div>
                    <div class="ggmc-modal-footer-right">
                        <button type="button" class="button" id="ggmc-preview-email">
                            <span class="dashicons dashicons-visibility"></span>
                            <?php esc_html_e( 'Preview', 'ggm-commerce' ); ?>
                        </button>
                        <button type="button" class="button" id="ggmc-send-test-email">
                            <span class="dashicons dashicons-email"></span>
                            <?php esc_html_e( 'Send Test', 'ggm-commerce' ); ?>
                        </button>
                        <button type="button" class="button button-primary" id="ggmc-save-template">
                            <span class="dashicons dashicons-saved"></span>
                            <?php esc_html_e( 'Save Template', 'ggm-commerce' ); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Preview Modal -->
        <div id="ggmc-preview-modal" class="ggmc-modal" style="display: none;">
            <div class="ggmc-modal-content ggmc-modal-preview">
                <div class="ggmc-modal-header">
                    <h2><?php esc_html_e( 'Email Preview', 'ggm-commerce' ); ?></h2>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <iframe id="ggmc-preview-frame" style="width: 100%; height: 600px; border: 1px solid #ddd;"></iframe>
                </div>
            </div>
        </div>

        <?php
    }

    /**
     * Get email template data for editing
     *
     * @param string $email_type Email type ID.
     * @return array Template data.
     */
    public function get_template_data( $email_type ) {
        $email_manager = ggm_commerce_emails();
        $email         = $email_manager->get_email( $email_type );

        if ( ! $email ) {
            return array();
        }

        // Check for saved template in database.
        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_email_templates';
        $saved      = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$table_name} WHERE email_type = %s",
            $email_type
        ) );

        if ( $saved && ! empty( $saved->content ) ) {
            return array(
                'email_type'            => $email_type,
                'title'                 => $email->get_title(),
                'subject'               => $saved->subject,
                'heading'               => $saved->heading,
                'content'               => $saved->content,
                'additional_recipients' => $saved->additional_recipients,
                'placeholders'          => $email->get_placeholders(),
                'is_custom'             => true,
            );
        }

        // Return defaults.
        return array(
            'email_type'            => $email_type,
            'title'                 => $email->get_title(),
            'subject'               => $email->get_default_subject(),
            'heading'               => $email->get_default_heading(),
            'content'               => $email->get_default_content(),
            'additional_recipients' => '',
            'placeholders'          => $email->get_placeholders(),
            'is_custom'             => false,
        );
    }

    /**
     * AJAX: Get email template data
     */
    public function ajax_get_template() {
        check_ajax_referer( 'ggmc_email_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
        }

        $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';

        if ( empty( $email_type ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid email type', 'ggm-commerce' ) ) );
        }

        $template_data = $this->get_template_data( $email_type );

        if ( empty( $template_data ) ) {
            wp_send_json_error( array( 'message' => __( 'Email type not found', 'ggm-commerce' ) ) );
        }

        wp_send_json_success( $template_data );
    }

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

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
        }

        $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';
        $subject    = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
        $heading    = isset( $_POST['heading'] ) ? sanitize_text_field( wp_unslash( $_POST['heading'] ) ) : '';
        $content    = isset( $_POST['content'] ) ? wp_kses_post( wp_unslash( $_POST['content'] ) ) : '';
        $additional = isset( $_POST['additional_recipients'] ) ? sanitize_text_field( wp_unslash( $_POST['additional_recipients'] ) ) : '';

        if ( empty( $email_type ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid email type', 'ggm-commerce' ) ) );
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_email_templates';

        // Check if template exists.
        $existing = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$table_name} WHERE email_type = %s",
            $email_type
        ) );

        $data = array(
            'email_type'            => $email_type,
            'subject'               => $subject,
            'heading'               => $heading,
            'content'               => $content,
            'additional_recipients' => $additional,
            'updated_at'            => current_time( 'mysql' ),
        );

        if ( $existing ) {
            $wpdb->update( $table_name, $data, array( 'id' => $existing ) );
        } else {
            $email_manager = ggm_commerce_emails();
            $email         = $email_manager->get_email( $email_type );
            $data['recipient_type'] = $email ? $email->get_recipient_type() : 'customer';
            $data['created_at']     = current_time( 'mysql' );
            $wpdb->insert( $table_name, $data );
        }

        wp_send_json_success( array( 'message' => __( 'Template saved', 'ggm-commerce' ) ) );
    }

    /**
     * AJAX: Preview email
     */
    public function ajax_preview_email() {
        // Set up error handling to catch PHP errors.
        $error_message = '';
        set_error_handler( function( $errno, $errstr, $errfile, $errline ) use ( &$error_message ) {
            $error_message = "PHP Error: $errstr in $errfile on line $errline";
            return true;
        } );

        try {
            check_ajax_referer( 'ggmc_email_admin', 'nonce' );

            if ( ! current_user_can( 'manage_options' ) ) {
                restore_error_handler();
                wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            }

            $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';
            $subject    = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
            $heading    = isset( $_POST['heading'] ) ? sanitize_text_field( wp_unslash( $_POST['heading'] ) ) : '';
            $content    = isset( $_POST['content'] ) ? wp_kses_post( wp_unslash( $_POST['content'] ) ) : '';

            if ( empty( $email_type ) ) {
                restore_error_handler();
                wp_send_json_error( array( 'message' => __( 'Email type is required', 'ggm-commerce' ) ) );
            }

            $email_manager = ggm_commerce_emails();
            $email         = $email_manager->get_email( $email_type );

            if ( ! $email ) {
                restore_error_handler();
                // translators: %s: email type identifier.
                wp_send_json_error( array( 'message' => sprintf( __( 'Invalid email type: %s', 'ggm-commerce' ), $email_type ) ) );
            }

            // Generate preview with sample data.
            $preview_html = $email->get_preview( $subject, $heading, $content );

            restore_error_handler();

            if ( ! empty( $error_message ) ) {
                wp_send_json_error( array( 'message' => $error_message ) );
            }

            wp_send_json_success( array( 'html' => $preview_html ) );
        } catch ( Exception $e ) {
            restore_error_handler();
            wp_send_json_error( array( 'message' => 'Exception: ' . $e->getMessage() ) );
        } catch ( Error $e ) {
            restore_error_handler();
            wp_send_json_error( array( 'message' => 'Fatal Error: ' . $e->getMessage() ) );
        }
    }

    /**
     * AJAX: Send test email
     */
    public function ajax_send_test_email() {
        check_ajax_referer( 'ggmc_email_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
        }

        $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';
        $recipient  = isset( $_POST['recipient'] ) ? sanitize_email( wp_unslash( $_POST['recipient'] ) ) : '';

        if ( empty( $recipient ) ) {
            $current_user = wp_get_current_user();
            $recipient    = $current_user->user_email;
        }

        $email_manager = ggm_commerce_emails();
        $email         = $email_manager->get_email( $email_type );

        if ( ! $email ) {
            wp_send_json_error( array( 'message' => __( 'Invalid email type', 'ggm-commerce' ) ) );
        }

        // Send test with sample data.
        $result = $email->send_test( $recipient );

        if ( $result ) {
            wp_send_json_success( array(
                'message' => sprintf(
                    /* translators: %s: email address */
                    __( 'Test email sent to %s', 'ggm-commerce' ),
                    $recipient
                ),
            ) );
        } else {
            wp_send_json_error( array( 'message' => __( 'Failed to send test email', 'ggm-commerce' ) ) );
        }
    }

    /**
     * AJAX: Reset email template to default
     */
    public function ajax_reset_template() {
        check_ajax_referer( 'ggmc_email_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
        }

        $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';

        if ( empty( $email_type ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid email type', 'ggm-commerce' ) ) );
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_email_templates';

        // Delete custom template to revert to defaults.
        $wpdb->delete( $table_name, array( 'email_type' => $email_type ) );

        // Return default template data.
        $template_data = $this->get_template_data( $email_type );

        wp_send_json_success( array(
            'message'  => __( 'Template reset to default', 'ggm-commerce' ),
            'template' => $template_data,
        ) );
    }

    /**
     * AJAX: Toggle email enabled/disabled
     */
    public function ajax_toggle_email() {
        check_ajax_referer( 'ggmc_email_admin', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
        }

        $email_type = isset( $_POST['email_type'] ) ? sanitize_text_field( wp_unslash( $_POST['email_type'] ) ) : '';
        $enabled    = isset( $_POST['enabled'] ) && $_POST['enabled'] === 'true' ? 1 : 0;

        if ( empty( $email_type ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid email type', 'ggm-commerce' ) ) );
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_email_templates';

        // Check if template exists.
        $existing = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$table_name} WHERE email_type = %s",
            $email_type
        ) );

        if ( $existing ) {
            $wpdb->update(
                $table_name,
                array( 'enabled' => $enabled, 'updated_at' => current_time( 'mysql' ) ),
                array( 'id' => $existing )
            );
        } else {
            // Create new entry with enabled status.
            $email_manager = ggm_commerce_emails();
            $email         = $email_manager->get_email( $email_type );

            $wpdb->insert( $table_name, array(
                'email_type'     => $email_type,
                'subject'        => $email ? $email->get_default_subject() : '',
                'heading'        => $email ? $email->get_default_heading() : '',
                'enabled'        => $enabled,
                'recipient_type' => $email ? $email->get_recipient_type() : 'customer',
                'created_at'     => current_time( 'mysql' ),
                'updated_at'     => current_time( 'mysql' ),
            ) );
        }

        wp_send_json_success( array(
            'message' => $enabled
                ? __( 'Email enabled', 'ggm-commerce' )
                : __( 'Email disabled', 'ggm-commerce' ),
        ) );
    }
}

/**
 * Get email admin settings instance
 *
 * @return GGM_Commerce_Email_Admin_Settings
 */
function ggm_commerce_email_admin() {
    return GGM_Commerce_Email_Admin_Settings::instance();
}
