<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

class AdminProductService
{

    public function __construct()
    {
        $this->init();
    }

    public function manageProductColumns($columns)
    {
        $columns['location'] = 'Locație';
        return $columns;
    }

    /**
     * @param string $column
     * @param int $product_id
     * @return void
     */
    public function manageProductPostCustomColumns($column, $product_id)
    {
        if ($column == 'location') {
            $product = wc_get_product($product_id);

            if ($product->meta_exists('location_ext')) {
                /** @var array<string, array{name: string, price: float}>|string $ext */
                $ext = $product->get_meta('location_ext');

                if (is_string($ext)) {
                    /** @var array<string, array{name: string, price: float}>|false $ext */
                    $ext = unserialize($ext);
                }

                if ($ext !== false) {
                    echo implode(", ", array_column($ext, 'name'));
                    return;
                }
            }

            echo $product->get_meta('location_name');
        }
    }

    public function manageProductFilters($post_type)
    {
        global $wpdb;

        $values = $wpdb->get_results(
            "SELECT DISTINCT meta_value FROM $wpdb->postmeta pm WHERE pm.meta_key = 'location_name'",
            ARRAY_A
        );

        if ($post_type == 'product') {
            // Add your filter input here. Make sure the input name matches the $_GET value you are checking above.
            echo '<select name="location">';

            echo '<option value>Arata toate locatiile</option>';

            foreach ($values as $item) {
                $checked = (isset($_GET['location']) && $_GET['location'] === $item['meta_value']) ? 'selected' : '';
                echo '<option value="' . $item['meta_value'] . '" ' . $checked . '>' . $item['meta_value'] . '</option>';
            }

            echo '</select>';
        }
    }

    public function applyProductFilters($query)
    {
        global $pagenow;

        // Ensure it is an edit.php admin page, the filter exists and has a value, and that it's the products page
        if ($query->is_admin && $pagenow == 'edit.php' && isset($_GET['location']) && $_GET['location'] != '' && $_GET['post_type'] == 'product') {
            // Create meta query array and add to WP_Query
            $meta_key_query = array(
                array(
                    'key' => 'location_name',
                    'value' => esc_attr($_GET['location']),
                )
            );
            $query->set('meta_query', $meta_key_query);
        }
    }

    public function init()
    {
        // Add custom columns
        add_filter('manage_edit-product_columns', [$this, 'manageProductColumns'], 9999);

        // Get data for custom columns
        add_action('manage_product_posts_custom_column', [$this, 'manageProductPostCustomColumns'], 10, 2);

        // Add filters for custom columns
        add_action('restrict_manage_posts', [$this, 'manageProductFilters']);

        // Apply filters for custom columns
        add_action('pre_get_posts', [$this, 'applyProductFilters']);
    }
}
