<?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 WcElectronInvoice\WooCommerce\Product;

use WcElectronInvoice\Plugin;

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

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

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

    /**
     * Add Product Tab
     *
     * @param $wooTabs
     *
     * @return mixed
     * @since 1.0.0
     *
     */
    public static function wooCommerceTabsFilter($wooTabs)
    {
        // @codingStandardsIgnoreLine
        $tabs = include_once Plugin::getPluginDirPath('/inc/wc/metabox/productTabArgs.php');

        $prefix  = self::PREFIX;
        $newTabs = array();

        if (! empty($tabs)) {
            foreach ($tabs as $key => $tab) {
                $newTabs["{$prefix}{$key}"] = $tab;
            }
        }

        return \WcElectronInvoice\Functions\arrayInsertInPos($newTabs, $wooTabs, 12);
    }

    /**
     * Add Product data in Panel
     *
     * @since 1.0.0
     */
    public function wooCommerceProductDataPanel()
    {
        // @codingStandardsIgnoreLine
        $fieldsArgs = include_once Plugin::getPluginDirPath('/inc/wc/metabox/productDataArgs.php');
        $prefix     = self::PREFIX;

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

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

                // Check is field args not empty.
                if (is_array($fieldArgs['field']) && ! empty($fieldArgs['field'])) {
                    $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;
                    $inputType($inputArgs);
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo $after;
                }
                echo '</div>';
            }
        }
    }

    /**
     * Store
     *
     * @param $postID
     *
     * @throws \WC_Data_Exception
     * @since 1.0.0
     *
     */
    public function storeProductData($postID)
    {
        // Get product data args for retrieved id args.
        // @codingStandardsIgnoreLine
        $fieldsArgs = include_once Plugin::getPluginDirPath('/inc/wc/metabox/productDataArgs.php');

        if (! empty($fieldsArgs)) {
            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_UNSAFE_RAW);
                    $type  = str_replace('woocommerce_wp_', '', $type);

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

                    if (! empty($value)) {
                        // Store meta.
                        update_post_meta($postID, $key, esc_attr($value));
                    }
                }
            }
        }
    }
}