

<?php $__env->startSection('content'); ?>
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
.autocomplete-active { background: #0d6efd !important; color: white !important; }
.input-focus { border: 2px solid #0d6efd !important; box-shadow: 0 0 0 0.2rem rgba(13,110,253,.25); }
.suggestions { position: absolute; z-index: 2000; max-height: 220px; overflow: auto; background: white; border: 1px solid #ddd; width: 100%; border-radius: 4px; }
.suggestion-item { padding:8px 10px; cursor:pointer; }
.suggestion-item.active { background:#e9f2ff; }
.position-relative { position: relative; }
</style>

<div class="container-fluid">
    <h4 class="mb-3">Payment Entry</h4>

    <div class="row mb-2">
        <div class="col-md-3">
            <label>Date</label>
            <input type="date" id="payment_date" class="form-control input-focus" value="<?php echo e(date('Y-m-d')); ?>">
        </div>

        
        <div class="col-md-4 position-relative">
            <label>Line (type and press Enter)</label>
            <input type="text" id="lineInput" class="form-control input-focus" placeholder="Type line" autocomplete="off">
            <div id="lineSuggestions" class="suggestions d-none"></div>
        </div>

        
        <div class="col-md-3 position-relative">
            <label>Supplier</label>
            <input type="text" id="person_search" class="form-control input-focus" placeholder="Search Person" autocomplete="off">
            <div id="personSuggestions" class="suggestions d-none"></div>
        </div>
    </div>

    <div class="row mb-3">
        <div class="col-md-6">
            <table class="table table-bordered">
                <tr><th>Total Amount</th><td id="total_amount">0.00</td></tr>
                <tr><th>Paid Till Now</th><td id="paid_amount_total">0.00</td></tr>
                <tr><th>Balance</th><td id="balance_amount" class="fw-bold text-danger">0.00</td></tr>
            </table>
        </div>
    </div>

    <div class="row mb-2">
        <div class="col-md-6">
            <label>Description</label>
            <input type="text" id="description" class="form-control input-focus" value="Giving cash to party">
        </div>

        <div class="col-md-3">
            <label>Payment Amount</label>
            <input type="number" id="paid_amount" class="form-control input-focus" placeholder="Enter amount & press Enter">
        </div>
    </div>

    <input type="hidden" id="line_id">
    <input type="hidden" id="supplier_id">
    <input type="hidden" id="payment_type" value="purchase">

    <input type="hidden" id="line_name">
<input type="hidden" id="supplier_name">

</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(function(){

    const csrf = $('meta[name="csrf-token"]').attr('content');

    /** Helper: debounce */
    function debounce(fn, delay=300){
        let timer;
        return function(...args){
            clearTimeout(timer);
            timer = setTimeout(()=> fn.apply(this,args), delay);
        }
    }

    /** General autocomplete */
    function setupAutocomplete(input, suggestionsDiv, url, onSelect, method='GET'){
        let selectedIndex = -1;

    function renderList(items){
    suggestionsDiv.empty();
    selectedIndex = -1;

    if(items.length === 0){
        const noData = $('<div>')
            .addClass('suggestion-item text-muted')
            .css({ cursor: 'not-allowed' })
            .text('No data found');

        suggestionsDiv.append(noData);
        suggestionsDiv.removeClass('d-none');
        return;
    }

    items.forEach((item, i)=>{
        const div = $('<div>')
            .addClass('suggestion-item')
            .text(item.name)
            .attr('data-id', item.id);

        if(i === selectedIndex) div.addClass('active');
        suggestionsDiv.append(div);
    });

    suggestionsDiv.removeClass('d-none');
}


        input.on('input', debounce(function(){
            let query = $(this).val();
            if(query.length < 1){
                suggestionsDiv.addClass('d-none');
                selectedIndex = -1;
                return;
            }

            const requestData = method==='POST' ? {_token: csrf, q: query} : {q: query};

            $.ajax({
                url: url,
                type: method,
                data: requestData,
                success: function(data){
                    renderList(data);
                }
            });
        }));

        input.on('keydown', function(e){
            const items = suggestionsDiv.children('.suggestion-item');
            if(items.length === 0) return;

            if(e.key === 'ArrowDown'){
                e.preventDefault();
                selectedIndex = (selectedIndex +1) % items.length;
                items.removeClass('active').eq(selectedIndex).addClass('active');
            } else if(e.key === 'ArrowUp'){
                e.preventDefault();
                selectedIndex = (selectedIndex -1 + items.length) % items.length;
                items.removeClass('active').eq(selectedIndex).addClass('active');
            }else if(e.key === 'Enter'){
    e.preventDefault();
    const sel = selectedIndex>=0 ? items.eq(selectedIndex) : items.eq(0);

    // ❌ block if no data
    if(!sel.data('id')) return;

    const id = sel.data('id');
    const name = sel.text();
    input.val(name);
    onSelect(id, name);
    suggestionsDiv.addClass('d-none');
    selectedIndex = -1;

    if(input.attr('id') === 'person_search'){
        fetchBalances();
    }

            }
        });

        suggestionsDiv.on('click', '.suggestion-item', function(){
    if(!$(this).data('id')) return; // ❌ block no-data click

    const id = $(this).data('id');
    const name = $(this).text();
    input.val(name);
    onSelect(id, name);
    suggestionsDiv.addClass('d-none');
    selectedIndex = -1;

    if(input.attr('id') === 'person_search'){
        fetchBalances();
    }
});


        $(document).on('click', function(e){
            if(!$(e.target).closest(input).length && !$(e.target).closest(suggestionsDiv).length){
                suggestionsDiv.addClass('d-none');
                selectedIndex = -1;
            }
        });
    }

    /** LINE autocomplete */
    setupAutocomplete(
        $('#lineInput'),
        $('#lineSuggestions'),
        "<?php echo e(route('user.purchase_payments.lines.search')); ?>",
        function(id, name){
            $('#line_id').val(id);
            $('#line_name').val(name);
            $('#person_search').focus();
        }
    );

    /** SUPPLIER autocomplete */
    setupAutocomplete(
        $('#person_search'),
        $('#personSuggestions'),
        "<?php echo e(route('user.purchase_payments.searchperson')); ?>",
        function(id, name){
            $('#supplier_id').val(id);
            $('#supplier_name').val(name);
            $('#description').focus();
        },
        'get'
    );

    /** Fetch balances based on selected date, line, and supplier */
    function fetchBalances(){
        const line_id = $('#line_id').val();
        const supplier_id = $('#supplier_id').val();
        const payment_date = $('#payment_date').val();

        if(!line_id || !supplier_id || !payment_date) return;

        $.post("<?php echo e(route('user.purchase_payments.getbalance')); ?>", {
            _token: csrf,
            line_id: line_id,
            supplier_id: supplier_id,
            payment_date: payment_date
        }, function(res){
            $('#total_amount').text(parseFloat(res.total).toFixed(2));
            $('#paid_amount_total').text(parseFloat(res.paid).toFixed(2));
            $('#balance_amount').text(parseFloat(res.balance).toFixed(2));
        });
    }

    /** Move focus from description to paid amount */
    $('#description').on('keydown', function(e){
        if(e.key === 'Enter'){
            e.preventDefault();
            $('#paid_amount').focus();
        }
    });

    /** Save payment on Enter */
    $('#paid_amount').on('keydown', function(e){
        if(e.key === 'Enter'){
            e.preventDefault();

            const data = {
                _token: csrf,
                payment_date: $('#payment_date').val(),
                line_id: $('#line_id').val(),
                line_name: $('#line_name').val(),
                supplier_name: $('#supplier_name').val(),
                supplier_id: $('#supplier_id').val(),
                description: $('#description').val(),
                paid_amount: $('#paid_amount').val(),
                payment_type: $('#payment_type').val()
            };

            $.post("<?php echo e(route('user.purchase_payments.store')); ?>", data, function(res){
                alert('Payment saved successfully!');
                $('#lineInput, #person_search, #description, #paid_amount').val('');
                $('#line_id, #supplier_id').val('');
                $('#lineInput').focus();
                $('#total_amount, #paid_amount_total, #balance_amount').text('0.00');
            });
        }
    });

    /** Re-fetch balances if date changes */
    $('#payment_date').on('change', fetchBalances);
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layout.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\mandi\resources\views/user/purchase_payments/index.blade.php ENDPATH**/ ?>