<?php
namespace ShopyPress\Services;
if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Models\ShopyPressProduct;

class CollectionTaxonomyService {

    /**
     * Sync collection term from Shopify collection data
     * Creates or updates the taxonomy term and stores Shopify collection ID
     *
     * @param array $collection Shopify collection data with id, title, handle, description, descriptionHtml, image, updatedAt
     * @return int|null Term ID on success, null on failure
     */
    public function syncCollectionTerm(array $collection): ?int {
        if (empty($collection['id']) || empty($collection['title'])) {
            return null;
        }

        $collection_id = $collection['id'];
        $collection_title = $collection['title'];
        $collection_handle = $collection['handle'] ?? sanitize_title($collection_title);

        // Check if term already exists by meta
        $term_id = $this->findTermByShopifyId($collection_id);

        
        if ($term_id) {
            // Update existing term
            wp_update_term($term_id, ShopyPressProduct::COLLECTION_TAXONOMY, [
                'name' => $collection_title,
                'slug' => $collection_handle,
            ]);
        } else {
            // Create new term
            $result = wp_insert_term($collection_title, ShopyPressProduct::COLLECTION_TAXONOMY, [
                'slug' => $collection_handle,
            ]);

            if (is_wp_error($result)) {
                // If term exists with this slug, try to get it
                $existing_term = get_term_by('slug', $collection_handle, ShopyPressProduct::COLLECTION_TAXONOMY);
                if ($existing_term) {
                    $term_id = $existing_term->term_id;
                    // Update the meta to link it
                    update_term_meta($term_id, '_shopify_collection_id', $collection_id);
                } else {
                    return null;
                }
            } else {
                $term_id = $result['term_id'];
            }
        }

        // Store Shopify collection ID in term meta
        if ($term_id) {
            update_term_meta($term_id, '_shopify_collection_id', $collection_id);
            update_term_meta($term_id, '_shopify_collection_handle', $collection_handle);

            // Store additional collection information
            if (isset($collection['description'])) {
                update_term_meta($term_id, '_shopify_collection_description', $collection['description']);
            }

            if (isset($collection['descriptionHtml'])) {
                update_term_meta($term_id, '_shopify_collection_description_html', $collection['descriptionHtml']);
            }

            if (isset($collection['image'])) {
                update_term_meta($term_id, '_shopify_collection_image_url', $collection['image']['url'] ?? '');
                update_term_meta($term_id, '_shopify_collection_image_alt', $collection['image']['altText'] ?? '');
            }

            if (isset($collection['updatedAt'])) {
                update_term_meta($term_id, '_shopify_collection_updated_at', $collection['updatedAt']);
            }
        }

        return $term_id;
    }

    /**
     * Find taxonomy term by Shopify collection ID
     *
     * @param string $shopify_collection_id Shopify collection ID
     * @return int|null Term ID or null if not found
     */
    public function findTermByShopifyId(string $shopify_collection_id): ?int {
        $terms = get_terms([
            'taxonomy' => ShopyPressProduct::COLLECTION_TAXONOMY,
            'hide_empty' => false,
            'meta_query' => [
                [
                    'key' => '_shopify_collection_id',
                    'value' => $shopify_collection_id,
                    'compare' => '='
                ]
            ]
        ]);

        if (!empty($terms) && !is_wp_error($terms)) {
            return $terms[0]->term_id;
        }

        return null;
    }

    /**
     * Get term IDs for an array of Shopify collection data
     *
     * @param array $collections Array of Shopify collection data
     * @return array Array of term IDs
     */
    public function getTermIdsForCollections(array $collections): array {
        $term_ids = [];

        foreach ($collections as $collection) {
            $term_id = $this->syncCollectionTerm($collection);
            if ($term_id) {
                $term_ids[] = $term_id;
            }
        }

        return $term_ids;
    }

    /**
     * Delete empty collection terms
     * Removes terms that have no posts assigned and recreates them if needed later
     */
    public function cleanupEmptyCollections(): void {
        $terms = get_terms([
            'taxonomy' => ShopyPressProduct::COLLECTION_TAXONOMY,
            'hide_empty' => false,
        ]);

        if (is_wp_error($terms)) {
            return;
        }

        foreach ($terms as $term) {
            // Check if term has any posts
            $count = $this->getTermPostCount($term->term_id);

            if ($count === 0) {
                // Delete the term
                wp_delete_term($term->term_id, ShopyPressProduct::COLLECTION_TAXONOMY);
            }
        }
    }

    /**
     * Get actual post count for a term
     *
     * @param int $term_id Term ID
     * @return int Number of posts with this term
     */
    private function getTermPostCount(int $term_id): int {
        $query = new \WP_Query([
            'post_type' => ShopyPressProduct::PRODUCT_SLUG,
            'tax_query' => [
                [
                    'taxonomy' => ShopyPressProduct::COLLECTION_TAXONOMY,
                    'field' => 'term_id',
                    'terms' => $term_id,
                ]
            ],
            'posts_per_page' => 1,
            'fields' => 'ids',
        ]);

        return $query->found_posts;
    }

    /**
     * Clear all collection terms for a product
     *
     * @param int $post_id WordPress post ID
     */
    public function clearProductCollections(int $post_id): void {
        wp_set_object_terms($post_id, [], ShopyPressProduct::COLLECTION_TAXONOMY);
    }

    /**
     * Assign collection terms to a product
     *
     * @param int $post_id WordPress post ID
     * @param array $term_ids Array of term IDs to assign
     */
    public function assignCollectionsToProduct(int $post_id, array $term_ids): void {
        if (empty($term_ids)) {
            $this->clearProductCollections($post_id);
            return;
        }

        wp_set_object_terms($post_id, $term_ids, ShopyPressProduct::COLLECTION_TAXONOMY);
    }
}
