<?php
namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\JournalEntryGenerator;
use ComptaFlowPro\Services\ChartOfAccounts;
use ComptaFlowPro\Services\DB;
use ComptaFlowPro\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-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-by-meetempo') . '</h1>';
        
        if ($action === 'list') {
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-financial&action=new')) . '" class="page-title-action">' . esc_html__('Add New', 'comptaflow-by-meetempo') . '</a>';
        }

        self::showMessages();

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

        echo '</div>';
    }

    private static function handleActions(): void {
        if (!isset($_POST['_wpnonce']) && !isset($_GET['action'])) {
            return;
        }
        
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce_post && wp_verify_nonce($nonce_post, 'comptaflow_financial_action')) {
            if (isset($_POST['action']) && ($_POST['action'] === 'create' || $_POST['action'] === 'update')) {
                self::saveFinancialOperation();
            }
        }
        
        if (isset($_GET['action']) && $_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_delete_financial')) {
                self::deleteFinancialOperation();
            }
        }
        
        if (isset($_GET['action']) && $_GET['action'] === 'mark_paid' && isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $nonce_paid = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce_paid, 'comptaflow_mark_paid_' . $id)) {
                self::markAsPaid($id);
            }
        }
    }

    private static function saveFinancialOperation(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        $type = sanitize_text_field($_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($_POST['label_kind'] ?? ''),
                    'acquisition_date' => sanitize_text_field($_POST['date_txn_kind'] ?? ''),
                    'acquisition_ht' => floatval($_POST['amount_ttc_kind'] ?? 0),
                    'acquisition_tva' => 0,
                    'acquisition_ttc' => floatval($_POST['amount_ttc_kind'] ?? 0),
                    'depreciation_duration' => intval($_POST['depreciation_duration'] ?? 3),
                    'account_code' => sanitize_text_field($_POST['asset_account'] ?? ''),
                    'payment_status' => 'PAID',
                    'status' => 'ACTIVE',
                    'created_by' => $user_id,
                ];
                $wpdb->insert($p . 'immobilizations', $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(['immob_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 = __('In-kind contribution recorded successfully!', 'comptaflow-by-meetempo');

            } else {
                $type_config = self::getTypeConfig($type);
                $has_vat = $type_config['has_vat'] ?? false;
                
                if ($has_vat) {
                    $is_manual = isset($_POST['manual_amounts']) && $_POST['manual_amounts'] === 'on';
                    if ($is_manual) {
                        $amount_ht = floatval($_POST['amount_ht_manual'] ?? 0);
                        $amount_tva = floatval($_POST['amount_tva_manual'] ?? 0);
                        $amount_ttc = floatval($_POST['amount_ttc_manual'] ?? 0);
                        $vat_rate = floatval($_POST['vat_rate'] ?? 0);
                    } else {
                        $vat_rate = floatval($_POST['vat_rate'] ?? 20);
                        $amount_ttc = floatval($_POST['amount_ttc_auto'] ?? 0);
                        $amount_ht = round($amount_ttc / (1 + ($vat_rate / 100)), 2);
                        $amount_tva = $amount_ttc - $amount_ht;
                    }
                    $vat_code = sanitize_text_field($_POST['vat_code'] ?? '');
                } else {
                    $amount_ttc = floatval($_POST['amount_ttc'] ?? 0);
                    $amount_ht = $amount_ttc;
                    $amount_tva = 0; 
                    $vat_rate = 0; 
                    $vat_code = '';
                }
                
                $data = [
                    'type' => $type, 
                    'date_txn' => sanitize_text_field($_POST['date_txn'] ?? ''),
                    'label' => sanitize_text_field($_POST['label'] ?? ''), 
                    'amount_ttc' => $amount_ttc,
                    'amount_ht' => $amount_ht, 
                    'amount_tva' => $amount_tva,
                    'vat_rate' => $vat_rate, 
                    'vat_code' => $vat_code,
                    'payment_status' => sanitize_text_field($_POST['payment_status'] ?? 'PAID'),
                    'partner_name' => sanitize_text_field($_POST['partner_name'] ?? ''),
                    'piece_ref' => sanitize_text_field($_POST['piece_ref'] ?? ''),
                    'journal_code' => 'OD', 
                    'created_by' => $user_id,
                ];
                
                if ($type === 'BANK_TRANSFER') {
                    $data['meta_json'] = wp_json_encode([
                        'source_account' => sanitize_text_field($_POST['source_account'] ?? '512'), 
                        'dest_account' => sanitize_text_field($_POST['dest_account'] ?? '512')
                    ]);
                }

                $id = intval($_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 journal entries regenerated!', 'comptaflow-by-meetempo');
                } else {
                    $data['uuid'] = wp_generate_uuid4();
                    $data['created_at'] = current_time('mysql');
                    $wpdb->insert($p . 'transactions', $data);
                    $transaction_id = $wpdb->insert_id;
                    $message = __('Operation saved with journal entries generated!', 'comptaflow-by-meetempo');
                }
                
                JournalEntryGenerator::generateFinancialEntries($data, $transaction_id);
            }
            
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_financial', 'saved', $message, 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_financial', 'error', __('Error:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    private static function markAsPaid(int $id): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        $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_financial', 'error', __('This operation is already paid or not found.', 'comptaflow-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_financial', 'marked_paid', __('Operation marked as paid! Treasury entry generated.', 'comptaflow-by-meetempo'), 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_financial', 'error', __('Error:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    private static function deleteFinancialOperation(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        try {
            $wpdb->query('START TRANSACTION');
            $wpdb->delete($p . 'journal_entries', ['transaction_id' => $id]);
            $wpdb->delete($p . 'transactions', ['id' => $id]);
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_financial', 'deleted', __('Operation deleted with all journal entries.', 'comptaflow-by-meetempo'), 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_financial', 'error', __('Error deleting:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    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-by-meetempo') : esc_html__('New Financial Operation', 'comptaflow-by-meetempo')) . '</h2>';
        echo '<form method="post" id="financial-form">';
        wp_nonce_field('comptaflow_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-by-meetempo') . ' *</th><td>';
        self::renderTypeSelector($item['type'] ?? '');
        echo '</td></tr>';
        
        echo '<tbody id="standard-fields">';
        echo '<tr><th>' . esc_html__('Date', 'comptaflow-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__('Label', 'comptaflow-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-by-meetempo') . ' *</th><td>';
        echo esc_html__('From:', 'comptaflow-by-meetempo') . ' <input type="text" name="source_account" placeholder="512" value="512" style="width: 80px;"> ';
        echo esc_html__('To:', 'comptaflow-by-meetempo') . ' <input type="text" name="dest_account" placeholder="512" value="512" style="width: 80px;">';
        echo '<p class="description">' . esc_html__('512 = Bank, 530 = Cash', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Payment Status', 'comptaflow-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__('Paid immediately', 'comptaflow-by-meetempo') . '</option>';
        echo '<option value="PENDING"' . selected($selected_status, 'PENDING', false) . '>' . esc_html__('To pay later', 'comptaflow-by-meetempo') . '</option>';
        echo '</select></td></tr>';
        
        echo '<tr><th>' . esc_html__('Third Party / Bank', 'comptaflow-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-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-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-by-meetempo') . '*</th><td><input type="text" name="label_kind" class="regular-text"></td></tr>';
        echo '<tr><th>' . esc_html__('Contribution Value (€)', 'comptaflow-by-meetempo') . '*</th><td><input type="number" step="0.01" min="0" name="amount_ttc_kind"></td></tr>';
        echo '<tr><th>' . esc_html__('Fixed Asset Account', 'comptaflow-by-meetempo') . '*</th><td><select name="asset_account">';
        $immo_accounts = ChartOfAccounts::getAccountsByClass(2);
        foreach ($immo_accounts as $account) {
            if (strpos($account['code'], '28') === 0 || strpos($account['code'], '29') === 0) continue;
            echo '<option value="' . esc_attr($account['code']) . '">' . esc_html($account['code'] . ' - ' . $account['label']) . '</option>';
        }
        echo '</select></td></tr>';
        echo '<tr><th>' . esc_html__('Depreciation Duration (years)', 'comptaflow-by-meetempo') . '*</th><td><input type="number" name="depreciation_duration" value="3"></td></tr>';
        echo '</tbody>';
        
        echo '</table>';
        submit_button($action === 'edit' ? __('Update', 'comptaflow-by-meetempo') : __('Save', 'comptaflow-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-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_ttc = $item['amount_ttc'] ?? '';
        
        echo '<tr id="simple-amount-row"><th>' . esc_html__('Amount (€)', 'comptaflow-by-meetempo') . ' *</th><td><input type="number" step="0.01" min="0" name="amount_ttc" id="amount_simple" value="' . esc_attr($amount_ttc) . '" required></td></tr>';
        
        echo '<tr id="vat-toggle-row" style="display:none;"><th>' . esc_html__('Entry Mode', 'comptaflow-by-meetempo') . '</th><td><label><input type="checkbox" name="manual_amounts" id="manual_amounts"> ' . esc_html__('Manual entry for Net/VAT/Gross', 'comptaflow-by-meetempo') . '</label></td></tr>';
        
        echo '<tr id="auto-amount-row" style="display:none;"><th>' . esc_html__('Gross Amount', 'comptaflow-by-meetempo') . ' *</th><td><input type="number" step="0.01" min="0" name="amount_ttc_auto" id="amount_ttc_auto" value="' . esc_attr($amount_ttc) . '"> €</td></tr>';
        
        echo '<tr id="manual-amount-row" style="display:none;"><th>' . esc_html__('Detailed Amounts', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo esc_html__('Net:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_ht_manual" value="' . esc_attr($item['amount_ht'] ?? '') . '" step="0.01" style="width:100px;"> € ';
        echo esc_html__('VAT:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_tva_manual" value="' . esc_attr($item['amount_tva'] ?? '') . '" step="0.01" style="width:100px;"> € ';
        echo esc_html__('Gross:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_ttc_manual" value="' . esc_attr($amount_ttc) . '" step="0.01" style="width:100px;"> €';
        echo '</td></tr>';
        
        echo '<tr id="vat-rate-row" style="display:none;"><th>' . esc_html__('VAT Rate', 'comptaflow-by-meetempo') . '</th><td>';
        self::renderVATSelector($item);
        echo '</td></tr>';
    }
    
    private static function renderVATSelector(array $item): void {
        $vat_rates = DB::getActiveVATRates('FR');
        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' => 'FR-20', 'rate_name' => __('Standard rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 10.00, 'rate_code' => 'FR-10', 'rate_name' => __('Reduced rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 5.50, 'rate_code' => 'FR-5_5', 'rate_name' => __('Super reduced rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 0.00, 'rate_code' => 'FR-0', 'rate_name' => __('Exempt', 'comptaflow-by-meetempo')]
            ];
        }
        
        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 esc_html(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-financial');
        $table->prepare_items();
        
        add_filter('comptaflow_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['immob_id'])) {
                    $actions['view'] = sprintf(
                        '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '">%s</a>', 
                        esc_html__('View Fixed Asset (Pro)', 'comptaflow-by-meetempo')
                    );
                }
                return $actions;
            }

            if ($item->payment_status === 'PENDING') {
                $mark_paid_url = wp_nonce_url(
                    admin_url('admin.php?page=comptaflow-financial&action=mark_paid&id=' . $item->id), 
                    'comptaflow_mark_paid_' . $item->id
                );
                $actions['mark_paid'] = sprintf(
                    '<a href="%s" class="button button-primary button-small">%s</a>', 
                    esc_url($mark_paid_url),
                    esc_html__('Mark as Paid', 'comptaflow-by-meetempo')
                );
            }
            
            $actions['edit'] = sprintf(
                '<a href="%s">%s</a>', 
                esc_url(admin_url('admin.php?page=comptaflow-financial&action=edit&id=' . $item->id)),
                esc_html__('Edit', 'comptaflow-by-meetempo')
            );
            $actions['delete'] = sprintf(
                '<a href="%s" onclick="return confirm(\'%s\')">%s</a>', 
                esc_url(wp_nonce_url(admin_url("admin.php?page=comptaflow-financial&action=delete&id={$item->id}"), 'comptaflow_delete_financial')),
                esc_js(__('Delete this operation?', 'comptaflow-by-meetempo')),
                esc_html__('Delete', 'comptaflow-by-meetempo')
            );
            
            return $actions;
        }, 10, 2);
        
        $table->display();
    }
    
    private static function getFinancialOperationTypes($flatten = false): array {
        $types = [
            'capital_group' => [
                'label' => '💰 ' . __('CAPITAL', 'comptaflow-by-meetempo'),
                'has_vat' => false,
                'options' => [
                    'CAPITAL_INCREASE' => __('Capital increase (101)', 'comptaflow-by-meetempo'),
                    'CAPITAL_CASH_INJECTION' => __('Cash capital contribution (101)', 'comptaflow-by-meetempo'),
                    'CAPITAL_IN_KIND' => __('In-kind contribution - Equipment (101)', 'comptaflow-by-meetempo'),
                    'CAPITAL_CONTRIBUTION' => __('Shareholder loan contribution (455)', 'comptaflow-by-meetempo'),
                    'OWNER_DRAWING' => __('Shareholder loan withdrawal (455)', 'comptaflow-by-meetempo'),
                ]
            ],
            'capital_advanced' => [
                'label' => '💰 ' . __('ADVANCED CAPITAL', 'comptaflow-by-meetempo'),
                'has_vat' => false,
                'options' => [
                    'CC_TO_CAPITAL' => __('Shareholder loan to capital conversion (455/101)', 'comptaflow-by-meetempo'),
                    'CC_INTEREST' => __('Interest on shareholder loan (6615/455)', 'comptaflow-by-meetempo'),
                    'DIVIDEND_TO_CC' => __('Dividends to shareholder account (457/455)', 'comptaflow-by-meetempo'),
                ]
            ],
            'loans_group' => [
                'label' => '🏛️ ' . __('LOANS', 'comptaflow-by-meetempo'),
                'has_vat' => false,
                'options' => [
                    'LOAN_RECEIVED' => __('Loan received (164)', 'comptaflow-by-meetempo'),
                    'LOAN_REPAYMENT' => __('Loan repayment (164)', 'comptaflow-by-meetempo'),
                    'INTEREST_PAYMENT' => __('Interest payment (661)', 'comptaflow-by-meetempo'),
                ]
            ],
            'fiscal_group' => [
                'label' => '🏛️ ' . __('TAX & SOCIAL', 'comptaflow-by-meetempo'),
                'has_vat' => false,
                'options' => [
                    'VAT_PAYMENT' => __('VAT payment (44551)', 'comptaflow-by-meetempo'),
                    'CORPORATE_TAX' => __('Corporate tax payment (444)', 'comptaflow-by-meetempo'),
                    'DIVIDEND_PAYMENT' => __('Dividend distribution (457)', 'comptaflow-by-meetempo'),
                ]
            ],
            'treasury_group' => [
                'label' => '💼 ' . __('TREASURY', 'comptaflow-by-meetempo'),
                'has_vat' => false,
                'options' => [
                    'BANK_TRANSFER' => __('Transfer between accounts (512)', 'comptaflow-by-meetempo'),
                    'CASH_DEPOSIT' => __('Cash deposit (530)', 'comptaflow-by-meetempo'),
                    'CASH_WITHDRAWAL' => __('Cash withdrawal (530)', 'comptaflow-by-meetempo'),
                ]
            ],
            'services_group' => [
                'label' => '💳 ' . __('SERVICES & FEES (with VAT)', 'comptaflow-by-meetempo'),
                'has_vat' => true,
                'options' => [
                    'BANK_FEES' => __('Bank fees (627)', 'comptaflow-by-meetempo'),
                    'LEGAL_FEES' => __('Legal/notary fees (6226)', 'comptaflow-by-meetempo'),
                    'ACCOUNTING_FEES' => __('Accounting fees (6226)', 'comptaflow-by-meetempo'),
                ]
            ]
        ];
        
        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 {
        settings_errors('comptaflow_financial');
    }
}
