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

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

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

        /**
         * Automatic payroll calculator
         */
        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));
                $('#net_pay_display').text('£' + netPay.toFixed(2));
                $('#total_cost_display').text('£' + totalCost.toFixed(2));
            };

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

        /**
         * Confirmation dialogs
         */
        initConfirmDialogs: function() {
            $('a[data-confirm]').on('click', function(e) {
                var message = $(this).data('confirm') || 'Are you sure?';
                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 $annualVATRows = $('.annual-vat-fields-row');
            
            if ($vatRegimeSelector.length > 0) {
                function toggleAnnualVATFields() {
                    $annualVATRows.toggle($vatRegimeSelector.val() === 'ANNUAL');
                }
                $vatRegimeSelector.on('change', toggleAnnualVATFields);
                toggleAnnualVATFields();
            }
        },

        /**
         * Toggle manual Net/VAT/Gross input (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();
        },

        /**
         * VAT code sync with select dropdown
         */
        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') || '');
            }

            // Initialise with existing code (if editing)
            var initialCode = $select.data('initial-code');
            if (initialCode) {
                $hiddenCode.val(initialCode);
            } else {
                sync();
            }

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

        /**
         * Account selector (Expenses, Sales, Manual Journal)
         */
        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;

            // Retrieve accounts from wp_localize_script
            var accounts = (typeof comptaflow_uk_data !== 'undefined' && comptaflow_uk_data.accounts) 
                ? comptaflow_uk_data.accounts 
                : {};

            // Account class filter (5xxx for purchases, 4xxx for sales, etc.)
            var accountClassFilter = $searchInput.data('class-filter') || '';

            // Quick select buttons
            $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' });
            });

            // Search
            $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) {
                    // Filter by class if defined
                    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;">No account found</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);
            }
        },
        /**
         * Manual journal entry (NL) lines management
         */
        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 = $('#cfuk-manual-od-form');

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

            function fmt(n) {
                return parseFloat(n || 0).toLocaleString('en-GB', {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('At least one line is required.');
                    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('Please enter at least one valid line.');
                    e.preventDefault();
                    return;
                }

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

            recalculate();
        }
    };

    // Expose globally
    window.ComptaFlowUK_Admin = ComptaFlowUK_Admin;

})(jQuery);