<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
require_once '../includes/invoice_number.php';

$clients = $conn->query("SELECT id, name FROM clients WHERE status = 1 ORDER BY name");
$products = $conn->query("SELECT id, name FROM products WHERE status = 1 ORDER BY name");

$invoice_no = 'QTY/' . date('YmdHis');
?>

<div class="content">
<h2>Create Sales Invoice</h2>

<form method="post" action="save.php" id="salesForm">

<input type="hidden" name="invoice_no" value="<?= $invoice_no ?>">
<b></b> <span id="invoicePreview">Select Client</span>

<!-- Client -->
<label>Client:</label>
<input type="text" id="clientInput" list="client_list" placeholder="Type client name" required>
<input type="hidden" name="client_id" id="clientId" required>
<button type="button" id="addClientBtn" style="display:none;">+ Add New Client</button>

<datalist id="client_list">
<?php while($c = $clients->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($c['name']) ?>" data-id="<?= $c['id'] ?>"></option>
<?php endwhile; ?>
</datalist>

<hr>

<table class="list-table" id="salesTable">
<tr>
    <th>Product</th>
    <th>Batch</th>
    <th>MRP</th>
    <th>Available</th>
    <th>Qty</th>
    <th>Selling Price (Incl GST)</th>
    <th>Disc Type</th>
    <th>Disc Value</th>
    <th>Final Unit Price</th>
    <th>GST %</th>
    <th>Line Total</th>
    <th>Action</th>
</tr>

<tr class="salesRow">
    <td class="product-cell">
		<div class="prod-name-wrap">
			<input type="text" class="productInput" list="product_list">
			<input type="hidden" name="product_id[]">
		</div>
		<div class="prod-desc-wrap">
			<textarea name="description[]" class="item-desc" placeholder="Item description (optional)"></textarea>
		</div>
    </td>
    <td>
        <select class="batchSelect" name="purchase_item_id[]">
            <option value="">Select Batch</option>
        </select>
    </td>
    <td class="mrp">0.00</td>
    <td class="availQty">0</td>
    <td><input type="number" step="0.01" class="qty" name="qty[]" min="0"></td>
    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]"></td>
    <td>
        <select class="discType" name="disc_type[]">
            <option value="">None</option>
            <option value="percent">%</option>
            <option value="amount">₹</option>
        </select>
    </td>
    <td><input type="number" step="0.01" class="discValue" name="disc_value[]"></td>
    <td class="finalUnitPrice">0.00</td>
    <td class="gstPercent">0</td>
    <td class="lineTotal">0.00</td>
    <td><button type="button" class="removeRow" disabled>X</button></td>
</tr>
</table>

<button type="button" id="addRow">+ Add Row</button>

<hr>

<!-- Overall Discount -->
<label>Overall Discount:</label>
<select name="overall_discount_type" id="overallDiscType">
    <option value="">None</option>
    <option value="percent">%</option>
    <option value="amount">₹</option>
</select>
<input type="number" step="0.01" name="overall_discount_value" id="overallDiscValue">

<br><br>

<!-- Totals -->
<div style="float:right;width:300px;border:1px solid #ccc;padding:10px;">
    <p>Gross: ₹ <span id="grossTotal">0.00</span></p>
    <p>GST: ₹ <span id="gstTotal">0.00</span></p>
    <p><b>Net: ₹ <span id="netTotal">0.00</span></b></p>
</div>
<div style="clear:both;"></div>

<br>

<!-- Payment -->
<label>Received Amount:</label>
<input type="number" step="0.01" name="received_amount" id="receivedAmount">

<label>Payment Mode:</label>
<select name="payment_mode">
    <option value="Cash">Cash</option>
    <option value="UPI">UPI</option>
    <option value="Card">Card</option>
    <option value="Bank">Bank Transfer</option>
</select>

<br><br>

<button type="submit" name="action" value="save">Save Draft</button>
<button type="submit" name="action" value="final"
        onclick="return confirm('Finalize and reduce stock?')">
    Complete Sale
</button>

</form>

<datalist id="product_list">
<?php while($p = $products->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($p['name']) ?>" data-id="<?= $p['id'] ?>"></option>
<?php endwhile; ?>
</datalist>

</div>

<!-- Add Client Modal -->
<div id="clientModal" style="display:none; position:fixed; top:20%; left:35%; background:#fff; padding:20px; border:1px solid #ccc; z-index:9999;">
<h3>Add New Client</h3>

<input id="new_client_name" placeholder="Name"><br><br>
<input id="new_client_phone" placeholder="Phone"><br><br>
<input id="new_client_address" placeholder="Address"><br><br>

<button id="saveClientBtn">Save</button>
<button onclick="closeClientModal()">Cancel</button>
</div>

<script>
const clientInput = document.getElementById('clientInput');
const clientIdInput = document.getElementById('clientId');
const addClientBtn = document.getElementById('addClientBtn');

clientInput.addEventListener('input', function () {
    let found = false;

    document.querySelectorAll('#client_list option').forEach(opt => {
        if (opt.value === clientInput.value) {
            clientIdInput.value = opt.dataset.id;
            found = true;
        }
    });

    if (found) {
        addClientBtn.style.display = 'none';
    } else {
        clientIdInput.value = '';
        addClientBtn.style.display = clientInput.value.trim() ? 'inline-block' : 'none';
    }
});

addClientBtn.onclick = function () {
    document.getElementById('clientModal').style.display = 'block';
};

function closeClientModal() {
    document.getElementById('clientModal').style.display = 'none';
}
document.getElementById('salesForm').addEventListener('submit', function(e){
    if(document.getElementById('clientId').value === ''){
        alert('Please select or add a client before saving invoice.');
        e.preventDefault();
        document.getElementById('clientInput').focus();
    }
});

function updateDraftInvoiceNo(clientId){
    fetch('ajax_get_client.php?id=' + clientId)
    .then(r=>r.json())
    .then(c=>{
        const fy = new Date().getMonth()+1 < 4 ? (new Date().getFullYear()-1)+'-'+(new Date().getFullYear()%100) : new Date().getFullYear()+'-'+((new Date().getFullYear()+1)%100);
        const type = c.gst_no ? 'B2B' : 'B2C';
        document.getElementById('invoicePreview').innerText = 'QTY/'+type+'/'+fy+'/AUTO';
    });
}


</script>

<script>
document.addEventListener('input', function(e){
    if(e.target.classList.contains('productInput')){
        const row = e.target.closest('tr');
        const hidden = row.querySelector('input[name="product_id[]"]');
        const batchSelect = row.querySelector('.batchSelect');
        const availCell = row.querySelector('.availQty');
        const mrpCell = row.querySelector('.mrp');
        const gstCell = row.querySelector('.gstPercent');
        const sellInput = row.querySelector('.sellPrice');

        let productId = null;

        document.querySelectorAll('#product_list option').forEach(opt=>{
            if(opt.value === e.target.value){
                productId = opt.dataset.id;
                hidden.value = productId;
            }
        });

        if(!productId){
            hidden.value = '';
            batchSelect.innerHTML = '<option value="">Select Batch</option>';
            availCell.innerText = '0';
            mrpCell.innerText = '0.00';
            gstCell.innerText = '0';
            sellInput.value = '';
            return;
        }

        fetch('get_batches.php?product_id=' + productId)
        .then(r=>r.json())
        .then(data=>{
            batchSelect.innerHTML = '<option value="">Select Batch</option>';

            data.forEach(b=>{
                const opt = document.createElement('option');
                opt.value = b.purchase_item_id;
                opt.dataset.avail = b.available_qty;
                opt.dataset.mrp = b.mrp;
                opt.dataset.baseprice = b.selling_price;
                opt.dataset.gst = b.gst_percent;
                opt.textContent = b.batch_no + ' | Qty: ' + b.available_qty;
                batchSelect.appendChild(opt);
            });
        });
    }
});

/* When batch selected */
document.addEventListener('change', function(e){
    if(e.target.classList.contains('batchSelect')){
        const row = e.target.closest('tr');
        const opt = e.target.options[e.target.selectedIndex];

        if(!opt || !opt.value) return;

        const avail = parseFloat(opt.dataset.avail || 0);
        const mrp = parseFloat(opt.dataset.mrp || 0);
        const basePrice = parseFloat(opt.dataset.baseprice || 0); // Excl GST
        const gst = parseFloat(opt.dataset.gst || 0);

        const sellPriceIncl = basePrice * (1 + gst/100);

        row.querySelector('.availQty').innerText = avail;
        row.querySelector('.mrp').innerText = mrp.toFixed(2);
        row.querySelector('.gstPercent').innerText = gst;
        row.querySelector('.sellPrice').value = sellPriceIncl.toFixed(2);
    }
});
</script>




<script>
function recalcRow(row){
    const qty = parseFloat(row.querySelector('.qty').value || 0);
    const sellPriceIncl = parseFloat(row.querySelector('.sellPrice').value || 0);
    const discType = row.querySelector('.discType').value;
    const discVal = parseFloat(row.querySelector('.discValue').value || 0);
    const gstp = parseFloat(row.querySelector('.gstPercent').innerText || 0);

    let finalUnit = sellPriceIncl;

    if(discType === 'percent'){
        finalUnit = sellPriceIncl - (sellPriceIncl * discVal / 100);
    } else if(discType === 'amount'){
        finalUnit = sellPriceIncl - discVal;
    }

    if(finalUnit < 0) finalUnit = 0;

    const baseUnit = finalUnit / (1 + gstp/100);
    const gstUnit = finalUnit - baseUnit;
    const lineTotal = finalUnit * qty;

    row.querySelector('.finalUnitPrice').innerText = finalUnit.toFixed(2);
    row.querySelector('.lineTotal').innerText = lineTotal.toFixed(2);

    recalcInvoiceTotals();
}

function recalcInvoiceTotals(){
    let gross = 0;
    let gstTotal = 0;

    document.querySelectorAll('#salesTable .salesRow').forEach(row=>{
        const line = parseFloat(row.querySelector('.lineTotal').innerText || 0);
        const qty = parseFloat(row.querySelector('.qty').value || 0);
        const finalUnit = parseFloat(row.querySelector('.finalUnitPrice').innerText || 0);
        const gstp = parseFloat(row.querySelector('.gstPercent').innerText || 0);

        gross += line;

        if(qty > 0){
            const baseUnit = finalUnit / (1 + gstp/100);
            const gstUnit = finalUnit - baseUnit;
            gstTotal += gstUnit * qty;
        }
    });

    const overallType = document.getElementById('overallDiscType').value;
    const overallVal = parseFloat(document.getElementById('overallDiscValue').value || 0);

    let net = gross;

    if(overallType === 'percent'){
        net = gross - (gross * overallVal / 100);
    } else if(overallType === 'amount'){
        net = gross - overallVal;
    }

    if(net < 0) net = 0;

    document.getElementById('grossTotal').innerText = gross.toFixed(2);
    document.getElementById('gstTotal').innerText = gstTotal.toFixed(2);
    document.getElementById('netTotal').innerText = net.toFixed(2);
}

document.addEventListener('input', function(e){
    if(
        e.target.classList.contains('qty') ||
        e.target.classList.contains('sellPrice') ||
        e.target.classList.contains('discType') ||
        e.target.classList.contains('discValue') ||
        e.target.id === 'overallDiscType' ||
        e.target.id === 'overallDiscValue' ||
        e.target.id === 'receivedAmount'
    ){
        const row = e.target.closest('.salesRow');
        if(row) recalcRow(row);
        else recalcInvoiceTotals();
    }
});
</script>


<script>
document.getElementById('addRow').onclick = function(){
    const table = document.getElementById('salesTable');
    const firstRow = table.querySelector('.salesRow');
    const newRow = firstRow.cloneNode(true);

    newRow.querySelectorAll('input').forEach(i => i.value = '');
    newRow.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
    newRow.querySelector('.mrp').innerText = '0.00';
    newRow.querySelector('.availQty').innerText = '0';
    newRow.querySelector('.gstPercent').innerText = '0';
    newRow.querySelector('.finalUnitPrice').innerText = '0.00';
    newRow.querySelector('.lineTotal').innerText = '0.00';

    newRow.querySelector('.removeRow').disabled = false;

    table.appendChild(newRow);
};

document.addEventListener('click', function(e){
    if(e.target.classList.contains('removeRow')){
        const row = e.target.closest('.salesRow');
        row.remove();
        recalcInvoiceTotals();
    }
});
</script>



<script>
document.getElementById('saveClientBtn').onclick = function(){

    const name = document.getElementById('new_client_name').value;
    const phone = document.getElementById('new_client_phone').value;
    const address = document.getElementById('new_client_address').value;

    if(name.trim() === ''){
        alert('Client name required');
        return;
    }

    const fd = new FormData();
    fd.append('name', name);
    fd.append('phone', phone);
    fd.append('address', address);

    fetch('ajax_add_client.php', { method:'POST', body:fd })
    .then(r => r.json())
    .then(res => {
        if(res.status === 'ok'){
            // add to datalist
            const opt = document.createElement('option');
            opt.value = res.name;
            opt.dataset.id = res.id;
            document.getElementById('client_list').appendChild(opt);

            // auto select
            document.getElementById('clientInput').value = res.name;
            document.getElementById('clientId').value = res.id;

            // close modal
            closeClientModal();
            document.getElementById('addClientBtn').style.display = 'none';
        } else {
            alert(res.msg);
        }
    });
};
</script>



<?php require_once '../includes/footer.php'; ?>
