<?php
namespace WTC_CHECKOUT\Modules\Coupons\Frontend;
use WTC_CHECKOUT\Modules\Coupons\Services\CouponManager;
defined('ABSPATH') || exit;
class CouponAccountHandler {
    private static $instance = null;
    public static function get_instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    private $endpoint;
    public function __construct() {
        $this->endpoint = get_option('wtc_coupon_endpoint', 'kuponlarim');
        add_action('init', [$this, 'add_coupons_endpoint']);
        add_filter('query_vars', [$this, 'add_coupons_query_vars'], 0);
        if (get_option('wtc_coupons_enabled', 'no') === 'yes') {
            add_filter('woocommerce_account_menu_items', [$this, 'add_coupons_menu_item'], 999);
            add_action('woocommerce_account_' . $this->endpoint . '_endpoint', [$this, 'render_coupons_content']);
        }     
    }
    public function add_coupons_endpoint() {
        add_rewrite_endpoint($this->endpoint, EP_ROOT | EP_PAGES);
    }
    public function add_coupons_query_vars($vars) {
        $vars[] = $this->endpoint;
        return $vars;
    }
    public function add_coupons_menu_item($items) {
        $new_items = array();
        $menu_title = get_option('wtc_coupon_menu_title', __('Kuponlarım', 'wtc-checkout'));
        $added = false;
        foreach ($items as $key => $value) {
            $new_items[$key] = $value;
            if ($key === 'dashboard') {
                $new_items[$this->endpoint] = $menu_title;
                $added = true;
            }
        }
        if (!$added) {
            $new_items[$this->endpoint] = $menu_title;
        }
        return $new_items;
    }
    public function render_coupons_content() {
        if (get_option('wtc_coupons_enabled', 'no') !== 'yes') return;
        $user_id = get_current_user_id();
        $coupons = CouponManager::get_instance()->get_user_special_coupons($user_id);
        if (empty($coupons)) {
            echo '<div class="woocommerce-info">' . esc_html__('Şu an aktif kuponunuz bulunmuyor.', 'wtc-checkout') . '</div>';
            return;
        }
        echo '<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive wtc-coupons-table">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Kod', 'wtc-checkout') . '</th>';
        echo '<th>' . esc_html__('İndirim', 'wtc-checkout') . '</th>';
        echo '<th>' . esc_html__('Geçerlilik', 'wtc-checkout') . '</th>';
        echo '<th>' . esc_html__('Kullanım Koşulları', 'wtc-checkout') . '</th>';
        echo '</tr></thead><tbody>';
        foreach ($coupons as $coupon) {
            $code = $coupon->get_code();
            $description = $coupon->get_description();
            $discount_type = $coupon->get_discount_type();
            $amount = $coupon->get_amount();
            $expiry = $coupon->get_date_expires() ? $coupon->get_date_expires()->date_i18n(get_option('date_format')) : __('Süresiz', 'wtc-checkout');
            $discount_display = ($discount_type === 'percent') ? '%' . $amount : wp_strip_all_tags(wc_price($amount));
            $restrictions = [];
            /* translators: %1$s: Minimum amount */
            if ($coupon->get_minimum_amount() > 0) $restrictions[] = sprintf(__('Min. Harcama: %1$s', 'wtc-checkout'), wp_strip_all_tags(wc_price($coupon->get_minimum_amount())));
            /* translators: %1$s: Maximum amount */
            if ($coupon->get_maximum_amount() > 0) $restrictions[] = sprintf(__('Max. Harcama: %1$s', 'wtc-checkout'), wp_strip_all_tags(wc_price($coupon->get_maximum_amount())));
            $product_ids = $coupon->get_product_ids();
            if (!empty($product_ids)) {
                $list_data = array_map(function($id) {
                    return [
                        'name' => get_the_title($id),
                        'url'  => get_permalink($id)
                    ];
                }, $product_ids);
                /* translators: %1$d: Product count */
                $restrictions[] = '<div class="wtc-info-trigger" data-title="'.__('Geçerli Ürünler', 'wtc-checkout').'" data-list="'.esc_attr(wp_json_encode($list_data)).'">' . sprintf(__('%1$d Ürün için geçerli', 'wtc-checkout'), count($product_ids)) . '</div>';
            }
            $cat_ids = $coupon->get_product_categories();
            if (!empty($cat_ids)) {
                $list_data = array_map(function($id) {
                    $term = get_term($id);
                    $link = get_term_link($id);
                    return [
                        'name' => $term ? $term->name : '',
                        'url'  => is_wp_error($link) ? '#' : $link
                    ];
                }, $cat_ids);
                /* translators: %1$d: Category count */
                $restrictions[] = '<div class="wtc-info-trigger" data-title="'.__('Geçerli Kategoriler', 'wtc-checkout').'" data-list="'.esc_attr(wp_json_encode($list_data)).'">' . sprintf(__('%1$d Kategori için geçerli', 'wtc-checkout'), count($cat_ids)) . '</div>';
            }
            if (taxonomy_exists('product_brand')) {
                $brand_ids = $coupon->get_meta('product_brands');
                if (!empty($brand_ids) && is_array($brand_ids)) {
                    $list_data = array_map(function($id) {
                        $term = get_term($id);
                        $link = get_term_link($id);
                        return [
                            'name' => $term ? $term->name : '',
                            'url'  => is_wp_error($link) ? '#' : $link
                        ];
                    }, $brand_ids);
                    /* translators: %1$d: Brand count */
                    $restrictions[] = '<div class="wtc-info-trigger" data-title="' . esc_attr__('Geçerli Markalar', 'wtc-checkout') . '" data-list="' . esc_attr(wp_json_encode(array_filter($list_data))) . '">' . sprintf(__('%1$d Marka için geçerli', 'wtc-checkout'), count($brand_ids)) . '</div>';
                }
            }
            echo '<tr>';
            $copy_icon  = \WTC_CHECKOUT\Core\Helpers\SvgIconHelper::get('copy', 'wtc-icon-copy');
            $check_icon = \WTC_CHECKOUT\Core\Helpers\SvgIconHelper::get('check', 'wtc-icon-check');
            $copy_icon  = str_replace('<svg ', '<svg width="18" height="18" ', $copy_icon);
            $check_icon = str_replace('<svg ', '<svg width="18" height="18" style="display:none;" ', $check_icon);
            $icon_html = '<span class="wtc-copy-coupon-wrapper wtc-copy-coupon" title="' . esc_attr__('Kopyala', 'wtc-checkout') . '" data-code="' . esc_attr($code) . '" style="cursor:pointer; display:inline-flex; align-items:center; margin-left:5px; vertical-align:middle; color:var(--wtc-accent-blue);">' . $copy_icon . $check_icon . '</span>';
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo '<td class="wtc-coupon-code"><strong>' . esc_html($code) . '</strong> ' . $icon_html . (!empty($description) ? '<br><small class="wtc-coupon-desc">' . esc_html($description) . '</small>' : '') . '</td>';
            echo '<td>' . wp_kses_post($discount_display) . '</td>';
            echo '<td>' . esc_html($expiry) . '</td>';
            echo '<td style="font-size:12px;">' . (!empty($restrictions) ? wp_kses_post(implode('<br>', $restrictions)) : esc_html__('Tüm ürünlerde geçerli', 'wtc-checkout')) . '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    }
}