<?php defined('ABSPATH') || exit;

if (dejavo_managing_stock_check()) {
    global $product;
    $total_sold = $product->get_total_sales() ?? 0;
    $total_quantity = $total_sold + floatval(dejavo_product_quantity());
    if ($total_quantity > 0) {
        $percent_sold = intval(($total_sold / $total_quantity) * 100);
        $percent_sold = min($percent_sold, 100);
    } else {
        $percent_sold = 0;
    }
    ?>
    <div class="hint--top product_stock_bar" aria-label="<?php echo $percent_sold . __('% فروش رفته', 'dejavo'); ?>">
        <div class="stock_bar">
            <div class="stock_bar_amount" data-percent="<?= $percent_sold ?>"
                 style="" aria-valuenow="<?= $percent_sold ?>" aria-valuemin="0"
                 aria-valuemax="100"></div>
        </div> <div class="product_sale_info">
            <?php
                echo '<div class="product_total_sold">' . sprintf(__('تعداد فروش : %s', 'dejavo'), $total_sold) . '</div>';
                echo '<div class="product_total_quantity">' . sprintf(__(' باقیمانده : %s', 'dejavo'), dejavo_product_quantity()) . '</div>';
             ?>
        </div>
    </div>
    <script>
        jQuery(document).ready(function ($) {
            let processBar = document.querySelector(".stock_bar_amount"),
                width = 0;
            setProgress = setInterval(progressBar, 30);

            function progressBar() {
                if (width >= <?= $percent_sold ?>) {
                    clearInterval(setProgress);
                } else {
                    width += 1;
                    processBar.style.width = width + "%";
                    processBar.textContent = width + " %";
                }
            }
        });
    </script>

<?php }