/**
 * ComptaFlow - Gestion dynamique des lignes de facture
 */
(function($) {
    'use strict';

    var lineIndex = 0;

    function init() {
        var $body = $('#cfp-lines-body');
        if (!$body.length) {
            return;
        }

        // Compter les lignes existantes
        lineIndex = $body.find('.cfp-line-row').length;

        // Ajouter une ligne
        $('#cfp-add-line').on('click', function() {
            addLine();
        });

        // Supprimer une ligne (delegation)
        $body.on('click', '.cfp-remove-line', function() {
            var $row = $(this).closest('.cfp-line-row');
            if ($body.find('.cfp-line-row').length > 1) {
                $row.remove();
                recalculate();
            }
        });

        // Recalculer sur changement
        $body.on('input change', '.cfp-line-qty, .cfp-line-price, .cfp-line-vat', function() {
            recalculateLine($(this).closest('.cfp-line-row'));
            recalculate();
        });

        // Calcul initial
        $body.find('.cfp-line-row').each(function() {
            recalculateLine($(this));
        });
        recalculate();
    }

    function addLine() {
        var $template = $('#cfp-line-template');
        if (!$template.length) {
            return;
        }

        var html = $template.html();
        var $row = $(html);

        // Reinitialiser les valeurs
        $row.find('input[type="text"]').val('');
        $row.find('.cfp-line-qty').val(1);
        $row.find('.cfp-line-price').val(0);
        $row.find('.cfp-line-total').text('0,00 \u20ac');

        $('#cfp-lines-body').append($row);
        lineIndex++;

        // Focus sur le champ description
        $row.find('input[type="text"]:first').focus();
    }

    function recalculateLine($row) {
        var qty = parseFloat($row.find('.cfp-line-qty').val()) || 0;
        var price = parseFloat($row.find('.cfp-line-price').val()) || 0;
        var totalHt = qty * price;

        $row.find('.cfp-line-total').text(formatNumber(totalHt) + ' \u20ac');
    }

    function recalculate() {
        var totalHt = 0;
        var totalTva = 0;

        $('#cfp-lines-body .cfp-line-row').each(function() {
            var $row = $(this);
            var qty = parseFloat($row.find('.cfp-line-qty').val()) || 0;
            var price = parseFloat($row.find('.cfp-line-price').val()) || 0;
            var vatRate = parseFloat($row.find('.cfp-line-vat').val()) || 0;

            var lineHt = qty * price;
            var lineTva = lineHt * (vatRate / 100);

            totalHt += lineHt;
            totalTva += lineTva;
        });

        var totalTtc = totalHt + totalTva;

        $('#cfp-total-ht').text(formatNumber(totalHt) + ' \u20ac');
        $('#cfp-total-tva').text(formatNumber(totalTva) + ' \u20ac');
        $('#cfp-total-ttc').text(formatNumber(totalTtc) + ' \u20ac');
    }

    function formatNumber(n) {
        return n.toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
    }

    $(document).ready(init);

})(jQuery);
