<?php

namespace BWDK\Woo;

use BWDK\Support\Constant;
use WC_Order;

class WooHooks
{

    public $options;

    public $product_card_position;

    public $order;
    public $order_id;

    public function register(): void
    {

        $this->options = get_option(Constant::BWDK_OPTION_NAME);


        add_action('wp_head', [$this, 'renderHead']);
        add_action('wp_footer', [$this, 'renderFooter']);


        $top_banner_status = $this->options["top-banner"]['status'] ?? [];

        if ($top_banner_status) {
            add_action('wp_body_open', [$this, 'renderTopBanner']);
        }


        $product_card_status = $this->options['product-card']['status'] ?? '1';
        $product_card_position = $this->options['product-card']['position'] ?? 'woocommerce_before_shop_loop_item';
        if ($product_card_status) {

            if ($product_card_position == "woocommerce_before_shop_loop_item") {
                $this->product_card_position = $product_card_position;
            }
            add_action($product_card_position, [$this, 'renderProductCardBadge'], 1);
        }


        $product_single_status = $this->options['product-single']['status'] ?? '1';
        $product_single_position = $this->options['product-single']['position'] ?? 'woocommerce_after_add_to_cart_button';


        if ($product_single_status) {
            add_action($product_single_position, [$this, 'renderAddToCardButton']);
        }


        $checkout_status = $this->options['checkout']['status'] ?? '1';
        $checkout_position = $this->options['checkout']['position'] ?? 'woocommerce_before_checkout_form';
        add_action($checkout_position, [$this, 'renderCompCheckout']);


        $cart_status = $this->options['cart']['status'] ?? '1';
        $cart_position = $this->options['cart']['position'] ?? 'woocommerce_before_checkout_form';
        add_action($cart_position, [$this, 'renderCompCart']);




        $minicart_status = $this->options['minicart']['status'] ?? '1';



        if ($minicart_status) {
            add_action('woocommerce_widget_shopping_cart_total', [$this, 'renderMiniCart']);
        }




        $product_single_badge_status = $this->options['product-single-badge']['status'] ?? '1';
        $product_single_badge_position = $this->options['product-single-badge']['position'] ?? 'woocommerce_before_single_product_summary';
        if ($product_single_badge_status) {
            add_action($product_single_badge_position, [$this, 'renderThumbnailSingleBadge']);
        }







        add_action('woocommerce_before_thankyou', [$this,'renderFailedPayment']);
        add_action('woocommerce_order_details_after_order_table_items', [$this,'renderContentThankyou'] );




        add_shortcode('bwdk_top_banner', [$this, 'shotcodeTopBanner']);
        add_shortcode('bwdk_add_to_cart_button', [$this, 'shotcodeAddToCardButton']);
        add_shortcode('bwdk_comp1', [$this, 'shotcodeComp1']);
        add_shortcode('bwdk_minicart', [$this, 'shotcodeMiniCart']);
        add_shortcode('bwdk_thumbnail_single_badge', [$this, 'shotcodeThumbnailSingleBadge']);
        add_shortcode('bwdk_product_card_badge', [$this, 'shotcodeProductCardBadge']);

        add_shortcode('bwdk_thankyou', [$this, 'shotcodeThankyou']);


        /*
        list shortcodes



        [bwdk_top_banner]
        [bwdk_add_to_cart_button]
        [bwdk_comp1]
        [bwdk_thumbnail_single_badge]
        [bwdk_product_card_badge]
        [bwdk_minicart]



        */
    }

    public function renderFailedPayment($order_id){
        $this->order =wc_get_order($order_id);
        $this->render('failed-payment');

    }

    public function renderContentThankyou( $order)
    {
        $this->order =$order;

        $this->render('content-thankyou');
    }

    public function renderFooter()
    {

        $this->render('footer');
    }

    public function renderThumbnailSingleBadge()
    {
        $this->render('thumbnail-single-badge');
    }

    public function renderProductCardBadge()
    {
        $this->render('product-card-badge');
    }
    public function renderTopBanner()
    {
        $this->render('top-banner');
    }

    public function renderAddToCardButton()
    {
        $this->render('add-to-card-button');
    }
    public function renderMiniCart()
    {

        $this->getBuffered('mini-cart');
    }
    public function renderCompCart()
    {
        $this->render('comp-1');
    }
    public function renderCompCheckout()
    {
        $this->render('comp-1');
    }





    public function renderHead(): void
    {
        $this->render('head');
    }


    public function shotcodeThumbnailSingleBadge()
    {
        $this->getBuffered('thumbnail-single-badge');
    }

    public function shotcodeProductCardBadge()
    {
        $this->getBuffered('product-card-badge');
    }
    public function shotcodeTopBanner()
    {
        $this->getBuffered('top-banner');
    }

    public function shotcodeAddToCardButton()
    {
        $this->getBuffered('add-to-card-button');
    }
    public function shotcodeMiniCart()
    {
        $this->getBuffered('mini-cart');
    }
    public function shotcodeComp1()
    {
        $this->getBuffered('comp-1');
    }
    public function shotcodeThankyou($atts = [])
    {
        if ( ! defined('DONOTCACHEPAGE') ) define('DONOTCACHEPAGE', true);
        nocache_headers();

        $atts = shortcode_atts([
            'order' => 0,
            'key'   => '',
        ], (array) $atts, 'bwdk_thankyou');

        $order_id = isset($_GET['order'])
            ? absint($_GET['order'])
            : absint($atts['order']);

        $key = isset($_GET['key'])
            ? wc_clean( wp_unslash($_GET['key']) )
            : wc_clean( (string) $atts['key'] );

        if ( ! $order_id ) {
            return $this->error_box('شناسهٔ سفارش مشخص نیست.');
        }

        $order = wc_get_order($order_id);
        if ( ! $order instanceof WC_Order ) {
            return $this->error_box('سفارش یافت نشد.');
        }

        if ( ! $this->viewer_is_allowed($order, $key) ) {
            return $this->error_box('دسترسی به این سفارش مجاز نیست.');
        }

        $this->order =$order;
        $this->getBuffered('thankyou');
    }
    private function viewer_is_allowed(WC_Order $order, string $key): bool
    {
        // valid order key (guest-friendly)
        if ( $key && hash_equals($order->get_order_key(), $key) ) {
            return true;
        }

        // or owner/admin/shop-manager
        $uid = (int) get_current_user_id();
        if ( $uid && ( (int) $order->get_user_id() === $uid ) ) return true;
        if ( current_user_can('manage_woocommerce') || current_user_can('edit_shop_orders') ) return true;

        return false;
    }

    private function error_box(string $msg): string
    {
        $safe = esc_html($msg);
        return '<div class="woocommerce-notices-wrapper"><ul class="woocommerce-error" role="alert"><li>'.$safe.'</li></ul></div>';
    }


    protected function render(string $view): void
    {
        $path = BWDK_PATH . 'src/Woo/Views/' . $view . '.php';
        if (file_exists($path)) {
            include $path;
        }
    }

    protected function getBuffered(string $view)
    {
        ob_start();
        $this->render($view);
        $html=ob_get_clean();

        echo $html;

    }
}
