<?php

namespace CodeConfig\EAW\App\CartManager;

use CodeConfig\EAW\AppSettings;
use CodeConfig\EAW\Utils\Singleton;

defined('ABSPATH') || exit('No direct script access allowed');

class CustomQuantity
{
    use Singleton;
    protected $settings;

    public function doHooks()
    {
        $this->settings = AppSettings::getInstance();

        if ($this->settings->getParams('cqEnable')) {
            add_filter('woocommerce_locate_template', [$this, 'get_cart_quantity_template'], 10, 3);
            add_action('ccpeaw_before_eaw_custom_quantity', [$this, 'before_add_to_cart_form'], 99);
            add_action('woocommerce_after_add_to_cart_button', [$this, 'after_add_to_cart_form'], 99);

            add_action('wp_head', [$this, 'addCustomQuantityStyle']);
        }
    }

    public function addCustomQuantityStyle()
    {
        if ($this->settings->getParams('cqEnable')) {
            $custom_css = sprintf(
                ':root {
        --eaw-cq-pm-bg: %1$s;
        --eaw-cq-pm-text: %2$s;
        --eaw-cq-btn-bg: %3$s;
        --eaw-cq-btn-text: %4$s;
        --eaw-cq-quantity-text: %5$s;
        --eaw-cq-border-color: %6$s;
        --eaw-cq-border-radius: %7$dpx;
    }',
                esc_attr($this->settings->getParams('cqPmBgColor')),
                esc_attr($this->settings->getParams('cqPmTextColor')),
                esc_attr($this->settings->getParams('cqBtnBgColor')),
                esc_attr($this->settings->getParams('cqBtnTextColor')),
                esc_attr($this->settings->getParams('cqQuantityTextColor')),
                esc_attr($this->settings->getParams('cqBtnBorderColor')),
                absint($this->settings->getParams('cqBtnBorderRadius'))
            );

            wp_add_inline_style('your-plugin-main-style-handle', $custom_css);

        }
    }

    public function get_cart_quantity_template($template, $template_name, $template_path)
    {
        wp_enqueue_script('ccpeaw-custom-quantity');
        if ($template_name === 'global/quantity-input.php') {
            $template = CCPEAW_PATH . 'templates/quantity/eaw-quantity-input.php';
        }

        return $template;
    }


    public function before_add_to_cart_form()
    {
        $inline_class = $this->settings->getParams('enableInlineQuantity') ? 'eaw-inline-quantity' : '';
        echo '<div class="eaw-product-card-wrapper ' . esc_attr($inline_class) . '">';
    }

    public function after_add_to_cart_form()
    {
        echo '</div>';
    }
}
