<?php
/**
 * WooCommerce Coupon Service
 *
 * Fetches and manages WooCommerce coupons for BoostBot.
 *
 * @package BoostBot
 * @since   1.0.0
 */

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

/**
 * Class BoostBot_WooCommerce_Coupon_Service
 *
 * Service for interacting with WooCommerce coupons.
 */
class BoostBot_WooCommerce_Coupon_Service {

    /**
     * Check if WooCommerce is active.
     *
     * @return bool
     */
    public function is_woocommerce_active(): bool {
        return class_exists( 'WooCommerce' );
    }

    /**
     * Get all available (valid) coupons.
     *
     * @param array $args Query arguments.
     * @return array Array of coupon data.
     */
    public function get_available_coupons( array $args = array() ): array {
        if ( ! $this->is_woocommerce_active() ) {
            return array();
        }

        $defaults = array(
            'posts_per_page' => -1,
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
        );

        $args    = wp_parse_args( $args, $defaults );
        $coupons = get_posts( $args );
        $result  = array();

        foreach ( $coupons as $coupon_post ) {
            $coupon = new WC_Coupon( $coupon_post->ID );

            // Skip expired coupons.
            $expiry = $coupon->get_date_expires();
            if ( $expiry && $expiry->getTimestamp() < time() ) {
                continue;
            }

            // Skip fully used coupons.
            $usage_limit = $coupon->get_usage_limit();
            $usage_count = $coupon->get_usage_count();
            if ( $usage_limit > 0 && $usage_count >= $usage_limit ) {
                continue;
            }

            $result[] = $this->format_coupon( $coupon );
        }

        return $result;
    }

    /**
     * Get coupon by code.
     *
     * @param string $code Coupon code.
     * @return array|null Coupon data or null.
     */
    public function get_coupon_by_code( string $code ): ?array {
        if ( ! $this->is_woocommerce_active() ) {
            return null;
        }

        $coupon = new WC_Coupon( $code );

        if ( ! $coupon->get_id() ) {
            return null;
        }

        return $this->format_coupon( $coupon );
    }

    /**
     * Get coupon by ID.
     *
     * @param int $id Coupon ID.
     * @return array|null Coupon data or null.
     */
    public function get_coupon_by_id( int $id ): ?array {
        if ( ! $this->is_woocommerce_active() ) {
            return null;
        }

        $coupon = new WC_Coupon( $id );

        if ( ! $coupon->get_id() ) {
            return null;
        }

        return $this->format_coupon( $coupon );
    }

    /**
     * Get coupons for a chatbot.
     *
     * @param int $chatbot_id Chatbot ID.
     * @return array Array of coupon data.
     */
    public function get_coupons_for_chatbot( int $chatbot_id ): array {
        if ( ! class_exists( 'BoostBot_Bot_Model' ) ) {
            return array();
        }

        $bot_model = new BoostBot_Bot_Model();
        $chatbot   = $bot_model->get( $chatbot_id );

        if ( ! $chatbot ) {
            return array();
        }

        // Get settings from bot.
        $settings = array();
        if ( ! empty( $chatbot->settings ) ) {
            $settings = is_string( $chatbot->settings )
                ? json_decode( $chatbot->settings, true )
                : (array) $chatbot->settings;
        }

        $selected_coupon_ids = $settings['coupons'] ?? array();

        if ( empty( $selected_coupon_ids ) ) {
            return array();
        }

        $result = array();
        foreach ( $selected_coupon_ids as $coupon_id ) {
            $coupon = $this->get_coupon_by_id( intval( $coupon_id ) );
            if ( $coupon ) {
                $result[] = $coupon;
            }
        }

        return $result;
    }

    /**
     * Format coupon for API response.
     *
     * @param WC_Coupon $coupon Coupon object.
     * @return array Formatted coupon data.
     */
    private function format_coupon( WC_Coupon $coupon ): array {
        $expiry = $coupon->get_date_expires();

        return array(
            'id'              => $coupon->get_id(),
            'code'            => $coupon->get_code(),
            'description'     => $coupon->get_description(),
            'discount_type'   => $coupon->get_discount_type(),
            'amount'          => (float) $coupon->get_amount(),
            'expiry_date'     => $expiry ? $expiry->format( 'Y-m-d' ) : null,
            'minimum_amount'  => (float) $coupon->get_minimum_amount(),
            'maximum_amount'  => (float) $coupon->get_maximum_amount(),
            'usage_limit'     => $coupon->get_usage_limit(),
            'usage_count'     => $coupon->get_usage_count(),
            'product_ids'     => $coupon->get_product_ids(),
            'category_ids'    => $coupon->get_product_categories(),
            'free_shipping'   => $coupon->get_free_shipping(),
            'individual_use'  => $coupon->get_individual_use(),
        );
    }

    /**
     * Validate if coupon is usable.
     *
     * @param string $code   Coupon code.
     * @param float  $total  Cart total (optional).
     * @return array Validation result with 'valid' and 'message'.
     */
    public function validate_coupon( string $code, float $total = 0 ): array {
        if ( ! $this->is_woocommerce_active() ) {
            return array(
                'valid'   => false,
                'message' => __( 'WooCommerce is not active', 'boostbot' ),
            );
        }

        $coupon = new WC_Coupon( $code );

        if ( ! $coupon->get_id() ) {
            return array(
                'valid'   => false,
                'message' => __( 'קופון לא קיים', 'boostbot' ),
            );
        }

        // Check expiry.
        $expiry = $coupon->get_date_expires();
        if ( $expiry && $expiry->getTimestamp() < time() ) {
            return array(
                'valid'   => false,
                'message' => __( 'קופון פג תוקף', 'boostbot' ),
            );
        }

        // Check usage limit.
        $usage_limit = $coupon->get_usage_limit();
        $usage_count = $coupon->get_usage_count();
        if ( $usage_limit > 0 && $usage_count >= $usage_limit ) {
            return array(
                'valid'   => false,
                'message' => __( 'קופון נוצל עד תום', 'boostbot' ),
            );
        }

        // Check minimum amount.
        $minimum = (float) $coupon->get_minimum_amount();
        if ( $minimum > 0 && $total > 0 && $total < $minimum ) {
            return array(
                'valid'   => false,
                'message' => sprintf(
                    /* translators: 1: currency symbol, 2: minimum amount */
                    __( 'נדרש סכום מינימלי של %1$s%2$s', 'boostbot' ),
                    function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '₪',
                    number_format( $minimum, 0 )
                ),
            );
        }

        return array(
            'valid'   => true,
            'message' => __( 'קופון תקין', 'boostbot' ),
            'coupon'  => $this->format_coupon( $coupon ),
        );
    }
}







