<?php
namespace WTC_CHECKOUT\Modules\Contracts\Services;
defined('ABSPATH') || exit;
class EmailService {
    public function __construct() {
        add_filter('woocommerce_email_attachments', array($this, 'attach_contract_pdfs'), 10, 3);
    }
    public function attach_contract_pdfs($attachments, $email_id, $order) {
        $settings = get_option('wtc_contract_settings', array());
        if (!isset($settings['attach_pdf_email']) || !$settings['attach_pdf_email']) {
            return $attachments;
        }
        if ($email_id !== 'customer_completed_order') {
            return $attachments;
        }
        if (!$order instanceof \WC_Order) {
            return $attachments;
        }
        try {
            $mss_path = $order->get_meta('_wtc_mss_pdf_path');
            if (!empty($mss_path) && file_exists($mss_path)) {
                $attachments[] = $mss_path;
            }
            $obf_path = $order->get_meta('_wtc_obf_pdf_path');
            if (!empty($obf_path) && file_exists($obf_path)) {
                $attachments[] = $obf_path;
            }
            $custom_path = $order->get_meta('_wtc_custom_pdf_path');
            if (!empty($custom_path) && file_exists($custom_path)) {
                $attachments[] = $custom_path;
            }
        } catch (\Exception $e) {
            return $attachments;
        }
        return $attachments;
    }
    private function should_attach_pdfs($email_id) {
        $allowed_emails = apply_filters('wtc_contract_pdf_email_types', [
            'customer_completed_order'
        ]);
        return in_array($email_id, $allowed_emails);
    }
    private function is_valid_pdf($path) {
        if (empty($path)) {
            return false;
        }
        $upload_dir = wp_upload_dir();
        $contracts_base_dir = $upload_dir['basedir'] . '/sozlesmeler/';
        if (!str_starts_with($path, $contracts_base_dir)) {
            return false;
        }
        if (!str_ends_with(strtolower($path), '.pdf')) {
            return false;
        }
        if (!file_exists($path)) {
            return false;
        }
        return true;
    }
} 