<?php
namespace WTC_CHECKOUT\Modules\Contracts\Admin;
use WTC_CHECKOUT\Modules\Contracts\Services\OrderContractService;
defined('ABSPATH') || exit;
class OrderContractsMetaBox {
    public function __construct() {
        add_action('add_meta_boxes', array($this, 'add_contracts_meta_box'));
    }
    public function add_contracts_meta_box() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        add_meta_box(
            'wtc_contracts_meta_box',
            __('Sözleşmeler', 'wtc-checkout'),
            array($this, 'render_contracts_meta_box'),
            'shop_order',
            'side',
            'high'
        );
        add_meta_box(
            'wtc_contracts_meta_box',
            __('Sözleşmeler', 'wtc-checkout'),
            array($this, 'render_contracts_meta_box'),
            'woocommerce_page_wc-orders',
            'side',
            'high'
        );
    }
    public function render_contracts_meta_box($post_or_order) {
        $order_id = 0;
        if (is_a($post_or_order, 'WP_Post')) {
            $order_id = $post_or_order->ID;
        } elseif (is_a($post_or_order, 'WC_Order')) {
            $order_id = $post_or_order->get_id();
        } else {
            global $theorder;
            if (isset($theorder) && is_a($theorder, 'WC_Order')) {
                $order_id = $theorder->get_id();
            } else {
                if (isset($_GET['id'], $_GET['_wtc_order_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wtc_order_nonce'])), 'wtc_order_meta_box')) {
                    $order_id = absint($_GET['id']);
                } else {
                    $order_id = 0;
                }
            }
        }
        if (!$order_id) {
            echo '<p>' . esc_html__('Sipariş bilgisi bulunamadı.', 'wtc-checkout') . '</p>';
            return;
        }
        $order_nonce = wp_create_nonce('wtc_order_meta_box');
        $contract_service = new OrderContractService();
        $links = $contract_service->get_contract_links($order_id);
        if (empty($links)) {
            echo '<p>' . esc_html__('Bu sipariş için sözleşme bulunamadı.', 'wtc-checkout') . '</p>';
            return;
        }
        echo '<ul class="wc-order-downloads">';
        foreach ($links as $type => $link) {
            echo '<li class="download">';
            echo '<div class="download-file">';
            echo '<a href="' . esc_url($link['url']) . '" target="_blank" class="button">' . esc_html($link['title']) . '</a>';
            echo '</div>';
            echo '</li>';
        }
        echo '</ul>';
    }
} 