 
<?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: 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="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">Final Amount</label>
                            <input class="form-control text-end" readonly id="finalAmountBox" value="0.00">
                        </div>
                    </div>


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

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

    </div>
</div>
<script>
$(document).ready(function() {

    /* ================= REMOVE BUTTON TOGGLE ================= */
    function toggleRemoveBtn() {
        if ($('.item-row').length > 1) {
            $('#removeItem').show();
        } else {
            $('#removeItem').hide();
        }
    }

    toggleRemoveBtn();

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

        row.find('input').val('');
        row.find('select').val('percent');
        row.find('.item-total').val('');

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

    /* ================= REMOVE ITEM ================= */
    $('#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);
    });

    /* ================= 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();
            }
        }
    });

    /* ================= CALCULATION ================= */
    function calc() {

        let sub = 0;

        $('.item-row').each(function() {

            let makingType = $(this).find('[name="making_type[]"]').val();
            // allow user to type a number with or without a % sign
            let makingRaw = $(this).find('[name="making[]"]').val() || '';
            let makingVal = parseFloat(makingRaw.toString().replace(/%/g, '')) || 0;
            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 hmVal = +$(this).find('[name="hm_value[]"]').val() || 0;

            let metal = net * rate;
            let making = (makingType === 'percent') ? (metal * makingVal / 100) : makingVal;
            let total = metal + making + stone + hmVal;

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

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

        sub += otherTotal;

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

        let discountAmount = 0;

        if (discountType === 'percent') {
            discountAmount = sub * discountValue / 100;
        } else {
            discountAmount = discountValue;
        }

        sub -= discountAmount;

        if (sub < 0) sub = 0;

        /* ---------- GST ---------- */
        let cgst = +(sub * 0.015).toFixed(2);
        let sgst = +(sub * 0.015).toFixed(2);
        let totalGst = +(cgst + sgst).toFixed(2);
        let finalTotal = +(sub + totalGst).toFixed(2);

        $('#cgstBox').val(cgst.toFixed(2));
        $('#sgstBox').val(sgst.toFixed(2));
        $('#totalGstBox').val(totalGst.toFixed(2));
        $('#finalAmountBox').val(finalTotal.toFixed(2));

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

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

    /* Trigger calculation */
    // recalc whenever anything changes, including select dropdowns
    $(document).on('input change', 'input, select', calc);

    // when user toggles the making type we may want to clean up the input
    $(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') {
            // strip any rupee symbol and leave only digits (user may have typed % manually)
            inp.val(val.replace(/[^0-9\.\%]/g, '').replace(/\%/g, ''));
        } else {
            // remove any percent sign when switching to fixed value
            inp.val(val.replace(/\%/g, ''));
        }
        calc();
    });

    calc();

});

/* ================= OTHER CHARGES ADD ================= */

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();
});
</script>
<?php include 'include/footer.php'; ?> 
