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

// -------- INVOICE NUMBER AUTO GENERATE FUNCTION --------
function generateInvoiceNo($con) {
    $prefix = 'RNW-';   // agar prefix nahi chahiye to isko '' kar dena
    $start  = 100;      // starting number (00100)
    $digits = 5;        // kitne digits ka number: 00100 => 5

    $sql = "SELECT invoice_no FROM invoices ORDER BY id DESC LIMIT 1";
    $res = mysqli_query($con, $sql);

    if ($res && mysqli_num_rows($res) > 0) {
        $row = mysqli_fetch_assoc($res);
        $last_invoice_no = $row['invoice_no'];

        // sirf number nikaal lo (RNW-00123 => 00123)
        $num = preg_replace('/\D/', '', $last_invoice_no);

        if ($num === '') {
            $num = $start;
        } else {
            $num = (int)$num + 1;
            if ($num < $start) {
                $num = $start;
            }
        }
    } else {
        // agar koi invoice nahi hai to 00100 se start
        $num = $start;
    }

    return $prefix . str_pad($num, $digits, '0', STR_PAD_LEFT);
}

// GET / first load pe invoice no generate
$generated_invoice_no = generateInvoiceNo($con);

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

    $customer_name   = $_POST['customer_name'];
    $customer_phone  = $_POST['customer_phone'];
    $customer_address= $_POST['customer_address'];
    // $invoice_no = $_POST['invoice_no']; // user se nahi, hum khud generate karenge
    $invoice_no      = generateInvoiceNo($con); // dobara generate (safety ke liye)
    $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'];

    // Insert Invoice
    $sql = "INSERT INTO invoices 
        (customer_name, customer_phone, customer_address, invoice_no, invoice_date, state_name, pan_no, gstin_no, invoice_type, grand_total)
        VALUES 
        ('$customer_name','$customer_phone','$customer_address','$invoice_no','$invoice_date','$state_name','$pan_no','$gstin_no','$invoice_type','$grand_total')";

    mysqli_query($con, $sql);

    $invoice_id = mysqli_insert_id($con);

    // Insert Items
    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];

        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')");
    }

    header("Location: invoice_view.php?id=$invoice_id");
    exit;
}
?>

<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">Invoice Generator </div>
                    <div class="card-body">

                        <!-- FORM AB ISI PAGE PE POST HOGA -->
                        <form action="" method="POST">

                            <h5>Customer Info</h5>
                            <input type="text" name="customer_name" class="form-control mb-2" placeholder="Customer Name" required>
                            <input type="text" name="customer_phone" class="form-control mb-2" placeholder="Phone Number">
                            <input type="text" name="customer_address" class="form-control mb-3" placeholder="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($generated_invoice_no); ?>" readonly>
                                </div>
                                <div class="col-md-4">
                                    <label>Invoice Date:</label>
                                    <input type="date" name="invoice_date" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label>State Name:</label>
                                    <input type="text" name="state_name" class="form-control"  >
                                </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">
                                </div>
                                <div class="col-md-4">
                                    <label>GSTIN No:</label>
                                    <input type="text" name="gstin_no" class="form-control">
                                </div>
                            </div>

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

                            <div id="itemRows">

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

                            </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" 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">Paid</option>
                                        <option value="unpaid">Unpaid</option>
                                    </select>
                                </div>
                            </div>

                            <br>
                            <button class="btn btn-primary w-100">Generate 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();
    }
});

</script>

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