<?php

namespace Kanzu\StoreVoiceAI\Services;

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Discount_Offers
{

    // Get active coupons
    public function get_active_coupons()
    {
        $args = [
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
            'posts_per_page' => -1, // Get all coupons
        ];

        $query   = new \WP_Query($args);
        $coupons = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $coupon = new \WC_Coupon(get_the_ID());

                if ($coupon->is_valid()) {
                    $coupons[] = [
                        'code'        => $coupon->get_code(),
                        'description' => $coupon->get_description(),
                    ];
                }
            }
            wp_reset_postdata();
        }

        return $coupons;
    }

    // Get products that are on sale
    public function get_sale_products()
    {
        $args = [
            'post_type'      => 'product',
            'posts_per_page' => 5, // Limit the number of sale products displayed
            'meta_key' => '_price', // Ensure products are ordered by price
            'meta_query' => [
                [
                    'key'     => '_sale_price',
                    'value'   => 0,
                    'compare' => '>',
                    'type'    => 'NUMERIC',
                ],
            ],
        ];

        $query         = new \WP_Query($args);
        $sale_products = [];

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $product = wc_get_product(get_the_ID());

                // Only consider products that have a sale price
                if ($product->is_on_sale()) {
                    $sale_products[] = [
                        'name'          => $product->get_name(),
                        'regular_price' => wc_price($product->get_regular_price()),
                        'sale_price'    => wc_price($product->get_sale_price()),
                        'link'          => get_permalink($product->get_id()),
                    ];
                }
            }
            wp_reset_postdata();
        }

        return $sale_products;
    }

}
