/**
 * ComptaFlow Admin Scripts
 * Version 1.0.3
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        ComptaFlow_Admin.init();
    });

    var ComptaFlow_Admin = {
        
        init: function() {
            this.initPayrollCalculator();
            this.initConfirmDialogs();
            this.initSettingsConditionalFields();
            this.initManualAmountsToggle();
            this.initVATCodeSync();
            this.initAccountSelector();
            this.initManualODForm();
        },

        /**
         * Calculateur automatique pour la paie
         */
        initPayrollCalculator: function() {
            var $grossInput = $('#gross_salary');
            var $employeeContribInput = $('#employee_contributions');
            var $employerContribInput = $('#employer_contributions');
            var $taxInput = $('#withholding_tax');

            if ($grossInput.length === 0) return;

            var calculatePayroll = function() {
                var gross = parseFloat($grossInput.val()) || 0;
                var employeeContrib = parseFloat($employeeContribInput.val()) || 0;
                var employerContrib = parseFloat($employerContribInput.val()) || 0;
                var tax = parseFloat($taxInput.val()) || 0;

                var netBeforeTax = gross - employeeContrib;
                var netPay = netBeforeTax - tax;
                var totalCost = gross + employerContrib;

                $('#net_before_tax_display').text(netBeforeTax.toFixed(2).replace('.', ',') + ' €');
                $('#net_pay_display').text(netPay.toFixed(2).replace('.', ',') + ' €');
                $('#total_cost_display').text(totalCost.toFixed(2).replace('.', ',') + ' €');
            };

            $('.cfp-payroll-input').on('input', calculatePayroll);
            calculatePayroll();
        },

        /**
         * Dialogues de confirmation
         */
        initConfirmDialogs: function() {
            $('a[data-confirm]').on('click', function(e) {
                var message = $(this).data('confirm') || 'Êtes-vous sûr ?';
                if (!confirm(message)) {
                    e.preventDefault();
                }
            });
        },

        /**
         * Settings page - conditional fields
         */
        initSettingsConditionalFields: function() {
            var $exerciseRadios = $('input[name="exercise_type"]');
            var $customRow = $('.custom-exercise-row');
            
            if ($exerciseRadios.length > 0) {
                $exerciseRadios.on('change', function() {
                    $customRow.toggle(this.value === 'custom');
                });
            }
            
            var $vatRegimeSelector = $('#vat_regime_selector');
            var $ca12Rows = $('.ca12-fields-row');
            
            if ($vatRegimeSelector.length > 0) {
                function toggleCA12Fields() {
                    $ca12Rows.toggle($vatRegimeSelector.val() === 'SIMPLIFIE');
                }
                $vatRegimeSelector.on('change', toggleCA12Fields);
                toggleCA12Fields();
            }
        },

        /**
         * Toggle saisie manuelle HT/TVA/TTC (Expenses, Sales)
         */
        initManualAmountsToggle: function() {
            var $checkbox = $('#manual_amounts');
            if ($checkbox.length === 0) return;

            var $autoRow = $('#auto_mode_row');
            var $manualRow = $('#manual_mode_row');
            var $autoInput = $('#amount_ttc_auto');

            function toggle() {
                var isManual = $checkbox.is(':checked');
                $autoRow.toggle(!isManual);
                $manualRow.toggle(isManual);
                
                if (isManual) {
                    $autoInput.removeAttr('required');
                } else {
                    $autoInput.attr('required', 'required');
                }
            }

            $checkbox.on('change', toggle);
            toggle();
        },

        /**
         * Synchronisation code TVA avec le select
         */
        initVATCodeSync: function() {
            var $select = $('#vat_rate_select');
            var $hiddenCode = $('#vat_code');

            if ($select.length === 0 || $hiddenCode.length === 0) return;

            function sync() {
                var $selected = $select.find('option:selected');
                $hiddenCode.val($selected.data('code') || '');
            }

            // Initialisation avec le code existant (si édition)
            var initialCode = $select.data('initial-code');
            if (initialCode) {
                $hiddenCode.val(initialCode);
            } else {
                sync();
            }

            $select.on('change', sync);
        },

        /**
         * Sélecteur de compte comptable (Expenses, Sales, ManualJournal)
         */
        initAccountSelector: function() {
            var $searchInput = $('#account_search');
            var $resultsDiv = $('#search-results');
            var $selectedDiv = $('#selected-account');
            var $hiddenInput = $('#account_code');
            var $quickButtons = $('.account-quick-select');

            if ($searchInput.length === 0) return;

            // Récupère les comptes depuis wp_localize_script
            var accounts = (typeof comptaflow_data !== 'undefined' && comptaflow_data.accounts) 
                ? comptaflow_data.accounts 
                : {};

            // Filtre de classe de comptes (6 pour dépenses, 7 pour ventes, etc.)
            var accountClassFilter = $searchInput.data('class-filter') || '';

            // Boutons raccourcis
            $quickButtons.on('click', function() {
                var code = $(this).data('code');
                var label = $(this).data('label');
                selectAccount(code, label);
                $quickButtons.css({ background: '#f8f9fa', color: 'black' });
                $(this).css({ background: '#d63638', color: 'white' });
            });

            // Recherche
            $searchInput.on('input', function() {
                var query = $(this).val().trim().toLowerCase();
                if (query.length < 2) {
                    $resultsDiv.hide();
                    return;
                }
                searchAccounts(query);
            });

            function searchAccounts(query) {
                var results = [];

                for (var code in accounts) {
                    // Filtre par classe si défini
                    if (accountClassFilter && !code.startsWith(accountClassFilter)) continue;

                    var account = accounts[code];
                    var score = 0;

                    if (code.indexOf(query) !== -1) score = 90;
                    if (account.label && account.label.toLowerCase().indexOf(query) !== -1) {
                        score = Math.max(score, 70);
                    }
                    if (account.keywords) {
                        for (var i = 0; i < account.keywords.length; i++) {
                            if (account.keywords[i].toLowerCase().indexOf(query) !== -1) {
                                score = Math.max(score, 80);
                                break;
                            }
                        }
                    }

                    if (score > 0) {
                        results.push({ code: code, label: account.label, score: score });
                    }
                }

                results.sort(function(a, b) { return b.score - a.score; });
                displayResults(results.slice(0, 5));
            }

            function displayResults(results) {
                if (results.length === 0) {
                    $resultsDiv.html('<div style="padding: 10px;">Aucun compte trouvé</div>');
                } else {
                    var html = '';
                    results.forEach(function(account) {
                        html += '<div class="account-result" data-code="' + account.code + '" data-label="' + account.label + '" style="padding: 8px; border-bottom: 1px solid #eee; cursor: pointer;">';
                        html += '<strong>' + account.code + '</strong> - ' + account.label;
                        html += '</div>';
                    });
                    $resultsDiv.html(html);

                    $resultsDiv.find('.account-result').on('click', function() {
                        selectAccount($(this).data('code'), $(this).data('label'));
                        $resultsDiv.hide();
                        $searchInput.val('');
                    });
                }
                $resultsDiv.show();
            }

            function selectAccount(code, label) {
                $hiddenInput.val(code);
                $selectedDiv.html('<strong>' + code + '</strong> - ' + label);
            }
        },
        /**
         * Gestion des lignes OD manuelles
         */
        initManualODForm: function() {
            var $tbody = $('#od-lines-tbody');
            var $addBtn = $('#add-line');
            var $totalDebit = $('#total-debit');
            var $totalCredit = $('#total-credit');
            var $difference = $('#difference');
            var $linesJson = $('#lines_json');
            var $form = $('#cfp-manual-od-form');

            if ($tbody.length === 0) return;

            function fmt(n) {
                return parseFloat(n || 0).toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            }

            function recalculate() {
                var totalD = 0, totalC = 0;

                $tbody.find('.od-line-row').each(function() {
                    var d = parseFloat($(this).find('.line-debit').val() || 0);
                    var c = parseFloat($(this).find('.line-credit').val() || 0);
                    totalD += d;
                    totalC += c;
                });

                $totalDebit.text(fmt(totalD));
                $totalCredit.text(fmt(totalC));

                var diff = totalD - totalC;
                $difference.text(fmt(Math.abs(diff)));
                $difference.css('color', (Math.abs(diff) < 0.01) ? '#00a32a' : '#d63638');
            }

            function addLine() {
                var $template = $tbody.find('.od-line-row').first().clone();
                $template.find('input').each(function() {
                    $(this).val(this.type === 'number' ? '0' : '');
                });
                $tbody.append($template);
            }

            $addBtn.on('click', addLine);

            $tbody.on('click', '.remove-line', function() {
                if ($tbody.find('.od-line-row').length <= 1) {
                    alert('Il faut au moins une ligne.');
                    return;
                }
                $(this).closest('.od-line-row').remove();
                recalculate();
            });

            $tbody.on('input', 'input', recalculate);

            $form.on('submit', function(e) {
                var lines = [];

                $tbody.find('.od-line-row').each(function() {
                    var compte = $(this).find('.line-compte').val().trim();
                    var libelle = $(this).find('.line-libelle').val().trim();
                    var debit = parseFloat($(this).find('.line-debit').val() || 0);
                    var credit = parseFloat($(this).find('.line-credit').val() || 0);

                    if (compte && (debit > 0 || credit > 0)) {
                        lines.push({compte: compte, libelle: libelle, debit: debit, credit: credit});
                    }
                });

                if (lines.length === 0) {
                    alert('Veuillez saisir au moins une ligne valide.');
                    e.preventDefault();
                    return;
                }

                $linesJson.val(JSON.stringify(lines));
            });

            recalculate();
        }
    };

    // Exposer globalement
    window.ComptaFlow_Admin = ComptaFlow_Admin;

})(jQuery);