<?php 
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    = $payments['UPI'] ?? 0;
$cheque = $payments['Cheque'] ?? 0;
$metal  = $payments['Metal'] ?? 0;
$cash   = $payments['Cash'] ?? 0;
$card   = $payments['Card'] ?? 0;

/* ===== DUES CALCULATION ===== */
$dues = max(0, ($invoice['final_amount'] ?? 0) - ($upi+$cheque+$metal+$cash+$card));
$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-right: 0px;padding-left: 0px;">
                                <select class="form-control" name="making_type[]">
                                    <option value="percent" <?=($it['hm_type']=='percent')?'selected':'' ?>>%</option>
                                    <option value="value" <?=($it['hm_type']=='value')?'selected':'' ?>>₹</option>
                                </select>
                            </div>
                            <div class="col-md-1" style="padding-right: 0px;padding-left: 0px;">
                                <?php
                                // compute display value: if stored type was percent, revert the calculation so user sees the percentage
                                $making_display = $it['making'];
                                if($it['hm_type'] === 'percent'){
                                    $metal = ($it['net_weight'] ?? 0) * ($it['rate'] ?? 0);
                                    if($metal > 0) {
                                        $pct = ($it['making'] / $metal) * 100;
                                        $making_display = round($pct,2) . '%';
                                    }
                                }
                                ?>
                                <input class="form-control" name="making[]" placeholder="Making (₹ or %)"
                                    value="<?= htmlspecialchars($making_display) ?>">
                            </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">Final Amount</label>
                            <input class="form-control text-end" readonly id="finalAmountBox" placeholder="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('');
        row.find('select').val('percent');
        row.find('.item-total').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 sub = 0;

        $('.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 hmVal = +$(this).find('[name="hm_value[]"]').val() || 0;
            // tolerate percentage symbol in input
            let makingRaw = $(this).find('[name="making[]"]').val() || '';
            let makingVal = parseFloat(makingRaw.toString().replace(/%/g, '')) || 0;
            let makingType = $(this).find('[name="making_type[]"]').val();

            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 state = $('input[name="state"]').val().toLowerCase().trim();

        let cgst = 0;
        let sgst = 0;
        let igst = 0;

        if (state === 'west bengal') {
            cgst = +(sub * 0.015).toFixed(2);
            sgst = +(sub * 0.015).toFixed(2);
        } else {
            igst = +(sub * 0.03).toFixed(2);
        }

        let totalGst = cgst + sgst + igst;
        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));
    }

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

});

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