<?php
/**
 * TitanCart Notifications REST Controller
 *
 * Manages notification event toggles per receiver (customer/admin)
 * and email template CRUD.
 *
 * @package TitanCart\REST\Settings
 */

namespace TitanCart\REST\Settings;

defined( 'ABSPATH' ) || exit;

class NotificationsController {

    private $db;
    private $namespace = 'titancart/v1';

    public function __construct() {
        $this->db = titancart_db();
    }

    public function register_routes(): void {
        // Notification event toggles
        register_rest_route( $this->namespace, '/notifications/events', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_events' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
        register_rest_route( $this->namespace, '/notifications/settings', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_settings' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
        register_rest_route( $this->namespace, '/notifications/settings', [
            'methods'             => 'PUT',
            'callback'            => [ $this, 'update_settings' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);

        // Email templates
        register_rest_route( $this->namespace, '/email/templates', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_templates' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
        register_rest_route( $this->namespace, '/email/templates/(?P<id>\d+)', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_template' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
        register_rest_route( $this->namespace, '/email/templates/(?P<id>\d+)', [
            'methods'             => 'PUT',
            'callback'            => [ $this, 'update_template' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
        register_rest_route( $this->namespace, '/email/templates/(?P<id>\d+)/status', [
            'methods'             => 'PUT',
            'callback'            => [ $this, 'toggle_template_status' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);

        // Documents (stub list)
        register_rest_route( $this->namespace, '/notifications/documents', [
            'methods'             => 'GET',
            'callback'            => [ $this, 'get_documents' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);

        // Test email sender
        register_rest_route( $this->namespace, '/email/test', [
            'methods'             => 'POST',
            'callback'            => [ $this, 'send_test_email' ],
            'permission_callback' => [ $this, 'check_admin' ],
        ]);
    }

    public function check_admin(): bool {
        return current_user_can( 'manage_options' );
    }

    /* ────────────────────────────────────────────────────────────────────
     * Helper: prefixed table name
     * ──────────────────────────────────────────────────────────────────── */
    private function t( string $name ): string {
        return $this->db->table( $name );
    }

    /* ────────────────────────────────────────────────────────────────────
     * Event schema — defines all notification events grouped by category
     * ──────────────────────────────────────────────────────────────────── */
    private function event_schema(): array {
        // Fetch dynamic order statuses from tc_order_statuses + translations
        $os_tbl  = $this->t('order_statuses');
        $ost_tbl = $this->t('order_status_translations');
        $statuses = $this->db->getArray(
            "SELECT os.handle, COALESCE(ost.name, os.handle) AS name
             FROM {$os_tbl} os
             LEFT JOIN {$ost_tbl} ost ON ost.status_id = os.id AND ost.language_code = 'en'
             WHERE os.type = 'order'
             ORDER BY os.position ASC"
        );
        if ( empty( $statuses ) ) {
            $statuses = [
                [ 'handle' => 'pending',    'name' => 'Pending' ],
                [ 'handle' => 'processing', 'name' => 'Processing' ],
                [ 'handle' => 'on_hold',    'name' => 'On Hold' ],
                [ 'handle' => 'completed',  'name' => 'Completed' ],
                [ 'handle' => 'cancelled',  'name' => 'Cancelled' ],
                [ 'handle' => 'refunded',   'name' => 'Refunded' ],
                [ 'handle' => 'failed',     'name' => 'Failed' ],
            ];
        }

        // Build order status events dynamically
        $order_events = [
            [ 'id' => 'order.shipped', 'name' => 'Products were shipped', 'receivers' => ['customer','admin'] ],
        ];
        foreach ( $statuses as $s ) {
            $handle = is_array($s) ? $s['handle'] : $s->handle;
            $name   = is_array($s) ? $s['name']   : $s->name;
            $order_events[] = [
                'id'        => 'order.status_' . $handle,
                'name'      => 'Order status changed to ' . $name,
                'receivers' => ['customer','admin'],
            ];
        }
        $order_events[] = [ 'id' => 'order.updated', 'name' => 'Order was updated', 'receivers' => ['customer','admin'] ];

        return [
            [
                'group' => 'Orders',
                'events' => $order_events,
            ],
            [
                'group' => 'Products',
                'events' => [
                    [ 'id' => 'product.back_in_stock',  'name' => 'Product is back in stock',      'receivers' => ['customer'] ],
                    [ 'id' => 'product.low_stock',       'name' => 'Product low stock alert',       'receivers' => ['admin'] ],
                ],
            ],
            [
                'group' => 'Account',
                'events' => [
                    [ 'id' => 'account.activated',         'name' => 'Account was activated',         'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.deactivated',       'name' => 'Account was deactivated',       'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.updated',           'name' => 'Account was updated',           'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.created',           'name' => 'Account was created',           'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.group_activated',   'name' => 'Customer group activation',     'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.group_deactivated', 'name' => 'Customer group deactivation',   'receivers' => ['customer','admin'] ],
                    [ 'id' => 'account.password_recovery', 'name' => 'Password recovery',             'receivers' => ['customer','admin'] ],
                ],
            ],
            [
                'group' => 'Customers',
                'events' => [
                    [ 'id' => 'customer.group_requested',      'name' => 'Customer group membership requested', 'receivers' => ['admin'] ],
                    [ 'id' => 'customer.requires_activation',  'name' => 'Account requires activation',         'receivers' => ['admin'] ],
                ],
            ],
            [
                'group' => 'Gift Cards',
                'events' => [
                    [ 'id' => 'giftcard.status_pending',  'name' => 'Gift card status changed to Pending',  'receivers' => ['customer'] ],
                    [ 'id' => 'giftcard.status_active',   'name' => 'Gift card status changed to Active',   'receivers' => ['customer'] ],
                    [ 'id' => 'giftcard.status_disabled',  'name' => 'Gift card status changed to Disabled', 'receivers' => ['customer'] ],
                    [ 'id' => 'giftcard.status_used',     'name' => 'Gift card status changed to Used',     'receivers' => ['customer'] ],
                    [ 'id' => 'giftcard.updated',         'name' => 'Gift card updated',                    'receivers' => ['customer'] ],
                ],
            ],
            [
                'group' => 'Reviews',
                'events' => [
                    [ 'id' => 'review.reply_added',  'name' => 'New reply was added to review',  'receivers' => ['customer'] ],
                    [ 'id' => 'review.new_posted',   'name' => 'New review posted',               'receivers' => ['admin'] ],
                ],
            ],
            [
                'group' => 'System',
                'events' => [
                    [ 'id' => 'system.shipping_error', 'name' => 'Realtime shipping errors', 'receivers' => ['admin'] ],
                ],
            ],
        ];
    }

    /* ────────────────────────────────────────────────────────────────────
     * GET /notifications/events — schema of all events with groups
     * ──────────────────────────────────────────────────────────────────── */
    public function get_events( $request ): \WP_REST_Response {
        return new \WP_REST_Response( $this->event_schema(), 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * GET /notifications/settings — current toggle values
     * ──────────────────────────────────────────────────────────────────── */
    public function get_settings( $request ): \WP_REST_Response {
        $tbl = $this->t('notification_settings');
        $rows = $this->db->getArray(
            "SELECT event_id, receiver, transport, enabled FROM {$tbl}"
        );
        // Key by event_id|receiver|transport
        $map = [];
        foreach ( $rows as $r ) {
            $key = $r->event_id . '|' . $r->receiver . '|' . $r->transport;
            $map[ $key ] = (int) $r->enabled;
        }
        return new \WP_REST_Response( $map, 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * PUT /notifications/settings — bulk upsert toggles
     * Body: { "order.shipped|customer|email": 1, "order.shipped|admin|email": 0, ... }
     * ──────────────────────────────────────────────────────────────────── */
    public function update_settings( $request ): \WP_REST_Response {
        $body = $request->get_json_params();
        if ( ! is_array( $body ) ) {
            return new \WP_REST_Response( [ 'error' => 'Invalid body' ], 400 );
        }

        global $wpdb;
        $table = $wpdb->prefix . 'tc_notification_settings';

        foreach ( $body as $key => $enabled ) {
            $parts = explode( '|', $key );
            if ( count( $parts ) !== 3 ) continue;

            $event_id  = sanitize_text_field( $parts[0] );
            $receiver  = in_array( $parts[1], ['customer','admin'], true ) ? $parts[1] : 'customer';
            $transport = sanitize_text_field( $parts[2] );
            $enabled   = $enabled ? 1 : 0;

            $wpdb->query( $wpdb->prepare(
                "INSERT INTO {$table} (event_id, receiver, transport, enabled)
                 VALUES (%s, %s, %s, %d)
                 ON DUPLICATE KEY UPDATE enabled = VALUES(enabled)",
                $event_id, $receiver, $transport, $enabled
            ));
        }

        return new \WP_REST_Response( [ 'saved' => true ], 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * GET /email/templates — list all templates
     * ──────────────────────────────────────────────────────────────────── */
    public function get_templates( $request ): \WP_REST_Response {
        $tbl      = $this->t('email_templates');
        $receiver = sanitize_text_field( $request->get_param('receiver') ?? '' );

        if ( in_array( $receiver, ['customer','admin'], true ) ) {
            $rows = $this->db->getArray(
                "SELECT id, slug, receiver, name, subject, status, created_at, updated_at FROM {$tbl} WHERE receiver = ?s ORDER BY name ASC",
                $receiver
            );
        } else {
            $rows = $this->db->getArray(
                "SELECT id, slug, receiver, name, subject, status, created_at, updated_at FROM {$tbl} ORDER BY receiver ASC, name ASC"
            );
        }

        // If table is empty, seed defaults
        if ( empty( $rows ) ) {
            $this->seed_default_templates();
            $rows = $this->db->getArray(
                "SELECT id, slug, receiver, name, subject, status, created_at, updated_at FROM {$tbl} ORDER BY receiver ASC, name ASC"
            );
        }

        return new \WP_REST_Response( $rows, 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * GET /email/templates/{id} — single template with body
     * ──────────────────────────────────────────────────────────────────── */
    public function get_template( $request ): \WP_REST_Response {
        $id  = (int) $request['id'];
        $tbl = $this->t('email_templates');
        $row = $this->db->getRow( "SELECT * FROM {$tbl} WHERE id = ?i", $id );
        if ( ! $row ) {
            return new \WP_REST_Response( [ 'error' => 'Template not found' ], 404 );
        }
        return new \WP_REST_Response( $row, 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * PUT /email/templates/{id} — update template subject + body
     * ──────────────────────────────────────────────────────────────────── */
    public function update_template( $request ): \WP_REST_Response {
        $id   = (int) $request['id'];
        $body = $request->get_json_params();

        $update = [];
        if ( isset( $body['subject'] ) )   $update['subject']   = sanitize_text_field( $body['subject'] );
        if ( isset( $body['body_html'] ) ) $update['body_html'] = wp_kses_post( $body['body_html'] );
        if ( isset( $body['name'] ) )      $update['name']      = sanitize_text_field( $body['name'] );
        if ( isset( $body['status'] ) )    $update['status']    = in_array( $body['status'], ['active','disabled'], true ) ? $body['status'] : 'active';

        if ( empty( $update ) ) {
            return new \WP_REST_Response( [ 'error' => 'Nothing to update' ], 400 );
        }

        global $wpdb;
        $table = $wpdb->prefix . 'tc_email_templates';
        $wpdb->update( $table, $update, [ 'id' => $id ] );

        return new \WP_REST_Response( [ 'saved' => true ], 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * PUT /email/templates/{id}/status — quick toggle Active/Disabled
     * ──────────────────────────────────────────────────────────────────── */
    public function toggle_template_status( $request ): \WP_REST_Response {
        $id   = (int) $request['id'];
        $body = $request->get_json_params();
        $status = ( isset( $body['status'] ) && $body['status'] === 'disabled' ) ? 'disabled' : 'active';

        global $wpdb;
        $table = $wpdb->prefix . 'tc_email_templates';
        $wpdb->update( $table, [ 'status' => $status ], [ 'id' => $id ] );

        return new \WP_REST_Response( [ 'status' => $status ], 200 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * GET /notifications/documents — static list of document types
     * ──────────────────────────────────────────────────────────────────── */
    public function get_documents( $request ): \WP_REST_Response {
        $docs = [
            [ 'name' => 'Invoice',            'code' => 'order.invoice',               'description' => 'Branded printable invoice — opened from each order, the customer account, and a link in order confirmation emails.' ],
            [ 'name' => 'Order Summary',      'code' => 'order.summary',               'description' => 'Brief order summary for confirmation emails.' ],
            [ 'name' => 'Packing Slip',       'code' => 'packing_slip.default',        'description' => 'Packing slip for warehouse fulfillment.' ],
            [ 'name' => 'Gift Card Voucher',  'code' => 'gift_card.default',           'description' => 'Printable gift card voucher.' ],
        ];
        return new \WP_REST_Response( $docs, 200 );
    }

    /**
     * Send a test email using the active transport (php_mail / SMTP / sendmail).
     *
     * POST /titancart/v1/email/test
     * Body: { "type": "order_confirmation|new_order_admin|order_status_update", "to": "email@example.com" }
     */
    public function send_test_email( $request ): \WP_REST_Response {
        $body = $request->get_json_params();
        $type = sanitize_key( $body['type'] ?? '' );
        $to   = sanitize_email( $body['to'] ?? '' );

        if ( ! $type ) {
            return new \WP_REST_Response( [ 'success' => false, 'message' => 'Missing "type" parameter.' ], 400 );
        }
        if ( ! is_email( $to ) ) {
            return new \WP_REST_Response( [ 'success' => false, 'message' => 'Invalid email address.' ], 400 );
        }

        $mailer = new \TitanCart\Modules\Orders\Mailer();
        $result = $mailer->send_test( $type, $to );

        return new \WP_REST_Response( $result, $result['success'] ? 200 : 500 );
    }

    /* ────────────────────────────────────────────────────────────────────
     * Email layout wrapper — responsive, clean, works in all clients
     * ──────────────────────────────────────────────────────────────────── */
    private function email_wrap( string $body ): string {
        return '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>{site_name}</title></head>'
            . '<body style="margin:0;padding:0;background:#f4f5f7;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,Helvetica,Arial,sans-serif;color:#1c2430;font-size:15px;line-height:1.6;">'
            . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f5f7;"><tr><td align="center" style="padding:32px 16px;">'
            . '<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,0.06);">'
            /* Header */
            . '<tr><td style="background:#171717;padding:24px 32px;text-align:center;">'
            . '<span style="color:#ffffff;font-size:20px;font-weight:700;letter-spacing:-0.3px;">{site_name}</span>'
            . '</td></tr>'
            /* Body */
            . '<tr><td style="padding:32px;">' . $body . '</td></tr>'
            /* Footer */
            . '<tr><td style="padding:20px 32px;background:#f9fafb;border-top:1px solid #e5e7eb;text-align:center;font-size:12px;color:#6b7280;">'
            . '<p style="margin:0 0 4px;">This email was sent by <strong>{site_name}</strong></p>'
            . '<p style="margin:0;"><a href="{site_url}" style="color:#2563eb;text-decoration:none;">{site_url}</a></p>'
            . '</td></tr>'
            . '</table></td></tr></table></body></html>';
    }

    /* ── Reusable fragments ── */
    private function btn( string $url, string $label, string $bg = '#171717' ): string {
        return '<table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px 0;"><tr>'
            . '<td style="background:'.$bg.';border-radius:6px;padding:12px 28px;text-align:center;">'
            . '<a href="'.$url.'" style="color:#ffffff;text-decoration:none;font-weight:600;font-size:14px;">'.$label.'</a>'
            . '</td></tr></table>';
    }

    private function order_details_block(): string {
        return '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
            . '<tr style="background:#f9fafb;"><td style="padding:10px 16px;font-size:13px;font-weight:600;color:#6b7280;">Order Details</td></tr>'
            . '<tr><td style="padding:16px;">{order_items}</td></tr>'
            . '<tr><td style="padding:12px 16px;border-top:1px solid #e5e7eb;text-align:right;font-weight:700;font-size:16px;">Total: {order_total}</td></tr>'
            . '</table>';
    }

    private function address_block(): string {
        return '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;">'
            . '<tr><td width="50%" valign="top" style="padding-right:12px;">'
            . '<p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;">Billing Address</p>'
            . '<p style="margin:0;font-size:13px;">{billing_address}</p></td>'
            . '<td width="50%" valign="top" style="padding-left:12px;">'
            . '<p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;">Shipping Address</p>'
            . '<p style="margin:0;font-size:13px;">{shipping_address}</p></td>'
            . '</tr></table>';
    }

    /* ────────────────────────────────────────────────────────────────────
     * Seed default email templates on first access
     * ──────────────────────────────────────────────────────────────────── */
    private function seed_default_templates(): void {

        $btn = function( $url, $label, $bg = '#171717' ) { return $this->btn( $url, $label, $bg ); };
        $od  = $this->order_details_block();
        $ad  = $this->address_block();

        /* ── Order status body for customer ── */
        $cust_order_body = function( $status_msg ) use ( $btn, $od, $ad ) {
            return $this->email_wrap(
                '<p style="margin:0 0 16px;">Dear {customer_name},</p>'
                . '<p style="margin:0 0 16px;">' . $status_msg . '</p>'
                . '<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">Order: <strong style="color:#1c2430;">#{order_id}</strong></p>'
                . $od . $ad
                . $btn( '{order_url}', 'View Your Order' )
                . '<p style="margin:0;font-size:13px;color:#6b7280;">If you have any questions, simply reply to this email.</p>'
            );
        };

        /* ── Order status body for admin ── */
        $admin_order_body = function( $status_msg ) use ( $od ) {
            return $this->email_wrap(
                '<p style="margin:0 0 16px;">' . $status_msg . '</p>'
                . '<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">Order: <strong style="color:#1c2430;">#{order_id}</strong> &mdash; Customer: {customer_name} ({customer_email})</p>'
                . $od
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Total: <strong style="color:#1c2430;">{order_total}</strong></p>'
            );
        };

        $defaults = [
            /* ═══════════════════════════════════════════════════════════
             * CUSTOMER TEMPLATES
             * ═══════════════════════════════════════════════════════════ */
            [ 'slug' => 'order_placed', 'receiver' => 'customer',
              'name' => 'Order Confirmation',
              'subject' => 'Your order #{order_id} has been placed',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Dear {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Thank you for your order! We\'ve received your order and it\'s now being processed. Here\'s a summary of what you ordered:</p>'
                . '<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">Order Number: <strong style="color:#1c2430;">#{order_id}</strong></p>'
                . $od . $ad
                . $btn( '{order_url}', 'View Your Order' )
                . '<p style="margin:0;font-size:13px;color:#6b7280;">We\'ll send you another email when your order ships. If you have any questions, simply reply to this email.</p>'
              ),
            ],
            [ 'slug' => 'order_status_paid', 'receiver' => 'customer',
              'name' => 'Order notification: Paid',
              'subject' => 'Order #{order_id} — Payment received',
              'body' => $cust_order_body( 'Great news! We\'ve received your payment for the order below. Your order is now being prepared.' ),
            ],
            [ 'slug' => 'order_status_complete', 'receiver' => 'customer',
              'name' => 'Order notification: Complete',
              'subject' => 'Order #{order_id} — Complete',
              'body' => $cust_order_body( 'Your order has been marked as complete. We hope you enjoy your purchase!' ),
            ],
            [ 'slug' => 'order_status_open', 'receiver' => 'customer',
              'name' => 'Order notification: Open',
              'subject' => 'Order #{order_id} — Awaiting payment',
              'body' => $cust_order_body( 'Your order is currently awaiting payment. Please complete your payment to proceed.' ),
            ],
            [ 'slug' => 'order_status_failed', 'receiver' => 'customer',
              'name' => 'Order notification: Failed',
              'subject' => 'Order #{order_id} — Payment failed',
              'body' => $cust_order_body( 'Unfortunately, the payment for your order could not be processed. Please try again or use a different payment method.' ),
            ],
            [ 'slug' => 'order_status_declined', 'receiver' => 'customer',
              'name' => 'Order notification: Declined',
              'subject' => 'Order #{order_id} — Declined',
              'body' => $cust_order_body( 'Your order has been declined. If you believe this is an error, please contact our support team.' ),
            ],
            [ 'slug' => 'order_status_backordered', 'receiver' => 'customer',
              'name' => 'Order notification: Backordered',
              'subject' => 'Order #{order_id} — Backordered',
              'body' => $cust_order_body( 'One or more items in your order are currently on backorder. We\'ll notify you as soon as they\'re available and your order ships.' ),
            ],
            [ 'slug' => 'order_status_cancelled', 'receiver' => 'customer',
              'name' => 'Order notification: Cancelled',
              'subject' => 'Order #{order_id} — Cancelled',
              'body' => $cust_order_body( 'Your order has been cancelled. If a payment was made, a refund will be processed within 5–10 business days.' ),
            ],
            [ 'slug' => 'order_shipped', 'receiver' => 'customer',
              'name' => 'Order Shipped',
              'subject' => 'Order #{order_id} has been shipped',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Dear {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Your order <strong>#{order_id}</strong> has been shipped! Here are the details:</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;"><strong>Tracking Number:</strong> {tracking_number}</td></tr>'
                . '<tr><td style="padding:12px 16px;border-top:1px solid #e5e7eb;font-size:13px;"><strong>Carrier:</strong> {shipping_method}</td></tr>'
                . '</table>'
                . $btn( '{tracking_url}', 'Track Your Package', '#2563eb' )
                . $od
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Delivery times may vary depending on your location and the shipping method selected.</p>'
              ),
            ],
            [ 'slug' => 'order_tracking', 'receiver' => 'customer',
              'name' => 'Order Tracking',
              'subject' => 'Tracking information for order #{order_id}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Dear {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Tracking information has been updated for your order <strong>#{order_id}</strong>.</p>'
                . '<p style="margin:0 0 8px;font-size:13px;"><strong>Tracking Number:</strong> {tracking_number}</p>'
                . $btn( '{tracking_url}', 'Track Your Package', '#2563eb' )
              ),
            ],
            [ 'slug' => 'back_in_stock', 'receiver' => 'customer',
              'name' => 'Back in Stock Notification',
              'subject' => '{product_name} is back in stock!',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Good news! <strong>{product_name}</strong> is back in stock and available for purchase. Don\'t miss out — popular items can sell out fast!</p>'
                . $btn( '{product_url}', 'Shop Now', '#2563eb' )
                . '<p style="margin:0;font-size:13px;color:#6b7280;">You received this email because you signed up for a back-in-stock notification.</p>'
              ),
            ],
            [ 'slug' => 'gift_card', 'receiver' => 'customer',
              'name' => 'Gift Card',
              'subject' => 'You received a gift card!',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Congratulations!</p>'
                . '<p style="margin:0 0 16px;">You\'ve received a <strong>{gift_card_amount}</strong> gift card for <strong>{site_name}</strong>.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0;background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;text-align:center;">'
                . '<tr><td style="padding:24px;"><p style="margin:0 0 8px;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:1px;">Your Gift Card Code</p>'
                . '<p style="margin:0;font-size:24px;font-weight:700;letter-spacing:2px;color:#171717;">{gift_card_code}</p></td></tr></table>'
                . '<p style="margin:0 0 16px;font-size:13px;">Enter this code at checkout to apply the balance to your order.</p>'
                . $btn( '{site_url}', 'Start Shopping' )
              ),
            ],
            [ 'slug' => 'account_welcome', 'receiver' => 'customer',
              'name' => 'Account Welcome',
              'subject' => 'Welcome to {site_name}!',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Welcome to <strong>{site_name}</strong>! Your account has been created successfully. Here\'s what you can do:</p>'
                . '<ul style="margin:0 0 16px;padding-left:20px;font-size:14px;color:#374151;">'
                . '<li style="margin-bottom:8px;">Track your orders in real-time</li>'
                . '<li style="margin-bottom:8px;">Save your favorite products to your wishlist</li>'
                . '<li style="margin-bottom:8px;">Speed through checkout with saved addresses</li>'
                . '<li style="margin-bottom:8px;">Earn loyalty rewards on every purchase</li>'
                . '</ul>'
                . $btn( '{site_url}', 'Start Shopping' )
              ),
            ],
            [ 'slug' => 'account_activation', 'receiver' => 'customer',
              'name' => 'Account Activation',
              'subject' => 'Your account has been activated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Your account at <strong>{site_name}</strong> has been activated. You can now log in and start shopping.</p>'
                . $btn( '{site_url}', 'Visit Store' )
              ),
            ],
            [ 'slug' => 'account_deactivation', 'receiver' => 'customer',
              'name' => 'Account Deactivation',
              'subject' => 'Your account has been deactivated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Your account at <strong>{site_name}</strong> has been deactivated. If you believe this is an error, please contact our support team.</p>'
              ),
            ],
            [ 'slug' => 'password_recovery', 'receiver' => 'customer',
              'name' => 'Password Recovery',
              'subject' => 'Password reset for {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">We received a request to reset the password for your <strong>{site_name}</strong> account. Click the button below to set a new password:</p>'
                . $btn( '{reset_url}', 'Reset Your Password', '#2563eb' )
                . '<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">This link will expire in 24 hours.</p>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">If you didn\'t request this, you can safely ignore this email. Your password will remain unchanged.</p>'
              ),
            ],
            [ 'slug' => 'group_activation', 'receiver' => 'customer',
              'name' => 'Customer Group Activation',
              'subject' => 'Your group membership has been activated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Your membership in the <strong>{group_name}</strong> customer group at <strong>{site_name}</strong> has been activated. You may now have access to special pricing and promotions.</p>'
                . $btn( '{site_url}', 'Visit Store' )
              ),
            ],
            [ 'slug' => 'group_deactivation', 'receiver' => 'customer',
              'name' => 'Customer Group Deactivation',
              'subject' => 'Your group membership has been deactivated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Your membership in the <strong>{group_name}</strong> customer group at <strong>{site_name}</strong> has been deactivated. If you have questions, please contact our support team.</p>'
              ),
            ],
            [ 'slug' => 'review_reply', 'receiver' => 'customer',
              'name' => 'Review Reply Notification',
              'subject' => 'New reply to your review on {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">Someone has replied to your review on <strong>{product_name}</strong>:</p>'
                . '<div style="margin:16px 0;padding:16px;background:#f9fafb;border-left:3px solid #2563eb;border-radius:0 6px 6px 0;font-size:14px;color:#374151;">{reply_text}</div>'
                . $btn( '{product_url}', 'View Review', '#2563eb' )
              ),
            ],
            [ 'slug' => 'promo_coupon', 'receiver' => 'customer',
              'name' => 'Promotions: Coupon',
              'subject' => 'Special offer from {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">We have a special offer just for you! Use the coupon code below to get <strong>{discount_amount}</strong> off your next order:</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:20px 0;background:#f9fafb;border:2px dashed #2563eb;border-radius:6px;text-align:center;">'
                . '<tr><td style="padding:20px;"><p style="margin:0;font-size:22px;font-weight:700;letter-spacing:3px;color:#2563eb;">{coupon_code}</p></td></tr></table>'
                . $btn( '{site_url}', 'Shop Now', '#2563eb' )
              ),
            ],
            [ 'slug' => 'loyalty_points', 'receiver' => 'customer',
              'name' => 'Loyalty Rewards Points',
              'subject' => 'You earned loyalty points at {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Hi {customer_name},</p>'
                . '<p style="margin:0 0 16px;">You\'ve earned <strong>{points_earned} loyalty points</strong> from your recent activity at <strong>{site_name}</strong>.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Points Earned:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;text-align:right;">+{points_earned}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Current Balance:</td><td style="padding:12px 16px;font-size:16px;font-weight:700;text-align:right;color:#2563eb;border-top:1px solid #e5e7eb;">{points_balance}</td></tr>'
                . '</table>'
                . $btn( '{site_url}', 'Use Your Points' )
              ),
            ],

            /* ═══════════════════════════════════════════════════════════
             * ADMIN TEMPLATES
             * ═══════════════════════════════════════════════════════════ */
            [ 'slug' => 'order_placed', 'receiver' => 'admin',
              'name' => 'New Order Notification',
              'subject' => 'New order #{order_id} placed',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A new order has been placed on <strong>{site_name}</strong>.</p>'
                . '<p style="margin:0 0 8px;font-size:13px;color:#6b7280;">Order: <strong style="color:#1c2430;">#{order_id}</strong> &mdash; Customer: {customer_name} ({customer_email})</p>'
                . $od . $ad
                . $btn( '{order_admin_url}', 'View in Admin' )
              ),
            ],
            [ 'slug' => 'order_status_paid', 'receiver' => 'admin',
              'name' => 'Order notification: Paid',
              'subject' => 'Order #{order_id} — Payment received',
              'body' => $admin_order_body( 'Payment has been received for the following order.' ),
            ],
            [ 'slug' => 'order_status_complete', 'receiver' => 'admin',
              'name' => 'Order notification: Complete',
              'subject' => 'Order #{order_id} — Complete',
              'body' => $admin_order_body( 'The following order has been marked as complete.' ),
            ],
            [ 'slug' => 'order_status_open', 'receiver' => 'admin',
              'name' => 'Order notification: Open',
              'subject' => 'Order #{order_id} — Open',
              'body' => $admin_order_body( 'The following order status has changed to Open (awaiting payment).' ),
            ],
            [ 'slug' => 'order_status_failed', 'receiver' => 'admin',
              'name' => 'Order notification: Failed',
              'subject' => 'Order #{order_id} — Failed',
              'body' => $admin_order_body( 'Payment has failed for the following order. The customer has been notified.' ),
            ],
            [ 'slug' => 'order_status_declined', 'receiver' => 'admin',
              'name' => 'Order notification: Declined',
              'subject' => 'Order #{order_id} — Declined',
              'body' => $admin_order_body( 'The following order has been declined.' ),
            ],
            [ 'slug' => 'order_status_backordered', 'receiver' => 'admin',
              'name' => 'Order notification: Backordered',
              'subject' => 'Order #{order_id} — Backordered',
              'body' => $admin_order_body( 'The following order has been placed on backorder due to insufficient stock.' ),
            ],
            [ 'slug' => 'order_status_cancelled', 'receiver' => 'admin',
              'name' => 'Order notification: Cancelled',
              'subject' => 'Order #{order_id} — Cancelled',
              'body' => $admin_order_body( 'The following order has been cancelled.' ),
            ],
            [ 'slug' => 'password_recovery', 'receiver' => 'admin',
              'name' => 'Password Recovery',
              'subject' => 'Admin password reset for {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A password reset has been requested for your administrator account at <strong>{site_name}</strong>.</p>'
                . '<p style="margin:0 0 16px;">Click the button below to set a new password:</p>'
                . $btn( '{reset_url}', 'Reset Password', '#2563eb' )
                . '<p style="margin:0;font-size:13px;color:#6b7280;">This link will expire in 24 hours. If you didn\'t request this, please secure your account immediately.</p>'
              ),
            ],
            [ 'slug' => 'low_stock', 'receiver' => 'admin',
              'name' => 'Product Low Stock Notification',
              'subject' => 'Low stock alert: {product_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;font-size:16px;font-weight:600;color:#d97706;">&#9888; Low Stock Alert</p>'
                . '<p style="margin:0 0 16px;">The following product is running low on stock:</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Product:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;">{product_name}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">SKU:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{product_code}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Current Stock:</td><td style="padding:12px 16px;font-size:13px;font-weight:700;color:#dc2626;border-top:1px solid #e5e7eb;">{stock_amount}</td></tr>'
                . '</table>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Please restock this item to avoid losing sales.</p>'
              ),
            ],
            [ 'slug' => 'new_review', 'receiver' => 'admin',
              'name' => 'New Review Posted',
              'subject' => 'New product review on {site_name}',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A new product review has been submitted on <strong>{site_name}</strong>.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Product:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;">{product_name}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Rating:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{review_rating} / 5</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">By:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{reviewer_name}</td></tr>'
                . '</table>'
                . '<div style="margin:16px 0;padding:16px;background:#f9fafb;border-radius:6px;font-size:14px;color:#374151;">{review_text}</div>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Review this submission in your admin panel to approve or reject it.</p>'
              ),
            ],
            [ 'slug' => 'shipping_error', 'receiver' => 'admin',
              'name' => 'Shipping Request Error',
              'subject' => 'Shipping rate request error',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;font-size:16px;font-weight:600;color:#dc2626;">&#9888; Shipping Rate Error</p>'
                . '<p style="margin:0 0 16px;">An error occurred when requesting realtime shipping rates:</p>'
                . '<div style="margin:16px 0;padding:16px;background:#fef2f2;border:1px solid #fecaca;border-radius:6px;font-size:13px;font-family:monospace;color:#991b1b;">{error_message}</div>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Check your shipping carrier API credentials and settings.</p>'
              ),
            ],
            [ 'slug' => 'account_created', 'receiver' => 'admin',
              'name' => 'User Account Creation',
              'subject' => 'New customer account created',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A new customer account has been created on <strong>{site_name}</strong>.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Name:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;">{customer_name}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Email:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{customer_email}</td></tr>'
                . '</table>'
              ),
            ],
            [ 'slug' => 'account_activation', 'receiver' => 'admin',
              'name' => 'User Account Activation',
              'subject' => 'Customer account activated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Customer account has been activated on <strong>{site_name}</strong>.</p>'
                . '<p style="margin:0;font-size:13px;">Customer: <strong>{customer_name}</strong> ({customer_email})</p>'
              ),
            ],
            [ 'slug' => 'account_deactivation', 'receiver' => 'admin',
              'name' => 'User Account Deactivation',
              'subject' => 'Customer account deactivated',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">Customer account has been deactivated on <strong>{site_name}</strong>.</p>'
                . '<p style="margin:0;font-size:13px;">Customer: <strong>{customer_name}</strong> ({customer_email})</p>'
              ),
            ],
            [ 'slug' => 'group_request', 'receiver' => 'admin',
              'name' => 'Customer Group Request',
              'subject' => 'Customer group membership requested',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A customer has requested membership in a customer group.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Customer:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;">{customer_name} ({customer_email})</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Requested Group:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{group_name}</td></tr>'
                . '</table>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Review and approve this request in the Customers section of your admin panel.</p>'
              ),
            ],
            [ 'slug' => 'requires_activation', 'receiver' => 'admin',
              'name' => 'Account Requires Activation',
              'subject' => 'Customer account requires activation',
              'body' => $this->email_wrap(
                '<p style="margin:0 0 16px;">A new customer account requires manual activation on <strong>{site_name}</strong>.</p>'
                . '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">'
                . '<tr><td style="padding:12px 16px;font-size:13px;">Name:</td><td style="padding:12px 16px;font-size:13px;font-weight:600;">{customer_name}</td></tr>'
                . '<tr><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">Email:</td><td style="padding:12px 16px;font-size:13px;border-top:1px solid #e5e7eb;">{customer_email}</td></tr>'
                . '</table>'
                . '<p style="margin:0;font-size:13px;color:#6b7280;">Go to Customers in your admin panel to activate this account.</p>'
              ),
            ],
        ];

        global $wpdb;
        $table = $wpdb->prefix . 'tc_email_templates';
        foreach ( $defaults as $d ) {
            $wpdb->insert( $table, [
                'slug'      => $d['slug'],
                'receiver'  => $d['receiver'],
                'name'      => $d['name'],
                'subject'   => $d['subject'],
                'body_html' => $d['body'],
                'status'    => 'active',
            ]);
        }
    }
}
