<?php

namespace CodeConfig\EAW\Ajax;

use CodeConfig\EAW\App\CartManager\MenuCart;
use CodeConfig\EAW\AppSettings;

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

class Frontend
{
    public static function getClassIcon()
    {
        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $icon_id = sanitize_text_field(wp_unslash($_POST['icon_id'] ?? ''));
        $type    = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));

        if (is_numeric($icon_id) && $type && $class = AppSettings::getInstance()->getClassIcon($icon_id, $type)) {

            wp_send_json_success([
                'message' => $class,
                'status'  => 'success',
            ]);
        }

        wp_send_json_error([
            'message' => 'Icon not found',
            'status'  => 'error',
        ]);
    }

    public static function getMenuCartText()
    {

        check_ajax_referer('ccpeaw', 'eaw_nonce');

        $result          = [
            'status'  => '',
            'message' => '',
        ];

        $display_type    = sanitize_text_field(wp_unslash($_POST['display_type'] ?? ''));
        $cart_total_type =  sanitize_text_field(wp_unslash($_POST['cart_total_type'] ?? ''));
        if ($display_type && $cart_total_type) {
            if (isset(WC()->cart)) {
                $wc_cart            = WC()->cart;
                $cart_content_count = $wc_cart->get_cart_contents_count();
                $cart_total         = $cart_total_type === 'total' ? $wc_cart->get_total() : $wc_cart->get_cart_subtotal();
            } else {
                $cart_total = $cart_content_count = 0;
            }
            ob_start();
            MenuCart::get_menu_cart_text($display_type, $cart_total, $cart_content_count);
            $html = ob_get_clean();
            if ($html) {
                $result['status']  = 'success';
                $result['message'] = $html;
            }
        }
        wp_send_json($result);
    }
}
