<?php
/**
 * GGM Commerce Email Template Base Class
 * Abstract base class for all email types
 */

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

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

abstract class GGM_Commerce_Email_Template {

    /**
     * Email type identifier
     *
     * @var string
     */
    protected $id = '';

    /**
     * Email title for admin display
     *
     * @var string
     */
    protected $title = '';

    /**
     * Email description
     *
     * @var string
     */
    protected $description = '';

    /**
     * Recipient type: 'customer' or 'admin'
     *
     * @var string
     */
    protected $recipient_type = 'customer';

    /**
     * Saved template data from database
     *
     * @var array|null
     */
    protected $template_data = null;

    /**
     * Current order object
     *
     * @var object|null
     */
    protected $order = null;

    /**
     * Current shipment object (for shipped/delivered emails)
     *
     * @var object|null
     */
    protected $shipment = null;

    /**
     * Constructor
     */
    public function __construct() {
        // Child classes should set id, title, description, recipient_type
    }

    /**
     * Get email ID
     *
     * @return string
     */
    public function get_id() {
        return $this->id;
    }

    /**
     * Get email title
     *
     * @return string
     */
    public function get_title() {
        return $this->title;
    }

    /**
     * Get email description
     *
     * @return string
     */
    public function get_description() {
        return $this->description;
    }

    /**
     * Get recipient type
     *
     * @return string
     */
    public function get_recipient_type() {
        return $this->recipient_type;
    }

    /**
     * Get default subject line
     *
     * @return string
     */
    abstract public function get_default_subject();

    /**
     * Get default heading
     *
     * @return string
     */
    abstract public function get_default_heading();

    /**
     * Get default template content
     *
     * @return string
     */
    abstract public function get_default_content();

    /**
     * Get saved template from database
     *
     * @return array|null
     */
    public function get_saved_template() {
        if ( null !== $this->template_data ) {
            return $this->template_data;
        }

        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $this->template_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_email_templates WHERE email_type = %s",
                $this->id
            ),
            ARRAY_A
        );

        return $this->template_data;
    }

    /**
     * Check if email is enabled
     *
     * @return bool
     */
    public function is_enabled() {
        $template = $this->get_saved_template();

        // If no template saved, default to enabled
        if ( ! $template ) {
            return true;
        }

        return (bool) $template['enabled'];
    }

    /**
     * Get subject with placeholders replaced
     *
     * @param object $order Order object.
     * @return string
     */
    public function get_subject( $order ) {
        $template = $this->get_saved_template();
        $subject  = $template && ! empty( $template['subject'] ) ? $template['subject'] : $this->get_default_subject();

        return $this->replace_placeholders( $subject, $order );
    }

    /**
     * Get heading with placeholders replaced
     *
     * @param object $order Order object.
     * @return string
     */
    public function get_heading( $order ) {
        $template = $this->get_saved_template();
        $heading  = $template && ! empty( $template['heading'] ) ? $template['heading'] : $this->get_default_heading();

        return $this->replace_placeholders( $heading, $order );
    }

    /**
     * Get full HTML content
     *
     * @param object $order      Order object.
     * @param array  $extra_args Extra arguments.
     * @return string
     */
    public function get_content( $order, $extra_args = array() ) {
        $this->order = $order;

        // Get template content
        $template = $this->get_saved_template();
        $content  = $template && ! empty( $template['content'] ) ? $template['content'] : $this->get_default_content();

        // Replace placeholders
        $content = $this->replace_placeholders( $content, $order, $extra_args );

        // Wrap in email wrapper
        return $this->wrap_email_content( $content, $order );
    }

    /**
     * Wrap content in email HTML structure
     *
     * @param string $content Email body content.
     * @param object $order   Order object.
     * @return string
     */
    protected function wrap_email_content( $content, $order ) {
        $heading = $this->get_heading( $order );

        ob_start();
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html( $this->get_subject( $order ) ); ?></title>
    <?php $this->output_styles(); ?>
</head>
<div style="margin: 0; padding: 0; background-color: #f3f4f6; font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;">
    <table role="presentation" style="width: 100%; border-collapse: collapse;">
        <tr>
            <td align="center" style="padding: 40px 20px;">
                <table role="presentation" style="width: 100%; max-width: 600px; border-collapse: collapse; background: #ffffff; border-radius: 8px;">
                    <?php $this->output_header(); ?>
                    <tr>
                        <td style="padding: 32px;">
                            <?php if ( ! empty( $heading ) ) : ?>
                            <h1 style="margin: 0 0 24px 0; font-size: 24px; color: #1f2937; font-weight: 600;"><?php echo esc_html( $heading ); ?></h1>
                            <?php endif; ?>
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Content contains HTML template
                            echo $content;
                            ?>
                        </td>
                    </tr>
                    <?php $this->output_footer(); ?>
                </table>
            </td>
        </tr>
    </table>
</div>
</html>
        <?php
        return ob_get_clean();
    }

    /**
     * Output email styles
     */
    protected function output_styles() {
        ?>
    <style>
        body {
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        table {
            border-collapse: collapse;
        }
        td {
            vertical-align: top;
        }
        .order-table {
            width: 100%;
            margin: 24px 0;
            border-collapse: collapse;
        }
        .order-table th {
            background: #f9fafb;
            padding: 12px;
            text-align: left;
            font-size: 12px;
            font-weight: 600;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e5e7eb;
        }
        .order-table td {
            padding: 12px;
            border-bottom: 1px solid #e5e7eb;
            font-size: 14px;
            color: #1f2937;
        }
        .order-table .text-right {
            text-align: right;
        }
        .order-table .text-center {
            text-align: center;
        }
        .totals-table {
            width: 100%;
            max-width: 300px;
            margin-left: auto;
            margin-top: 24px;
        }
        .totals-table td {
            padding: 8px 0;
            font-size: 14px;
        }
        .totals-table .total-row td {
            font-weight: 600;
            font-size: 16px;
            border-top: 2px solid #1f2937;
            padding-top: 12px;
        }
        .address-box {
            background: #f9fafb;
            padding: 16px;
            border-radius: 6px;
            margin: 12px 0;
        }
        .address-box h4 {
            margin: 0 0 8px 0;
            font-size: 14px;
            font-weight: 600;
            color: #1f2937;
        }
        .address-box p {
            margin: 0;
            font-size: 14px;
            color: #4b5563;
            line-height: 1.5;
        }
        .button {
            display: inline-block;
            padding: 12px 24px;
            background: #2563eb;
            color: #ffffff !important;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 500;
            font-size: 14px;
        }
        .button:hover {
            background: #1d4ed8;
        }
        .variation {
            font-size: 12px;
            color: #6b7280;
            font-style: italic;
        }
        .sku {
            font-size: 11px;
            color: #9ca3af;
        }
    </style>
        <?php
    }

    /**
     * Output email header
     */
    protected function output_header() {
        $business_options = get_option( 'ggm_commerce_business_options', array() );
        $business_name    = ! empty( $business_options['name'] ) ? $business_options['name'] : get_bloginfo( 'name' );
        ?>
                    <tr>
                        <td style="background: #1e3a5f; padding: 24px; text-align: center; border-radius: 8px 8px 0 0;">
                            <h2 style="margin: 0; font-size: 24px; color: #ffffff; font-weight: 600;"><?php echo esc_html( $business_name ); ?></h2>
                        </td>
                    </tr>
        <?php
    }

    /**
     * Output email footer
     */
    protected function output_footer() {
        $business_options = get_option( 'ggm_commerce_business_options', array() );
        $business_name    = ! empty( $business_options['name'] ) ? $business_options['name'] : get_bloginfo( 'name' );
        $business_address = ! empty( $business_options['address'] ) ? $business_options['address'] : '';
        $business_email   = ! empty( $business_options['email'] ) ? $business_options['email'] : get_option( 'admin_email' );
        ?>
                    <tr>
                        <td style="background: #f9fafb; padding: 24px; text-align: center; border-radius: 0 0 8px 8px; border-top: 1px solid #e5e7eb;">
                            <p style="margin: 0 0 8px 0; font-size: 14px; color: #6b7280;"><?php echo esc_html( $business_name ); ?></p>
                            <?php if ( ! empty( $business_address ) ) : ?>
                            <p style="margin: 0 0 8px 0; font-size: 12px; color: #9ca3af;"><?php echo esc_html( $business_address ); ?></p>
                            <?php endif; ?>
                            <p style="margin: 0; font-size: 12px; color: #9ca3af;">
                                <a href="mailto:<?php echo esc_attr( $business_email ); ?>" style="color: #2563eb; text-decoration: none;"><?php echo esc_html( $business_email ); ?></a>
                            </p>
                        </td>
                    </tr>
        <?php
    }

    /**
     * Replace placeholders in content
     *
     * @param string $content    Content with placeholders.
     * @param object $order      Order object.
     * @param array  $extra_args Extra arguments.
     * @return string
     */
    protected function replace_placeholders( $content, $order, $extra_args = array() ) {
        $placeholders = $this->get_placeholder_values( $order, $extra_args );

        foreach ( $placeholders as $placeholder => $value ) {
            $content = str_replace( '{' . $placeholder . '}', $value, $content );
        }

        return $content;
    }

    /**
     * Get placeholder values
     *
     * @param object $order      Order object.
     * @param array  $extra_args Extra arguments.
     * @return array
     */
    protected function get_placeholder_values( $order, $extra_args = array() ) {
        $business_options = get_option( 'ggm_commerce_business_options', array() );
        $currency_options = get_option( 'ggm_commerce_currency_options', array() );
        $currency_symbol  = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '$';

        $placeholders = array(
            // Order placeholders
            'order_number'     => $order->order_number ?? '',
            'order_date'       => isset( $order->created_at ) ? gmdate( 'F j, Y', strtotime( $order->created_at ) ) : '',
            'order_total'      => $currency_symbol . number_format( (float) ( $order->total_amount ?? 0 ), 2 ),
            'order_subtotal'   => $currency_symbol . number_format( (float) ( $order->subtotal ?? 0 ), 2 ),
            'order_tax'        => $currency_symbol . number_format( (float) ( $order->tax_amount ?? 0 ), 2 ),
            'order_shipping'   => $currency_symbol . number_format( (float) ( $order->shipping_amount ?? 0 ), 2 ),
            'order_status'     => ucfirst( $order->status ?? '' ),
            'payment_method'   => $order->payment_method ?? '',
            'payment_status'   => ucfirst( $order->payment_status ?? '' ),

            // Customer placeholders
            'customer_name'       => trim( ( $order->customer_first_name ?? '' ) . ' ' . ( $order->customer_last_name ?? '' ) ),
            'customer_first_name' => $order->customer_first_name ?? '',
            'customer_last_name'  => $order->customer_last_name ?? '',
            'customer_email'      => $order->customer_email ?? '',

            // Address placeholders
            'billing_address'  => $this->format_address( $order, 'billing' ),
            'shipping_address' => $this->format_address( $order, 'shipping' ),

            // Site placeholders
            'site_name' => get_bloginfo( 'name' ),
            'site_url'  => home_url(),

            // Business placeholders
            'business_name'    => $business_options['name'] ?? get_bloginfo( 'name' ),
            'business_address' => $business_options['address'] ?? '',
            'business_phone'   => $business_options['phone'] ?? '',
            'business_email'   => $business_options['email'] ?? get_option( 'admin_email' ),

            // Order items table
            'order_items_table' => $this->render_order_items_table( $order ),

            // Custom checkout fields
            'checkout_fields' => $this->render_checkout_fields( $order ),
        );

        // Add shipment placeholders if available
        if ( ! empty( $extra_args['shipment_id'] ) ) {
            $shipment = $this->get_shipment( $extra_args['shipment_id'] );
            if ( $shipment ) {
                $placeholders['tracking_number'] = $shipment->tracking_number ?? '';
                $placeholders['tracking_url']    = $shipment->tracking_url ?? '';
                $placeholders['carrier_name']    = $shipment->carrier ?? '';
            } else {
                // Use sample data for preview if shipment not found
                $placeholders['tracking_number'] = $extra_args['tracking_number'] ?? 'SAMPLE123456789';
                $placeholders['tracking_url']    = $extra_args['tracking_url'] ?? 'https://track.example.com/SAMPLE123456789';
                $placeholders['carrier_name']    = $extra_args['carrier_name'] ?? 'Sample Carrier';
            }
        } else {
            // Default tracking placeholders
            $placeholders['tracking_number'] = '';
            $placeholders['tracking_url']    = '';
            $placeholders['carrier_name']    = '';
        }

        // Add refund placeholders if available
        if ( ! empty( $extra_args['refund_amount'] ) ) {
            $placeholders['refund_amount'] = $currency_symbol . number_format( (float) $extra_args['refund_amount'], 2 );
            $placeholders['refund_reason'] = $extra_args['refund_reason'] ?? '';
        }

        return $placeholders;
    }

    /**
     * Format address for display
     *
     * @param object $order Order object.
     * @param string $type  Address type: 'billing' or 'shipping'.
     * @return string
     */
    protected function format_address( $order, $type = 'billing' ) {
        $prefix = $type . '_';

        $parts = array();

        $name = trim( ( $order->{$prefix . 'first_name'} ?? '' ) . ' ' . ( $order->{$prefix . 'last_name'} ?? '' ) );
        if ( ! empty( $name ) ) {
            $parts[] = $name;
        }

        if ( ! empty( $order->{$prefix . 'company'} ) ) {
            $parts[] = $order->{$prefix . 'company'};
        }

        if ( ! empty( $order->{$prefix . 'address_1'} ) ) {
            $parts[] = $order->{$prefix . 'address_1'};
        }

        if ( ! empty( $order->{$prefix . 'address_2'} ) ) {
            $parts[] = $order->{$prefix . 'address_2'};
        }

        $city_state_zip = array();
        if ( ! empty( $order->{$prefix . 'city'} ) ) {
            $city_state_zip[] = $order->{$prefix . 'city'};
        }
        if ( ! empty( $order->{$prefix . 'state'} ) ) {
            $city_state_zip[] = $order->{$prefix . 'state'};
        }
        if ( ! empty( $order->{$prefix . 'postcode'} ) ) {
            $city_state_zip[] = $order->{$prefix . 'postcode'};
        }
        if ( ! empty( $city_state_zip ) ) {
            $parts[] = implode( ', ', $city_state_zip );
        }

        if ( ! empty( $order->{$prefix . 'country'} ) ) {
            $parts[] = $order->{$prefix . 'country'};
        }

        return implode( '<br>', $parts );
    }

    /**
     * Render order items table HTML
     *
     * @param object $order Order object.
     * @return string
     */
    protected function render_order_items_table( $order ) {
        if ( empty( $order->items ) ) {
            return '';
        }

        $currency_options = get_option( 'ggm_commerce_currency_options', array() );
        $currency_symbol  = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '$';

        ob_start();
        ?>
        <table class="order-table">
            <thead>
                <tr>
                    <th style="width: 50%;">Product</th>
                    <th class="text-center">Qty</th>
                    <th class="text-right">Price</th>
                    <th class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $order->items as $item ) : ?>
                <tr>
                    <td>
                        <strong><?php echo esc_html( $item->product_name ); ?></strong>
                        <?php if ( ! empty( $item->variation_data ) ) : ?>
                            <br><span class="variation"><?php echo esc_html( $item->variation_data ); ?></span>
                        <?php endif; ?>
                        <?php if ( ! empty( $item->product_sku ) ) : ?>
                            <br><span class="sku">SKU: <?php echo esc_html( $item->product_sku ); ?></span>
                        <?php endif; ?>
                    </td>
                    <td class="text-center"><?php echo esc_html( $item->quantity ); ?></td>
                    <td class="text-right"><?php echo esc_html( $currency_symbol . number_format( (float) $item->price, 2 ) ); ?></td>
                    <td class="text-right"><?php echo esc_html( $currency_symbol . number_format( (float) $item->total, 2 ) ); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <table class="totals-table" style="width:100%; max-width:300px; margin-left:auto; margin-top:24px;">
            <tr>
                <td style="padding:8px 0; font-size:14px;">Subtotal:</td>
                <td style="padding:8px 0; font-size:14px; text-align:right;"><?php echo esc_html( $currency_symbol . number_format( (float) ( $order->subtotal ?? 0 ), 2 ) ); ?></td>
            </tr>
            <?php if ( ! empty( $order->tax_amount ) && $order->tax_amount > 0 ) : ?>
            <tr>
                <td style="padding:8px 0; font-size:14px;"><?php echo esc_html( $order->tax_label ?? 'Tax' ); ?>:</td>
                <td style="padding:8px 0; font-size:14px; text-align:right;"><?php echo esc_html( $currency_symbol . number_format( (float) $order->tax_amount, 2 ) ); ?></td>
            </tr>
            <?php endif; ?>
            <?php if ( ! empty( $order->shipping_amount ) && $order->shipping_amount > 0 ) : ?>
            <tr>
                <td style="padding:8px 0; font-size:14px;">Shipping:</td>
                <td style="padding:8px 0; font-size:14px; text-align:right;"><?php echo esc_html( $currency_symbol . number_format( (float) $order->shipping_amount, 2 ) ); ?></td>
            </tr>
            <?php endif; ?>
            <tr class="total-row">
                <td style="padding:12px 0 8px; font-size:16px; font-weight:600; border-top:2px solid #1f2937;">Total:</td>
                <td style="padding:12px 0 8px; font-size:16px; font-weight:600; border-top:2px solid #1f2937; text-align:right;"><?php echo esc_html( $currency_symbol . number_format( (float) ( $order->total_amount ?? 0 ), 2 ) ); ?></td>
            </tr>
        </table>
        <?php
        return ob_get_clean();
    }

    /**
     * Render custom checkout fields for email.
     *
     * @param object $order Order object.
     * @return string HTML table or empty string.
     */
    protected function render_checkout_fields( $order ) {
        if ( ! class_exists( 'GGM_Commerce_Checkout_Fields' ) ) {
            return '';
        }

        $order_id = $order->id ?? 0;
        if ( ! $order_id ) {
            return '';
        }

        $cf_manager = GGM_Commerce_Checkout_Fields::get_instance();
        return $cf_manager->get_email_fields_html( $order_id );
    }

    /**
     * Get shipment by ID
     *
     * @param int $shipment_id Shipment ID.
     * @return object|null
     */
    protected function get_shipment( $shipment_id ) {
        if ( ! class_exists( 'GGM_Commerce_Shipments' ) ) {
            return null;
        }

        return GGM_Commerce_Shipments::get_shipment( $shipment_id );
    }

    /**
     * Get recipient email address
     *
     * @param object $order Order object.
     * @return string
     */
    public function get_recipient( $order ) {
        if ( 'admin' === $this->recipient_type ) {
            return ggm_commerce_emails()->get_admin_email();
        }

        // Check for additional recipients
        $template = $this->get_saved_template();
        $emails   = array( $order->customer_email );

        if ( $template && ! empty( $template['additional_recipients'] ) ) {
            $additional = array_map( 'trim', explode( ',', $template['additional_recipients'] ) );
            $emails     = array_merge( $emails, $additional );
        }

        return implode( ', ', array_unique( array_filter( $emails ) ) );
    }

    /**
     * Trigger the email
     *
     * @param int   $order_id   Order ID.
     * @param array $extra_args Extra arguments.
     * @return bool
     */
    public function trigger( $order_id, $extra_args = array() ) {
        // Get order data
        $orders = GGM_Commerce_Orders::get_instance();
        $order  = $orders->get_order( $order_id );

        if ( ! $order ) {
            return false;
        }

        // Get recipient
        $recipient = $this->get_recipient( $order );
        if ( empty( $recipient ) ) {
            return false;
        }

        // Get subject and content
        $subject = $this->get_subject( $order );
        $content = $this->get_content( $order, $extra_args );

        // Send email
        $email_manager = ggm_commerce_emails();
        $sent          = $email_manager->send_email( $recipient, $subject, $content );

        // Log email
        $email_manager->log_email(
            $this->id,
            $order_id,
            $recipient,
            $subject,
            $sent
        );

        return $sent;
    }

    /**
     * Get available placeholders for this email
     *
     * @return array
     */
    public function get_placeholders() {
        return array(
            'order_number'        => __( 'Order number', 'ggm-commerce' ),
            'order_date'          => __( 'Order date', 'ggm-commerce' ),
            'order_total'         => __( 'Order total', 'ggm-commerce' ),
            'order_subtotal'      => __( 'Order subtotal', 'ggm-commerce' ),
            'order_tax'           => __( 'Tax amount', 'ggm-commerce' ),
            'order_shipping'      => __( 'Shipping amount', 'ggm-commerce' ),
            'order_status'        => __( 'Order status', 'ggm-commerce' ),
            'payment_method'      => __( 'Payment method', 'ggm-commerce' ),
            'customer_name'       => __( 'Customer full name', 'ggm-commerce' ),
            'customer_first_name' => __( 'Customer first name', 'ggm-commerce' ),
            'customer_email'      => __( 'Customer email', 'ggm-commerce' ),
            'billing_address'     => __( 'Billing address', 'ggm-commerce' ),
            'shipping_address'    => __( 'Shipping address', 'ggm-commerce' ),
            'site_name'           => __( 'Site name', 'ggm-commerce' ),
            'site_url'            => __( 'Site URL', 'ggm-commerce' ),
            'business_name'       => __( 'Business name', 'ggm-commerce' ),
            'business_email'      => __( 'Business email', 'ggm-commerce' ),
            'order_items_table'   => __( 'Order items table (HTML)', 'ggm-commerce' ),
            'checkout_fields'     => __( 'Custom checkout fields (HTML)', 'ggm-commerce' ),
        );
    }

    /**
     * Save template to database
     *
     * @param array $data Template data.
     * @return bool
     */
    public function save_template( $data ) {
        global $wpdb;

        $existing = $this->get_saved_template();

        $template_data = array(
            'email_type'            => $this->id,
            'subject'               => sanitize_text_field( $data['subject'] ?? $this->get_default_subject() ),
            'heading'               => sanitize_text_field( $data['heading'] ?? $this->get_default_heading() ),
            'content'               => wp_kses_post( $data['content'] ?? '' ),
            'enabled'               => isset( $data['enabled'] ) ? (int) $data['enabled'] : 1,
            'additional_recipients' => sanitize_text_field( $data['additional_recipients'] ?? '' ),
            'updated_at'            => current_time( 'mysql' ),
        );

        if ( $existing ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $result = $wpdb->update(
                "{$wpdb->prefix}ggmc_email_templates",
                $template_data,
                array( 'id' => $existing['id'] ),
                array( '%s', '%s', '%s', '%s', '%d', '%s', '%s' ),
                array( '%d' )
            );
        } else {
            $template_data['created_at'] = current_time( 'mysql' );

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_email_templates",
                $template_data,
                array( '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' )
            );
        }

        // Clear cached template
        $this->template_data = null;

        return false !== $result;
    }

    /**
     * Reset template to defaults
     *
     * @return bool
     */
    public function reset_template() {
        global $wpdb;

        $existing = $this->get_saved_template();

        if ( ! $existing ) {
            return true;
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $result = $wpdb->delete(
            "{$wpdb->prefix}ggmc_email_templates",
            array( 'id' => $existing['id'] ),
            array( '%d' )
        );

        // Clear cached template
        $this->template_data = null;

        return false !== $result;
    }

    /**
     * Get sample order data for preview
     *
     * @return object
     */
    protected function get_sample_order() {
        return (object) array(
            'id'                   => 12345,
            'order_number'         => 'GGM-12345',
            'status'               => 'processing',
            'payment_status'       => 'paid',
            'payment_method'       => 'Stripe',
            'created_at'           => gmdate( 'Y-m-d H:i:s' ),
            'customer_first_name'  => 'John',
            'customer_last_name'   => 'Doe',
            'customer_email'       => 'john.doe@example.com',
            'billing_first_name'   => 'John',
            'billing_last_name'    => 'Doe',
            'billing_address_1'    => '123 Main Street',
            'billing_address_2'    => 'Apt 4B',
            'billing_city'         => 'New York',
            'billing_state'        => 'NY',
            'billing_postcode'     => '10001',
            'billing_country'      => 'United States',
            'shipping_first_name'  => 'John',
            'shipping_last_name'   => 'Doe',
            'shipping_address_1'   => '123 Main Street',
            'shipping_address_2'   => 'Apt 4B',
            'shipping_city'        => 'New York',
            'shipping_state'       => 'NY',
            'shipping_postcode'    => '10001',
            'shipping_country'     => 'United States',
            'subtotal'             => 149.97,
            'tax_amount'           => 13.50,
            'tax_label'            => 'Tax',
            'shipping_amount'      => 9.99,
            'total_amount'         => 173.46,
            'items'                => array(
                (object) array(
                    'product_name'   => 'Sample Product 1',
                    'product_sku'    => 'SAMPLE-001',
                    'variation_data' => 'Size: Medium, Color: Blue',
                    'quantity'       => 2,
                    'price'          => 49.99,
                    'total'          => 99.98,
                ),
                (object) array(
                    'product_name'   => 'Sample Product 2',
                    'product_sku'    => 'SAMPLE-002',
                    'variation_data' => '',
                    'quantity'       => 1,
                    'price'          => 49.99,
                    'total'          => 49.99,
                ),
            ),
        );
    }

    /**
     * Get sample extra args for preview
     *
     * @return array
     */
    protected function get_sample_extra_args() {
        return array(
            'shipment_id'     => 1,
            'tracking_number' => 'TRACK123456789',
            'tracking_url'    => 'https://track.example.com/TRACK123456789',
            'carrier_name'    => 'Express Shipping Co.',
            'refund_amount'   => 50.00,
            'refund_reason'   => 'Product not as described',
        );
    }

    /**
     * Get preview HTML
     *
     * @param string $subject Custom subject.
     * @param string $heading Custom heading.
     * @param string $content Custom content.
     * @return string
     */
    public function get_preview( $subject = '', $heading = '', $content = '' ) {
        $order      = $this->get_sample_order();
        $extra_args = $this->get_sample_extra_args();

        // Use provided values or defaults
        if ( empty( $subject ) ) {
            $subject = $this->get_default_subject();
        }
        if ( empty( $heading ) ) {
            $heading = $this->get_default_heading();
        }
        if ( empty( $content ) ) {
            $content = $this->get_default_content();
        }

        // Replace placeholders in content
        $content = $this->replace_placeholders( $content, $order, $extra_args );

        // Build full email with custom heading
        $this->order = $order;

        ob_start();
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html( $this->replace_placeholders( $subject, $order, $extra_args ) ); ?></title>
    <?php $this->output_styles(); ?>
</head>
<div style="margin: 0; padding: 0; background-color: #f3f4f6; font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;">
    <table role="presentation" style="width: 100%; border-collapse: collapse;">
        <tr>
            <td align="center" style="padding: 40px 20px;">
                <table role="presentation" style="width: 100%; max-width: 600px; border-collapse: collapse; background: #ffffff; border-radius: 8px;">
                    <?php $this->output_header(); ?>
                    <tr>
                        <td style="padding: 32px;">
                            <?php if ( ! empty( $heading ) ) : ?>
                            <h1 style="margin: 0 0 24px 0; font-size: 24px; color: #1f2937; font-weight: 600;"><?php echo esc_html( $this->replace_placeholders( $heading, $order, $extra_args ) ); ?></h1>
                            <?php endif; ?>
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            echo $content;
                            ?>
                        </td>
                    </tr>
                    <?php $this->output_footer(); ?>
                </table>
            </td>
        </tr>
    </table>
</div>
</html>
        <?php
        return ob_get_clean();
    }

    /**
     * Send test email
     *
     * @param string $recipient Email address.
     * @return bool
     */
    public function send_test( $recipient ) {
        $order      = $this->get_sample_order();
        $extra_args = $this->get_sample_extra_args();

        // Get template values (saved or default)
        $template = $this->get_saved_template();
        $subject  = $template && ! empty( $template['subject'] ) ? $template['subject'] : $this->get_default_subject();
        $heading  = $template && ! empty( $template['heading'] ) ? $template['heading'] : $this->get_default_heading();
        $content_template = $template && ! empty( $template['content'] ) ? $template['content'] : $this->get_default_content();

        // Replace placeholders
        $subject = $this->replace_placeholders( $subject, $order, $extra_args );
        $subject = '[TEST] ' . $subject;

        $content = $this->replace_placeholders( $content_template, $order, $extra_args );

        // Build full email HTML
        $this->order = $order;

        ob_start();
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo esc_html( $subject ); ?></title>
    <?php $this->output_styles(); ?>
</head>
<div style="margin: 0; padding: 0; background-color: #f3f4f6; font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;">
    <table role="presentation" style="width: 100%; border-collapse: collapse;">
        <tr>
            <td align="center" style="padding: 40px 20px;">
                <table role="presentation" style="width: 100%; max-width: 600px; border-collapse: collapse; background: #ffffff; border-radius: 8px;">
                    <?php $this->output_header(); ?>
                    <tr>
                        <td style="padding: 32px;">
                            <div style="background: #fef3c7; border-left: 4px solid #d97706; padding: 12px; margin-bottom: 24px;">
                                <strong style="color: #92400e;">⚠️ This is a test email</strong>
                                <p style="margin: 4px 0 0; color: #92400e; font-size: 13px;">Sent from your GGM Commerce email settings. Sample data is used for preview.</p>
                            </div>
                            <?php if ( ! empty( $heading ) ) : ?>
                            <h1 style="margin: 0 0 24px 0; font-size: 24px; color: #1f2937; font-weight: 600;"><?php echo esc_html( $this->replace_placeholders( $heading, $order, $extra_args ) ); ?></h1>
                            <?php endif; ?>
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            echo $content;
                            ?>
                        </td>
                    </tr>
                    <?php $this->output_footer(); ?>
                </table>
            </td>
        </tr>
    </table>
</div>
</html>
        <?php
        $html = ob_get_clean();

        // Send email
        $email_manager = ggm_commerce_emails();
        return $email_manager->send_email( $recipient, $subject, $html );
    }
}
