<?php 
include 'db.php';
?>
<?php
$title = "Invoice Form";
include 'include/header.php';?>
<div id="page-wrapper">
    <div id="page-inner">

        <div class="card">
            <div class="card-header  text-white">
                <h4>Invoice Generator</h4>
            </div>

            <div class="card-body">
                <form method="POST" action="invoice_save.php" id="invoiceForm">

                    <!-- ================= 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"></div>
                        <div class="col-md-4"><input class="form-control" name="phone" placeholder="Phone"></div>
                        <div class="col-md-4"><input class="form-control" name="pan_no" placeholder="PAN"></div>
                        <div class="col-md-4"><input class="form-control" name="gst_no" placeholder="GST"></div>
                        <div class="col-md-4"><input class="form-control" name="address" placeholder="Address"></div>
                        <div class="col-md-4">
                            <input class="form-control" name="state" placeholder="State" list="stateList">

                            <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="city" placeholder="City"></div>
                        <div class="col-md-4"><input class="form-control" name="pincode" placeholder="Pincode"></div>
                    </div>

                    <!-- ================= ITEMS ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Invoice Items</h5>

                    <!-- PRODUCT LIST (ONE TIME ONLY) -->
                    <datalist id="productList">
                        <?php
                            $p=mysqli_query($con,"SELECT * FROM products");
                            while($r=mysqli_fetch_assoc($p)){
                        ?>
                        <option value="<?= $r['product_name'] ?>" data-hsn="<?= $r['hsn'] ?>">
                            <?php } ?>
                    </datalist>

                    <div id="items">

                        <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="Type product name">
                            </div>

                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;">
                                <input class="form-control hsn-input" name="hsn[]" placeholder="HSN">
                            </div>

                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="gross[]" placeholder="Gross"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="net[]" placeholder="Net"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="rate[]" placeholder="Rate"></div>
                            <!--<div class="col-md-1" style="padding-right: 0px;padding-left: 0px;">-->
                            <!--    <select class="form-control making-type" name="making_type[]">-->
                            <!--        <option value="percent">%</option>-->
                            <!--        <option value="value">â‚¹</option>-->
                            <!--    </select>-->
                            <!--</div>-->
                            <!--<div class="col-md-1" style="padding-right: 0px;padding-left: 0px;">-->
                            <!--    <input-->
                            <!--        class="form-control" name="making[]" placeholder="Making (â‚¹ or %)">-->
                            <!--</div>-->
                            <div class="col-md-1" style="padding-right:0;padding-left:0;">
                                <input class="form-control making-percent" name="making[]" placeholder="Making %">
                            </div>

                            <div class="col-md-1" style="padding-right:0;padding-left:0;">
                                <input class="form-control making-amount" placeholder="Value">
                            </div>

                            <!-- ðŸ”¥ IMPORTANT hidden input -->
                            <input type="hidden" name="making_amount[]">
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="stone[]" placeholder="Stone"></div>



                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;"><input
                                    class="form-control" name="hm_value[]" placeholder="HM"></div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;">
                                <input class="item-total form-control" readonly placeholder="Total">
                            </div>



                        </div>
                    </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">

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

                    </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">Value</option>
                                <option value="percent">%</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"
                                placeholder="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 class="fw-semibold">UPI</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[UPI]" placeholder="0">
                        </div>

                        <div class="col-md-2">
                            <label class="fw-semibold">Cheque</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Cheque]" placeholder="0">
                        </div>

                        <div class="col-md-2">
                            <label class="fw-semibold">Metal</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Metal]" placeholder="0">
                        </div>

                        <div class="col-md-2">
                            <label class="fw-semibold">Cash</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Cash]" placeholder="0">
                        </div>

                        <div class="col-md-2">
                            <label class="fw-semibold">Card</label>
                            <input class="form-control text-end pay-input" name="pay_fixed[Card]" placeholder="0">
                        </div>
                        <div class="col-md-2">
                            <label class="fw-semibold">Dues</label>
                            <input class="form-control text-end" readonly id="duesBox">
                        </div>
                    </div>
                    <!-- ================= PAYMENT ================= -->
                    <h5 class="border-bottom pb-2 mt-4">Payment Details</h5>

                    <div class="row g-2 text-center">
                        <!-- Payment inputs -->
                        ...
                    </div>

                    <!-- ================= GST DETAILS ================= -->
                    <h5 class="border-bottom pb-2 mt-4">GST Details</h5>
                    <div class="row g-2 text-center">
                        <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" value="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" value="0.00">
                            </div>

                            <div class="col-md-3">
                                <label class="fw-semibold">Total GST (3%)</label>
                                <input class="form-control text-end" readonly id="totalGstBox" value="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" value="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>
                    </div>


                    <button class="btn btn-primary w-100 mt-4">Generate Invoice</button>

                </form>
            </div>
        </div>

    </div>
</div>
<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('');
        row.find('.item-total').val('');

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

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

    $(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;

        /* ================= ITEMS ================= */
        $('.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('.making-amount');
            let makingAmount = parseFloat(makingInput.val()) || 0;

            $(this).find('[name="making_amount[]"]').val(makingAmount);

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

            if (makingAmount > 0) {
                $(this).find('[name="making[]"]').val(percent.toFixed(2));
            } else {
                $(this).find('[name="making[]"]').val('');
            }

            let total = metal + makingAmount + 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 = parseFloat($('#discountValue').val()) || 0;

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

        if (discountAmount < 0) discountAmount = 0;

        /* ================= GST ================= */
        let cgst = itemSub * 0.015;
        let sgst = itemSub * 0.015;
        let totalGst = cgst + sgst;

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

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

        let hmGstTotal = hmTotal * 0.18;

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

        if (finalTotal < 0) finalTotal = 0;

        /* ================= 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, roundedTotal - paid);
        $('#duesBox').val(dues.toFixed(2));
    }
    $(document).on('input change', 'input, select', calc);

    calc();
});

/* MAKING ₹ → % AUTO */
$(document).on('input', '.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 makingAmount = parseFloat($(this).val()) || 0;

    let percent = 0;

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

    let percentInput = $(this).find('[name="making[]"]');

    // ✅ sirf tab update kare jab user % field me focus na ho
    if (!percentInput.is(':focus')) {

        if (makingAmount > 0) {
            percentInput.val(percent.toFixed(2));
        } else {
            percentInput.val('');
        }

    }
    row.find('[name="making_amount[]"]').val(makingAmount.toFixed(2));

    calc(); // ✅ direct call (trigger hata diya)
});
/* % → ₹ AUTO (IMPORTANT ADD) */
$(document).on('input', '.making-percent', 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 makingAmount = (metal * percent / 100);

    // ✅ value update
    row.find('.making-amount').val(makingAmount > 0 ? makingAmount.toFixed(2) : '');

    // ✅ hidden input
    row.find('[name="making_amount[]"]').val(makingAmount.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();
    $(document).trigger('input');
});

/* ================= 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'; ?>