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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid Invoice");

$inv = $conn->query("SELECT * FROM sales_invoices WHERE id = $id")->fetch_assoc();
if (!$inv) die("Invoice not found");

// If already final, redirect to view
if ($inv['status'] === 'final') {
    header("Location: view.php?id=" . $id);
    exit;
}

// Load clients & products
$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");

// Load invoice items
$items = $conn->query("
    SELECT si.*, p.name AS product_name
    FROM sales_items si
    JOIN products p ON p.id = si.product_id
    WHERE si.sales_invoice_id = $id
");
?>

<div class="content">
<h2>Edit Sales Invoice (<?= htmlspecialchars($inv['invoice_no']) ?>)</h2>

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

<input type="hidden" name="sales_invoice_id" value="<?= $id ?>">

<!-- Client -->
<label>Client:</label>
<input type="text" id="clientInput" list="client_list" value="<?= htmlspecialchars($conn->query("SELECT name FROM clients WHERE id=".$inv['client_id'])->fetch_assoc()['name']) ?>" required>
<input type="hidden" name="client_id" id="clientId" value="<?= $inv['client_id'] ?>" required>

<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>

<?php while($row = $items->fetch_assoc()): ?>
<tr class="salesRow">
    <td class="product-cell">
		<div class="prod-name-wrap">
        <input type="text" class="productInput" list="product_list" value="<?= htmlspecialchars($row['product_name']) ?>">
        <input type="hidden" name="product_id[]" value="<?= $row['product_id'] ?>">
		</div>
		<div class="prod-desc-wrap">
			<textarea name="description[]" class="item-desc" placeholder="Item description (optional)"><?= htmlspecialchars($row['description']) ?></textarea>
		</div>
    </td>
    <td>
        <select class="batchSelect" name="purchase_item_id[]">
            <option value="<?= $row['purchase_item_id'] ?>">Batch <?= htmlspecialchars($row['batch_no']) ?></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[]" value="<?= $row['sold_qty'] ?>"></td>
    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]" value="<?= number_format($row['selling_price_incl'],2,'.','') ?>"></td>
    <td>
        <select class="discType" name="disc_type[]">
            <option value="">None</option>
            <option value="percent" <?= $row['discount_type']=='percent'?'selected':'' ?>>%</option>
            <option value="amount" <?= $row['discount_type']=='amount'?'selected':'' ?>>₹</option>
        </select>
    </td>
    <td><input type="number" step="0.01" class="discValue" name="disc_value[]" value="<?= $row['discount_value'] ?>"></td>
    <td class="finalUnitPrice"><?= number_format($row['selling_price_incl'],2) ?></td>
    <td class="gstPercent"><?= $row['gst_percent'] ?></td>
    <td class="lineTotal"><?= number_format($row['total_amount'],2) ?></td>
    <td><button type="button" class="removeRow">X</button></td>
</tr>
<?php endwhile; ?>

</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" <?= $inv['overall_discount_type']=='percent'?'selected':'' ?>>%</option>
    <option value="amount" <?= $inv['overall_discount_type']=='amount'?'selected':'' ?>>₹</option>
</select>
<input type="number" step="0.01" name="overall_discount_value" id="overallDiscValue" value="<?= $inv['overall_discount_value'] ?>">

<br><br>

<div style="float:right;width:300px;border:1px solid #ccc;padding:10px;">
    <p>Gross: ₹ <span id="grossTotal"><?= number_format($inv['gross_total'],2) ?></span></p>
    <p>GST: ₹ <span id="gstTotal"><?= number_format($inv['total_gst'],2) ?></span></p>
    <p><b>Net: ₹ <span id="netTotal"><?= number_format($inv['net_total'],2) ?></span></b></p>
</div>
<div style="clear:both;"></div>

<br>

<label>Received Amount:</label>
<input type="number" step="0.01" name="received_amount" id="receivedAmount" value="<?= $inv['received_amount'] ?>">

<label>Payment Mode:</label>
<select name="payment_mode">
    <option value="Cash" <?= $inv['payment_mode']=='Cash'?'selected':'' ?>>Cash</option>
    <option value="UPI" <?= $inv['payment_mode']=='UPI'?'selected':'' ?>>UPI</option>
    <option value="Card" <?= $inv['payment_mode']=='Card'?'selected':'' ?>>Card</option>
    <option value="Bank" <?= $inv['payment_mode']=='Bank'?'selected':'' ?>>Bank Transfer</option>
</select>

<br><br>

<button type="submit" name="action" value="save">Update 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>

<script>
document.addEventListener('input', function(e){
    if(e.target.classList.contains('productInput')){
        const row = e.target.closest('.salesRow');
        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; // excl GST
                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('.salesRow');
        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);

        recalcRow(row);
    }
});
</script>
<script>
document.addEventListener('input', function(e){
    if(e.target.classList.contains('productInput')){
        const row = e.target.closest('.salesRow');
        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_info.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; // excl GST
                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('.salesRow');
        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);

        recalcRow(row);
    }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function(){

    document.querySelectorAll('.salesRow').forEach(row => {

        const batchSelect = row.querySelector('.batchSelect');
        const purchaseItemId = batchSelect.value;

        if(!purchaseItemId) return;

        fetch('get_batch_info.php?id=' + purchaseItemId)
        .then(r => r.json())
        .then(b => {

            const basePrice = parseFloat(b.selling_price || 0); // excl GST
            const gst = parseFloat(b.gst_percent || 0);
            const mrp = parseFloat(b.mrp || 0);
            const avail = parseFloat(b.available_qty || 0);

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

            row.querySelector('.mrp').innerText = mrp.toFixed(2);
            row.querySelector('.availQty').innerText = avail;
            row.querySelector('.gstPercent').innerText = gst;
            row.querySelector('.sellPrice').value = sellPriceIncl.toFixed(2);

            recalcRow(row); // push into totals
        });
    });

});
</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 qty = parseFloat(row.querySelector('.qty').value || 0);
        const finalUnit = parseFloat(row.querySelector('.finalUnitPrice').innerText || 0);
        const gstp = parseFloat(row.querySelector('.gstPercent').innerText || 0);
        const line = parseFloat(row.querySelector('.lineTotal').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.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('#salesTable .salesRow').forEach(row => {
        recalcRow(row);
    });
});
</script>

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