<?php
namespace WTC_CHECKOUT\Modules\Contracts\Services;
defined('ABSPATH') || exit;
class ContractManager {
    private $order_contract_service;
    public function __construct() {
        add_action('init', [$this, 'register_contract_hooks'], 10);
        add_action('init', [$this, 'init_contract_download_service'], 5);
        add_action('woocommerce_checkout_order_processed', [$this, 'generate_order_contracts']);
    }
    public function register_contract_hooks() {
        $this->order_contract_service = new OrderContractService();
        $settings = get_option('wtc_contract_settings', array());
        $mss_active = isset($settings['mss_active']) && $settings['mss_active'];
        $obf_active = isset($settings['obf_active']) && $settings['obf_active'];
        $custom_active = isset($settings['custom_active']) && $settings['custom_active'];
        if (!$mss_active && !$obf_active && !$custom_active) {
            return;
        }
        if (!empty($settings['show_pdf_thankyou'])) {
            add_action('woocommerce_thankyou', array($this->order_contract_service, 'display_contract_links'), 20);
        }
        if (!empty($settings['show_pdf_myaccount'])) {
            add_action('woocommerce_view_order', array($this->order_contract_service, 'display_contract_links'), 20);
        }
        if (!empty($settings['show_pdf_email'])) {
            add_action('woocommerce_email_order_details', function($order) {
                $links = $this->order_contract_service->get_contract_links($order->get_id());
                if (empty($links)) return;
                echo '<div style="margin: 20px 0;">';
                foreach ($links as $type => $link) {
                    echo sprintf(
                        '<a href="%s" style="display:inline-block; margin:5px 10px 5px 0; padding:8px 15px; background:#f8f8f8; border:1px solid #ddd; color:#333; text-decoration:none;">%s</a>',
                        esc_url($link['url']),
                        esc_html($link['title'])
                    );
                }
                echo '</div>';
            }, 30, 1);
        }
    }
    public function init_contract_download_service() {
        new ContractDownloadService();
    }
    public function generate_order_contracts($order_id) {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        $settings = get_option('wtc_contract_settings', array());
        if (!isset($this->order_contract_service)) {
            $this->order_contract_service = new OrderContractService();
        }
        $this->order_contract_service->generateOrderContracts($order_id);
    }
} 