<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db.php';

if (!isset($_GET['id'])) {
    echo "Invoice ID missing";
    exit;
}

$invoice_id = (int)$_GET['id'];

/* ================= FETCH INVOICE ================= */
$invoice = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM invoices WHERE id='$invoice_id'"));
if (!$invoice) {
    echo "Invoice not found";
    exit;
}

/* ================= FETCH ITEMS ================= */
$items = [];
$item_res = mysqli_query($con, "SELECT * FROM invoice_items WHERE invoice_id='$invoice_id'");
while ($row = mysqli_fetch_assoc($item_res)) {
    $items[] = $row;
}

/* ================= FETCH OTHER CHARGES ================= */
/* ================= FETCH OTHER CHARGES ================= */
$otherCharges = [];

$other_res = mysqli_query(
    $con,
    "SELECT * FROM invoice_other_charges WHERE invoice_id='$invoice_id'"
);

while ($row = mysqli_fetch_assoc($other_res)) {
    $otherCharges[] = $row;
}
/* ================= FETCH PAYMENTS ================= */
$payments = [];

$pay_res = mysqli_query($con, "SELECT * FROM invoice_payments WHERE invoice_id='$invoice_id'");
while ($row = mysqli_fetch_assoc($pay_res)) {
    $payments[$row['payment_type']] = $row['amount'];
}

/* ===== DEFAULT VALUES ===== */
$upi    = isset($payments['UPI']) ? $payments['UPI'] : '';
$cheque = isset($payments['Cheque']) ? $payments['Cheque'] : '';
$metal  = isset($payments['Metal']) ? $payments['Metal'] : '';
$cash   = isset($payments['Cash']) ? $payments['Cash'] : '';
$card   = isset($payments['Card']) ? $payments['Card'] : '';
/* ===== DUES CALCULATION ===== */
$upi_val    = (float)$upi;
$cheque_val = (float)$cheque;
$metal_val  = (float)$metal;
$cash_val   = (float)$cash;
$card_val   = (float)$card;

$dues = max(0, ($invoice['final_amount'] ?? 0) - ($upi_val + $cheque_val + $metal_val + $cash_val + $card_val));
$title = "Invoice Edit";

include 'include/header.php'; ?>


<div id="page-wrapper">
    <div id="page-inner">
        <div class="card">
            <div class="card-header text-white">
                <h4>Edit Invoice</h4>
            </div>
            <div class="card-body">
                <form method="POST" action="invoice_update.php" id="invoiceForm">
                    <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                    <div class="col-md-12 mb-3">
                        <label class="fw-semibold">Invoice No</label>
                        <input class="form-control" name="invoice_no"
                            value="<?= htmlspecialchars($invoice['invoice_no']) ?>" required>
                    </div>
                    <!-- ================= CLIENT DETAILS ================= -->
                    <h5 class="border-bottom pb-2">Customer Details</h5>
                    <div class="row g-2">
                        <div class="col-md-4"><input class="form-control" name="client_name" placeholder="Customer Name"
                                required value="<?= htmlspecialchars($invoice['client_name']) ?>"></div>
                        <div class="col-md-4"><input class="form-control" name="phone" placeholder="Phone"
                                value="<?= htmlspecialchars($invoice['phone']) ?>"></div>
                        <div class="col-md-4"><input class="form-control" name="pan_no" placeholder="PAN"
                                value="<?= htmlspecialchars($invoice['pan_no'] ?? '') ?>"></div>
                        <div class="col-md-4"><input class="form-control" name="gst_no" placeholder="GST"
                                value="<?= htmlspecialchars($invoice['gst_no'] ?? '') ?>"></div>
                        <div class="col-md-4"><input class="form-control" name="address" placeholder="Address"
                                value="<?= htmlspecialchars($invoice['address']) ?>"></div>
                        <div class="col-md-4">
                            <input class="form-control" name="state" placeholder="State" list="stateList"
                                value="<?= htmlspecialchars($invoice['state'] ?? '') ?>">

                            <datalist id="stateList">
                                <option value="Andhra Pradesh">
                                <option value="Arunachal Pradesh">
                                <option value="Assam">
                                <option value="Bihar">
                                <option value="Chhattisgarh">
                                <option value="Goa">
                                <option value="Gujarat">
                                <option value="Haryana">
                                <option value="Himachal Pradesh">
                                <option value="Jharkhand">
                                <option value="Karnataka">
                                <option value="Kerala">
                                <option value="Madhya Pradesh">
                                <option value="Maharashtra">
                                <option value="Manipur">
                                <option value="Meghalaya">
                                <option value="Mizoram">
                                <option value="Nagaland">
                                <option value="Odisha">
                                <option value="Punjab">
                                <option value="Rajasthan">
                                <option value="Sikkim">
                                <option value="Tamil Nadu">
                                <option value="Telangana">
                                <option value="Tripura">
                                <option value="Uttar Pradesh">
                                <option value="Uttarakhand">
                                <option value="West Bengal">
                            </datalist>
                        </div>
                        <!-- <div class="col-md-4"><input class="form-control" name="state" placeholder="State"
                                value="<?= htmlspecialchars($invoice['state'] ?? '') ?>"></div> -->

                        <div class="col-md-4"><input class="form-control" name="city" placeholder="City"
                                value="<?= htmlspecialchars($invoice['city'] ?? '') ?>"></div>
                        <div class="col-md-4"><input class="form-control" name="pincode" placeholder="Pincode"
                                value="<?= htmlspecialchars($invoice['pincode'] ?? '') ?>"></div>
                    </div>

                    <!-- ================= ITEMS ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Invoice Items</h5>
                    <datalist id="productList">
                        <?php
                        $p = mysqli_query($con, "SELECT * FROM products");
                        while ($r = mysqli_fetch_assoc($p)) {
                        ?>
                        <option value="<?= htmlspecialchars($r['product_name']) ?>"
                            data-hsn="<?= htmlspecialchars($r['hsn']) ?>">
                            <?php } ?>
                    </datalist>

                    <div id="items">
                        <?php foreach ($items as $it): ?>
                        <input type="hidden" name="item_id[]" value="<?= $it['id'] ?>">
                        <div class="row g-1 item-row mb-2 align-items-end">
                            <div class="col-md-3" style="padding-right: 0px; "><input class="form-control product-input"
                                    name="desc[]" list="productList" placeholder="Product name"
                                    value="<?= htmlspecialchars($it['description']) ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control hsn-input" name="hsn[]" placeholder="HSN"
                                    value="<?= htmlspecialchars($it['hsn'] ?? '') ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="gross[]" placeholder="Gross"
                                    value="<?= htmlspecialchars($it['gross_weight']) ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="net[]" placeholder="Net"
                                    value="<?= htmlspecialchars($it['net_weight']) ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="rate[]" placeholder="Rate"
                                    value="<?= htmlspecialchars($it['rate']) ?>"></div>

                            <div class="col-md-1" style="padding:0;">
                                <input class="form-control making-percent" name="making[]" placeholder="Making %" value="<?php
                                                $item_metal = $it['net_weight'] * $it['rate'];
                                                echo ($item_metal > 0) ? round(($it['making'] / $item_metal) * 100, 2) : 0;
                                                ?>">
                            </div>

                            <div class="col-md-1" style="padding:0;">
                                <input class="form-control making-amount" name="making_amount[]" placeholder="Value"
                                    value="<?= $it['making'] ?>">
                            </div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="stone[]" placeholder="Stone"
                                    value="<?= htmlspecialchars($it['stone_value']) ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="hm_value[]" placeholder="HM"
                                    value="<?= htmlspecialchars($it['hm_value'] ?? '') ?>"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="item-total form-control" readonly placeholder="Total"
                                    value="<?= number_format($it['total'], 2) ?>"></div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="d-flex gap-2 mt-3">
                        <button type="button" id="addItem" class="btn btn-success btn-sm mt-2">+ Add Item</button>
                        <button type="button" id="removeItem" class="btn btn-danger btn-sm mt-2" style="display:none;">-
                            Remove Item</button>
                    </div>

                    <!-- ================= OTHER CHARGES ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Other Charges</h5>

                    <div id="otherCharges">

                        <?php if (!empty($otherCharges)): ?>
                        <?php foreach ($otherCharges as $oc): ?>
                        <div class="row g-2 mb-2 other-row align-items-end">
                            <div class="col-md-6">
                                <input class="form-control" name="other_name[]"
                                    value="<?= htmlspecialchars($oc['charge_name']) ?>" placeholder="Charge Name">
                            </div>

                            <div class="col-md-4">
                                <input class="form-control text-end other-amount" name="other_amount[]"
                                    value="<?= htmlspecialchars($oc['amount']) ?>" placeholder="0.00">
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <?php else: ?>
                        <div class="row g-2 mb-2 other-row align-items-end">
                            <div class="col-md-6">
                                <input class="form-control" name="other_name[]" placeholder="Charge Name">
                            </div>

                            <div class="col-md-4">
                                <input class="form-control text-end other-amount" name="other_amount[]"
                                    placeholder="0.00">
                            </div>
                        </div>
                        <?php endif; ?>

                    </div>

                    <div class="d-flex gap-2 mt-2">
                        <button type="button" id="addOther" class="btn btn-success btn-sm">
                            + Add Charge
                        </button>

                        <button type="button" id="removeOther" class="btn btn-danger btn-sm" style="display:none;">
                            - Remove
                        </button>
                    </div>
                    <!-- ================= DISCOUNT ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Discount</h5>
                    <div class="row g-2 align-items-end">
                        <div class="col-md-3">
                            <label class="form-label small fw-semibold">Type</label>
                            <select class="form-control" name="discount_type" id="discountType">
                                <option value="value" <?= ($invoice['discount_type'] == 'value') ? 'selected' : '' ?>>
                                    Value
                                </option>
                                <option value="percent"
                                    <?= ($invoice['discount_type'] == 'percent') ? 'selected' : '' ?>>%
                                </option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label small fw-semibold">Discount</label>
                            <input class="form-control text-end" name="discount_value" id="discountValue"
                                value="<?= $invoice['discount_value'] ?? 0 ?>">
                        </div>
                    </div>
                    <!-- ================= PAYMENT ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Payment Details</h5>
                    <div class="row g-2 text-center">
                        <div class="col-md-2">
                            <label>UPI</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[UPI]" value="<?= $upi ?>">
                        </div>

                        <div class="col-md-2">
                            <label class="fw-semibold">Cheque</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Cheque]"
                                value="<?= $cheque ?>">
                        </div>
                        <div class="col-md-2">
                            <label>Metal</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Metal]"
                                value="<?= $metal ?>">
                        </div>
                        <div class="col-md-2">
                            <label>Cash</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Cash]" value="<?= $cash ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="fw-semibold">Card</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Card]" value="<?= $card ?>">
                        </div>
                        <div class="col-md-2">
                            <label>Dues</label>
                            <input class="form-control text-end" readonly id="duesBox"
                                value="<?= number_format($dues, 2) ?>">
                        </div>
                    </div>
                    <!-- ================= GST DETAILS ================= -->
                    <h5 class="border-bottom pb-2 mt-4">GST Details</h5>
                    <div class="row g-2 text-center">
                        <div class="col-md-3">
                            <label class="fw-semibold">CGST (1.5%)</label>
                            <input class="form-control text-end" readonly id="cgstBox" placeholder="0.00">
                        </div>
                        <div class="col-md-3">
                            <label class="fw-semibold">SGST (1.5%)</label>
                            <input class="form-control text-end" readonly id="sgstBox" placeholder="0">
                        </div>
                        <div class="col-md-3">
                            <label class="fw-semibold">Total GST (3%)</label>
                            <input class="form-control text-end" readonly id="totalGstBox" placeholder="0.00">
                        </div>
                        <div class="col-md-3">
                            <label class="fw-semibold">HM GST (18%)</label>
                            <input class="form-control text-end" readonly id="hmGstBox" value="0.00">
                        </div>
                        <div class="col-md-3">
                            <label class="fw-semibold">Final Amount</label>
                            <input class="form-control text-end" readonly id="finalAmountBox" placeholder="0.00">
                        </div>
                        <div class="col-md-3">
                            <label class="fw-semibold">Round Off</label>
                            <input class="form-control text-end" readonly id="roundOffBox" value="0.00">
                        </div>

                        <div class="col-md-3">
                            <label class="fw-semibold">Grand Total</label>
                            <input class="form-control text-end" readonly id="grandTotalBox" value="0.00">
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 mt-4">Update Invoice</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- ================= JAVASCRIPT ================= -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {

    function toggleRemoveBtn() {
        if ($('.item-row').length > 1) {
            $('#removeItem').show();
        } else {
            $('#removeItem').hide();
        }
    }

    toggleRemoveBtn();

    $('#addItem').click(function() {
        let row = $('.item-row:first').clone();

        row.find('input').val('');

        // ðŸ”¥ IMPORTANT
        row.find('[name="making_amount[]"]').val('');

        $('#items').append(row);
        toggleRemoveBtn();
    });

    $('#removeItem').click(function() {
        if ($('.item-row').length > 1) {
            $('.item-row:last').remove();
        }
        toggleRemoveBtn();
        calc();
    });

    // Auto HSN
    $(document).on('input', '.product-input', function() {
        let val = $(this).val();
        let hsn = '';

        $('#productList option').each(function() {
            if ($(this).val() === val) {
                hsn = $(this).data('hsn');
            }
        });

        $(this).closest('.item-row').find('.hsn-input').val(hsn);
    });

    function calc() {

        let itemSub = 0;

        /* ================= ITEM CALC ================= */
        $('.item-row').each(function() {

            let net = +$(this).find('[name="net[]"]').val() || 0;
            let rate = +$(this).find('[name="rate[]"]').val() || 0;
            let stone = +$(this).find('[name="stone[]"]').val() || 0;

            let metal = net * rate;

            let makingInput = $(this).find('[name="making_amount[]"]');
            let making = parseFloat(makingInput.val()) || 0;

            let percent = 0;
            if (metal > 0) {
                percent = (making / metal) * 100;
            }

            $(this).find('[name="making[]"]').val(percent.toFixed(2));

            let total = metal + making + stone;

            itemSub += total;
            $(this).find('.item-total').val(total.toFixed(2));
        });

        /* ================= OTHER ================= */
        let otherTotal = 0;
        $('.other-amount').each(function() {
            otherTotal += parseFloat($(this).val()) || 0;
        });

        /* ================= DISCOUNT ================= */
        let discountType = $('#discountType').val();
        let discountValue = +$('#discountValue').val() || 0;

        let discountAmount = (discountType === 'percent') ?
            itemSub * discountValue / 100 :
            discountValue;

        if (discountAmount < 0) discountAmount = 0;

        /* ================= STATE ================= */
        let state = $('input[name="state"]').val().toLowerCase().trim();

        /* ================= HM CALC ================= */
        let hmTotal = 0;

        $('.item-row').each(function() {
            hmTotal += parseFloat($(this).find('[name="hm_value[]"]').val()) || 0;
        });

        let hmGstTotal = hmTotal * 0.18;

        /* ================= GST ================= */
        let cgst = 0,
            sgst = 0,
            igst = 0;

        if (state === 'west bengal') {
            cgst = itemSub * 0.015;
            sgst = itemSub * 0.015;
        } else {
            igst = itemSub * 0.03;
        }

        let totalGst = cgst + sgst + igst;

        /* ================= FINAL ================= */
        let finalTotal = itemSub +
            totalGst +
            hmTotal +
            hmGstTotal +
            otherTotal -
            discountAmount;

        /* ROUND OFF */
        let roundedTotal = Math.round(finalTotal);
        let roundOff = roundedTotal - finalTotal;

        /* UI */
        $('#cgstBox').val(cgst.toFixed(2));
        $('#sgstBox').val(sgst.toFixed(2));
        $('#totalGstBox').val(totalGst.toFixed(2));
        $('#hmGstBox').val(hmGstTotal.toFixed(2));
        $('#finalAmountBox').val(finalTotal.toFixed(2));

        $('#roundOffBox').val(roundOff.toFixed(2));
        $('#grandTotalBox').val(roundedTotal.toFixed(2));

        /* ================= PAYMENT ================= */
        let paid = 0;

        $('.pay-input').each(function() {
            let val = $(this).val();
            if (val !== '') {
                paid += parseFloat(val) || 0;
            }
        });

        let dues = Math.max(0, finalTotal - paid);
        $('#duesBox').val(dues.toFixed(2));
    }

    $(document).on('input change', 'input, select', calc);

    $(document).on('change', '[name="making_type[]"]', function() {
        let row = $(this).closest('.item-row');
        let inp = row.find('[name="making[]"]');
        let val = inp.val().toString();
        if ($(this).val() === 'percent') {
            inp.val(val.replace(/[^0-9\.\%]/g, '').replace(/\%/g, ''));
        } else {
            inp.val(val.replace(/\%/g, ''));
        }
        calc();
    });

    calc();

});
$(document).on('input', '[name="making_amount[]"]', function() {

    let row = $(this).closest('.item-row');

    let net = +row.find('[name="net[]"]').val() || 0;
    let rate = +row.find('[name="rate[]"]').val() || 0;

    let metal = net * rate;

    let amount = parseFloat($(this).val()) || 0;

    let percent = 0;

    if (metal > 0) {
        percent = (amount / metal) * 100;
    }

    row.find('[name="making[]"]').val(percent.toFixed(2));

    calc();
});

/* % → ₹ AUTO (ADD THIS) */
$(document).on('input', '[name="making[]"]', function() {

    let row = $(this).closest('.item-row');

    let net = +row.find('[name="net[]"]').val() || 0;
    let rate = +row.find('[name="rate[]"]').val() || 0;

    let metal = net * rate;

    let percent = parseFloat($(this).val()) || 0;

    let amount = (metal * percent / 100);

    row.find('[name="making_amount[]"]').val(amount > 0 ? amount.toFixed(2) : '');

    calc();
});
/* ================= OTHER CHARGES ================= */

function toggleOtherRemove() {
    if ($('.other-row').length > 1) {
        $('#removeOther').show();
    } else {
        $('#removeOther').hide();
    }
}

toggleOtherRemove();

$('#addOther').click(function() {
    let row = $('.other-row:first').clone();
    row.find('input').val('');
    $('#otherCharges').append(row);
    toggleOtherRemove();
});

$('#removeOther').click(function() {
    if ($('.other-row').length > 1) {
        $('.other-row:last').remove();
    }
    toggleOtherRemove();
    calc();
});

/* ================= ENTER KEY NAVIGATION ================= */
$(document).on('keydown', 'input, select', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();

        let inputs = $('input, select').filter(':visible');
        let index = inputs.index(this);

        if (index + 1 < inputs.length) {
            inputs.eq(index + 1).focus();
        } else {
            $('#invoiceForm').submit();
        }
    }
});
</script>
<?php include 'include/footer.php'; ?>