<?php

namespace CodeClouds\Unify\Actions;

use \CodeClouds\Unify\Service\Helper;
/**
 * Checkout actions.
 * @package CodeClouds\Unify
 */
class Cart
{

    /**
     * Custom Buy Now Button
     */
    public static function add_custom_buy_now_button()
    {
        $pro_license = Helper::getProLicenseFromUnify();
        if (empty($pro_license)) {
            return;
        }

        global $product;

        include_once __DIR__ . '/../Templates/buy-now-button.php';
    }

    /**
     * Redirect to checkout using custom Buy Now button
     */
    public static function redirect_to_checkout($redirect_url)
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_REQUEST['is_buy_now']) && sanitize_text_field(wp_unslash($_REQUEST['is_buy_now']))) {
            // Verify nonce for buy now action
            if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), 'unify_buy_now_nonce')) {
                wp_die(esc_html__('Security check failed. Please try again.', 'unify'));
            }
            
            global $woocommerce;

            $redirect_url = wc_get_checkout_url();
        }
        return $redirect_url;
    }

    /**
     * Clear rest items from cart and add the buy now item and qty
     */
    public static function clearcart()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (!empty($_POST['product_id']) && !empty($_POST['product_qty'])) {
            // Verify nonce for cart clearing action
            if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'unify_clear_cart_nonce')) {
                wp_die(esc_html__('Security check failed. Please try again.', 'unify'));
            }
            
            $product_id = sanitize_text_field(wp_unslash($_POST['product_id']));
            // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $product_qty = sanitize_text_field(wp_unslash($_POST['product_qty']));

            global $woocommerce;
            $woocommerce->cart->empty_cart();
            $woocommerce->cart->add_to_cart($product_id, $product_qty);

            die();
        }
    }

}
