<?php $__env->startSection('head_title', __('Nove Ulazne Fakture') . ' - ' . __('Fakture')); ?>

<?php $__env->startPush('head_links'); ?>

<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>

<?php echo $__env->make('_layout.partials.breadcrumbs', [
    'pageTitle' => __("Ulazne Fakture"),
    'breadcrumbs' => [
        route('truck.procurement') => __('Ulazne Fakture')
    ]
], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<style>
    
    .dropdown-menu {
        padding: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        border-radius: 10px;
    }
    .dropdown-menu .dropdown-item {
        margin-bottom: 5px;
    }
    .dropdown-menu .dropdown-item:last-child {
        margin-bottom: 0;
    }
    .dropdown-menu .dropdown-item i {
        margin-right: 8px;
    }

    #entity-list-table thead th:first-child.sorting::after,
    #entity-list-table thead th:first-child.sorting_asc::after,
    #entity-list-table thead th:first-child.sorting_desc::after {
        display: none;
    }

    #entity-list-table th:nth-child(2),
    #entity-list-table td:nth-child(2) {
        max-width: 200px; 
        overflow: hidden;
        text-overflow: ellipsis; 
        white-space: nowrap; 
    }

    th, td {
        white-space: nowrap;
    }
    
    .date-highlight {
        padding: 5px;
        border-radius: 5px;
        display: inline-block;
    }
    .date-red {
        background-color: red;
        color: white;
    }
    .date-yellow {
        background-color: yellow;
        color: black;
    }
    .date-green {
        background-color: green;
        color: white;
    }
    .summary-box {
        padding: 20px;
        border-radius: 10px;
        color: black;
        text-align: center;
        font-size: 20px;
    }

    .summary-box {
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            background: #f8f9fa;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

    .summary-eur {
        background-color: white;
    }
    .summary-km {
        background-color: white;
    }
    .summary-rsd {
        background-color: white;
    }

    .card-option {
        cursor: pointer;
        border-radius: 10px;
        border: 2px solid transparent;
    }
    .card-option:hover {
        border-color: #007bff;
    }
    .card-option.active {
        border-color: #007bff;
        background-color: #e9ecef;
    }
    .input-amount {
        display: none;
        margin-top: 10px;
    }
    
    .modal-content {
        border-radius: 10px !important;
    }

    .rounded-swal {
        border-radius: 10px;
    }

    .debt-debt {
        color: red;
    }

    .modal-values {
        border-top: 1px solid #ddd; /* Linija iznad */
        padding-top: 10px;
        padding-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        text-align: center;
    }

    .modal-values div {
        flex: 1;
        padding: 0 3px;
    }

</style>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-heading d-flex justify-content-between">
                <div class="card-heading-title">
                    <h3 class="card-title"><?php echo app('translator')->get('Lista ulaznih faktura'); ?></h3>
                </div>
                <div class="card-heading-actions">
                    <a href="<?php echo e(route('truck.invoices_create_procurement')); ?>" class="btn btn-primary">
                        <i class="fa fa-plus"></i>
                        <?php echo app('translator')->get('Kreiraj fakturu'); ?>
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="entity-list-table" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <th class=""><?php echo app('translator')->get('ID'); ?></th>
                                <th class=""><?php echo app('translator')->get('Firma'); ?></th>
                                <th class=""><?php echo app('translator')->get('Datum'); ?></th>
                                <th class=""><?php echo app('translator')->get('Rok placanja'); ?></th>
                                <th class=""><?php echo app('translator')->get('Za uplatu'); ?></th>
                                <th></th>
                                <th class="disabled-sorting text-right"><?php echo app('translator')->get('Opcije'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
    
                        </tbody>
                        
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="summary-box summary-km">
            <div>Fakture u valuti KM</div>
            <div class="text-danger"><?php echo app('translator')->get('Ukupno'); ?>: <span id="pending-km">0</span> KM</div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="summary-box summary-eur">
            <div>Fakture u valuti EUR</div>
            <div class="text-danger"><?php echo app('translator')->get('Ukupno'); ?>: <span id="pending-eur">0</span> EUR</div>
        </div>
    </div>
</div>

<!-- Modal za pregled fakture-->
<div class="modal fade" id="invoiceModal" tabindex="-1" role="dialog" aria-labelledby="invoiceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div style="background-color: white !important;" class="modal-header">
                <h5 style="color:black;" class="modal-title" id="invoiceModalLabel">Pregled Fakture</h5>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Zatvori</button>
            </div>
            <div class="modal-body">
                <iframe id="invoiceFrame" src="" style="width: 100%; height: 800px; border: none;"></iframe>
            </div>
            <div class="modal-footer">
                
                
            </div>
        </div>
    </div>
</div>

<!-- Modal za placanje fakture -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="invoiceModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div style="text-align:center!important; background-color: white !important;" class="modal-header">
                <h5 style="color:black;" class="modal-title" id="invoiceModalLabel">Način plaćanja fakture:</h5>
                <h2 class="invoice_id"></h2>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card card-option active" id="fullPaymentOption">
                            <div class="card-body text-center">
                                Pun iznos fakture
                            </div>
                        </div>
                    </div>
                    <div style="text-align: center !important;" class="col-md-6">
                        <div class="card card-option" id="partialPaymentOption">
                            <div class="card-body text-center">
                                Djelimično plaćanje
                            </div>
                        </div>
                        <div class="input-amount" id="amountInputContainer" style="display: flex; align-items: center; justify-content: center; text-align: center;">
                            <label for="amountInput" style="margin-right: 10px;">Iznos:</label>
                            <input type="text" class="form-control" id="amountInput" name="amountInput" style="width: 100px; margin-right: 10px; text-align: center;" placeholder="100.00" step="0.001">
                            <span class="input-group-text currency"></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-values">
                
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Zatvori</button>
                <button type="button" class="btn btn-success" id="saveBtn">Sačuvaj</button>
            </div>
        </div>
    </div>
</div>


<?php $__env->stopSection(); ?>

<?php $__env->startPush('footer_scripts'); ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>


<script>
$(function() {

    // $('#generate-pdf').on('click', function() {
    //     var filteredData = table.rows({ filter: 'applied' }).data().toArray();
        
    //     $.ajax({
    //         url: '/generate-pdf',
    //         type: 'POST',
    //         data: { data: filteredData },
    //         success: function(response) {
    //             var link = document.createElement('a');
    //             link.href = response.url;
    //             link.download = 'tabela.pdf';
    //             document.body.appendChild(link);
    //             link.click();
    //             document.body.removeChild(link);
    //         }
    //     });
    // });
    
    var blade = {
        datatablesAjaxUrl: "<?= route('truck.invoices_datatable_procurement'); ?>",
    };

    // Function to update summary values
    function updateSummary() {
        $.ajax({
            url: "<?php echo e(route('truck.invoices_summary_procurement')); ?>",
            type: "GET",
            dataType: "json",
            success: function(response) {
                // Update summary values for KM
                $('#pending-km').text(response.pending.km);
                // Update summary values for EUR
                $('#pending-eur').text(response.pending.eur);
            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });
    }

    // Call the updateSummary function on document ready
    updateSummary();

    // DATATABLES
    $('#entity-list-table').DataTable({
        "responsive": true,
        "autoWidth": true,
        "processing": true,
        "serverSide": true,
        "language": {
            "search": "Unesite broj fakture:"
        },
        "ajax": {
            url: blade.datatablesAjaxUrl,
            type: "post",
        },
        "columns": [
            {"data": "id_invoice", orderable: false, "className": "", responsivePriority: 1},
            {"data": "company", orderable: false, "className": "", responsivePriority: 3},
            {"data": "date_start", orderable: false, searchable: false, "className": "", responsivePriority: 4},
            {"data": "date_end", orderable: false, searchable: false, "className": "", responsivePriority: 2},
            {"data": "debt", orderable: false, searchable: false, "className": "", responsivePriority: 5},
            {"data": "paids", orderable: false, searchable: false, "className": "", responsivePriority: 6},
            {"data": "actions", orderable: false, searchable: false, "className": "text-right", responsivePriority: 7}
        ],
        "order": [[0, "asc"]],
        "rowCallback": function(row, data, index) {
            var today = moment();
            var dateEnd = moment(data.date_end, 'DD-MM-YYYY'); // Adjust the date format to match your data

            // Reset any previous highlighting
            $('td:eq(3)', row).removeClass('date-red date-yellow date-green');

            // Add the appropriate class based on the date condition
            if (data.status == 1) {
                $('td:eq(3)', row).html('<span class="date-highlight date-green">' + data.date_end + '</span>');
            } else if (today.isSameOrAfter(dateEnd, 'day')) {
                $('td:eq(3)', row).html('<span class="date-highlight date-red">' + data.date_end + '</span>');
            } else if (today.isSameOrAfter(dateEnd.subtract(7, 'days'), 'day')) {
                $('td:eq(3)', row).html('<span class="date-highlight date-yellow">' + data.date_end + '</span>');
            } else {
                $('td:eq(3)', row).html(data.date_end);
            }

            if (parseFloat(data.debt) < parseFloat(data.price)) {
                $('td:eq(4)', row).addClass('debt-debt')
                                .attr('title', 'Iznos fakture ' + data.price)
                                .tooltip();
            } else {
                $('td:eq(4)', row).removeClass('debt-debt')
                                .removeAttr('title')
                                .tooltip('dispose');
            }
        },
        "initComplete": function() {
            $('[data-toggle="tooltip"]').tooltip();
        }
    });


    // DELETE MODAL
    let options = {
        "title": "Obriši",
        "liveSelector": '[data-action="delete"]'
    };

    $('#entity-list-table').questionPop(options).on('success.qp', function() {
        $('#entity-list-table').DataTable().draw('page');
        updateSummary(); // Update the summary after deletion
    });

    //MODAL ZA POTVRDU PLACANJA
    $(document).ready(function() {
        var id;
        var idInvoice;
        var price;
        var pricePart;
        var amount;
        var debt;
        var currency;
        $(document).on('click', '#openModalBtn', function() {

            id = $(this).data('id');
            idInvoice = $(this).data('id-invoice');
            price = $(this).data('price');
            pricePart = $(this).data('price-part');
            debt = $(this).data('debt');
            currency = $(this).data('currency');

            amount = price - (parseFloat(pricePart) || 0);


            $('#myModal').modal('show');

            $('.invoice_id').text(idInvoice);
            $('.currency').text(currency);
            $('#amountInput').val(amount.toFixed(2));

            console.log(debt, price);

            if (parseFloat(debt) < parseFloat(price)) {

                
                var modalValuesHtml = `
                    <div>Ukupan iznos : ${price}</div>
                    <div>Uplaćeno : ${pricePart}</div>
                    <div>Dug : ${debt}</div>
                `;
                $('.modal-values').html(modalValuesHtml);
            }

            $('#amountInputContainer').hide(); //sakrij cenu za odredjen iznos
        });

            $('#fullPaymentOption').click(function() {
                $(this).addClass('active');
                $('#partialPaymentOption').removeClass('active');
                $('#amountInputContainer').hide();
            });

            $('#partialPaymentOption').click(function() {
                $(this).addClass('active');
                $('#fullPaymentOption').removeClass('active');
                $('#amountInputContainer').show();
            });

            $('#saveBtn').click(function() {
                var enteredAmount = parseFloat($('#amountInput').val());
                var isFullPayment = !$('#partialPaymentOption').hasClass('active');

                var data = {
                    id: id,
                    isFullPayment: isFullPayment,
                    enteredAmount: isFullPayment ? 0 : enteredAmount // Ako je isFullPayment true, enteredAmount postavljamo na 0
                };

                if (!isFullPayment && enteredAmount > amount) {
                    Swal.fire({
                        title: 'Greška!',
                        text: 'Uneli ste iznos koji premašuje iznos dugovanja.',
                        footer: 'Iznos dugovanja po fakturi ' + amount.toFixed(2) + ' ' + currency,
                        customClass: {
                            popup: 'rounded-swal'
                        }
                    });
                    return;
                }

                console.log(isFullPayment ? 'Plaćanje u celosti' : 'Određeni iznos za plaćanje:', isFullPayment ? 'N/A' : enteredAmount);
                console.log('bororororor');
                $.ajax({
                    url: '<?= route('truck.invoices_paid_procurement'); ?>',
                    method: 'POST',
                    data: data,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        console.log(response);
                        $('#myModal').modal('hide');
                        $('#entity-list-table').DataTable().draw('page');
                        updateSummary();
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                        // Dodajte kod za obradu greške ako je potrebno
                    }
                });
            });


    });

    
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('_layout.layout', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/drventar/vd-trans.com/fakture/resources/views/truck/procurement/index.blade.php ENDPATH**/ ?>