<?php

namespace Rtc\PlantShopWC\Frontend\Models;

class SingleProductModel {


    public function get_neighbor_data( array $data, int $current_product_id = 0 ): array {

        $groups = array(
            'good' => array(
                'title' => __( 'Good Neighbors', 'plantshop-wc' ),
                'slug'  => 'good-neighbors',
                'ids'   => array(),
                'notes' => array(),
            ),
            'bad'  => array(
                'title' => __( 'Bad Neighbors', 'plantshop-wc' ),
                'slug'  => 'bad-neighbors',
                'ids'   => array(),
                'notes' => array(),
            ),
        );

        foreach ( array(
            'good_neighbors' => 'good',
            'bad_neighbors'  => 'bad',
        ) as $key => $group ) {

            if ( empty( $data[ $key ] ) || ! is_array( $data[ $key ] ) ) {
                continue;
            }

            foreach ( $data[ $key ] as $row ) {

                if ( empty( $row['id'] ) ) {
                    continue;
                }

                $product_id = (int) $row['id'];

                if ( $current_product_id && $product_id === $current_product_id ) {
                    continue;
                }

                    $product = wc_get_product( $product_id );
                if ( $product ) {

                    if ( $product->is_type( 'variation' ) ) {
                        $parent_id = (int) $product->get_parent_id();
                        if ( $parent_id > 0 ) {
                            $product_id = $parent_id;
                        }
                    }
                }

                if ( $product_id && ! in_array( $product_id, $groups[ $group ]['ids'], true ) ) {

                    $groups[ $group ]['ids'][] = $product_id;

                    if ( ! empty( $row['note'] ) ) {

                        $groups[ $group ]['notes'][ $product_id ] = (string) $row['note'];

                    }
                }
            }
        }

        return $groups;
    }
}
