
<?php $__env->startSection('title', 'Vendor Cash Flow Report'); ?>

<?php $__env->startSection('content'); ?>
<div class="page-content">
    <div class="row">
        <div class="col-md-12 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h6 class="card-title mb-0">Vendor Cash Flow Report</h6>
                        <button class="btn btn-info btn-sm" id="refresh-stats">
                            <i class="fas fa-sync-alt me-1"></i> Refresh Stats
                        </button>
                    </div>

                    
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card border-start border-secondary border-4 shadow-sm">
                                <div class="card-body d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-muted small">Vendors</div>
                                        <h4 class="mb-0 fw-bold" id="stat-vendors">—</h4>
                                    </div>
                                    <i class="fas fa-truck fa-2x text-secondary opacity-50"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card border-start border-primary border-4 shadow-sm">
                                <div class="card-body d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-muted small">Total PO Value</div>
                                        <h4 class="mb-0 fw-bold" id="stat-po-value">—</h4>
                                    </div>
                                    <i class="fas fa-file-invoice-dollar fa-2x text-primary opacity-50"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card border-start border-success border-4 shadow-sm">
                                <div class="card-body d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-muted small">Total Paid</div>
                                        <h4 class="mb-0 fw-bold" id="stat-paid">—</h4>
                                    </div>
                                    <i class="fas fa-check-double fa-2x text-success opacity-50"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card border-start border-danger border-4 shadow-sm">
                                <div class="card-body d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="text-muted small">Outstanding</div>
                                        <h4 class="mb-0 fw-bold" id="stat-outstanding">—</h4>
                                    </div>
                                    <i class="fas fa-hourglass-half fa-2x text-danger opacity-50"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    
                    <div class="row mb-3 g-2">
                        <div class="col-md-2">
                            <label class="form-label">PO Date From</label>
                            <input type="date" class="form-control form-control-sm" id="f-date-from" value="<?php echo e($dateFrom); ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">PO Date To</label>
                            <input type="date" class="form-control form-control-sm" id="f-date-to" value="<?php echo e($dateTo); ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Vendor</label>
                            <select class="form-select form-select-sm" id="f-vendor">
                                <option value="">All Vendors</option>
                                <?php $__currentLoopData = $vendors; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $vendor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($vendor->id); ?>"><?php echo e($vendor->name); ?><?php echo e($vendor->code ? ' ('.$vendor->code.')' : ''); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                        <div class="col-md-4 d-flex align-items-end gap-2">
                            <button class="btn btn-primary btn-sm" id="btn-apply">
                                <i class="fas fa-search me-1"></i> Apply
                            </button>
                            <button class="btn btn-secondary btn-sm" id="btn-reset">Reset</button>
                            <button class="btn btn-success btn-sm" id="btn-export">
                                <i class="fas fa-download me-1"></i> Export CSV
                            </button>
                        </div>
                    </div>

                    
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover table-sm" id="cashflow-table">
                            <thead>
                                <tr>
                                    <th>Vendor Name</th>
                                    <th>Code</th>
                                    <th class="text-center">POs</th>
                                    <th class="text-end">Total PO Amount</th>
                                    <th class="text-end">Total Paid</th>
                                    <th class="text-end">Outstanding</th>
                                    <th class="text-center">Payment %</th>
                                    <th>Last Payment</th>
                                </tr>
                            </thead>
                            <tfoot class="table-secondary fw-bold">
                                <tr>
                                    <th colspan="3">Totals</th>
                                    <th class="text-end" id="foot-po">—</th>
                                    <th class="text-end" id="foot-paid">—</th>
                                    <th class="text-end" id="foot-outstanding">—</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function () {
    var fmt = function(v) {
        return parseFloat(v || 0).toLocaleString('en-PK', { minimumFractionDigits: 2 });
    };

    var table = $('#cashflow-table').DataTable({
        processing: true,
        serverSide: false,
        ajax: {
            url: "<?php echo e(route('reports.vendor-cash-flow')); ?>",
            data: function (d) {
                d.date_from = $('#f-date-from').val();
                d.date_to   = $('#f-date-to').val();
                d.vendor_id = $('#f-vendor').val();
            }
        },
        columns: [
            { data: 'vendor_name',      name: 'vendor_name' },
            { data: 'vendor_code',      name: 'vendor_code' },
            { data: 'po_count',         name: 'po_count', className: 'text-center' },
            { data: 'total_po_amount',  name: 'total_po_amount', className: 'text-end',
              render: function(d) { return fmt(d); } },
            { data: 'total_paid',       name: 'total_paid', className: 'text-end',
              render: function(d) { return fmt(d); } },
            { data: 'outstanding',      name: 'outstanding', className: 'text-end',
              render: function(d) {
                  var val = parseFloat(d || 0);
                  var cls = val > 0 ? 'text-danger fw-bold' : 'text-success fw-bold';
                  return '<span class="' + cls + '">' + fmt(d) + '</span>';
              }},
            { data: null, orderable: false, className: 'text-center',
              render: function(row) {
                  if (!row.total_po_amount || parseFloat(row.total_po_amount) === 0) return '—';
                  var pct = Math.min(100, (parseFloat(row.total_paid) / parseFloat(row.total_po_amount)) * 100);
                  var cls = pct >= 100 ? 'bg-success' : (pct >= 50 ? 'bg-warning' : 'bg-danger');
                  return '<div class="progress" style="height:18px;min-width:80px">' +
                      '<div class="progress-bar ' + cls + '" style="width:' + pct.toFixed(1) + '%">' +
                      pct.toFixed(1) + '%</div></div>';
              }},
            { data: 'last_payment_date', name: 'last_payment_date',
              render: function(d) { return d ? d.substring(0, 10) : '<span class="text-muted">No payments</span>'; },
              orderable: false },
        ],
        order: [[5, 'desc']],
        pageLength: 25,
        drawCallback: function() {
            var api = this.api();
            var data = api.rows().data();
            var totalPO = 0, totalPaid = 0, totalOut = 0;
            data.each(function(row) {
                totalPO  += parseFloat(row.total_po_amount || 0);
                totalPaid += parseFloat(row.total_paid || 0);
                totalOut  += parseFloat(row.outstanding || 0);
            });
            $('#foot-po').text(fmt(totalPO));
            $('#foot-paid').text(fmt(totalPaid));
            $('#foot-outstanding').html('<span class="text-danger">' + fmt(totalOut) + '</span>');
        }
    });

    function loadStats() {
        $.get("<?php echo e(route('reports.vendor-cash-flow-stats')); ?>", {
            date_from: $('#f-date-from').val(),
            date_to:   $('#f-date-to').val(),
            vendor_id: $('#f-vendor').val()
        }, function (res) {
            if (res.success && res.data) {
                $('#stat-vendors').text(res.data.vendor_count || 0);
                $('#stat-po-value').text(fmt(res.data.total_po_amount));
                $('#stat-paid').text(fmt(res.data.total_paid));
                $('#stat-outstanding').text(fmt(res.data.total_outstanding));
            }
        });
    }

    $('#btn-apply, #refresh-stats').on('click', function () {
        table.ajax.reload();
        loadStats();
    });

    $('#btn-reset').on('click', function () {
        $('#f-date-from').val('<?php echo e($dateFrom); ?>');
        $('#f-date-to').val('<?php echo e($dateTo); ?>');
        $('#f-vendor').val('');
        table.ajax.reload();
        loadStats();
    });

    $('#btn-export').on('click', function () {
        var rows = table.rows().data();
        if (rows.length === 0) { alert('No data to export.'); return; }
        var csv = ['Vendor Name,Code,POs,Total PO Amount,Total Paid,Outstanding,Last Payment'];
        rows.each(function (row) {
            csv.push([
                '"' + (row.vendor_name || '') + '"',
                '"' + (row.vendor_code || '') + '"',
                row.po_count || 0,
                parseFloat(row.total_po_amount || 0).toFixed(2),
                parseFloat(row.total_paid || 0).toFixed(2),
                parseFloat(row.outstanding || 0).toFixed(2),
                row.last_payment_date ? row.last_payment_date.substring(0, 10) : ''
            ].join(','));
        });
        var blob = new Blob([csv.join('\n')], { type: 'text/csv' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'vendor-cash-flow-' + new Date().toISOString().slice(0,10) + '.csv';
        link.click();
    });

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

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\reports\vendor-cash-flow.blade.php ENDPATH**/ ?>