<?php
/**
 * QuickEditProduct.php
 *
 * @since      {$_SINCE}
 * @package    WcElectronInvoice\WooCommerce\Product
 * @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\WooCommerce\Fields\TaxFields;
use function WcElectronInvoice\Functions\filterInput;

/**
 * Class QuickEditProduct
 *
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class QuickEditProduct
{
    private $type = 'product';

    /**
     * Column
     *
     * @param $columns
     *
     * @return array
     */
    public static function reverseChargeColumn($columns)
    {
        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if ('free' === $level) {
            return $columns;
        }

        $reverseChargeGlobalActive = TaxFields::getReverseChargeActiveGlobally();
        if('yes' !== $reverseChargeGlobalActive) {
            $customColumn = array(
                'reverse_charge' => sprintf('<span class="wc-reverse_charge parent-tips" data-tip="%s"><img title="%s" width="12" src="%s"></span>',
                    esc_html_x('Reverse Charge', 'admin-table-list', WC_EL_INV_TEXTDOMAIN),
                    esc_html__('Active Reverse Charge', WC_EL_INV_TEXTDOMAIN),
                    esc_url(WC_EL_INV_URL . 'assets/images/rc.png')
                ),
            );

            $columns = \WcElectronInvoice\Functions\arrayInsertInPos($customColumn, $columns, 8);
        }

        return $columns;
    }

    /**
     * customColumn
     *
     * @param $columnName
     * @param $postID
     */
    public static function customColumn($columnName, $postID)
    {
        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if ('free' === $level) {
            return;
        }

        $reverseChargeGlobalActive = TaxFields::getReverseChargeActiveGlobally();
        if('yes' !== $reverseChargeGlobalActive) {
            switch ($columnName) {
                case'reverse_charge':
                    $currencySymbol = get_woocommerce_currency_symbol();
                    $product = wc_get_product($postID);
                    $activeRC = $product->get_meta('_active_reverse_charge');
                    if ('yes' === $activeRC) {
                        echo '<input style="display:none;" type="checkbox" readonly="readonly" checked="checked"/>';
                        echo sprintf('<span><img width="20" src="%s" title="%s"></span>',
                            esc_url(WC_EL_INV_URL . 'assets/images/rc.png'),
                            esc_html__('Reverse charge activated', WC_EL_INV_TEXTDOMAIN)
                        );
                    } else {
                        echo '<input style="display:none;" type="checkbox" readonly="readonly"/>';
                        echo sprintf('<span><img width="20" src="%s" title="%s"></span>',
                            esc_url(WC_EL_INV_URL . 'assets/images/deactivate.png'),
                            esc_html__('Reverse charge disabled', WC_EL_INV_TEXTDOMAIN)
                        );
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Display "reverse_charge" in custom quick edit
     *
     * @param $column
     * @param $screen
     *
     * @since 2.5.2
     *
     */
    public function display($column, $screen)
    {
        $output = '';

        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if ('free' === $level) {
            return;
        }

        $reverseChargeGlobalActive = TaxFields::getReverseChargeActiveGlobally() ?: false;
        if('yes' === $reverseChargeGlobalActive) {
            return;
        }

        // No product type?
        if ($screen !== $this->type) {
            return;
        }

        // No featured column.
        if ('reverse_charge' !== $column && $screen === $this->type) {
            return;
        }

        // Nonce.
        wp_nonce_field('reverse_charge_active_nonce', 'reverse_charge_active_nonce');

        // Fieldset.
        $output .= '<fieldset class="inline-edit-col-left inline-edit-reverse_charge"><div class="inline-edit-col column-edit-reverse_charge">';
        $output .= '<h4>' . esc_html__('Activate / Deactivate Reverse Charge.', WC_EL_INV_TEXTDOMAIN) . '</h4>';
        $output .= '<label class="alignleft  label-edit-reverse_charge">';
        $output .= '<input name="active_reverse_charge" id="active_reverse_charge" type="checkbox">';
        $output .= '<span class="checkbox-title">' . esc_html__('Activate Reverse Charge.',
                WC_EL_INV_TEXTDOMAIN) . '</span>';
        $output .= '</label>';
        $output .= '</div></fieldset>';

        // @codingStandardsIgnoreLine
        echo $output;
    }

    /**
     * Display "reverse_charge" in custom bulk quick edit
     *
     * @param $column
     * @param $screen
     *
     * @return void
     */
    public function displayBulk($column, $screen)
    {
        $output = '';

        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if ('free' === $level) {
            return;
        }

        $reverseChargeGlobalActive = TaxFields::getReverseChargeActiveGlobally() ?: false;
        if('yes' === $reverseChargeGlobalActive) {
            return;
        }

        // No product type?
        if ($screen !== $this->type) {
            return;
        }

        // No featured column.
        if ('reverse_charge' !== $column && $screen === $this->type) {
            return;
        }

        // Nonce.
        wp_nonce_field('reverse_charge_active_nonce', 'reverse_charge_active_nonce');

        // Fieldset.
        $output .= '<fieldset class="inline-edit-col-left inline-edit-reverse_charge"><div class="inline-edit-col column-edit-reverse_charge">';
        $output .= '<h4>' . esc_html__('Activate / Deactivate Reverse Charge.', WC_EL_INV_TEXTDOMAIN) . '</h4>';
        $output .= '<label class="alignleft  label-edit-reverse_charge">';
        $output .= '<input name="active_reverse_charge" id="active_reverse_charge" type="checkbox">';
        $output .= '<span class="checkbox-title">' . esc_html__('Activate Reverse Charge.',
                WC_EL_INV_TEXTDOMAIN) . '</span>';
        $output .= '</label>';
        $output .= '<input type="hidden" name="active_reverse_charge_bulk_edit" value="1" />';
        $output .= '</div></fieldset>';

        // @codingStandardsIgnoreLine
        echo $output;
    }

    /**
     * Store "featured" in custom quick edit
     *
     * @param $postID
     * @param $post
     *
     * @return bool
     * @since 2.5.2
     *
     */
    public function store($postID, $post)
    {
        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if ('free' === $level) {
            return false;
        }

        $reverseChargeGlobalActive = TaxFields::getReverseChargeActiveGlobally() ?: false;
        if('yes' === $reverseChargeGlobalActive) {
            return false;
        }

        // Don't save revisions and autosaves.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return false;
        }

        if (wp_is_post_revision($postID) || wp_is_post_autosave($postID)) {
            return false;
        }

        // Verify Nonce.
        // @codingStandardsIgnoreLine
        $postNonce    = \WcElectronInvoice\Functions\filterInput($_POST, 'reverse_charge_active_nonce',
            FILTER_UNSAFE_RAW);
        $requestNonce = \WcElectronInvoice\Functions\filterInput($_REQUEST, 'reverse_charge_active_nonce',
            FILTER_UNSAFE_RAW);

        if (isset($_REQUEST['active_reverse_charge_bulk_edit']) &&
            1 === (int)$_REQUEST['active_reverse_charge_bulk_edit']
        ) {
            if (! wp_verify_nonce($requestNonce, 'reverse_charge_active_nonce')) {
                return false;
            }
        } else {
            if (! wp_verify_nonce($postNonce, 'reverse_charge_active_nonce')) {
                return false;
            }
        }

        // Don't save for revisions.
        if (isset($post->post_type) && $post->post_type === 'revision') {
            return $postID;
        }

        // Return if is post type not listings type.
        if (isset($_REQUEST['active_reverse_charge_bulk_edit']) &&
            1 === (int)$_REQUEST['active_reverse_charge_bulk_edit']
        ) {
            if ($_REQUEST['post_type'] !== $this->type) {
                return false;
            }
        } else {
            if ($_POST['post_type'] !== $this->type) {
                return false;
            }
        }

        // Current user cap check.
        if (! current_user_can('edit_post', $postID)) {
            return false;
        }

        if (isset($_REQUEST['active_reverse_charge_bulk_edit']) &&
            1 === (int)$_REQUEST['active_reverse_charge_bulk_edit']
        ) {
            // Bulk save
            $posts = ! empty($_REQUEST['post']) ? $_REQUEST['post'] : [];
            if (! empty($posts)) {
                if (array_key_exists('active_reverse_charge', $_REQUEST) &&
                    isset($_REQUEST['active_reverse_charge']) &&
                    'on' === $_REQUEST['active_reverse_charge']
                ) {
                    foreach ($posts as $postID) {
                        update_post_meta($postID, '_active_reverse_charge', 'yes');
                    }
                } else {
                    foreach ($posts as $postID) {
                        update_post_meta($postID, '_active_reverse_charge', 'no');
                    }
                }
            }
        } else {
            // Quick Save.
            if (array_key_exists('active_reverse_charge', $_POST) &&
                isset($_REQUEST['active_reverse_charge']) &&
                'on' === $_REQUEST['active_reverse_charge']
            ) {
                update_post_meta($postID, '_active_reverse_charge', 'yes');
            } else {
                update_post_meta($postID, '_active_reverse_charge', 'no');
            }
        }
    }
}
