<?php
// File: src/Admin/Screens/FinancialScreen.php
// Version 6.0 - UK Adaptation - Full workflow 18 types + CAPITAL_IN_KIND

namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\JournalEntryGenerator;
use ComptaFlowUK\Services\ChartOfAccounts;
use ComptaFlowUK\Services\DB;
use ComptaFlowUK\Admin\Tables\TransactionsTable;

defined('ABSPATH') || exit;

class FinancialScreen {

    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }

        self::handleActions();

        $action = isset($_GET['action']) ? sanitize_key($_GET['action']) : 'list';

        echo '<div class="wrap">';
        echo '<h1 class="wp-heading-inline">' . esc_html__('💼 Financial Operations', 'comptaflow-uk-by-meetempo') . '</h1>';
        
        if ($action === 'list') {
            echo '<a href="?page=comptaflow-uk-financial&action=new" class="page-title-action">' . esc_html__('Add New', 'comptaflow-uk-by-meetempo') . '</a>';
        }

        self::showMessages();

        if ($action === 'new' || $action === 'edit') {
            self::renderForm($action);
        } else {
            self::renderList();
        }

        echo '</div>';
    }

    private static function handleActions(): void {
        $get_action = isset($_GET['action']) ? sanitize_key($_GET['action']) : '';
        if (!isset($_POST['_wpnonce']) && empty($get_action)) {
            return;
        }
        
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce_post && wp_verify_nonce($nonce_post, 'comptaflow_uk_financial_action')) {
            $post_action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
            if ($post_action === 'create' || $post_action === 'update') {
                self::saveFinancialOperation();
            }
        }
        
        if ($get_action === 'delete' && isset($_GET['id'])) {
            $nonce_delete = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce_delete, 'comptaflow_uk_delete_financial')) {
                self::deleteFinancialOperation();
            }
        }
        
        if ($get_action === 'mark_paid' && isset($_GET['id'])) {
            $id = absint($_GET['id']);
            $nonce_paid = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce_paid, 'comptaflow_uk_mark_paid_' . $id)) {
                self::markAsPaid($id);
            }
        }
    }

    private static function saveFinancialOperation(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        $user_id = get_current_user_id();
        $type = sanitize_text_field(wp_unslash($_POST['type']));

        try {
            $wpdb->query('START TRANSACTION');
            
            $transaction_id = 0;
            $message = '';
            
            if ($type === 'CAPITAL_IN_KIND') {
                $immob_data = [
                    'uuid' => wp_generate_uuid4(),
                    'asset_name' => sanitize_text_field(wp_unslash($_POST['label_kind'])),
                    'acquisition_date' => sanitize_text_field(wp_unslash($_POST['date_txn_kind'])),
                    'acquisition_ht' => floatval(wp_unslash($_POST['amount_gross_kind'])),
                    'acquisition_tva' => 0,
                    'acquisition_ttc' => floatval(wp_unslash($_POST['amount_gross_kind'])),
                    'depreciation_duration' => absint($_POST['depreciation_duration']),
                    'account_code' => sanitize_text_field(wp_unslash($_POST['asset_account'])),
                    'payment_status' => 'PAID',
                    'status' => 'ACTIVE',
                    'created_by' => $user_id,
                ];
                $wpdb->insert($p . 'fixed_assets', $immob_data);
                $immob_id = $wpdb->insert_id;

                $transaction_data = [
                    'uuid' => $immob_data['uuid'], 
                    'type' => 'CAPITAL_IN_KIND',
                    'date_txn' => $immob_data['acquisition_date'], 
                    'label' => $immob_data['asset_name'],
                    'amount_ttc' => $immob_data['acquisition_ttc'], 
                    'amount_ht' => $immob_data['acquisition_ht'],
                    'amount_tva' => 0, 
                    'payment_status' => 'PAID',
                    'meta_json' => wp_json_encode(['asset_id' => $immob_id, 'asset_account' => $immob_data['account_code']]),
                    'created_by' => $user_id, 
                    'created_at' => current_time('mysql'),
                ];
                $wpdb->insert($p . 'transactions', $transaction_data);
                $transaction_id = $wpdb->insert_id;
                
                JournalEntryGenerator::generateFinancialEntries($transaction_data, $transaction_id);
                $message = 'Capital contribution in kind recorded successfully!';

            } else {
                $type_config = self::getTypeConfig($type);
                $has_vat = $type_config['has_vat'] ?? false;
                
                if ($has_vat) {
                    $is_manual = isset($_POST['manual_amounts']) && sanitize_text_field(wp_unslash($_POST['manual_amounts'])) === 'on';
                    if ($is_manual) {
                        $amount_net = floatval(wp_unslash($_POST['amount_net_manual'] ?? 0));
                        $amount_vat = floatval(wp_unslash($_POST['amount_vat_manual'] ?? 0));
                        $amount_gross = floatval(wp_unslash($_POST['amount_gross_manual'] ?? 0));
                        $vat_rate = floatval(wp_unslash($_POST['vat_rate'] ?? 0));
                    } else {
                        $vat_rate = floatval(wp_unslash($_POST['vat_rate'] ?? 20));
                        $amount_gross = floatval(wp_unslash($_POST['amount_gross_auto']));
                        $amount_net = round($amount_gross / (1 + ($vat_rate / 100)), 2);
                        $amount_vat = $amount_gross - $amount_net;
                    }
                    $vat_code = sanitize_text_field(wp_unslash($_POST['vat_code'] ?? ''));
                } else {
                    $amount_gross = floatval(wp_unslash($_POST['amount_gross']));
                    $amount_net = $amount_gross;
                    $amount_vat = 0; 
                    $vat_rate = 0; 
                    $vat_code = '';
                }
                
                $data = [
                    'type' => $type, 
                    'date_txn' => sanitize_text_field(wp_unslash($_POST['date_txn'])),
                    'label' => sanitize_text_field(wp_unslash($_POST['label'])), 
                    'amount_ttc' => $amount_gross,
                    'amount_ht' => $amount_net, 
                    'amount_tva' => $amount_vat,
                    'vat_rate' => $vat_rate, 
                    'vat_code' => $vat_code,
                    'payment_status' => sanitize_text_field(wp_unslash($_POST['payment_status'] ?? 'PAID')),
                    'partner_name' => sanitize_text_field(wp_unslash($_POST['partner_name'] ?? '')),
                    'piece_ref' => sanitize_text_field(wp_unslash($_POST['piece_ref'] ?? '')),
                    'journal_code' => 'NL', 
                    'created_by' => $user_id,
                ];
                
                if ($type === 'BANK_TRANSFER') {
                    $data['meta_json'] = wp_json_encode([
                        'source_account' => sanitize_text_field(wp_unslash($_POST['source_account'] ?? '1200')), 
                        'dest_account' => sanitize_text_field(wp_unslash($_POST['dest_account'] ?? '1200'))
                    ]);
                }

                $id = absint($_POST['id'] ?? 0);
                if ($id) {
                    $wpdb->delete($p . 'journal_entries', ['transaction_id' => $id]);
                    $wpdb->update($p . 'transactions', $data, ['id' => $id]);
                    $transaction_id = $id;
                    $message = 'Operation updated with entries regenerated!';
                } else {
                    $data['uuid'] = wp_generate_uuid4();
                    $data['created_at'] = current_time('mysql');
                    $wpdb->insert($p . 'transactions', $data);
                    $transaction_id = $wpdb->insert_id;
                    $message = 'Operation recorded with journal entries generated!';
                }
                
                JournalEntryGenerator::generateFinancialEntries($data, $transaction_id);
            }
            
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_uk_financial', 'saved', $message, 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_uk_financial', 'error', __('Error: ', 'comptaflow-uk-by-meetempo') . $e->getMessage());
        }
    }
    
    private static function markAsPaid(int $id): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        
        $transaction = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$p}transactions WHERE id = %d", $id), ARRAY_A);
        
        if (!$transaction || $transaction['payment_status'] === 'PAID') {
            add_settings_error('comptaflow_uk_financial', 'error', __('This operation is already settled or not found.', 'comptaflow-uk-by-meetempo'));
            return;
        }
        
        try {
            $wpdb->query('START TRANSACTION');
            $wpdb->update($p . 'transactions', ['payment_status' => 'PAID', 'payment_date' => current_time('mysql')], ['id' => $id]);
            JournalEntryGenerator::generatePaymentEntry($transaction, $id);
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_uk_financial', 'marked_paid', __('Operation marked as settled! Cash entry generated.', 'comptaflow-uk-by-meetempo'), 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_uk_financial', 'error', __('Error: ', 'comptaflow-uk-by-meetempo') . $e->getMessage());
        }
    }
    
    private static function deleteFinancialOperation(): void {
        $id = absint($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        
        $wpdb->delete($p . 'journal_entries', ['transaction_id' => $id]);
        $wpdb->delete($p . 'transactions', ['id' => $id]);
        
        add_settings_error('comptaflow_uk_financial', 'deleted', __('Operation deleted with its entries.', 'comptaflow-uk-by-meetempo'), 'updated');
    }
        
    
    private static function renderForm(string $action): void {
        $item = [];
        if ($action === 'edit') {
            $id = intval($_GET['id'] ?? 0);
            if ($id) {
                $item = DB::get_transaction_by_id($id);
            }
        }
        
        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit Operation', 'comptaflow-uk-by-meetempo') : esc_html__('New Financial Operation', 'comptaflow-uk-by-meetempo')) . '</h2>';
        echo '<form method="post" id="financial-form">';
        wp_nonce_field('comptaflow_uk_financial_action');
        echo '<input type="hidden" name="action" value="' . ($action === 'edit' ? 'update' : 'create') . '">';
        if ($action === 'edit') {
            echo '<input type="hidden" name="id" value="' . esc_attr($item['id'] ?? '') . '">';
        }
        
        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Operation Type *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        self::renderTypeSelector($item['type'] ?? '');
        echo '</td></tr>';
        
        echo '<tbody id="standard-fields">';
        echo '<tr><th>' . esc_html__('Date *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="date" name="date_txn" value="' . esc_attr($item['date_txn'] ?? gmdate('Y-m-d')) . '" required></td></tr>';
        
        echo '<tbody id="amount-section">';
        self::renderAmountFields($item);
        echo '</tbody>';
        
        echo '<tr><th>' . esc_html__('Description *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="text" name="label" value="' . esc_attr($item['label'] ?? '') . '" required class="regular-text"></td></tr>';
        
        echo '<tr id="bank-transfer-fields" style="display:none;"><th>' . esc_html__('Accounts *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo esc_html__('From:', 'comptaflow-uk-by-meetempo') . ' <input type="text" name="source_account" placeholder="1200" value="1200" style="width: 80px;"> ';
        echo esc_html__('To:', 'comptaflow-uk-by-meetempo') . ' <input type="text" name="dest_account" placeholder="1200" value="1200" style="width: 80px;">';
        echo '<p class="description">' . esc_html__('1200 = Bank Current, 1230 = Petty Cash', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Payment Status *', 'comptaflow-uk-by-meetempo') . '</th><td><select name="payment_status">';
        $selected_status = $item['payment_status'] ?? 'PAID';
        echo '<option value="PAID"' . selected($selected_status, 'PAID', false) . '>' . esc_html__('Settled immediately', 'comptaflow-uk-by-meetempo') . '</option>';
        echo '<option value="PENDING"' . selected($selected_status, 'PENDING', false) . '>' . esc_html__('To settle later', 'comptaflow-uk-by-meetempo') . '</option>';
        echo '</select></td></tr>';
        
        echo '<tr><th>' . esc_html__('Counterparty / Bank', 'comptaflow-uk-by-meetempo') . '</th><td><input type="text" name="partner_name" value="' . esc_attr($item['partner_name'] ?? '') . '" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Reference', 'comptaflow-uk-by-meetempo') . '</th><td><input type="text" name="piece_ref" value="' . esc_attr($item['piece_ref'] ?? '') . '" class="regular-text"></td></tr>';
        echo '</tbody>';

        echo '<tbody id="in-kind-fields" style="display:none;">';
        echo '<tr><th>' . esc_html__('Contribution Date *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="date" name="date_txn_kind" value="' . esc_attr(gmdate('Y-m-d')) . '"></td></tr>';
        echo '<tr><th>' . esc_html__('Asset Name *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="text" name="label_kind" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Asset Value (£) *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="number" step="0.01" min="0" name="amount_gross_kind"></td></tr>';
        echo '<tr><th>' . esc_html__('Fixed Asset Account *', 'comptaflow-uk-by-meetempo') . '</th><td><select name="asset_account">';
        $asset_accounts = ChartOfAccounts::getAccountsByClass(0);
        foreach ($asset_accounts as $account) {
            // Filter to fixed asset range 0020-0059
            if (intval($account['code']) < 20 || intval($account['code']) > 599) continue;
            echo '<option value="' . esc_attr($account['code']) . '">' . esc_html($account['code'] . ' - ' . $account['label']) . '</option>';
        }
        echo '</select></td></tr>';
        echo '<tr><th>' . esc_html__('Useful Life (years) *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="number" name="depreciation_duration" value="3"></td></tr>';
        echo '</tbody>';
        
        echo '</table>';
        submit_button($action === 'edit' ? esc_attr__('Update', 'comptaflow-uk-by-meetempo') : esc_attr__('Save', 'comptaflow-uk-by-meetempo'));
        echo '</form>';
        }
    
    private static function renderTypeSelector(string $selected = ''): void {
        $types = self::getFinancialOperationTypes();
        echo '<select name="type" id="operation-type" required>';
        echo '<option value="">' . esc_html__('-- Choose a type --', 'comptaflow-uk-by-meetempo') . '</option>';
        foreach ($types as $group) {
            echo '<optgroup label="' . esc_attr($group['label']) . '">';
            foreach ($group['options'] as $type_key => $type_label) {
                echo '<option value="' . esc_attr($type_key) . '"' . selected($selected, $type_key, false) . ' data-has-vat="' . esc_attr($group['has_vat'] ? '1' : '0') . '">' . esc_html($type_label) . '</option>';
            }
            echo '</optgroup>';
        }
        echo '</select>';
    }
    
    private static function renderAmountFields(array $item): void {
        $amount_gross = $item['amount_ttc'] ?? '';
        
        echo '<tr id="simple-amount-row"><th>' . esc_html__('Amount (£) *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="number" step="0.01" min="0" name="amount_gross" id="amount_simple" value="' . esc_attr($amount_gross) . '" required></td></tr>';
        
        echo '<tr id="vat-toggle-row" style="display:none;"><th>' . esc_html__('Entry Mode', 'comptaflow-uk-by-meetempo') . '</th><td><label><input type="checkbox" name="manual_amounts" id="manual_amounts"> ' . esc_html__('Manual entry Net/VAT/Gross', 'comptaflow-uk-by-meetempo') . '</label></td></tr>';
        
        echo '<tr id="auto-amount-row" style="display:none;"><th>' . esc_html__('Gross Amount *', 'comptaflow-uk-by-meetempo') . '</th><td><input type="number" step="0.01" min="0" name="amount_gross_auto" id="amount_gross_auto" value="' . esc_attr($amount_gross) . '"> £</td></tr>';
        
        echo '<tr id="manual-amount-row" style="display:none;"><th>' . esc_html__('Detailed Amounts *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo esc_html__('Net:', 'comptaflow-uk-by-meetempo') . ' <input type="number" name="amount_net_manual" value="'.esc_attr($item['amount_ht'] ?? '').'" step="0.01" style="width:100px;"> £ ';
        echo esc_html__('VAT:', 'comptaflow-uk-by-meetempo') . ' <input type="number" name="amount_vat_manual" value="'.esc_attr($item['amount_tva'] ?? '').'" step="0.01" style="width:100px;"> £ ';
        echo esc_html__('Gross:', 'comptaflow-uk-by-meetempo') . ' <input type="number" name="amount_gross_manual" value="'.esc_attr($amount_gross).'" step="0.01" style="width:100px;"> £';
        echo '</td></tr>';
        
        echo '<tr id="vat-rate-row" style="display:none;"><th>' . esc_html__('VAT Rate', 'comptaflow-uk-by-meetempo') . '</th><td>';
        self::renderVATSelector($item);
        echo '</td></tr>';
    }
    
    private static function renderVATSelector(array $item): void {
        $vat_rates = DB::getActiveVATRates('GB');
        echo '<input type="hidden" name="vat_code" id="vat_code">';
        echo '<select name="vat_rate" id="vat_rate_select">';
        $selected_rate = $item['vat_rate'] ?? 20;
        
        if (empty($vat_rates)) {
            $vat_rates = [
                ['rate_value' => 20.00, 'rate_code' => 'GB-20', 'rate_name' => 'Standard rate'],
                ['rate_value' => 5.00, 'rate_code' => 'GB-5', 'rate_name' => 'Reduced rate'],
                ['rate_value' => 0.00, 'rate_code' => 'GB-0', 'rate_name' => 'Zero rate'],
                ['rate_value' => 0.00, 'rate_code' => 'GB-EXEMPT', 'rate_name' => 'Exempt']
            ];
        }
        
        foreach ($vat_rates as $rate) {
            $is_selected = (abs(floatval($rate['rate_value']) - floatval($selected_rate)) < 0.01);
            echo '<option value="' . esc_attr($rate['rate_value']) . '" data-code="' . esc_attr($rate['rate_code']) . '"' . ($is_selected ? ' selected' : '') . '>';
            echo number_format($rate['rate_value'], 2) . '% - ' . esc_html($rate['rate_name']);
            echo '</option>';
        }
        echo '</select>';
        
    }
    
    
    private static function renderList(): void {
        $financial_types = array_keys(self::getFinancialOperationTypes(true));
        $table = new TransactionsTable($financial_types, 'comptaflow-uk-financial');
        $table->prepare_items();
        
        add_filter('comptaflow_uk_transaction_row_actions', function($actions, $item) {
            if ($item->type === 'CAPITAL_IN_KIND') {
                unset($actions['edit'], $actions['delete']);
                $meta = json_decode($item->meta_json, true);
                if (!empty($meta['asset_id'])) {
                    $actions['view'] = '<a href="?page=comptaflow-uk-financial">' . esc_html__('View fixed asset', 'comptaflow-uk-by-meetempo') . '</a>';
                }
                return $actions;
            }

            if ($item->payment_status === 'PENDING') {
                $mark_paid_url = wp_nonce_url(
                    admin_url('admin.php?page=comptaflow-uk-financial&action=mark_paid&id=' . $item->id), 
                    'comptaflow_uk_mark_paid_' . $item->id
                );
                $actions['mark_paid'] = sprintf(
                    '<a href="%s" class="button button-primary button-small">' . esc_html__('Mark as settled', 'comptaflow-uk-by-meetempo') . '</a>', 
                    $mark_paid_url
                );
            }
            
            $actions['edit'] = sprintf(
                '<a href="?page=comptaflow-uk-financial&action=edit&id=%s">' . esc_html__('Edit', 'comptaflow-uk-by-meetempo') . '</a>', 
                $item->id
            );
            $actions['delete'] = sprintf(
                '<a href="%s" onclick="return confirm(\'' . esc_js(__('Delete this operation?', 'comptaflow-uk-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-uk-by-meetempo') . '</a>', 
                wp_nonce_url(admin_url("admin.php?page=comptaflow-uk-financial&action=delete&id={$item->id}"), 'comptaflow_uk_delete_financial')
            );
            
            return $actions;
        }, 10, 2);
        
        $table->display();
    }
    
    private static function getFinancialOperationTypes($flatten = false): array {
        $types = [
            'capital_group' => [
                'label' => '💰 CAPITAL',
                'has_vat' => false,
                'options' => [
                    'CAPITAL_INCREASE' => 'Share capital increase (3000)',
                    'CAPITAL_CASH_INJECTION' => 'Capital injection - Cash (3000)',
                    'CAPITAL_IN_KIND' => 'Capital contribution in kind - Assets (3000)',
                    'CAPITAL_CONTRIBUTION' => 'Director\'s loan to company (3050)',
                    'OWNER_DRAWING' => 'Director\'s loan repayment (3050)',
                ]
            ],
            'capital_advanced' => [
                'label' => '💰 ADVANCED CAPITAL',
                'has_vat' => false,
                'options' => [
                    'CC_TO_CAPITAL' => 'Convert director\'s loan to share capital (3050/3000)',
                    'CC_INTEREST' => 'Interest on director\'s loan (7810/3050)',
                    'DIVIDEND_TO_CC' => 'Dividends credited to director\'s loan (3060/3050)',
                ]
            ],
            'loans_group' => [
                'label' => '🏛️ LOANS',
                'has_vat' => false,
                'options' => [
                    'LOAN_RECEIVED' => 'Loan received (2300)',
                    'LOAN_REPAYMENT' => 'Loan repayment (2300)',
                    'INTEREST_PAYMENT' => 'Interest payment (7810)',
                ]
            ],
            'fiscal_group' => [
                'label' => '🏛️ TAX & STATUTORY',
                'has_vat' => false,
                'options' => [
                    'VAT_PAYMENT' => 'VAT payment to HMRC (2202)',
                    'CORPORATE_TAX' => 'Corporation Tax payment (2220)',
                    'DIVIDEND_PAYMENT' => 'Dividend distribution (3060)',
                ]
            ],
            'treasury_group' => [
                'label' => '💼 CASH MANAGEMENT',
                'has_vat' => false,
                'options' => [
                    'BANK_TRANSFER' => 'Transfer between accounts (1200)',
                    'CASH_DEPOSIT' => 'Cash deposit (1230)',
                    'CASH_WITHDRAWAL' => 'Cash withdrawal (1230)',
                ]
            ],
            'services_group' => [
                'label' => '💳 SERVICES & FEES (with VAT)',
                'has_vat' => true,
                'options' => [
                    'BANK_FEES' => 'Bank charges (7400)',
                    'LEGAL_FEES' => 'Legal fees - Solicitor/Barrister (7430)',
                    'ACCOUNTING_FEES' => 'Accountancy fees (7430)',
                ]
            ]
        ];
        
        if ($flatten) {
            $flat_array = [];
            foreach ($types as $group) {
                foreach ($group['options'] as $key => $label) {
                    $flat_array[$key] = $label;
                }
            }
            return $flat_array;
        }
        return $types;
    }
    
    private static function getTypeConfig(string $type): ?array {
        $all_types = self::getFinancialOperationTypes();
        foreach ($all_types as $group) {
            if (isset($group['options'][$type])) {
                return ['has_vat' => $group['has_vat']];
            }
        }
        return null;
    }
    
    private static function showMessages(): void {
        if (isset($_GET['deleted'])) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Operation deleted with its entries.', 'comptaflow-uk-by-meetempo') . '</p></div>';
        }
        settings_errors('comptaflow_uk_financial');
    }
}
