<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * WC Vendors Pro Emails Class
 *
 * @author     WC Vendors, Lindeni Mahlalela
 * @package    WCVendors_Pro
 * @subpackage WCVendors_Pro/emails/
 */
class WCV_Pro_Emails {
    /**
     * Construct, add ajax hooks
     *
     * @since 1.5.4
     */
    public function __construct() {
        add_filter( 'woocommerce_email_classes', array( $this, 'email_classes' ) );
        add_action( 'wp_ajax_wcv_quick_contact', array( $this, 'process_quick_contact' ) );

        add_action( 'wp_ajax_nopriv_wcv_quick_contact', array( $this, 'process_quick_contact' ) );
        add_action( 'wcvendors_vendor_ship', array( $this, 'schedule_customer_mark_received_email' ), 10, 2 );

        add_action( 'wcv_scheduled_customer_mark_received_email', array( $this, 'process_mark_received' ), 10, 2 );

        // Hook into WooCommerce order emails to add vendor details.
        add_action( 'woocommerce_email_after_order_table', array( $this, 'add_vendor_details_to_order_emails' ), 25, 4 );
    }

    /**
     * Add email class to WooCommerce emails
     *
     * @param array $emails The list of registered emails.
     *
     * @return array $emails
     * @since 1.5.4
     */
    public function email_classes( $emails ) {

        require_once 'class-vendor-contact-widget-email.php';
        require_once 'class-customer-mark-received-email.php';

        $emails['WC_Vendors_Pro_Email_Vendor_Contact_Widget']  = new WC_Vendors_Pro_Email_Vendor_Contact_Widget();
        $emails['WC_Vendors_Pro_Email_Customer_Mark_Received'] = new WC_Vendors_Pro_Email_Customer_Mark_Received();

        return $emails;
    }

    /**
     * Process the ajax request to send the email
     *
     * @return void
     * @since 1.5.4
     */
    public function process_quick_contact() {
        global $woocommerce;

        $emails = $woocommerce->mailer()->get_emails();

        // Nonce verification is handled in the send_email() method.
        if ( isset( $_REQUEST['vendor'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $emails['WC_Vendors_Pro_Email_Vendor_Contact_Widget']->send_email();
        }
    }

    /**
     * Process mark received.
     *
     * @param int $order_id The order id.
     * @param int $vendor_id The vendor id.
     * @return void
     * @version 1.0.0
     * @since   1.0.0
     */
    public function process_mark_received( $order_id, $vendor_id ) {
        global $woocommerce;

        $emails = $woocommerce->mailer()->get_emails();

        $emails['WC_Vendors_Pro_Email_Customer_Mark_Received']->trigger( $order_id, $vendor_id );
    }

    /**
     * Schedule sending email to customer asking them mark order received.
     *
     * @param int $order_id  The order ID.
     * @param int $vendor_id The vendor ID.
     */
    public function schedule_customer_mark_received_email( $order_id, $vendor_id ) {
        global $woocommerce;

        $order = wc_get_order( $order_id );

        $received = (array) $order->get_meta( 'wc_pv_shipped' );
        $received = array_filter( $received );
        $emails   = $woocommerce->mailer()->get_emails();
        $email    = $emails['WC_Vendors_Pro_Email_Customer_Mark_Received'];

        if ( ! $email->is_enabled() || ! in_array( $vendor_id, $received, true ) ) {
            return;
        }

        WC()->queue()->schedule_single(
            time() + DAY_IN_SECONDS * $email->get_option( 'period' ),
            'wcv_scheduled_customer_mark_received_email',
            array(
                'order_id'  => $order_id,
                'vendor_id' => $vendor_id,
            )
        );
    }

    /**
     * Add vendor details to WooCommerce order confirmation emails
     *
     * @param WC_Order $order The order object.
     * @param bool     $sent_to_admin Whether the email is being sent to admin.
     * @param bool     $plain_text Whether the email is plain text.
     * @param WC_Email $email The email object.
     * @return void
     * @since 2.0.0 - Show vendor information in customer email
     */
    public function add_vendor_details_to_order_emails( $order, $sent_to_admin, $plain_text, $email ) {
        // Only add vendor details to customer emails, not admin emails.
        if ( $sent_to_admin ) {
            return;
        }

        // Check if the setting is enabled.
        if ( 'yes' !== get_option( 'wcvendors_vendor_details_in_emails', 'no' ) ) {
            return;
        }

        // Only add to customer order emails (new order, processing, completed, etc.).
        $customer_email_types = array( 'customer_processing_order', 'customer_completed_order', 'customer_on_hold_order', 'customer_invoice' );
        if ( ! in_array( $email->id, $customer_email_types, true ) ) {
            return;
        }

        $this->display_vendor_details_for_order( $order, $plain_text );
    }

    /**
     * Display vendor details for each vendor in the order
     *
     * @param WC_Order $order The order object.
     * @param bool     $plain_text Whether the email is plain text.
     * @return void
     * @since 2.0.0 - Show vendor information in customer email
     */
    private function display_vendor_details_for_order( $order, $plain_text = false ) {
        if ( ! $order ) {
            return;
        }

        $vendors = array();

        /**
         *
         * Order items.
         *
         * @var WC_Order $order
         * @since 2.0.0 - Show vendor information in customer email
         * @var WC_Order_Item_Product[] $items
         */
        $items = $order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item->get_product_id();
            if ( ! $product_id ) {
                continue;
            }

            $vendor_id = WCV_Vendors::get_vendor_from_product( $product_id );
            if ( $vendor_id && ! isset( $vendors[ $vendor_id ] ) && WCV_Vendors::is_vendor( $vendor_id ) ) {
                $vendors[ $vendor_id ] = $this->get_vendor_store_details( $vendor_id );
            }
        }

        if ( empty( $vendors ) ) {
            return;
        }

        // Display vendor details.
        if ( $plain_text ) {
            $this->display_vendor_details_plain_text( $vendors );
        } else {
            $this->display_vendor_details_html( $vendors );
        }
    }

    /**
     * Get vendor store details
     *
     * @param int $vendor_id The vendor ID.
     * @return array The vendor store details.
     * @since 2.0.0 - Show vendor information in customer email
     */
    private function get_vendor_store_details( $vendor_id ) {
        $vendor_data = get_userdata( $vendor_id );

        return array(
            'store_name'  => get_user_meta( $vendor_id, 'pv_shop_name', true ),
            'store_phone' => get_user_meta( $vendor_id, '_wcv_store_phone', true ),
            'store_email' => $vendor_data ? $vendor_data->user_email : '',
        );
    }

    /**
     * Display vendor details in HTML format
     *
     * @param array $vendors Array of vendor details.
     * @return void
     * @since 2.0.0 - Show vendor information in customer email
     */
    private function display_vendor_details_html( $vendors ) {
        if ( empty( $vendors ) ) {
            return;
        }

        // Define styles once for reuse.
        $styles = $this->get_email_styles();

        // Section header.
        printf(
            '<h2 style="%s">%s</h2>',
            esc_attr( $styles['header'] ),
            esc_html__( 'Vendor Information', 'wcvendors-pro' )
        );

        // Vendor details container.
        foreach ( $vendors as $vendor_details ) {
            if ( empty( $vendor_details['store_name'] ) ) {
                continue;
            }

            printf( '<div style="%s">', esc_attr( $styles['vendor_container'] ) );

            // Store name.
            printf(
                '<div style="%s">%s</div>',
                esc_attr( $styles['store_name'] ),
                esc_html( $vendor_details['store_name'] )
            );

            // Contact details.
            echo '<div style="' . esc_attr( $styles['contact_container'] ) . '">';

            if ( ! empty( $vendor_details['store_phone'] ) ) {
                printf(
                    '<div style="%s">%s</div>',
                    esc_attr( $styles['contact_item'] ),
                    esc_html( $vendor_details['store_phone'] )
                );
            }

            if ( ! empty( $vendor_details['store_email'] ) ) {
                printf(
                    '<div style="%s"><a href="mailto:%s" style="%s">%s</a></div>',
                    esc_attr( $styles['contact_item'] ),
                    esc_attr( $vendor_details['store_email'] ),
                    esc_attr( $styles['email_link'] ),
                    esc_html( $vendor_details['store_email'] )
                );
            }

            echo '</div>';

            echo '</div>';
        }
    }

    /**
     * Get email styles for vendor details
     *
     * @return array Associative array of CSS styles.
     * @since 2.0.0 - Show vendor information in customer email
     */
    private function get_email_styles() {
        $font_family = '"Helvetica Neue", Helvetica, Roboto, Arial, sans-serif';

        return array(
            'header'            => sprintf(
                'color: #2c3e50; font-family: %s; font-size: 20px; font-weight: 600; line-height: 1.4; margin: 24px 0 16px 0; padding: 0;',
                $font_family
            ),
            'vendor_container'  => sprintf(
                'background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; margin: 16px 0; padding: 16px; font-family: %s;',
                $font_family
            ),
            'store_name'        => sprintf(
                'color: #2c3e50; font-family: %s; font-size: 16px; font-weight: 600; margin: 0 0 8px 0; line-height: 1.3;',
                $font_family
            ),
            'contact_container' => sprintf(
                'color: #6c757d; font-family: %s; font-size: 14px; line-height: 1.4; margin: 8px 0 0 0;',
                $font_family
            ),
            'contact_item'      => 'margin: 4px 0;',
            'email_link'        => 'color: #007cba; text-decoration: none;',
        );
    }

    /**
     * Display vendor details in plain text format
     *
     * @param array $vendors Array of vendor details.
     * @return void
     * @since 2.0.0 - Show vendor information in customer email
     */
    private function display_vendor_details_plain_text( $vendors ) {
        echo "\n\n" . esc_html__( 'VENDOR INFORMATION', 'wcvendors-pro' ) . "\n";
        echo esc_html( str_repeat( '-', 50 ) ) . "\n";

        foreach ( $vendors as $vendor_id => $vendor_details ) {
            if ( empty( $vendor_details['store_name'] ) ) {
                continue;
            }

            echo "\n" . esc_html( $vendor_details['store_name'] ) . "\n";

            if ( ! empty( $vendor_details['store_phone'] ) ) {
                echo esc_html__( 'Phone:', 'wcvendors-pro' ) . ' ' . esc_html( $vendor_details['store_phone'] ) . "\n";
            }

            if ( ! empty( $vendor_details['store_email'] ) ) {
                echo esc_html__( 'Email:', 'wcvendors-pro' ) . ' ' . esc_html( $vendor_details['store_email'] ) . "\n";
            }

            echo "\n";
        }
    }
}
