<?php
namespace WTC_CHECKOUT\Modules\Contracts\Services;
defined('ABSPATH') || exit;
class OrderContractService {
    public function generateOrderContracts($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) return;
        $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;
        }
        $contract_html = $this->capture_contract_html($order);
        $order_date = $order->get_date_created()->date('Y-m-d');
        $pdf_service = new PDFService();
        $contract_types = [];
        if ($mss_active) {
            $contract_types[] = 'mss';
        }
        if ($obf_active) {
            $contract_types[] = 'obf';
        }
        if ($custom_active) {
            $contract_types[] = 'custom';
        }
        foreach ($contract_types as $type) {
            if (!empty($contract_html[$type])) {
                $pdf_info = $pdf_service->generateContractPDF(
                    $contract_html[$type],
                    $order_id,
                    $type,
                    $order_date
                );
                $order->update_meta_data("_wtc_{$type}_pdf_path", $pdf_info['path']);
                $order->update_meta_data("_wtc_{$type}_pdf_url", $pdf_info['url']);
            }
        }
        $order->save();
    }
    private function capture_contract_html($order) {
        $templates = get_option('wtc_contract_templates', array());
        $replacements = $this->prepare_replacements_from_meta($order);
        $result = [];
        $contract_types = ['mss', 'obf', 'custom'];
        foreach ($contract_types as $type) {
            $template_key = "{$type}_template";
            $content = isset($templates[$template_key]) ? $templates[$template_key] : '';
            foreach ($replacements as $search => $replace) {
                $content = str_replace($search, $replace, (string)$content);
            }
            if (empty($content)) {
                $messages = [
                    'mss' => __('Mesafeli Satış Sözleşmesi şablonu henüz oluşturulmamış.', 'wtc-checkout'),
                    'obf' => __('Ön Bilgilendirme Formu şablonu henüz oluşturulmamış.', 'wtc-checkout'),
                    'custom' => __('Özel Sözleşme şablonu henüz oluşturulmamış.', 'wtc-checkout')
                ];
                $content = $messages[$type];
            }
            $result[$type] = wpautop($content);
        }
        return $result;
    }
    private function prepare_replacements_from_meta($order) {
        $company_info = get_option('wtc_company_info', array());
		$invoice_type = $order->get_meta('_billing_invoice_type');
        $replacements = array(
            '{SIPARIS_NO}' => $order->get_id(),
            '{SIPARIS_TARIHI}' => $order->get_date_created()->date('d.m.Y'),
            '{ODEME_YONTEMI}' => $order->get_payment_method_title(),
            '{SIPARIS_TOPLAMI}' => $order->get_formatted_order_total(),
            '{ARA_TOPLAM}' => wc_price($order->get_subtotal()),
            '{KARGO_UCRETI}' => wc_price($order->get_shipping_total()),
            '{VERGI_TUTARI}' => wc_price($order->get_total_tax()),
            '{INDIRIM_TUTARI}' => wc_price($order->get_total_discount()),
            '{TOPLAM_URUN}' => $order->get_item_count(),
            '{MUSTERI_IP}' => $order->get_customer_ip_address(),
            '{FATURA_AD_SOYAD}' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
            '{FATURA_FIRMA}' => $order->get_billing_company(),
            '{FATURA_TC_NO}' => $order->get_meta('_billing_tckn'),
            '{FATURA_VERGI_NO}' => $order->get_meta('_billing_tax_number'),
            '{FATURA_VERGI_DAIRESI}' => $order->get_meta('_billing_tax_office'),
            '{FATURA_TELEFON}' => $order->get_billing_phone(),
            '{FATURA_EMAIL}' => $order->get_billing_email(),
            '{TESLIMAT_AD_SOYAD}' => $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name(),
            '{TESLIMAT_FIRMA}' => $order->get_shipping_company(),
            '{F_ADI}' => $company_info['f_company_name'] ?? '',
            '{F_ADRES}' => $company_info['f_company_address'] ?? '',
            '{F_VD}' => $company_info['f_tax_office'] ?? '',
            '{F_VNO}' => $company_info['f_tax_number'] ?? '',
            '{F_TSN}' => $company_info['f_trade_registry_no'] ?? '',
            '{F_TEL}' => $company_info['f_phone'] ?? '',
            '{F_EPOSTA}' => $company_info['f_email'] ?? '',
            '{F_WEB}' => $company_info['f_website'] ?? '',
            '{F_IADE}' => $company_info['f_return_address'] ?? '',
            '{F_MERSIS}' => $company_info['f_mersis_no'] ?? '',
            '{F_TO}' => $company_info['f_trade_chamber'] ?? ''
        );
        if ($invoice_type === 'individual') {
            $replacements['{FATURA_FIRMA}'] = '';
            $replacements['{FATURA_VERGI_NO}'] = '';
            $replacements['{FATURA_VERGI_DAIRESI}'] = '';
        } elseif ($invoice_type === 'corporate') {
            $replacements['{FATURA_TC_NO}'] = '';
            if (get_option('wtc_corporate_names_required', 'no') !== 'yes') {
                $replacements['{FATURA_AD_SOYAD}'] = '';
            }
        }
        $product_names = array();
        foreach ($order->get_items() as $item) {
            $product_names[] = $item->get_name();
        }
        $replacements['{URUN_ADLARI}'] = implode(', ', $product_names);
        $items_list = '<table>';
        $items_list .= '<tr><th>Ürün</th><th>Adet</th><th>Birim Fiyat</th><th>Toplam</th></tr>';
        foreach ($order->get_items() as $item) {
            $quantity = $item->get_quantity();
            $subtotal = $item->get_subtotal();
            $unit_price = $subtotal / $quantity;
            $items_list .= sprintf(
                '<tr><td>%s</td><td style="text-align: right;">%d</td><td style="text-align: right;">%s</td><td style="text-align: right;">%s</td></tr>',
                $item->get_name(),
                $quantity,
                wc_price($unit_price),
                wc_price($subtotal)
            );
        }
        $items_list .= '</table>';
        $replacements['{URUN_LISTESI}'] = $items_list;
        $order_summary_table = '<table>';
        $order_summary_table .= '<tr><th>Ürün</th><th>Adet</th><th>Birim Fiyat</th><th>Toplam</th></tr>';
        foreach ($order->get_items() as $item) {
            $quantity = $item->get_quantity();
            $subtotal = $item->get_subtotal();
            $unit_price = $subtotal / $quantity;
            $order_summary_table .= sprintf(
                '<tr><td>%s</td><td style="text-align: right;">%d</td><td style="text-align: right;">%s</td><td style="text-align: right;">%s</td></tr>',
                $item->get_name(),
                $quantity,
                wc_price($unit_price),
                wc_price($subtotal)
            );
        }
        $order_summary_table .= sprintf(
            '<tr><td style="text-align: right;" colspan="3">ARA TOPLAM</td><td style="text-align: right;">%s</td></tr>',
            wc_price($order->get_subtotal())
        );
        $coupons = $order->get_coupon_codes();
        if (!empty($coupons)) {
            $replacements['{KUPON_KODU}'] = implode(', ', $coupons);
        } else {
            $replacements['{KUPON_KODU}'] = __('Kupon kullanılmadı', 'wtc-checkout');
        }
        if ($order->get_total_discount() > 0) {
            $order_summary_table .= sprintf(
                '<tr><td style="text-align: right;" colspan="3">İNDİRİM (%s)</td><td style="text-align: right;">%s</td></tr>',
                $replacements['{KUPON_KODU}'],
                wc_price($order->get_total_discount())
            );
        }
        $shipping_total = $order->get_shipping_total();
        $order_summary_table .= sprintf(
            '<tr><td style="text-align: right;" colspan="3">GÖNDERİM</td><td style="text-align: right;">%s</td></tr>',
            $shipping_total > 0 ? wc_price($shipping_total) : 'Ücretsiz'
        );
        if ($order->get_total_tax() > 0) {
            $order_summary_table .= sprintf(
                '<tr><td style="text-align: right;" colspan="3">VERGİ</td><td style="text-align: right;">%s</td></tr>',
                wc_price($order->get_total_tax())
            );
        }
        $order_summary_table .= sprintf(
            '<tr><th style="text-align: right;"colspan="3">TOPLAM</th><th style="text-align: right;">%s</th></tr>',
            wc_price($order->get_total())
        );
        $order_summary_table .= '</table>';
        $replacements['{SIPARIS_TABLOSU}'] = $order_summary_table;
        $replacements['{KARGO_UCRETI}'] = $shipping_total > 0 ? wc_price($shipping_total) : 'Ücretsiz';
        $billing_address = $order->get_address('billing');
        $billing_country = WC()->countries->get_countries()[$billing_address['country']] ?? $billing_address['country'];
        $billing_state = WC()->countries->get_states($billing_address['country'])[$billing_address['state']] ?? $billing_address['state'];
        $billing_address_parts = array(
            $billing_address['address_1'],
            $billing_address['address_2'],
            $billing_address['postcode'],
            $billing_address['city'],
            $billing_state, 
            $billing_country 
        );
        $billing_address_parts = array_filter($billing_address_parts);
        $shipping_address = $order->get_address('shipping');
        $shipping_country = WC()->countries->get_countries()[$shipping_address['country']] ?? $shipping_address['country'];
        $shipping_state = WC()->countries->get_states($shipping_address['country'])[$shipping_address['state']] ?? $shipping_address['state'];
        $shipping_address_parts = array(
            $shipping_address['address_1'],
            $shipping_address['address_2'],
            $shipping_address['postcode'],
            $shipping_address['city'],
            $shipping_state, 
            $shipping_country 
        );
        $shipping_address_parts = array_filter($shipping_address_parts);
        $replacements['{FATURA_ADRES_TAMAMI}'] = implode(', ', $billing_address_parts);
        $replacements['{TESLIMAT_ADRES_TAMAMI}'] = implode(', ', $shipping_address_parts);
        return $replacements;
    }
    public function get_contract_links($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) return [];
        $settings = get_option('wtc_contract_settings', array());
        $links = [];
        $nonce = wp_create_nonce('wtc_download_contract');
        $mss_path = $order->get_meta('_wtc_mss_pdf_path');
        $mss_url = $order->get_meta('_wtc_mss_pdf_url');
        if (!empty($mss_path) && !empty($mss_url) && file_exists($mss_path)) {
            $links['mss'] = [
                'url' => add_query_arg('_wpnonce', $nonce, $mss_url),
                'title' => __('Mesafeli Satış Sözleşmesi', 'wtc-checkout')
            ];
        }
        $obf_path = $order->get_meta('_wtc_obf_pdf_path');
        $obf_url = $order->get_meta('_wtc_obf_pdf_url');
        if (!empty($obf_path) && !empty($obf_url) && file_exists($obf_path)) {
            $links['obf'] = [
                'url' => add_query_arg('_wpnonce', $nonce, $obf_url),
                'title' => __('Ön Bilgilendirme Formu', 'wtc-checkout')
            ];
        }
        $custom_path = $order->get_meta('_wtc_custom_pdf_path');
        $custom_url = $order->get_meta('_wtc_custom_pdf_url');
        if (!empty($custom_path) && !empty($custom_url) && file_exists($custom_path)) {
            $links['custom'] = [
                'url' => add_query_arg('_wpnonce', $nonce, $custom_url),
                'title' => isset($settings['custom_title']) ? $settings['custom_title'] : __('Özel Sözleşme', 'wtc-checkout')
            ];
        }
        return $links;
    }
    public function display_contract_links($order_id) {
        $links = $this->get_contract_links($order_id);
        if (empty($links)) {
            return;
        }
        echo '<div class="wtc-contract-links">';
        echo '<h3>' . esc_html__('Sözleşmeler', 'wtc-checkout') . '</h3>';
        echo '<p>' . esc_html__('Aşağıdaki linklerden sözleşmelerinizi indirebilirsiniz:', 'wtc-checkout') . '</p>';
        echo '<div class="wtc-contract-buttons">';
        foreach ($links as $type => $link) {
            echo '<a href="' . esc_url($link['url']) . '" class="button wtc-contract-button" target="_blank">' . esc_html($link['title']) . '</a>';
        }
        echo '</div>';
        echo '</div>';
    }
} 