<?php
// === FETCH SCHOOL INFO ===
$school_name = $school_name ?? "My School";
$school_motto = $school_motto ?? "Learning for Excellence";
$school_address = $school_address ?? "123 School Lane, City, Country";

// === GENERATE UNIQUE INVOICE NUMBER ===
$invoice_no = uniqid("INV_");

// === INITIALIZE STUDENT VALUES ===
$reg_number = '';
$student_name = '';
$student_class = '';

if (isset($_POST['fetch_student'])) {
    $reg_number = $_POST['reg_number'];
    $stmt = $connection->prepare("SELECT firstname, othername, lastname, class FROM students WHERE reg_number = ?");
    $stmt->bind_param("s", $reg_number);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $result->num_rows > 0) {
        $student = $result->fetch_assoc();
        $student_name = $student['firstname'] . ' ' . $student['othername'] . ' ' . $student['lastname'];
        $student_class = $student['class'];
    }
}
?>

<!-- Student Fetch Form -->
<form method="POST" class="mb-3">
  <div class="input-group" style="max-width: 300px;">
    <input type="text" name="reg_number" class="form-control" placeholder="Enter Reg Number" required>
    <div class="input-group-append">
      <button type="submit" name="fetch_student" class="btn btn-primary">Fetch</button>
    </div>
  </div>
</form>

<!-- Invoice Form -->
<div class="card">
  <div class="panel panel-primary">
    <div class="panel-heading text-center">
      <h4>Create New Invoice</h4>
    </div>
    <div class="panel-body p-4">
      <form method="POST" action="save_invoice.php">
        <div class="row">
          <div class="col-md-6 mb-3">
            <h4><?= $school_name ?></h4>
            <h5><?= $school_motto ?></h5>
            <p><?= $school_address ?></p>
          </div>

          <div class="col-md-6 mb-3">
            <input type="text" name="cashier" class="form-control mb-2" placeholder="Cashier" value="<?= htmlspecialchars($staff_username) ?>" readonly>
            <input type="text" name="reg_number" class="form-control mb-2" placeholder="Reg Number" value="<?= htmlspecialchars($reg_number) ?>" readonly>
            <input type="text" name="invoice_no" class="form-control mb-2" placeholder="Invoice No" value="<?= $invoice_no ?>" readonly>
            <input type="text" name="student_name" class="form-control mb-2" placeholder="Student Name" value="<?= htmlspecialchars($student_name) ?>" readonly>
            <input type="text" name="student_class" class="form-control mb-2" placeholder="Student Class" value="<?= htmlspecialchars($student_class) ?>" readonly>
          </div>
        </div>

        <!-- Invoice Items -->
        <table class="table table-bordered mt-3" id="invoiceTable">
          <thead class="text-center bg-light">
            <tr>
              <th>Item</th>
              <th>Qty</th>
              <th>Unit Price (₦)</th>
              <th>Total (₦)</th>
              <th><button type="button" class="btn btn-sm btn-success" onclick="addRow()">+</button></th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><input type="text" name="item_name[]" class="form-control" placeholder="Enter item name" required></td>
              <td><input type="number" name="quantity[]" class="form-control qty" min="1" required></td>
              <td><input type="number" name="unit_price[]" class="form-control price" step="0.01" min="0" required></td>
              <td><input type="text" class="form-control total" readonly></td>
              <td><button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">×</button></td>
            </tr>
          </tbody>
        </table>

        <!-- Totals and Payment -->
        <div class="row">
          <div class="col-md-4 offset-md-8">
            <!-- DISCOUNT -->
            <div class="form-group">
              <label>Discount (₦)</label>
              <input type="number" name="discount" id="discount" class="form-control" value="0" min="0" step="0.01">
            </div>
            <div class="form-group">
              <label>Total Amount (₦)</label>
              <input type="text" name="total_amount" id="grandTotal" class="form-control" readonly>
            </div>
            <div class="form-group">
              <label>Amount Paid (₦)</label>
              <input type="number" name="amount_paid" id="amountPaid" class="form-control" min="0" step="0.01" required>
            </div>
            <div class="form-group">
              <label>Balance (₦)</label>
              <input type="text" name="balance" id="balance" class="form-control" readonly>
            </div>
          </div>
        </div>

        <!-- Submit -->
        <div class="text-center">
          <button type="submit" class="btn btn-primary">💾 Save Invoice</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function addRow() {
  const table = document.getElementById("invoiceTable").getElementsByTagName('tbody')[0];
  const newRow = table.insertRow();
  newRow.innerHTML = `
    <td><input type="text" name="item_name[]" class="form-control" placeholder="Enter item name" required></td>
    <td><input type="number" name="quantity[]" class="form-control qty" min="1" required></td>
    <td><input type="number" name="unit_price[]" class="form-control price" step="0.01" min="0" required></td>
    <td><input type="text" class="form-control total" readonly></td>
    <td><button type="button" class="btn btn-sm btn-danger" onclick="removeRow(this)">×</button></td>
  `;
  attachEvents();
}

function removeRow(button) {
  const row = button.closest("tr");
  row.remove();
  calculateTotal();
}

function attachEvents() {
  document.querySelectorAll(".qty, .price").forEach(input => {
    input.addEventListener("input", calculateTotal);
  });
}

function calculateTotal() {
  let grandTotal = 0;
  document.querySelectorAll("#invoiceTable tbody tr").forEach(row => {
    const qty = parseFloat(row.querySelector(".qty").value) || 0;
    const price = parseFloat(row.querySelector(".price").value) || 0;
    const total = qty * price;
    row.querySelector(".total").value = total.toFixed(2);
    grandTotal += total;
  });

  // APPLY DISCOUNT
  const discount = parseFloat(document.getElementById("discount").value) || 0;
  const netTotal = grandTotal - discount;
  document.getElementById("grandTotal").value = netTotal.toFixed(2);

  const paid = parseFloat(document.getElementById("amountPaid").value) || 0;
  document.getElementById("balance").value = (netTotal - paid).toFixed(2);
}

// === EVENT LISTENERS ===
document.getElementById("discount").addEventListener("input", calculateTotal);
document.getElementById("amountPaid").addEventListener("input", calculateTotal);
attachEvents();
</script>
