<?php
namespace WTC_CHECKOUT\Modules\Contracts\Frontend;
defined('ABSPATH') || exit;
use WC_Geolocation;
class ContractDisplayService {
    public function __construct() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        $settings = get_option('wtc_contract_settings', array());
        $position = isset($settings['position']) ? $settings['position'] : 'after_order_review';
        switch ($position) {
            case 'before_terms':
                $hook = 'woocommerce_checkout_before_terms_and_conditions';
                break;
            case 'after_terms':
            default:
                $hook = 'woocommerce_checkout_after_terms_and_conditions';
                break;
        }
        if ($position === 'after_order_review') {
            add_action($hook, array($this, 'add_contract_checkboxes'), 30); 
        } else {
            add_action($hook, array($this, 'add_contract_checkboxes'), 20);
        }
        add_action('wp_footer', array($this, 'add_contract_popups'));
        add_action('woocommerce_checkout_process', array($this, 'validate_contract_checkboxes'));
        add_action('wp_ajax_wtc_update_contracts', array($this, 'ajax_update_contracts'));
        add_action('wp_ajax_nopriv_wtc_update_contracts', array($this, 'ajax_update_contracts'));
    }
    public function add_contract_checkboxes() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        echo '<input type="hidden" name="_wtc_contract_nonce" value="' . esc_attr(wp_create_nonce('wtc_contract_checkout')) . '">';
        $settings = get_option('wtc_contract_settings', array());
        if (!isset($settings['mss_active']) && !isset($settings['obf_active']) && !isset($settings['custom_active'])) {
            return;
        }
        $templates = $this->prepare_templates();
        echo '<div class="wtc-contracts-wrapper">';
        if (isset($settings['mss_active']) && $settings['mss_active']) {
            $display_mode = isset($settings['mss_display_mode']) ? $settings['mss_display_mode'] : 'popup';
            echo '<div class="wtc-contract-container" data-contract="mss" data-mode="' . esc_attr($display_mode) . '">';
            echo '<div class="wtc-contract-text">';
            echo '<h3>' . esc_html__('Mesafeli Satış Sözleşmesi', 'wtc-checkout') . '</h3>';
            echo '<div class="wtc-contract-content" id="mss_text_content">' . wp_kses_post($templates['mss']) . '</div>';
            echo '</div>';
            echo '<p class="form-row validate-required">';
            echo '<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">';
            echo '<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="mss_acceptance" id="mss_acceptance">';
            if ($display_mode === 'popup') {
                echo '<a href="#" class="wtc-contract-link" data-contract="mss">';
            }
            echo esc_html__('Mesafeli Satış Sözleşmesi', 'wtc-checkout');
            if ($display_mode === 'popup') {
                echo '</a>';
            }
            echo esc_html__('\'ni okudum ve kabul ediyorum', 'wtc-checkout');
            echo '</label>';
            echo '</p>';
            echo '</div>';
        }
        if (isset($settings['obf_active']) && $settings['obf_active']) {
            $display_mode = isset($settings['obf_display_mode']) ? $settings['obf_display_mode'] : 'popup';
            echo '<div class="wtc-contract-container" data-contract="obf" data-mode="' . esc_attr($display_mode) . '">';
            echo '<div class="wtc-contract-text">';
            echo '<h3>' . esc_html__('Ön Bilgilendirme Formu', 'wtc-checkout') . '</h3>';
            echo '<div class="wtc-contract-content" id="obf_text_content">' . wp_kses_post($templates['obf']) . '</div>';
            echo '</div>';
            echo '<p class="form-row validate-required">';
            echo '<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">';
            echo '<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="obf_acceptance" id="obf_acceptance">';
            if ($display_mode === 'popup') {
                echo '<a href="#" class="wtc-contract-link" data-contract="obf">';
            }
            echo esc_html__('Ön Bilgilendirme Formu', 'wtc-checkout');
            if ($display_mode === 'popup') {
                echo '</a>';
            }
            echo esc_html__('\'nu okudum ve kabul ediyorum', 'wtc-checkout');
            echo '</label>';
            echo '</p>';
            echo '</div>';
        }
        if (isset($settings['custom_active']) && $settings['custom_active']) {
            $display_mode = isset($settings['custom_display_mode']) ? $settings['custom_display_mode'] : 'popup';
            $custom_title = isset($settings['custom_title']) ? $settings['custom_title'] : esc_html__('Özel Sözleşme', 'wtc-checkout');
            echo '<div class="wtc-contract-container" data-contract="custom" data-mode="' . esc_attr($display_mode) . '">';
            echo '<div class="wtc-contract-text">';
            echo '<h3>' . esc_html($custom_title) . '</h3>';
            echo '<div class="wtc-contract-content" id="custom_text_content">' . wp_kses_post($templates['custom']) . '</div>';
            echo '</div>';
            echo '<p class="form-row validate-required">';
            echo '<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">';
            echo '<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_acceptance" id="custom_acceptance">';
            if ($display_mode === 'popup') {
                echo '<a href="#" class="wtc-contract-link" data-contract="custom">';
            }
            echo esc_html($custom_title);
            if ($display_mode === 'popup') {
                echo '</a>';
            }
            echo esc_html__('\'ni okudum ve kabul ediyorum', 'wtc-checkout');
            echo '</label>';
            echo '</p>';
            echo '</div>';
        }
        echo '</div>';
    }
    public function add_contract_popups() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        if (!is_checkout()) return;
        $settings = get_option('wtc_contract_settings', array());
        $templates = $this->prepare_templates();
        $custom_title = isset($settings['custom_title']) ? $settings['custom_title'] : esc_html__('Özel Sözleşme', 'wtc-checkout');
        ?>
        <!-- POPUP MODAL -->
        <div id="wtc-contract-popup" class="wtc-modal" role="dialog" aria-modal="true" aria-labelledby="modal-title" aria-hidden="true">
            <div class="wtc-modal-overlay"></div>
            <div class="wtc-modal-wrapper">
                <div class="wtc-modal-content">
                    <header class="wtc-modal-header">
                        <h2 id="modal-title" class="wtc-modal-title"></h2>
                        <button type="button" class="wtc-close" aria-label="<?php esc_attr_e('Kapat', 'wtc-checkout'); ?>">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </header>
                    <div class="wtc-modal-body">
                        <div id="mss_popup_content" class="wtc-contract-content" style="display: none;">
                            <?php echo wp_kses_post($templates['mss']); ?>
                        </div>
                        <div id="obf_popup_content" class="wtc-contract-content" style="display: none;">
                            <?php echo wp_kses_post($templates['obf']); ?>
                        </div>
                        <div id="custom_popup_content" class="wtc-contract-content" style="display: none;">
                            <?php echo wp_kses_post($templates['custom']); ?>
                        </div>
                    </div>
                    <footer class="wtc-modal-footer">
                        <button type="button" class="button wtc-modal-accept"><?php esc_html_e('Kabul Et', 'wtc-checkout'); ?></button>
                        <button type="button" class="button wtc-modal-close"><?php esc_html_e('Kapat', 'wtc-checkout'); ?></button>
                    </footer>
                </div>
            </div>
        </div>
        <?php
    }
    public function validate_contract_checkboxes() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return;
        }
        if (!isset($_POST['_wtc_contract_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_contract_nonce'])), 'wtc_contract_checkout')) {
            return;
        }
        $settings = get_option('wtc_contract_settings', array());
        if (isset($settings['mss_active']) && $settings['mss_active'] && !isset($_POST['mss_acceptance'])) {
            wc_add_notice(__('Lütfen Mesafeli Satış Sözleşmesi\'ni kabul edin.', 'wtc-checkout'), 'error');
        }
        if (isset($settings['obf_active']) && $settings['obf_active'] && !isset($_POST['obf_acceptance'])) {
            wc_add_notice(__('Lütfen Ön Bilgilendirme Formu\'nu kabul edin.', 'wtc-checkout'), 'error');
        }
        if (isset($settings['custom_active']) && $settings['custom_active'] && !isset($_POST['custom_acceptance'])) {
            $custom_title = isset($settings['custom_title']) ? $settings['custom_title'] : __('Özel Sözleşme', 'wtc-checkout');
            /* translators: %s: Custom contract title */
            wc_add_notice(sprintf(__('Lütfen %s\'ni kabul edin.', 'wtc-checkout'), $custom_title), 'error');
        }
    }
    public function prepare_templates() {
        if (get_option('wtc_contracts_enabled', 'no') !== 'yes') {
            return ['mss' => '', 'obf' => '', 'custom' => ''];
        }
        $templates = get_option('wtc_contract_templates', array());
        $settings = get_option('wtc_contract_settings', array());
        $mss_template = isset($templates['mss_template']) ? $templates['mss_template'] : '';
        $obf_template = isset($templates['obf_template']) ? $templates['obf_template'] : '';
        $custom_template = isset($templates['custom_template']) ? $templates['custom_template'] : '';
        $replacements = $this->prepare_replacements();
        foreach ($replacements as $search => $replace) {
            $mss_template = str_replace($search, $replace, (string)$mss_template);
            $obf_template = str_replace($search, $replace, (string)$obf_template);
            $custom_template = str_replace($search, $replace, (string)$custom_template);
        }
        $mss = wpautop($mss_template);
        $obf = wpautop($obf_template);
        $custom = wpautop($custom_template);
        if (empty($mss)) {
            $mss = '<p>' . esc_html__('Mesafeli Satış Sözleşmesi şablonu oluşturulmamış.', 'wtc-checkout') . '</p>';
        }
        if (empty($obf)) {
            $obf = '<p>' . esc_html__('Ön Bilgilendirme Formu şablonu oluşturulmamış.', 'wtc-checkout') . '</p>';
        }
        if (empty($custom)) {
            $custom_title = isset($settings['custom_title']) ? $settings['custom_title'] : esc_html__('Özel Sözleşme', 'wtc-checkout');
            /* translators: %s: Custom contract title */
            $custom = '<p>' . sprintf(esc_html__('%s şablonu oluşturulmamış.', 'wtc-checkout'), $custom_title) . '</p>';
        }
        return [
            'mss' => $mss,
            'obf' => $obf,
            'custom' => $custom
        ];
    }
    private function prepare_replacements() {
        $replacements = array();
        $company_info = get_option('wtc_company_info', array());
        $company_field_map = array(
            'f_company_name' => '{F_ADI}',
            'f_company_address' => '{F_ADRES}',
            'f_tax_office' => '{F_VD}',
            'f_tax_number' => '{F_VNO}',
            'f_trade_registry_no' => '{F_TSN}',
            'f_phone' => '{F_TEL}',
            'f_email' => '{F_EPOSTA}',
            'f_website' => '{F_WEB}',
            'f_return_address' => '{F_IADE}',
            'f_mersis_no' => '{F_MERSIS}',
            'f_trade_chamber' => '{F_TO}'
        );
        foreach ($company_field_map as $field_key => $template_var) {
            $replacements[$template_var] = isset($company_info[$field_key]) ? $company_info[$field_key] : '';
        }
        if (function_exists('WC') && WC()->cart) {
            $cart = WC()->cart;
            $cart_total = $cart->get_total('edit');
            $cart_subtotal = $cart->get_subtotal();
            $shipping_total = $cart->get_shipping_total();
            $tax_total = $cart->get_total_tax();
            $discount_total = $cart->get_discount_total();
            $replacements['{SIPARIS_TOPLAMI}'] = wc_price($cart_total);
            $replacements['{ARA_TOPLAM}'] = wc_price($cart_subtotal);
            $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
            $packages = WC()->shipping()->get_packages();
            $shipping_method_title = '';
            if (!empty($chosen_shipping_methods) && !empty($packages)) {
                $chosen_method = $chosen_shipping_methods[0];
                $available_methods = $packages[0]['rates'];
                if (isset($available_methods[$chosen_method])) {
                    $method = $available_methods[$chosen_method];
                    $shipping_method_title = $method->get_label();
                    if ($shipping_total > 0) {
                        $replacements['{KARGO_UCRETI}'] = sprintf(
                            '%s (%s)',
                            $shipping_method_title,
                            wc_price($shipping_total)
                        );
                    } else {
                        $replacements['{KARGO_UCRETI}'] = sprintf(
                            '%s',
                            $shipping_method_title,
                            __('Ücretsiz', 'wtc-checkout')
                        );
                    }
                }
            } else {
                $replacements['{KARGO_UCRETI}'] = esc_html__('Kargo yöntemi seçilmedi', 'wtc-checkout');
            }
            $replacements['{VERGI_TUTARI}'] = wc_price($tax_total);
            $replacements['{INDIRIM_TUTARI}'] = wc_price($discount_total);
            $replacements['{TOPLAM_URUN}'] = $cart->get_cart_contents_count();
            $replacements['{SIPARIS_TARIHI}'] = date_i18n('d.m.Y');
            $chosen_payment_method = WC()->session->get('chosen_payment_method');
            if ($chosen_payment_method && WC()->payment_gateways()) {
                $payment_gateways = WC()->payment_gateways()->payment_gateways();
                $replacements['{ODEME_YONTEMI}'] = isset($payment_gateways[$chosen_payment_method]) ? 
                    $payment_gateways[$chosen_payment_method]->get_title() : 
                    (isset($_POST['payment_method'], $_POST['_wtc_contract_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_contract_nonce'])), 'wtc_contract_checkout') ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '');
            } else {
                $replacements['{ODEME_YONTEMI}'] = (isset($_POST['payment_method'], $_POST['_wtc_contract_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_contract_nonce'])), 'wtc_contract_checkout')) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
            }
            $applied_coupons = $cart->get_applied_coupons();
            $replacements['{KUPON_KODU}'] = !empty($applied_coupons) ? implode(', ', $applied_coupons) : esc_html__('Kupon kullanılmadı', 'wtc-checkout');
            $product_names = array();
            foreach ($cart->get_cart() as $cart_item) {
                $product = $cart_item['data'];
                $product_names[] = $product->get_name();
            }
            $replacements['{URUN_ADLARI}'] = implode(', ', $product_names);
            $items_table = '<table class="wtc-products-table">';
            $items_table .= '<tr><th>Ürün</th><th>Adet</th><th>Birim Fiyat</th><th>Toplam</th></tr>';
            foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
                $product = $cart_item['data'];
                $quantity = $cart_item['quantity'];
                $subtotal = $cart_item['line_subtotal'];
                $unit_price = $subtotal / $quantity;
                $items_table .= sprintf(
                    '<tr><td>%s</td><td>%d</td><td>%s</td><td>%s</td></tr>',
                    $product->get_name(),
                    $quantity,
                    wc_price($unit_price),
                    wc_price($subtotal)
                );
            }
            $items_table .= '</table>';
            $replacements['{URUN_LISTESI}'] = $items_table;
            $order_summary_table = '<table class="wtc-order-summary-table">';
            $order_summary_table .= '<tr><th>Ürün</th><th>Adet</th><th>Birim Fiyat</th><th>Toplam</th></tr>';
            foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
                $product = $cart_item['data'];
                $quantity = $cart_item['quantity'];
                $subtotal = $cart_item['line_subtotal'];
                $unit_price = $subtotal / $quantity;
                $order_summary_table .= sprintf(
                    '<tr><td>%s</td><td>%d</td><td>%s</td><td>%s</td></tr>',
                    $product->get_name(),
                    $quantity,
                    wc_price($unit_price),
                    wc_price($subtotal)
                );
            }
            $order_summary_table .= sprintf(
                '<tr class="summary-row"><td colspan="3">ARA TOPLAM</td><td>%s</td></tr>',
                wc_price($cart_subtotal)
            );
            if ($discount_total > 0) {
                $order_summary_table .= sprintf(
                    '<tr class="summary-row"><td colspan="3">İNDİRİM</td><td>%s</td></tr>',
                    wc_price($discount_total)
                );
            }
            $order_summary_table .= sprintf(
                '<tr class="summary-row"><td colspan="3">GÖNDERİM</td><td>%s</td></tr>',
                $shipping_total > 0 ? wc_price($shipping_total) : 'Ücretsiz'
            );
            if ($tax_total > 0) {
                $order_summary_table .= sprintf(
                    '<tr class="summary-row"><td colspan="3">VERGİ</td><td>%s</td></tr>',
                    wc_price($tax_total)
                );
            }
            $order_summary_table .= sprintf(
                '<tr class="summary-row total"><td colspan="3">TOPLAM</td><td>%s</td></tr>',
                wc_price($cart_total)
            );
            $order_summary_table .= '</table>';
            $replacements['{SIPARIS_TABLOSU}'] = $order_summary_table;
        }
        if (class_exists('WC_Geolocation')) {
            $geolocation = new WC_Geolocation();
            $replacements['{MUSTERI_IP}'] = $geolocation->get_ip_address();
        } else {
            $replacements['{MUSTERI_IP}'] = (isset($_POST['_wtc_contract_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_contract_nonce'])), 'wtc_contract_checkout') && isset($_SERVER['REMOTE_ADDR'])) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
        }
        $replacements['{FATURA_AD_SOYAD}'] = '<span class="wtc-billing-full-name"></span>';
        $replacements['{FATURA_FIRMA}'] = '<span class="wtc-billing-company"></span>';
        $replacements['{FATURA_TC_NO}'] = '<span class="wtc-billing-tckn"></span>';
        $replacements['{FATURA_VERGI_NO}'] = '<span class="wtc-billing-tax-number"></span>';
        $replacements['{FATURA_VERGI_DAIRESI}'] = '<span class="wtc-billing-tax-office"></span>';
        $replacements['{FATURA_ADRES_TAMAMI}'] = '<span class="wtc-billing-full-address"></span>';
        $replacements['{FATURA_TELEFON}'] = '<span class="wtc-billing-phone"></span>';
        $replacements['{FATURA_EMAIL}'] = '<span class="wtc-billing-email"></span>';
        $replacements['{TESLIMAT_AD_SOYAD}'] = '<span class="wtc-shipping-full-name"></span>';
        $replacements['{TESLIMAT_FIRMA}'] = '<span class="wtc-shipping-company"></span>';
        $replacements['{TESLIMAT_ADRES_TAMAMI}'] = '<span class="wtc-shipping-full-address"></span>';
        $replacements['{ODEME_YONTEMI}'] = '<span class="wtc-payment-method"></span>';
        return $replacements;
    }
    public function ajax_update_contracts() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wtc-contracts')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        $templates = $this->prepare_templates();
        wp_send_json_success(array(
            'mss' => $templates['mss'],
            'obf' => $templates['obf'],
            'custom' => $templates['custom']
        ));
    }
} 