<?php
include 'include/header.php';
include 'db.php'; // database connection

// ================== INVOICE ID CHECK ==================
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die('Invalid Invoice ID');
}

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

// ================== FETCH INVOICE MAIN DATA ==================
$invRes = mysqli_query($con, "SELECT * FROM invoices WHERE id = $invoice_id");
if (!$invRes || mysqli_num_rows($invRes) == 0) {
    die('Invoice not found');
}
$invoice = mysqli_fetch_assoc($invRes);

// ================== UPDATE (POST) ==================
if ($_SERVER['REQUEST_METHOD'] == "POST") {

    $invoice_id       = (int)$_POST['invoice_id'];
    $customer_name    = $_POST['customer_name'];
    $customer_phone   = $_POST['customer_phone'];
    $customer_address = $_POST['customer_address'];
    // invoice_no edit nahi kar rahe, wahi rahega
    $invoice_date     = $_POST['invoice_date'];
    $state_name       = $_POST['state_name'];
    $pan_no           = $_POST['pan_no'];
    $gstin_no         = $_POST['gstin_no'];
    $invoice_type     = $_POST['invoice_type'];
    $grand_total      = $_POST['grand_total'];

    // -------- UPDATE INVOICE TABLE --------
    $sql_upd = "UPDATE invoices SET
        customer_name   = '$customer_name',
        customer_phone  = '$customer_phone',
        customer_address= '$customer_address',
        invoice_date    = '$invoice_date',
        state_name      = '$state_name',
        pan_no          = '$pan_no',
        gstin_no        = '$gstin_no',
        invoice_type    = '$invoice_type',
        grand_total     = '$grand_total'
        WHERE id = '$invoice_id'";

    mysqli_query($con, $sql_upd);

    // -------- OLD ITEMS DELETE --------
    mysqli_query($con, "DELETE FROM invoice_items WHERE invoice_id = '$invoice_id'");

    // -------- NEW ITEMS INSERT --------
    if (!empty($_POST['item_name'])) {
        for ($i = 0; $i < count($_POST['item_name']); $i++) {
            $item_name  = $_POST['item_name'][$i];
            $item_qty   = $_POST['item_qty'][$i];
            $item_price = $_POST['item_price'][$i];
            $item_gst   = $_POST['item_gst'][$i];
            $item_total = $_POST['item_total'][$i];

            if ($item_name != '') {
                mysqli_query($con, "INSERT INTO invoice_items 
                    (invoice_id, item_name, item_qty, item_price, item_gst, item_total)
                    VALUES
                    ('$invoice_id', '$item_name', '$item_qty', '$item_price', '$item_gst', '$item_total')");
            }
        }
    }

    // Update ke baad view page pe redirect
    header("Location: invoice_view.php?id=" . $invoice_id);
    exit;
}

// ================== FETCH INVOICE ITEMS (FOR FORM) ==================
$itemsRes = mysqli_query($con, "SELECT * FROM invoice_items WHERE invoice_id = $invoice_id");
$items = [];
if ($itemsRes && mysqli_num_rows($itemsRes) > 0) {
    while ($row = mysqli_fetch_assoc($itemsRes)) {
        $items[] = $row;
    }
}
?>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row g-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        Edit Invoice (<?php echo htmlspecialchars($invoice['invoice_no']); ?>)
                    </div>
                    <div class="card-body">

                        <form action="" method="POST">
                            <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">

                            <h5>Customer Info</h5>
                            <input type="text" name="customer_name" class="form-control mb-2"
                                   placeholder="Customer Name"
                                   value="<?php echo htmlspecialchars($invoice['customer_name']); ?>" required>

                            <input type="text" name="customer_phone" class="form-control mb-2"
                                   placeholder="Phone Number"
                                   value="<?php echo htmlspecialchars($invoice['customer_phone']); ?>">

                            <input type="text" name="customer_address" class="form-control mb-3"
                                   placeholder="Address"
                                   value="<?php echo htmlspecialchars($invoice['customer_address']); ?>">

                            <hr>
                            <h5>Invoice Details</h5>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label>Invoice No:</label>
                                    <input type="text" name="invoice_no" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['invoice_no']); ?>" readonly>
                                </div>
                                <div class="col-md-4">
                                    <label>Invoice Date:</label>
                                    <input type="date" name="invoice_date" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['invoice_date']); ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label>State Name:</label>
                                    <input type="text" name="state_name" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['state_name']); ?>">
                                </div>
                            </div>

                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label>PAN No:</label>
                                    <input type="text" name="pan_no" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['pan_no']); ?>">
                                </div>
                                <div class="col-md-4">
                                    <label>GSTIN No:</label>
                                    <input type="text" name="gstin_no" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['gstin_no']); ?>">
                                </div>
                            </div>

                            <hr>
                            <h5>Invoice Items</h5>

                            <div id="itemRows">

                                <?php if (!empty($items)): ?>
                                    <?php foreach ($items as $it): ?>
                                        <div class="row mb-3 itemRow">
                                            <div class="col-md-3">
                                                <label>Description</label>
                                                <input type="text" name="item_name[]" class="form-control"
                                                       value="<?php echo htmlspecialchars($it['item_name']); ?>" required>
                                            </div>

                                            <div class="col-md-2">
                                                <label>Qty</label>
                                                <input type="number" name="item_qty[]" class="form-control qty"
                                                       value="<?php echo htmlspecialchars($it['item_qty']); ?>" required>
                                            </div>

                                            <div class="col-md-2">
                                                <label>Cost</label>
                                                <input type="number" name="item_price[]" class="form-control price"
                                                       value="<?php echo htmlspecialchars($it['item_price']); ?>" required>
                                            </div>

                                            <div class="col-md-2">
                                                <label>GST</label>
                                                <select name="item_gst[]" class="form-control gst">
                                                    <option value="0"  <?php if($it['item_gst']==0)  echo 'selected'; ?>>0%</option>
                                                    <option value="10" <?php if($it['item_gst']==10) echo 'selected'; ?>>10%</option>
                                                    <option value="18" <?php if($it['item_gst']==18) echo 'selected'; ?>>18%</option>
                                                    <option value="25" <?php if($it['item_gst']==25) echo 'selected'; ?>>25%</option>
                                                </select>
                                            </div>

                                            <div class="col-md-2">
                                                <label>Subtotal</label>
                                                <input type="number" name="item_total[]" class="form-control total"
                                                       value="<?php echo htmlspecialchars($it['item_total']); ?>" readonly>
                                            </div>

                                            <div class="col-md-1 mt-5 d-flex align-items-end">
                                                <button type="button" class="btn btn-danger btn-sm deleteRow">X</button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <!-- Agar kisi reason se items na ho to ek empty row -->
                                    <div class="row mb-3 itemRow">
                                        <div class="col-md-3">
                                            <label>Description</label>
                                            <input type="text" name="item_name[]" class="form-control" required>
                                        </div>

                                        <div class="col-md-2">
                                            <label>Qty</label>
                                            <input type="number" name="item_qty[]" class="form-control qty" value="1" required>
                                        </div>

                                        <div class="col-md-2">
                                            <label>Cost</label>
                                            <input type="number" name="item_price[]" class="form-control price" required>
                                        </div>

                                        <div class="col-md-2">
                                            <label>GST</label>
                                            <select name="item_gst[]" class="form-control gst">
                                                <option value="0">0%</option>
                                                <option value="10">10%</option>
                                                <option value="18">18%</option>
                                                <option value="25">25%</option>
                                            </select>
                                        </div>

                                        <div class="col-md-2">
                                            <label>Subtotal</label>
                                            <input type="number" name="item_total[]" class="form-control total" readonly>
                                        </div>

                                        <div class="col-md-1 mt-5 d-flex align-items-end">
                                            <button type="button" class="btn btn-danger btn-sm deleteRow">X</button>
                                        </div>
                                    </div>
                                <?php endif; ?>

                            </div>

                            <button type="button" class="btn btn-success btn-sm" onclick="addRow()">+ Add Item</button>

                            <hr>

                            <!-- -------------------- GRAND TOTAL BOX -------------------- -->
                            <div class="row">
                                <div class="col-md-4 ms-auto">
                                    <label><b>Total Amount:</b></label>
                                    <input type="number" name="grand_total" id="grand_total" class="form-control"
                                           value="<?php echo htmlspecialchars($invoice['grand_total']); ?>" readonly>
                                </div>
                                <div class="col-md-4 ms-auto">
                                    <label><b>Invoice Type:</b></label>
                                    <select name="invoice_type" class="form-control" required>
                                        <option value="">--- Select Invoice ---</option>
                                        <option value="paid"   <?php if($invoice['invoice_type']=='paid')   echo 'selected'; ?>>Paid</option>
                                        <option value="unpaid" <?php if($invoice['invoice_type']=='unpaid') echo 'selected'; ?>>Unpaid</option>
                                    </select>
                                </div>
                            </div>

                            <br>
                            <button class="btn btn-primary w-100">Update Invoice</button>

                        </form>

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

<script>
// -------------------- CALCULATE PER ROW ----------------------
function calculate(row) {
    let qty = parseFloat(row.querySelector('.qty').value) || 0;
    let price = parseFloat(row.querySelector('.price').value) || 0;
    let gst = parseFloat(row.querySelector('.gst').value) || 0;

    let base = qty * price;
    let gst_amount = base * (gst / 100);
    let total = base + gst_amount;

    row.querySelector('.total').value = total.toFixed(2);

    calculateGrandTotal();
}

// -------------------- CALCULATE GRAND TOTAL ----------------------
function calculateGrandTotal() {
    let totals = document.querySelectorAll('.total');
    let grand = 0;

    totals.forEach(t => {
        grand += parseFloat(t.value) || 0;
    });

    document.getElementById('grand_total').value = grand.toFixed(2);
}

// -------------------- ADD NEW ROW ----------------------
function addRow() {
    let html = `
        <div class="row mb-3 itemRow">
            <div class="col-md-3">
                <label>Description</label>
                <input type="text" name="item_name[]" class="form-control" required>
            </div>

            <div class="col-md-2">
                <label>Qty</label>
                <input type="number" name="item_qty[]" class="form-control qty" value="1" required>
            </div>

            <div class="col-md-2">
                <label>Cost</label>
                <input type="number" name="item_price[]" class="form-control price" required>
            </div>

            <div class="col-md-2">
                <label>GST</label>
                <select name="item_gst[]" class="form-control gst">
                    <option value="0">0%</option>
                    <option value="10">10%</option>
                    <option value="18">18%</option>
                    <option value="25">25%</option>
                </select>
            </div>

            <div class="col-md-2">
                <label>Subtotal</label>
                <input type="number" name="item_total[]" class="form-control total" readonly>
            </div>

            <div class="col-md-1 mt-5 d-flex align-items-end">
                <button type="button" class="btn btn-danger btn-sm deleteRow">X</button>
            </div>
        </div>
    `;

    document.getElementById("itemRows").insertAdjacentHTML("beforeend", html);
}

// -------------------- EVENT LISTENERS ----------------------
document.addEventListener("input", function(e) {
    if (
        e.target.classList.contains("qty") ||
        e.target.classList.contains("price") ||
        e.target.classList.contains("gst")
    ) {
        let row = e.target.closest(".itemRow");
        calculate(row);
    }
});

// DELETE ROW
document.addEventListener("click", function(e) {
    if (e.target.classList.contains("deleteRow")) {
        e.target.closest(".itemRow").remove();
        calculateGrandTotal();
    }
});

// OPTIONAL: page load pe ek baar grand total recalc
window.addEventListener('load', function(){
    calculateGrandTotal();
});
</script>

<?php include 'include/footer.php'; ?>
