<?php
/**
 * Taxes Tab
 *
 * @var array $settings
 * @var array|null $tenant_defaults
 * @var array|null $company_config
 * @var array $companies
 */

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

// Get federal tax config from company config or tenant defaults
$federalTaxes = $company_config['federal_taxes'] ?? $tenant_defaults['federal_taxes'] ?? [];

$tenantMunicipalServiceCode = (string) ($tenant_defaults['municipal_service_code'] ?? $tenant_defaults['service_code'] ?? 'N/A');
$tenantNationalServiceCode = (string) ($tenant_defaults['national_service_code'] ?? 'N/A');
$tenantNbsCode = (string) ($tenant_defaults['nbs_code'] ?? 'N/A');
$tenantIssRate = $tenant_defaults['iss_rate'] ?? 'N/A';
$tenantMunicipality = (string) ($tenant_defaults['municipality_code'] ?? 'N/A');

// Helper function to format server default display
$formatServerDefault = function($value, $suffix = '') {
    if ($value === null || $value === '' || $value === 'N/A') {
        return 'N/A';
    }
    if (is_bool($value)) {
        return $value ? __('Enabled', 'woocommerce-cloudxm-nfe') : __('Disabled', 'woocommerce-cloudxm-nfe');
    }
    if (is_numeric($value)) {
        return esc_html(number_format((float) $value, 2, ',', '.') . $suffix);
    }
    return esc_html((string) $value . $suffix);
};
?>

<h3><?php esc_html_e('NFSe Configuration', 'woocommerce-cloudxm-nfe'); ?></h3>
<p class="description"><?php esc_html_e('Settings for issuing Nota Fiscal de Serviços Eletrônica (NFSe).', 'woocommerce-cloudxm-nfe'); ?></p>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_municipal_service_code"><?php esc_html_e('Municipal Service Code', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="text" id="cloudxm_nfe_municipal_service_code" name="cloudxm_nfe_municipal_service_code" value="<?php echo esc_attr($settings['municipal_service_code'] ?? $settings['service_code'] ?? ''); ?>" class="regular-text"<?php echo ($tenantMunicipalServiceCode !== 'N/A') ? ' placeholder="' . esc_attr($tenantMunicipalServiceCode) . '"' : ''; ?>>
            <p class="description">
                <?php esc_html_e('Municipal service code (format varies by municipality). Used as the official fiscal lookup key for the municipality.', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo esc_html($tenantMunicipalServiceCode); ?></span>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_nbs_code"><?php esc_html_e('NBS Code', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="text" id="cloudxm_nfe_nbs_code" name="cloudxm_nfe_nbs_code" value="<?php echo esc_attr($settings['nbs_code'] ?? ''); ?>" class="regular-text"<?php echo ($tenantNbsCode !== 'N/A') ? ' placeholder="' . esc_attr($tenantNbsCode) . '"' : ''; ?>>
            <p class="description">
                <?php esc_html_e('National Service Classification (NBS) code (9-12 digits). Classifies services at national level.', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo esc_html($tenantNbsCode); ?></span>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_national_service_code"><?php esc_html_e('National Service Code', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="text" id="cloudxm_nfe_national_service_code" name="cloudxm_nfe_national_service_code" value="<?php echo esc_attr($settings['national_service_code'] ?? ''); ?>" class="regular-text"<?php echo ($tenantNationalServiceCode !== 'N/A') ? ' placeholder="' . esc_attr($tenantNationalServiceCode) . '"' : ''; ?>>
            <p class="description">
                <?php esc_html_e('6-digit national service code (cTribNac). Optional - validates the municipal service mapping resolved by the backend.', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo esc_html($tenantNationalServiceCode); ?></span>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_iss_rate"><?php esc_html_e('ISS Rate', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" id="cloudxm_nfe_iss_rate" name="cloudxm_nfe_iss_rate" value="<?php echo esc_attr($settings['iss_rate'] ?? ''); ?>" class="small-text" min="0" max="1" step="0.0001"<?php echo ($tenantIssRate !== 'N/A' && is_numeric($tenantIssRate)) ? ' placeholder="' . esc_attr((string) $tenantIssRate) . '"' : ''; ?>>
            <p class="description">
                <?php esc_html_e('ISS tax rate in decimal (0.05 = 5%).', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo esc_html((string) $tenantIssRate); ?></span>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_municipality_code"><?php esc_html_e('Municipality Code', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="text" id="cloudxm_nfe_municipality_code" name="cloudxm_nfe_municipality_code" value="<?php echo esc_attr($settings['municipality_code'] ?? ''); ?>" class="regular-text"<?php echo ($tenantMunicipality !== 'N/A') ? ' placeholder="' . esc_attr($tenantMunicipality) . '"' : ''; ?> pattern="\d{7}" title="<?php esc_attr_e('7-digit IBGE code', 'woocommerce-cloudxm-nfe'); ?>">
            <p class="description">
                <?php esc_html_e('IBGE municipality code (7 digits). Required for NFSe issuance if not provided by server default.', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong>
                <?php echo !empty($tenantMunicipality) && $tenantMunicipality !== 'N/A'
                    ? '<span style="color: #46b450;">' . esc_html($tenantMunicipality) . ' ✓</span>'
                    : '<span style="color: #dc3232;">N/A ✗</span>'; ?>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_complementary_info"><?php esc_html_e('Complementary Information', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <textarea id="cloudxm_nfe_complementary_info" name="cloudxm_nfe_complementary_info" class="large-text" rows="3"><?php echo esc_textarea($settings['complementary_info'] ?? ''); ?></textarea>
            <p class="description">
                <?php esc_html_e('Optional text appended to invoice observations.', 'woocommerce-cloudxm-nfe'); ?>
                <br>
                <?php esc_html_e('Available placeholders:', 'woocommerce-cloudxm-nfe'); ?>
                <code>{order_id}</code>,
                <code>{order_number}</code>,
                <code>{order_date}</code>,
                <code>{customer_name}</code>,
                <code>{customer_email}</code>,
                <code>{customer_phone}</code>,
                <code>{billing_city}</code>,
                <code>{billing_state}</code>,
                <code>{billing_address}</code>,
                <code>{order_total}</code>
            </p>
        </td>
    </tr>
</table>

<h3><?php esc_html_e('Federal Taxes (Optional)', 'woocommerce-cloudxm-nfe'); ?></h3>
<?php if (!empty($federalTaxes)): ?>
<p class="description">
    <?php esc_html_e('Configure federal tax retention values based on your company configuration on the server.', 'woocommerce-cloudxm-nfe'); ?>
    <?php if (!empty($company_config)): ?>
        <br><strong><?php esc_html_e('Showing configuration for:', 'woocommerce-cloudxm-nfe'); ?></strong> <?php echo esc_html($company_config['legal_name'] ?? 'Selected Company'); ?>
    <?php endif; ?>
</p>
<?php else: ?>
<p class="description">
    <?php esc_html_e('Configure federal tax retention values. Server configuration not available - please ensure your API connection is working and a company is selected.', 'woocommerce-cloudxm-nfe'); ?>
    <?php if (!empty($company_config['id'])): ?>
        <br><strong><?php esc_html_e('Company ID:', 'woocommerce-cloudxm-nfe'); ?></strong> <?php echo esc_html($company_config['id']); ?>
    <?php endif; ?>
</p>
<?php endif; ?>

<!-- PIS/COFINS -->
<?php
// Determine current value: saved setting takes priority, otherwise use server default
$pisCofinsCstValue = $settings['pis_cofins_cst'] ?? $federalTaxes['pis_cofins_cst'] ?? '';
?>
<h4><?php esc_html_e('PIS/COFINS (Programas de Integração Social)', 'woocommerce-cloudxm-nfe'); ?></h4>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_pis_cofins_cst"><?php esc_html_e('CST PIS/COFINS', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <select id="cloudxm_nfe_pis_cofins_cst" name="cloudxm_nfe_pis_cofins_cst" class="regular-text">
                <option value="00" <?php selected($pisCofinsCstValue, '00'); ?>>00 - <?php esc_html_e('Nenhum', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="01" <?php selected($pisCofinsCstValue, '01'); ?>>01 - <?php esc_html_e('Operação Tributável com Alíquota Básica', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="02" <?php selected($pisCofinsCstValue, '02'); ?>>02 - <?php esc_html_e('Operação Tributável com Alíquota Diferenciada', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="03" <?php selected($pisCofinsCstValue, '03'); ?>>03 - <?php esc_html_e('Operação Tributável com Alíquota por Unidade de Medida de Produto', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="04" <?php selected($pisCofinsCstValue, '04'); ?>>04 - <?php esc_html_e('Operação Tributável monofásica - Revenda a Alíquota Zero', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="05" <?php selected($pisCofinsCstValue, '05'); ?>>05 - <?php esc_html_e('Operação Tributável por Substituição Tributária', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="06" <?php selected($pisCofinsCstValue, '06'); ?>>06 - <?php esc_html_e('Operação Tributável a Alíquota Zero', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="07" <?php selected($pisCofinsCstValue, '07'); ?>>07 - <?php esc_html_e('Operação Tributável da Contribuição', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="08" <?php selected($pisCofinsCstValue, '08'); ?>>08 - <?php esc_html_e('Operação sem Incidência da Contribuição', 'woocommerce-cloudxm-nfe'); ?></option>
                <option value="09" <?php selected($pisCofinsCstValue, '09'); ?>>09 - <?php esc_html_e('Operação com Suspensão da Contribuição', 'woocommerce-cloudxm-nfe'); ?></option>
            </select>
            <p class="description">
                <?php esc_html_e('Código de Situação Tributária (CST) para PIS/COFINS.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['pis_cofins_cst'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo esc_html($federalTaxes['pis_cofins_cst'] ?? 'N/A'); ?></span>
                <?php endif; ?>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_pis_cofins_rate"><?php esc_html_e('Alíquota PIS (%)', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" step="0.01" id="cloudxm_nfe_pis_cofins_rate" name="cloudxm_nfe_pis_cofins_rate" value="<?php echo esc_attr($settings['pis_cofins_rate'] ?? ''); ?>" class="small-text" min="0" max="100">
            <p class="description">
                <?php esc_html_e('PIS rate percentage.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['pis_rate'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['pis_rate'], '%'); ?></span>
                <?php endif; ?>
            </p>
        </td>
    </tr>
    <tr>
        <th scope="row"><label for="cloudxm_nfe_cofins_rate"><?php esc_html_e('Alíquota COFINS (%)', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" step="0.01" id="cloudxm_nfe_cofins_rate" name="cloudxm_nfe_cofins_rate" value="<?php echo esc_attr($settings['cofins_rate'] ?? ''); ?>" class="small-text" min="0" max="100">
            <p class="description">
                <?php esc_html_e('COFINS rate percentage.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['cofins_rate'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong> <span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['cofins_rate'], '%'); ?></span>
                <?php endif; ?>
            </p>
        </td>
    </tr>
</table>

<!-- IRRF -->
<h4><?php esc_html_e('IRRF (Imposto de Renda Retido na Fonte)', 'woocommerce-cloudxm-nfe'); ?></h4>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_income_tax_retention"><?php esc_html_e('Retenção IRRF', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" step="0.01" id="cloudxm_nfe_income_tax_retention" name="cloudxm_nfe_income_tax_retention" value="<?php echo esc_attr($settings['income_tax_retention'] ?? ''); ?>" class="small-text" min="0">
            <p class="description">
                <?php esc_html_e('IRRF retention amount/rate.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['irrf_enabled']) || isset($federalTaxes['irrf_rate'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php if (!empty($federalTaxes['irrf_enabled'])): ?>
                        <span style="color: #46b450;"><?php echo esc_html_e('Enabled', 'woocommerce-cloudxm-nfe'); ?></span>
                        <?php if (isset($federalTaxes['irrf_rate'])): ?>
                            (<span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['irrf_rate'], '%'); ?></span>)
                        <?php endif; ?>
                        <?php if (isset($federalTaxes['irrf_min_value'])): ?>
                            — <?php esc_html_e('Min:', 'woocommerce-cloudxm-nfe'); ?> <span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['irrf_min_value']); ?></span>
                        <?php endif; ?>
                        <?php if (isset($federalTaxes['irrf_apply_pf']) || isset($federalTaxes['irrf_apply_pj'])): ?>
                            — <span style="color: #46b450;"><?php
                            $applyTo = [];
                            if (!empty($federalTaxes['irrf_apply_pf'])) $applyTo[] = __('PF', 'woocommerce-cloudxm-nfe');
                            if (!empty($federalTaxes['irrf_apply_pj'])) $applyTo[] = __('PJ', 'woocommerce-cloudxm-nfe');
                            echo esc_html(implode('/', $applyTo));
                            ?></span>
                        <?php endif; ?>
                    <?php else: ?>
                        <span style="color: #dc3232;"><?php echo esc_html_e('Disabled', 'woocommerce-cloudxm-nfe'); ?></span>
                    <?php endif; ?>
                <?php endif; ?>
            </p>
        </td>
    </tr>
</table>

<!-- INSS/CP -->
<h4><?php esc_html_e('INSS/CP (Contribuição Previdenciária)', 'woocommerce-cloudxm-nfe'); ?></h4>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_social_security_retention"><?php esc_html_e('Retenção INSS', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" step="0.01" id="cloudxm_nfe_social_security_retention" name="cloudxm_nfe_social_security_retention" value="<?php echo esc_attr($settings['social_security_retention'] ?? ''); ?>" class="small-text" min="0">
            <p class="description">
                <?php esc_html_e('INSS retention amount/rate as required by your fiscal setup.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['inss_enabled'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php if ($federalTaxes['inss_enabled']): ?>
                        <span style="color: #46b450;"><?php echo esc_html_e('Enabled', 'woocommerce-cloudxm-nfe'); ?></span>
                        <?php if (isset($federalTaxes['inss_rate'])): ?>
                            (<span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['inss_rate'], '%'); ?></span>)
                        <?php endif; ?>
                        <?php if (isset($federalTaxes['inss_min_value'])): ?>
                            <?php echo esc_html_e('Min:', 'woocommerce-cloudxm-nfe'); ?> <span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['inss_min_value']); ?></span>
                        <?php endif; ?>
                    <?php else: ?>
                        <span style="color: #dc3232;"><?php echo esc_html_e('Disabled', 'woocommerce-cloudxm-nfe'); ?></span>
                    <?php endif; ?>
                <?php endif; ?>
            </p>
        </td>
    </tr>
</table>

<!-- CSLL -->
<h4><?php esc_html_e('CSLL (Contribuição Social sobre o Lucro Líquido)', 'woocommerce-cloudxm-nfe'); ?></h4>
<table class="form-table">
    <tr>
        <th scope="row"><label for="cloudxm_nfe_social_contribution_retention"><?php esc_html_e('Retenção CSLL', 'woocommerce-cloudxm-nfe'); ?></label></th>
        <td>
            <input type="number" step="0.01" id="cloudxm_nfe_social_contribution_retention" name="cloudxm_nfe_social_contribution_retention" value="<?php echo esc_attr($settings['social_contribution_retention'] ?? ''); ?>" class="small-text" min="0">
            <p class="description">
                <?php esc_html_e('CSLL retention amount/rate.', 'woocommerce-cloudxm-nfe'); ?>
                <?php if (isset($federalTaxes['csll_enabled'])): ?>
                    <br><strong><?php esc_html_e('Server Default:', 'woocommerce-cloudxm-nfe'); ?></strong>
                    <?php if ($federalTaxes['csll_enabled']): ?>
                        <span style="color: #46b450;"><?php echo esc_html_e('Enabled', 'woocommerce-cloudxm-nfe'); ?></span>
                        <?php if (isset($federalTaxes['csll_rate'])): ?>
                            (<span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['csll_rate'], '%'); ?></span>)
                        <?php endif; ?>
                        <?php if (isset($federalTaxes['csll_min_value'])): ?>
                            <?php echo esc_html_e('Min:', 'woocommerce-cloudxm-nfe'); ?> <span style="color: #46b450;"><?php echo $formatServerDefault($federalTaxes['csll_min_value']); ?></span>
                        <?php endif; ?>
                    <?php else: ?>
                        <span style="color: #dc3232;"><?php echo esc_html_e('Disabled', 'woocommerce-cloudxm-nfe'); ?></span>
                    <?php endif; ?>
                <?php endif; ?>
            </p>
        </td>
    </tr>
</table>
