<?php
/**
 * Tabs.php
 *
 * @since      {$_SINCE}
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace WooPoPToFattureInCloudStock\WooCommerce;

use WooPoPToFattureInCloudStock\Plugin;
use function WooPoPToFattureInCloudStock\Functions\fattureInCloudModifyProduct;
use function WooPoPToFattureInCloudStock\Functions\getProductCategoryByCodList;
use function WooPoPToFattureInCloudStock\Functions\getProductCategoryByIDList;
use function WooPoPToFattureInCloudStock\Functions\getProductCodesList;

if (! defined('ABSPATH')) {
    exit;
}

/**
 * Class Tabs
 *
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class Tabs
{
    /**
     * Tab prefix
     *
     * @since 1.0.0
     */
    const PREFIX = 'wfc_ms-';

    /**
     * Default wc input type
     *
     * @since 1.0.0
     *
     * @var string
     */
    public static $defaultInputType = 'woocommerce_wp_text_input';

    /**
     * Add Product data in Panel
     *
     * @param $value
     *
     * @return void
     * @since 1.0.0
     */
    public function wooCommerceProductDataPanel($loop = null, $value = null)
    {
        // @codingStandardsIgnoreLine
        $fieldsArgs = include Plugin::getPluginDirPath('/inc/wc/metabox/productDataArgs.php');
        $prefix     = self::PREFIX;

        // Initialized.
        $inputTitle = false;
        $before     = "<div class='{$prefix}-wc_fields'>";
        $after      = "</div>";
        $inputType  = self::$defaultInputType;

        if (! empty($fieldsArgs)) {
            // Panel container
            // panel container id is target argument in tabs.
            echo "<div id='manage_stock-product-data' class='manage_stock_panel manage_stock_options_panel'>";
            foreach ($fieldsArgs as $key => $fieldArgs) {
                // Check if defined container.
                if (! empty($fieldArgs['container'])) {
                    // Container class.
                    $class = "{$prefix}-wc_fields_{$key}";
                    // Set field container element.
                    $before = "<{$fieldArgs['container']} class='{$class}'>";
                    $after  = "</{$fieldArgs['container']}>";
                }

                // Check is field args not empty.
                if (is_array($fieldArgs['field']) && ! empty($fieldArgs['field'])) {
                    $inputTitle = ! empty($fieldArgs['field']['args']['title']) ? $fieldArgs['field']['args']['title'] : null;
                    $inputType  = ! empty($fieldArgs['field']['type']) ? $fieldArgs['field']['type'] : $inputType;
                    $inputArgs  = ! empty($fieldArgs['field']['args']) ? $fieldArgs['field']['args'] : array();
                }

                // Add Field.
                if (! empty($inputArgs) && function_exists($inputType)) {
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo $before;
                    if ($inputTitle) {
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo "<h3 class='panel-title'>{$inputTitle}</h3>";
                    }

                    if ($loop !== null) {
                        $inputArgs['id'] = "{$inputArgs['id']}[{$loop}]";
                    }

                    if ($value) {
                        $inputArgs['value'] = $value;
                    } else {
                        $inputArgs['value'] = '';
                    }

                    $inputType($inputArgs);
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo $after;
                }
            }

            echo '</div>';
        }
    }

    /**
     * Store simple product
     *
     * @param $postID
     *
     * @return void
     * @throws \ErrorException
     */
    public function storeProductData($postID, $post)
    {
        // [Code => ID] - FIC product list.
        $codeLists = getProductCodesList();
        // [ID => Category] - FIC product list.
        $categoryByID = getProductCategoryByIDList();
        // [Code => Category] - FIC product list.
        $categoryByCode    = getProductCategoryByCodList();
        $productFicIDBySku = null;

        // Get product data args for retrieved id args.
        // @codingStandardsIgnoreLine
        $fieldsArgs = include_once Plugin::getPluginDirPath('/inc/wc/metabox/productDataArgs.php');

        if (! empty($fieldsArgs)) {
            $sku          = \WcElectronInvoice\Functions\filterInput($_POST, '_sku', FILTER_UNSAFE_RAW);
            $stockStatus  = \WcElectronInvoice\Functions\filterInput($_POST, '_stock_status', FILTER_UNSAFE_RAW);
            $initialStock = \WcElectronInvoice\Functions\filterInput($_POST, '_original_stock', FILTER_UNSAFE_RAW);

            // matches the sku code
            if (! empty($codeLists) && array_key_exists($sku, $codeLists)) {
                $productFicIDBySku = $codeLists[$sku];
            }

            foreach ($fieldsArgs as $key => $fieldArgs) {
                $key  = isset($fieldArgs['field']['args']['id']) ? $fieldArgs['field']['args']['id'] : '';
                $type = isset($fieldArgs['field']['type']) ? $fieldArgs['field']['type'] : '';

                if ($key && '' !== $key) {
                    // @codingStandardsIgnoreLine
                    $value = \WcElectronInvoice\Functions\filterInput($_POST, $key, FILTER_DEFAULT, array(
                        'filter' => array(FILTER_UNSAFE_RAW),
                        'flags'  => FILTER_FORCE_ARRAY,
                    ));
                    $value = is_array($value) ? reset($value) : $value;
                    $type  = str_replace('woocommerce_wp_', '', $type);

                    switch ($type) {
                        case 'checkbox':
                            $value = false === $value ? 'no' : $value;
                            break;
                        default:
                            break;
                    }

                    if (! empty($value)) {
                        // Store meta key _manage_product_stock.
                        update_post_meta($postID, $key, esc_attr($value));
                        if(! empty($categoryByID) && isset($categoryByID[$value])) {
                            update_post_meta($postID, "{$key}_category", esc_attr($categoryByID[$value]));
                        }
                    } else {
                        // method through the sku
                        if ($productFicIDBySku) {
                            update_post_meta($postID, $key, esc_attr($productFicIDBySku));
                            if(! empty($categoryByCode) && isset($categoryByCode[$sku])) {
                                update_post_meta($postID, "{$key}_category", esc_attr($categoryByCode[$sku]));
                            }
                        }
                    }

                    if(empty($value) && ! $productFicIDBySku) {
                        update_post_meta($postID, $key, '');
                        update_post_meta($postID, "{$key}_category", '');
                    }
                }
            }

            $productFicID = get_post_meta($postID, '_manage_product_stock', true) ?: null;
            $wcProduct    = wc_get_product($postID);

            if ($productFicID && 'simple' === $wcProduct->get_type()) {
                $args = array(
                    'data' => array(
                        'id'            => $productFicID,
                        'in_stock'      => apply_filters('wfc_ms-save_fic_product_in_stock_param', true, $stockStatus),
                        'stock_initial' => $initialStock,
                    ),
                );

                // Sync Fic stock whit WC stock
                $updateFicProduct = fattureInCloudModifyProduct(
                    $productFicID,
                    $args,
                    'get'
                );
                if ($updateFicProduct->ApiException && 200 !== $updateFicProduct->code) {
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    throw new \ErrorException(
                        "ApiException > fattureInCloudModifyProduct: " . esc_html($updateFicProduct->message),
                        esc_attr($updateFicProduct->code)
                    );
                }
            }
        }
    }

    /**
     * Store variation product
     *
     * @param $variation_id
     * @param $i
     *
     * @return void
     * @throws \ErrorException
     */
    public static function storeVariationProductData($variation_id, $i)
    {
        if (! empty($_POST)) {
            if (! empty($_POST['_manage_product_stock'])) {
                $ficProdID = $_POST['_manage_product_stock'][$i];
                $sku = $_POST['variable_sku'][$i];

                if ($ficProdID || $sku) {
                    // [Code => ID] - FIC product list.
                    $codeLists = getProductCodesList();
                    // [ID => Category] - FIC product list.
                    $categoryByID = getProductCategoryByIDList();
                    // [Code => Category] - FIC product list.
                    $categoryByCode    = getProductCategoryByCodList();

                    // matches the sku code
                    $productFicIDBySku = null;
                    if (! empty($codeLists) && array_key_exists($sku, $codeLists)) {
                        $productFicIDBySku = $codeLists[$sku];
                    }
                    // Store
                    if ($productFicIDBySku) {
                        update_post_meta($variation_id, '_manage_product_stock', esc_attr($productFicIDBySku));
                    } elseif($ficProdID) {
                        update_post_meta($variation_id, '_manage_product_stock', $ficProdID);
                    }

                    if($ficProdID && ! empty($categoryByID) && isset($categoryByID[$ficProdID])) {
                        update_post_meta($variation_id, '_manage_product_stock_category', esc_attr($categoryByID[$ficProdID]));
                    } else if($sku && ! empty($categoryByCode) && isset($categoryByCode[$sku])) {
                        update_post_meta($variation_id, '_manage_product_stock_category', esc_attr($categoryByCode[$sku]));
                    }

                    if(! $productFicIDBySku && ! $ficProdID && ! $sku) {
                        update_post_meta($variation_id, '_manage_product_stock', '');
                        update_post_meta($variation_id, '_manage_product_stock_category', '');
                    }

                    // Syc Fic product
                    $productFicID = get_post_meta($variation_id, '_manage_product_stock', true) ?: null;
                    $wcProduct    = wc_get_product($variation_id);
                    if ($productFicID && 'variation' === $wcProduct->get_type()) {
                        $variableStock = $_POST['variable_stock'][$i];
                        $stockStatus   = $_POST['variable_stock_status'][$i];
                        $args          = array(
                            'data' => array(
                                'id'            => $productFicID,
                                'in_stock'      => apply_filters('wfc_ms-save_variable_fic_product_in_stock_param', true, $stockStatus),
                                'stock_initial' => $variableStock,
                            ),
                        );

                        // Sync Fic stock whit WC stock
                        $updateFicProduct = \WooPoPToFattureInCloudStock\Functions\fattureInCloudModifyProduct(
                            $productFicID,
                            $args,
                            'get'
                        );
                        if ($updateFicProduct->ApiException && 200 !== $updateFicProduct->code) {
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                            throw new \ErrorException(
                                "ApiException > fattureInCloudModifyProduct: " . esc_html($updateFicProduct->message),
                                esc_attr($updateFicProduct->code)
                            );
                        }
                    }
                } else {
                    update_post_meta($variation_id, '_manage_product_stock', '');
                    update_post_meta($variation_id, '_manage_product_stock_category', '');
                }
            }
        }
    }
}