<?php
/**
 * Composable Product Type
 *
 * @package WC_Composable_Product
 */

namespace WC_Composable_Product;

defined('ABSPATH') || exit;

/**
 * Composable Product Type Class
 */
class Product_Type extends \WC_Product {
    /**
     * Product type
     *
     * @var string
     */
    protected $product_type = 'composable';

    /**
     * Constructor
     *
     * @param mixed $product Product ID or object
     */
    public function __construct($product = 0) {
        $this->supports[] = 'ajax_add_to_cart';
        parent::__construct($product);
    }

    /**
     * Get product type
     *
     * @return string
     */
    public function get_type() {
        return 'composable';
    }

    /**
     * Get selection limit
     *
     * @return int
     */
    public function get_selection_limit() {
        $limit = $this->get_meta('_composable_selection_limit', true);
        if (empty($limit)) {
            $limit = get_option('wc_composable_default_limit', 5);
        }
        return absint($limit);
    }

    /**
     * Get pricing mode
     *
     * @return string 'fixed' or 'sum'
     */
    public function get_pricing_mode() {
        $mode = $this->get_meta('_composable_pricing_mode', true);
        if (empty($mode)) {
            $mode = get_option('wc_composable_default_pricing', 'sum');
        }
        return $mode;
    }

    /**
     * Get product selection criteria
     *
     * @return array
     */
    public function get_selection_criteria() {
        return [
            'type' => $this->get_meta('_composable_criteria_type', true) ?: 'category',
            'categories' => $this->get_meta('_composable_categories', true) ?: [],
            'tags' => $this->get_meta('_composable_tags', true) ?: [],
            'skus' => $this->get_meta('_composable_skus', true) ?: '',
        ];
    }

    /**
     * Check if product is purchasable
     *
     * @return bool
     */
    public function is_purchasable() {
        return true;
    }

    /**
     * Check if product is sold individually
     *
     * @return bool
     */
    public function is_sold_individually() {
        return true;
    }

    /**
     * Get available products based on criteria
     *
     * @return array Array of WC_Product objects
     */
    public function get_available_products() {
        $criteria = $this->get_selection_criteria();
        $args = [
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC',
            'tax_query' => [],
        ];

        // Exclude composable products from selection
        $args['meta_query'] = [
            [
                'key' => '_product_type',
                'value' => 'composable',
                'compare' => '!=',
            ],
        ];

        switch ($criteria['type']) {
            case 'category':
                if (!empty($criteria['categories'])) {
                    $args['tax_query'][] = [
                        'taxonomy' => 'product_cat',
                        'field' => 'term_id',
                        'terms' => $criteria['categories'],
                        'operator' => 'IN',
                    ];
                }
                break;

            case 'tag':
                if (!empty($criteria['tags'])) {
                    $args['tax_query'][] = [
                        'taxonomy' => 'product_tag',
                        'field' => 'term_id',
                        'terms' => $criteria['tags'],
                        'operator' => 'IN',
                    ];
                }
                break;

            case 'sku':
                if (!empty($criteria['skus'])) {
                    $skus = array_map('trim', explode(',', $criteria['skus']));
                    $args['meta_query'][] = [
                        'key' => '_sku',
                        'value' => $skus,
                        'compare' => 'IN',
                    ];
                }
                break;
        }

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

        if ($query->have_posts()) {
            foreach ($query->posts as $post) {
                $product = wc_get_product($post->ID);
                if ($product && $product->is_in_stock() && $product->is_purchasable()) {
                    $products[] = $product;
                }
            }
        }

        wp_reset_postdata();
        return $products;
    }

    /**
     * Calculate price based on selected products
     *
     * @param array $selected_products Array of product IDs
     * @return float
     */
    public function calculate_composed_price($selected_products) {
        $pricing_mode = $this->get_pricing_mode();

        if ($pricing_mode === 'fixed') {
            return floatval($this->get_regular_price());
        }

        $total = 0;
        foreach ($selected_products as $product_id) {
            $product = wc_get_product($product_id);
            if ($product) {
                $total += floatval($product->get_price());
            }
        }

        return $total;
    }

    /**
     * Add to cart validation
     *
     * @param int $product_id Product ID
     * @param int $quantity Quantity
     * @param int $variation_id Variation ID
     * @param array $variations Variations
     * @param array $cart_item_data Cart item data
     * @return bool
     */
    public function add_to_cart_validation($product_id, $quantity, $variation_id = 0, $variations = [], $cart_item_data = []) {
        return true;
    }
}
