<?php

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

class AIEO_Fulfillment_Emails {

    public static function register() {
        
        add_action('woocommerce_email_before_order_table', array(__CLASS__, 'on_email_before_order_table'), 20, 4);
        
        add_filter('woocommerce_email_attachments', array(__CLASS__, 'on_email_attachments'), 20, 3);
    }

    public static function on_email_before_order_table($order, $sent_to_admin = false, $plain_text = false, $email = null) {
        if ($sent_to_admin || $plain_text) { return; }
        if (!is_object($order) || !method_exists($order, 'get_id')) { return; }
        if (!class_exists('AIEO_Runtime_Fulfillment_Tracking')) { return; }
        echo AIEO_Runtime_Fulfillment_Tracking::render_block((int) $order->get_id(), 'email'); 
    }

    
    public static function on_email_attachments($attachments, $email_id, $object) {
        if (!is_array($attachments)) { $attachments = array(); }
        if (!is_object($object) || !method_exists($object, 'get_id')) { return $attachments; }

        
        
        
        
        
        
        
        if (!class_exists('AIEO_DMM') || !class_exists('AIEO_Fulfillment_Documents')) { return $attachments; }
        $module = AIEO_DMM::instance()->get_module('fulfillment');
        if (!$module) { return $attachments; }

        
        if (method_exists($object, 'get_parent_id') && $object->get_parent_id() > 0) {
            $order = wc_get_order((int) $object->get_parent_id());
        } else {
            $order = wc_get_order((int) $object->get_id());
        }
        if (!$order) { return $attachments; }

        $docs = $module->documents();
        foreach ($docs as $type => $doc) {
            $cfg = (array) AIEO_Fulfillment_Settings::get('documents.' . $type, array());

            
            if (empty($cfg['auto_attach_enabled'])) { continue; }
            
            $configured = isset($cfg['attached_to_emails']) ? trim((string) $cfg['attached_to_emails']) : '';
            if ($configured === '') { continue; }
            $list = array_map('trim', explode(',', $configured));
            if (!in_array((string) $email_id, $list, true)) { continue; }

            if (!$doc->is_enabled_for($order)) { continue; }

            
            
            
            $existing = AIEO_Fulfillment_Documents::get_for_order_by_type((int) $order->get_id(), $type);
            if (!$existing || empty($existing['pdf_path'])) { continue; }

            $abs = WP_CONTENT_DIR . '/uploads/' . ltrim((string) $existing['pdf_path'], '/');
            if (file_exists($abs)) { $attachments[] = $abs; }
        }
        return $attachments;
    }
}
