<?php $__env->startSection('title', __('New Sale')); ?>

<?php $__env->startSection('content'); ?>
<form method="POST" action="<?php echo e(route('invoices.store')); ?>" id="sale-form">
    <?php echo csrf_field(); ?>
    <div class="row g-3">
        <div class="col-lg-8">
            <div class="card"><div class="card-body p-3 p-md-4">
                <div class="d-flex justify-content-between mb-3"><h6><?php echo e(__('Sale Items')); ?></h6><button type="button" id="add-row" class="btn btn-light btn-sm"><i class="fa-solid fa-plus"></i> <?php echo e(__('Add Item')); ?></button></div><input id="product-search" class="form-control mb-3" placeholder="<?php echo e(__('Search products by name or SKU')); ?>">
                <div class="table-responsive"><table class="table" id="items-table"><thead><tr><th><?php echo e(__('Product')); ?></th><th><?php echo e(__('Stock')); ?></th><th><?php echo e(__('Qty')); ?></th><th><?php echo e(__('Price')); ?></th><th><?php echo e(__('Total')); ?></th><th></th></tr></thead><tbody></tbody></table></div>
            </div></div>
        </div>
        <div class="col-lg-4"><div class="card"><div class="card-body p-4">
            <label class="form-label"><?php echo e(__('Sale Type')); ?></label>
            <select name="sale_type" id="sale-type" class="form-select mb-3"><option value="retail"><?php echo e(__('Retail')); ?></option><option value="wholesale"><?php echo e(__('Wholesale')); ?></option></select>
            <label class="form-label"><?php echo e(__('Customer')); ?></label>
            <select name="customer_id" id="customer-id" class="form-select mb-2"><option value=""><?php echo e(__('Walk-in / No Account')); ?></option><?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($customer->id); ?>"><?php echo e($customer->name); ?> · <?php echo e(ucfirst($customer->type)); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select>
            <div id="walk-in-details" class="row g-2 mb-3"><div class="col-7"><input name="walk_in_name" class="form-control" placeholder="<?php echo e(__('Walk-in Name')); ?>"></div><div class="col-5"><input name="walk_in_phone" class="form-control" placeholder="<?php echo e(__('Phone')); ?>"></div></div>
            <label class="form-label"><?php echo e(__('Currency')); ?></label>
            <select name="currency_code" class="form-select mb-3"><?php $__currentLoopData = $currencies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $currency): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($currency->code); ?>" <?php if($currency->is_default): echo 'selected'; endif; ?>><?php echo e($currency->code); ?> — <?php echo e($currency->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?></select>
            <label class="form-label"><?php echo e(__('Date')); ?></label><input type="date" name="invoice_date" class="form-control mb-3" value="<?php echo e(now()->toDateString()); ?>">
            <label class="form-label"><?php echo e(__('Discount')); ?></label><input type="number" name="discount" id="discount" class="form-control mb-3" value="0" min="0" step="0.01">
            <hr><div class="d-flex justify-content-between"><span><?php echo e(__('Subtotal')); ?></span><strong id="subtotal">0.00</strong></div><div class="d-flex justify-content-between mt-2 fs-5"><strong><?php echo e(__('Total')); ?></strong><strong id="grand-total">0.00</strong></div>
            <label class="form-label mt-3"><?php echo e(__('Amount Paid Now')); ?></label><input type="number" name="paid_amount" class="form-control" value="0" min="0" step="0.01">
            <select name="payment_method" class="form-select mt-2"><option value="cash"><?php echo e(__('Cash')); ?></option><option value="bank"><?php echo e(__('Bank')); ?></option><option value="mobile"><?php echo e(__('Mobile Money')); ?></option></select>
            <label class="form-label mt-3"><?php echo e(__('Notes')); ?></label><textarea name="notes" class="form-control" rows="2"></textarea>
            <button class="btn btn-success w-100 mt-4"><i class="fa-solid fa-check me-1"></i><?php echo e(__('Create Invoice')); ?></button>
        </div></div></div>
    </div>
</form>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
const products = <?php echo json_encode($productsForSale, 15, 512) ?>;
let rowNo = 0;
const tbody = document.querySelector('#items-table tbody');
const typeSelect = document.querySelector('#sale-type');
let productTerm = '';

function updateTotals() {
    let subtotal = 0;
    document.querySelectorAll('#items-table tbody tr').forEach((row) => {
        const product = products.find((item) => item.id == row.querySelector('.product').value);
        const quantity = Number(row.querySelector('.quantity').value) || 0;
        const price = product ? (typeSelect.value === 'wholesale' ? product.wholesale : product.retail) : 0;
        row.querySelector('.stock').textContent = product ? `${product.stock} <?php echo e(__('available')); ?>` : '—';
        row.querySelector('.price').textContent = price.toFixed(2);
        const lineTotal = quantity * price;
        row.querySelector('.line-total').textContent = lineTotal.toFixed(2);
        subtotal += lineTotal;
    });
    const total = Math.max(0, subtotal - (Number(document.querySelector('#discount').value) || 0));
    document.querySelector('#subtotal').textContent = subtotal.toFixed(2);
    document.querySelector('#grand-total').textContent = total.toFixed(2);
}

function addRow() {
    const index = rowNo++;
    const options = ['<option value=""><?php echo e(__('Select product')); ?></option>', ...products.filter((product)=>`${product.name} ${product.sku}`.toLowerCase().includes(productTerm)).map((product) => `<option value="${product.id}">${product.name} (${product.sku})</option>`)].join('');
    tbody.insertAdjacentHTML('beforeend', `<tr><td><select name="items[${index}][product_id]" class="form-select product" required>${options}</select></td><td class="stock text-muted">—</td><td><input name="items[${index}][quantity]" class="form-control quantity" type="number" step="0.01" min="0.01" value="1" required></td><td class="price">0.00</td><td class="line-total">0.00</td><td><button type="button" class="btn btn-light btn-sm remove text-danger"><i class="fa-solid fa-xmark"></i></button></td></tr>`);
    const row = tbody.lastElementChild;
    row.querySelector('.product').addEventListener('change', updateTotals);
    row.querySelector('.quantity').addEventListener('input', updateTotals);
    row.querySelector('.remove').addEventListener('click', () => { row.remove(); updateTotals(); });
}

document.querySelector('#add-row').addEventListener('click', addRow);
typeSelect.addEventListener('change', updateTotals);
document.querySelector('#discount').addEventListener('input', updateTotals);
document.querySelector('#customer-id').addEventListener('change', (event) => { document.querySelector('#walk-in-details').style.display = event.target.value ? 'none' : 'flex'; });
document.querySelector('#product-search').addEventListener('input', (event) => { productTerm=event.target.value.toLowerCase(); const previous=[...tbody.querySelectorAll('.product')].map(x=>x.value); tbody.innerHTML=''; rowNo=0; previous.forEach(()=>addRow()); });
addRow();
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\TradeERP\resources\views/invoices/create.blade.php ENDPATH**/ ?>