<form id="entity-form" class="form-horizontal" method="get" action="<?php echo e(route('finance_add_new_payment')); ?>"
    enctype="multipart/form-data" autocomplete="off">
    <?php echo csrf_field(); ?>
    <div class="row">
        <div class="col-lg-10">
            <div class="form-group">
                <label class="control-label"><?php echo app('translator')->get('Firma'); ?></label>
                <select id="companySelect" name="company" class="form-control <?= $errors->has("company") ? 'is-invalid' : ""; ?> enterable">
                    <option value="0" disabled selected><?php echo app('translator')->get('Izaberi'); ?></option>
                    <?php $__currentLoopData = $companies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $company): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($company->id); ?>" data-currency="<?php echo e($company->currency); ?>" <?php if(old('company', $entity->company) == $company->id): ?> selected <?php endif; ?>><?php echo e($company->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
                <?php echo $__env->make('_layout.partials.form.error', ['field' => 'company'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            </div>
        </div>  
        <div class="col-lg-2">
            <div id="currencyDisplay" class="form-group">
                <label class="control-label invisible"><?php echo app('translator')->get('Valuta'); ?></label> <!-- Nevidljiva labela za poravnanje -->
                <input 
                    id="currency"
                    type="text" 
                    class="form-control <?= $errors->has("price") ? 'is-invalid' : ""; ?> enterable" 
                    name="currency" 
                    placeholder="<?php echo app('translator')->get('Valuta'); ?>" 
                    value=""
                    readonly
                >
            </div>
        </div>  
    </div>
    
    <hr>
    <div class="row second" id="additional-section" style="display: none;">
        <div class="col-lg-12">
            <div class="row">
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="control-label"><?php echo app('translator')->get('Datum uplate na racun'); ?></label>
                            <input
                                type="text"
                                class="form-control <?= $errors->has("date_start") ? 'is-invalid' : ""; ?> enterable"
                                name="date_start"
                                id="date_start"
                                placeholder="<?php echo app('translator')->get('Datum'); ?>"
                                value=""
                            >
                        <?php echo $__env->make('_layout.partials.form.error', ['field' => 'date_start'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="control-label"><?php echo app('translator')->get('Referentni broj'); ?></label>
                            <input 
                                type="text" 
                                class="form-control <?= $errors->has("reference") ? 'is-invalid' : ""; ?> enterable" 
                                name="reference" 
                                placeholder="<?php echo app('translator')->get('Referentni broj'); ?>" 
                                value=""
                            >
                        <?php echo $__env->make('_layout.partials.form.error', ['field' => 'price'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="control-label"><?php echo app('translator')->get('Ukupan iznos za uplatu'); ?></label>
                            <input 
                                type="text" 
                                class="form-control <?= $errors->has("price") ? 'is-invalid' : ""; ?> enterable" 
                                name="price" 
                                placeholder="<?php echo app('translator')->get('0.00'); ?>" 
                                value=""
                            >
                        <?php echo $__env->make('_layout.partials.form.error', ['field' => 'price'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <hr>
        <div id="invoices" class="col-lg-12">
            
        </div>
    
    <hr>
    <div class="form-group row" id="submit-section" style="display: none;">
        <div class="col-sm-12 button-right">
            <button type="submit" class="btn btn-success waves-effect waves-light" id="button" data-index="4">
                <i class="fa fa-save"></i>
                <?php echo app('translator')->get('Sačuvaj'); ?>
            </button>
        </div>
    </div>
</form>

<?php $__env->startPush('head_links'); ?>
<link href="/theme/plugins/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css" rel="stylesheet">
<link href="/packages/fileinput/fileinput.css" rel="stylesheet">

<style>
    #currency {
        text-align: center;
    }
    .form-group input[readonly] {
        background-color: white; /* Opcionalno: stilizacija readonly inputa */
    }

    .button-right{
        display: flex;
        justify-content: flex-end;
    }

    #invoices {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .invoice {
        display: flex;
        flex-direction: column;
        padding: 10px;
        border: 1px solid #ddd;
        background-color: #f9f9f9;
        min-width: 200px;
        margin-bottom: 10px;
    }

    .invoice p {
        margin: 0;
        padding: 5px 0;
    }

    .total-value {
        flex-basis: 100%;
        padding: 10px;
        border-top: 2px solid #333;
        margin-top: 10px;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('footer_scripts'); ?>
<script type="text/javascript" src="<?php echo e(url('/theme/plugins/bootstrap-filestyle/js/bootstrap-filestyle.min.js')); ?>"></script>
<script src="/theme/plugins/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js"></script>
<script src="/packages/fileinput/fileinput.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.js"></script>

<script>
    $(function () {

        $('select').select2({
            minimumResultsForSearch: -1
        });

        $('#date_start').datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            todayHighlight: true
        });

        // FRONTEND VALIDACIJA
        $('#entity-form').validate({
            rules: {
                date_start:{
                   required: true
                },
                price: {
                    required: true,
                    number: true, // Osigurava da je unos broj
                    min: 0       // Osigurava da je broj veći od 0
                },
                reference:{
                    required: false
                }
            },
            messages:{
                date_start: {
                    required: "Datum je obavezan",
                },
                price: {
                    required: "Iznos je obavezan",
                    number: "Unos mora biti broj",
                    min: "Cena mora biti veća od 0"
                }
            }
        });

        function updateInvoices(id) {
            $.ajax({
                url: "<?php echo e(route('get_unpaid_invoices')); ?>",
                type: "POST",
                data: { id: id }, 
                dataType: "json",
                success: function(response) {
                    var invoices = response.invoices;
                var invoicesDiv = $('#invoices');
                invoicesDiv.empty(); // Očisti trenutni sadržaj

                var totalValue = 0; // Varijabla za ukupnu vrednost

                // Dodaj nove fakture
                invoices.forEach(function(invoice) {
                    var formattedDate = new Date(invoice.created_at).toLocaleDateString('hr-HR', {
                        day: '2-digit',
                        month: '2-digit',
                        year: 'numeric'
                    });

                    var invoiceHtml = `
                        <div class="invoice">
                            <p><strong>ID:</strong> ${invoice.id_invoice}</p>
                            <p><strong>Vrednost:</strong> ${invoice.debt} ${invoice.currency}</p>
                            <p><strong>Datum kreiranja:</strong> ${formattedDate}</p>
                        </div>
                    `;
                    invoicesDiv.append(invoiceHtml);

                    // Saberi vrednost
                    totalValue += parseFloat(invoice.debt); // Pretvaranje u float za sabiranje
                });

                // Prikazi ukupnu vrednost
                var totalHtml = `<div class="total-value button-right"><p><strong>Ukupna vrednost dugovanja:</strong> ${totalValue.toFixed(2)} ${invoices[0]?.currency || 'N/A'}</p></div>`;
                invoicesDiv.append(totalHtml);
                },
                error: function(xhr, status, error) {
                    console.error(error);
                }
            });
        }

        
        $('#companySelect').on('change', function() {
            var selectedOption = $(this).find('option:selected');
            var currency = selectedOption.data('currency');
            var companyId = selectedOption.val();

            // Ažuriramo skriveno polje
            $('#currency').val(currency);

            // Prikažemo dodatne sekcije
            if ($(this).val() !== "0") {
                $('#additional-section').show();
                $('#submit-section').show();

                if (companyId && companyId != 0) {
                    updateInvoices(companyId);
                }
            } else {
                $('#additional-section').hide();
                $('#submit-section').hide();
            }
        });
    });
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH /opt/cms/resources/views/truck/finance/partials/form.blade.php ENDPATH**/ ?>