<?php
/**
 * @since      1.0.0
 * @author     alfiopiccione <alfio.piccione@gmail.com>
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 alfiopiccione <alfio.piccione@gmail.com>
 *
 * 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.
 */

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

// don't add pmpro fields to front-end, if this addon is not active.
if (! is_admin() && ! \WcElectronInvoice\Functions\isPaidMembershipsProActive()) {
    return;
}

$page        = \WcElectronInvoice\Admin\Settings\OptionPage::init();
$countries   = new \WcElectronInvoice\Utils\Countries();
$euVat       = $countries->get_european_union_countries();
$userCountry = get_user_meta(get_current_user_id(), 'billing_country', true);

// Sdi required condition
$sdi           = \WcElectronInvoice\Functions\filterInput($_POST, 'billing_sdi_type', FILTER_UNSAFE_RAW);
$country       = \WcElectronInvoice\Functions\filterInput($_POST, 'bcountry', FILTER_UNSAFE_RAW);
if (! $country) {
    $country = \WcElectronInvoice\Functions\filterInput($_POST, 'billing_country', FILTER_UNSAFE_RAW);
}
$choiceDocType = \WcElectronInvoice\Functions\filterInput($_POST, 'billing_choice_type', FILTER_UNSAFE_RAW);
$action        = \WcElectronInvoice\Functions\filterInput($_POST, 'action', FILTER_UNSAFE_RAW);
$sdiRequired   = 'edit_address' !== $action &&
                 (in_array($userCountry, $euVat, true) || in_array($country, $euVat, true)) &&
                 ('IT' === $userCountry || 'IT' === $country);

// Disable Pec Unique code option
$disablePecSdi = $page->getOptions('invoice_disable_pec_sdi');
// Disable Tax code option
$disableTaxCode = $page->getOptions('invoice_disable_cf');
// Choice type
$choiceType = $page->getOptions('invoice_choice_type');
// Hide extra UE
$hideExtraUe = $page->getOptions('hide_outside_ue');
$isPeppolContext = \WcElectronInvoice\Integrations::isPeppolContext();

// Order billing type list
// Default list
$fieldsInvoiceTypeDefault = array(
    'private'   => esc_html__('Private', WC_EL_INV_TEXTDOMAIN),
    'company'   => esc_html__('Company', WC_EL_INV_TEXTDOMAIN),
    'freelance' => esc_html__('Freelance', WC_EL_INV_TEXTDOMAIN),
);
$billingTypeLists         = $page->getOptions('billing_invoice_type_list') ?: $fieldsInvoiceTypeDefault;
// Custom list
if ($billingTypeLists && ! is_array($billingTypeLists)) {
    $billingTypeLists = str_replace(' ', '|', trim($billingTypeLists));
    $billingTypeLists = explode('|', $billingTypeLists);
    if (is_array($billingTypeLists) && count($billingTypeLists) <= 4 && count($billingTypeLists) > 0) {
        //$field0 = array('' => __('Customer type', WC_EL_INV_TEXTDOMAIN));
        $field1 = isset($billingTypeLists[0]) ? explode(':', $billingTypeLists[0]) : array();
        $field2 = isset($billingTypeLists[1]) ? explode(':', $billingTypeLists[1]) : array();
        $field3 = isset($billingTypeLists[2]) ? explode(':', $billingTypeLists[2]) : array();
        $field4 = isset($billingTypeLists[3]) ? explode(':', $billingTypeLists[3]) : array();
        // Mapping the fields
        if (! empty($field1)) {
            $field1 = array($field1[0] => __(str_replace('_', ' ', $field1[1]), WC_EL_INV_TEXTDOMAIN));
        }
        if (! empty($field2)) {
            $field2 = array($field2[0] => __(str_replace('_', ' ', $field2[1]), WC_EL_INV_TEXTDOMAIN));
        }
        if (! empty($field3)) {
            $field3 = array($field3[0] => __(str_replace('_', ' ', $field3[1]), WC_EL_INV_TEXTDOMAIN));
        }
        if (! empty($field4)) {
            $field4 = array($field4[0] => __(str_replace('_', ' ', $field4[1]), WC_EL_INV_TEXTDOMAIN));
        }
        $fieldsInvoiceType = array_merge($field1, $field2, $field3, $field4);
    } else {
        $fieldsInvoiceType = $fieldsInvoiceTypeDefault;
    }
} else {
    $fieldsInvoiceType = $fieldsInvoiceTypeDefault;
}

// Option required
$requiredOption = 'required' === $page->getOptions('invoice_required') ?? false;
$type           = \WcElectronInvoice\Functions\filterInput($_POST, 'billing_invoice_type', FILTER_UNSAFE_RAW);

// Init VAT required
$required = (true === $requiredOption && ('freelance' === $type || 'company' === $type || '' === $type)) ?? false;

// Set required tax code
$requiredTaxCode = $required;
// Set not required if field disabled and private customer
if ('on' === $disableTaxCode && $type !== 'private') {
    $requiredTaxCode = false;
}

// Set required invoice type
$requiredInvoiceType = true;

// Set required choice type
$requiredChoiceType = true;

// Set not required vat and invoice type if no IT
// Used on process checkout
$requiredVat = $required;
if (false === $requiredOption && ($userCountry && 'IT' !== $userCountry || $country && 'IT' !== $country)) {
    $requiredVat         = false;
    $requiredChoiceType  = false;
    $requiredInvoiceType = false;
}

// Set not required for doc type is receipt
if ('receipt' === $choiceDocType) {
    $requiredInvoiceType = $sdiRequired = $requiredVat = $requiredTaxCode = false;
}

// Set required vat for Extra UE vat required (freelance and company)
if (! in_array($country, $euVat) && $requiredOption && $type !== 'private') {
    $requiredVat = true;
}

// Set Extra UE tax code required (private)
if (! in_array($country, $euVat) && $requiredOption && $type === 'private' && $choiceDocType !== 'receipt') {
    $requiredTaxCode = true;
}

// Check doc type and set required invoice type
if ('invoice' === $choiceDocType) {
    $requiredInvoiceType = true;
}

// No UE and hide set all fields not required
// Use on process checkout
if ('hide' === $hideExtraUe && ! in_array($country, $euVat)) {
    $requiredInvoiceType = $sdiRequired = $requiredVat = $requiredTaxCode = $requiredChoiceType = false;
}

// Extra-UE must never require POP fiscal fields.
if (! empty($country) && ! in_array($country, $euVat, true)) {
    $requiredInvoiceType = $sdiRequired = $requiredVat = $requiredTaxCode = $requiredChoiceType = false;
}

// No IT and hide set choice type field not required
// Used on process checkout
if ('hide' === $hideExtraUe && ! empty($country) && 'IT' !== $country) {
    $requiredChoiceType = false;
}

// Empty type required false
if (! $type) {
    $sdiRequired = $requiredVat = $requiredTaxCode = false;
}

// Private or custom no sdi required
if (($type !== 'company' && $type !== 'freelance')) {
    $sdiRequired = false;
}

/**
 * POP billing Fields
 */
$choiceInputType  = apply_filters('wc_el_inv-billing_choice_type', 'select'); // select or radio
$invoiceInputType = apply_filters('wc_el_inv-billing_invoice_type', 'select'); // select or radio
$choiceTypeDefault = ('on' === $choiceType || is_admin())
    ? apply_filters('wc_el_inv-billing_choice_type_default', 'receipt')
    : 'invoice';

// Cached user level
$cachedLevel = get_option('pop_user_level');

$wcFields = array(
    // Choice document type
    'billing_choice_type'  => array(
        'id'          => 'billing_choice_type',
        'type'        => $choiceInputType, // select or radio
        'class'       => array(
            'wp_pop-' . WC_EL_INV_VERSION_CLASS . '__level_' . $cachedLevel,
            'wc_el_inv-type-field',
            'form-row-wide',
            'radio' === $choiceInputType ? 'form-radio_fields' : '',
        ),
        'label'       => esc_html__('Choose the type of document', WC_EL_INV_TEXTDOMAIN),
        'description' => '',
        'placeholder' => esc_html__('Choose the type of document', WC_EL_INV_TEXTDOMAIN),
        'required'    => $requiredChoiceType,
        // Not logged user or unsaved choice_type
        'default'     => $choiceTypeDefault,
        'options'     => array(
            ''        => esc_html__('Choose the type of document', WC_EL_INV_TEXTDOMAIN),
            'receipt' => esc_html_x('Receipt', 'invoice_choice', WC_EL_INV_TEXTDOMAIN),
            'invoice' => esc_html_x('Invoice', 'invoice_choice', WC_EL_INV_TEXTDOMAIN),
        ),
    ),
    // Invoice type
    'billing_invoice_type' => array(
        'id'          => 'billing_invoice_type',
        'type'        => $invoiceInputType, // select or radio
        'class'       => array(
            'wp_pop-' . WC_EL_INV_VERSION_CLASS . '__level_' . $cachedLevel,
            'wc_el_inv-invoice-field',
            'form-row-wide',
            'radio' === $invoiceInputType ? 'form-radio_fields' : '',
        ),
        'label'       => esc_html__('Customer type', WC_EL_INV_TEXTDOMAIN),
        'description' => esc_html__('Please select Customer type', WC_EL_INV_TEXTDOMAIN),
        'placeholder' => esc_html__('Customer type', WC_EL_INV_TEXTDOMAIN),
        'required'    => $requiredInvoiceType,
        // Not logged user or unsaved invoice_type
        'default'     => apply_filters('wc_el_inv-billing_invoice_type_default', 'private'),
        'options'     => $fieldsInvoiceType,
    ),
    // Sdi
    'billing_sdi_type'     => array(
        'id'          => 'billing_sdi_type',
        'type'        => 'text',
        'class'       => array(
            'wp_pop-' . WC_EL_INV_VERSION_CLASS . '__level_' . $cachedLevel,
            'wc_el_inv-sdi-field',
            'form-row-wide',
        ),
        'label'       => esc_html__('Certified e-mail (PEC) or the unique code', WC_EL_INV_TEXTDOMAIN),
        'description' => esc_html__('Please enter your certified e-mail (PEC) or the unique code',
            WC_EL_INV_TEXTDOMAIN),
        'placeholder' => esc_html__('E-mail (PEC) or the unique code', WC_EL_INV_TEXTDOMAIN),
        'required'    => $sdiRequired,
    ),
    // Vat
    'billing_vat_number'   => array(
        'id'          => 'billing_vat_number',
        'type'        => 'text',
        'class'       => array(
            'wp_pop-' . WC_EL_INV_VERSION_CLASS . '__level_' . $cachedLevel,
            'wc_el_inv-vat-field',
            'form-row-wide',
        ),
        'label'       => esc_html__('VAT number', WC_EL_INV_TEXTDOMAIN),
        'description' => esc_html__('Please enter your VAT number (numbers only)', WC_EL_INV_TEXTDOMAIN),
        'placeholder' => esc_html__('VAT number', WC_EL_INV_TEXTDOMAIN),
        'required'    => $requiredVat,
    ),
    // Tax code
    'billing_tax_code'     => array(
        'id'          => 'billing_tax_code',
        'type'        => 'text',
        'class'       => array(
            'wp_pop-' . WC_EL_INV_VERSION_CLASS . '__level_' . $cachedLevel,
            'wc_el_inv-taxcode-field',
            'form-row-wide',
        ),
        'label'       => esc_html__('Tax Code', WC_EL_INV_TEXTDOMAIN),
        'description' => esc_html__('Please enter your Tax Code', WC_EL_INV_TEXTDOMAIN),
        'placeholder' => esc_html__('Tax Code', WC_EL_INV_TEXTDOMAIN),
        'required'    => $requiredTaxCode,
    ),
);

// Remove Choice type select
if ('on' !== $choiceType && ! is_admin()) {
    unset($wcFields['billing_choice_type']);
}

// billing_choice_type Unset empty value to checkout
if ('on' === $choiceType && ! is_admin()) {
    unset($wcFields['billing_choice_type']['options']['']);
}

// In PEPPOL context the SDI field must not exist at all.
if ($isPeppolContext) {
    unset($wcFields['billing_sdi_type']);
    if (isset($wcFields['billing_tax_code'])) {
        $wcFields['billing_tax_code']['required'] = '';
        $wcFields['billing_tax_code']['class'][]  = 'hide';
        $wcFields['billing_tax_code']['type']     = 'hidden';
        $wcFields['billing_tax_code']['value']    = '';
    }
}

// Disable "billing_sdi_type" field only in front.
if ('on' === $disablePecSdi && ! is_admin() && isset($wcFields['billing_sdi_type'])) {
    $wcFields['billing_sdi_type']['required'] = '';
    $wcFields['billing_sdi_type']['class'][]  = 'hide';
    $wcFields['billing_sdi_type']['type']     = 'hidden';
    $wcFields['billing_sdi_type']['value']    = '';
}

add_filter('wc_el_inv-billing_fields', function ($billingFields) use ($wcFields) {
    return array_merge($billingFields, $wcFields);
});
