<div class="container mt-4">
  <div class="card shadow-sm">
    <div class="card-header bg-success text-white">
      <h4 class="mb-0">Edit Invoice #<?= str_pad(htmlspecialchars($invoice['id']), 5, '0', STR_PAD_LEFT) ?>
      </h4>
    </div>
    <div class="card-body">

      <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
      <?php endif; ?>

      <form method="post" action="<?= BASE_URL ?>/invoice/edit/<?= $invoice['id']; ?>" id="invoiceForm">
          
          <!-- Invoice Details Card -->
<div class="card mb-4">
  <div class="card-header bg-light d-flex justify-content-between align-items-center">
    <h5 class="mb-0"> Invoice Details</h5>
  </div>
  <div class="card-body">
    <div class="row g-2">
      <!-- Invoice Type -->
      <div class="col-md-3">
        <select name="invoice_type" class="form-select form-select-sm" required>
          <option value="">-- Select Type --</option>
          <option value="Invoice"<?= ($invoice['invoice_type'] ?? '') === 'Invoice' ? 'selected' : '' ?>>Invoice</option>
          <option value="Quote"<?= ($invoice['invoice_type'] ?? '') === 'Quote' ? 'selected' : '' ?>>Quote</option>
        </select>
      </div>

      <!-- Invoice Date -->
      <div class="col-md-3">
        <div class="date-picker">
          <input type="text" id="invoice_date_display" class="form-control form-control-sm display"
                 placeholder="Invoice Date"  readonly>
          <input type="date" id="invoice_date" name="invoice_date" class="native-date" value="<?= htmlspecialchars($invoice['invoice_date']) ?>">
          <button type="button" class="calendar-btn" aria-label="Pick invoice date"
                  data-target="invoice_date">
            <i class="bi bi-calendar3"></i>
          </button>
        </div>
      </div>

      <!-- Due Date -->
      <div class="col-md-3">
        <div class="date-picker">
          <input type="text" id="due_date_display"  class="form-control form-control-sm display"
                 placeholder="Due Date" readonly>
          <input type="date" id="due_date" name="due_date" class="native-date" value="<?= htmlspecialchars($invoice['due_date']) ?>">
          <button type="button" class="calendar-btn" aria-label="Pick due date"
                  data-target="due_date">
            <i class="bi bi-calendar3"></i>
          </button>
        </div>
      </div>

      <!-- Status -->
      <div class="col-md-3">
        <select name="status" class="form-select form-select-sm" required>
            <option value="">Status</option>
            <option value="Pending" <?= ($invoice['status'] ?? '') === 'Pending' ? 'selected' : '' ?>>Pending</option>
            <option value="Paid" <?= ($invoice['status'] ?? '') === 'Paid' ? 'selected' : '' ?>>Paid</option>
            <option value="Overdue" <?= ($invoice['status'] ?? '') === 'Overdue' ? 'selected' : '' ?>>Overdue</option>
        </select>

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

        <!-- Customer Details -->
        <!-- Customer Details Section -->
<div class="card mb-4">
  <div class="card-header bg-light d-flex justify-content-between align-items-center">
    <h5 class="mb-0"> Customer Details</h5>
    <small class="text-muted">Select existing or add new</small>
  </div>
  <div class="card-body">
    
    <!--// Select existing customer -->
    <div class="mb-3">
      <label for="customerSelect" class="form-label fw-bold">Existing Customer</label>
      <select id="customerSelect" class="form-select form-select-sm">
        <option value="">Select existing customer</option>
        <?php foreach ($customers as $cust): ?>
                                <option value="<?= $cust['id']; ?>" <?= $invoice['customer_id'] == $cust['id'] ? 'selected' : ''; ?>
                                
                  data-name="<?= htmlspecialchars($cust['name']) ?>"
                  data-email="<?= htmlspecialchars($cust['email']) ?>"
                  data-phone="<?= htmlspecialchars($cust['phone']) ?>"
                  data-address_1="<?= htmlspecialchars($cust['address_1']) ?>"
                  data-address_2="<?= htmlspecialchars($cust['address_2']) ?>"
                  data-city="<?= htmlspecialchars($cust['city']) ?>"
                  data-country="<?= htmlspecialchars($cust['country']) ?>"
                  data-postcode="<?= htmlspecialchars($cust['postcode']) ?>"
                  data-unit_number="<?= htmlspecialchars($cust['unit_number']) ?>"
                                
                                >
                                    <?= htmlspecialchars($cust['name']); ?>
                                </option>
        <?php endforeach; ?>
      </select>
      <input type="hidden" name="customer_id" value="<?= htmlspecialchars($invoice['customer_id']) ?>" id="customer_id">
    </div>

    <!-- Customer form fields -->
    <div class="row g-2">
      <div class="col-md-6">
        <input type="text" name="customer_name" id="customer_name" placeholder="Customer Name" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['name'] ?? ''); ?>" required disabled>
      </div>
      <div class="col-md-6">
        <input type="email" name="customer_email" id="customer_email" placeholder="Email" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['email'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-6">
        <input type="text" name="customer_phone" id="customer_phone" placeholder="Phone" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['phone'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-6">
        <input type="text" name="unit_number" id="unit_number" placeholder="Unit Number" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['unit_number'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-6">
        <input type="text" name="address_1" id="address_1" placeholder="Address 1" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['address_1'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-6">
        <input type="text" name="address_2" id="address_2" placeholder="Address 2" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['address_2'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-4">
        <input type="text" name="city" id="city" placeholder="Town/City" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['city'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-4">
        <input type="text" name="country" id="country" placeholder="Country" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['country'] ?? ''); ?>" disabled>
      </div>
      <div class="col-md-4">
        <input type="text" name="postcode" id="postcode" placeholder="Postcode" class="form-control form-control-sm" value="<?= htmlspecialchars($customer['postcode'] ?? ''); ?>" disabled>
      </div>
    </div>
  </div>
</div>


        <hr>

        <!-- Products Section -->
<div class="card mb-4">
  <div class="card-header bg-light d-flex justify-content-between align-items-center">
    <h5 class="mb-0">Products</h5>
    <button type="button" class="btn btn-success btn-sm" id="addProductRow">
      <i class="bi bi-plus"></i> Add Product
    </button>
  </div>
  <div class="card-body p-2">
    <table class="table table-sm table-bordered align-middle mb-0" id="productsTable">
      <thead class="table-secondary">
        <tr>
          <th style="width: 35%;">Product</th>
          <th style="width: 10%;">Qty</th>
          <th style="width: 15%;">Price (R)</th>
          <th style="width: 15%;">Discount</th>
          <th style="width: 15%;">Sub Total (R)</th>
          <th style="width: 5%;"></th>
        </tr>
      </thead>
      <tbody>
                        <?php foreach ($invoiceItems as $item): ?>
                        <tr>
                            <td>
                                <div class="input-group input-group-sm">
                                <select class="form-select product-select" name="product_id[]">
            <option value="">-- Select Product --</option>
            <?php foreach ($products as $prod): ?>
                <?php
                    $isSelected = false;
                    if (!empty($item['product_id']) && $item['product_id'] == $prod['id']) {
                        $isSelected = true;
                    } elseif (empty($item['product_id']) && $item['product_name'] == $prod['name']) {
                        $isSelected = true;
                    }
                ?>
                <option value="<?= $prod['id']; ?>"
                    data-name="<?= htmlspecialchars($prod['name']); ?>"
                    data-price="<?= $prod['price']; ?>"
                    <?= $isSelected ? 'selected' : ''; ?>>
                    <?= htmlspecialchars($prod['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
            <input type="text" name="product_name[]" class="form-control product-name" placeholder="Or type name..." required value="<?= htmlspecialchars($item['product_name']); ?>">
                            </td>
                            </div>
                            <td><input type="number" name="quantity[]" class="form-control form-control-sm product-qty text-end" value="<?= $item['quantity']; ?>"></td>
                            <td><input type="number" name="price[]" step="0.01" class="form-control form-control-sm product-price text-end" value="<?= $item['price']; ?>"></td>
                            <td><input type="number" name="discount[]" step="0.01" class="form-control form-control-sm product-discount text-end" value="<?= $item['discount'] ?? 0; ?>"></td>
                            <td><input type="number" name="total[]" readonly class="form-control form-control-sm product-total text-end" value="<?= $item['total']; ?>"></td>
                            <td><button type="button" class="btn btn-danger btn-sm removeProductRow">&times;</button></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
    </table>
  </div>
</div>

<!-- Summary Section -->
<div class="card">
  <div class="card-header bg-light">
    <h5 class="mb-0">Summary</h5>
  </div>
  <div class="card-body">
    <div class="row g-3">
      
      <!-- Notes Section -->
      <div class="col-md-8">
        <textarea name="notes"  class="form-control form-control-sm" rows="5" placeholder="Additional Notes..."><?= htmlspecialchars($invoice['notes']) ?></textarea>
      </div>

      <!-- Totals Section -->
      <div class="col-md-4">
        <table class="table table-sm table-borderless align-middle mb-0">
          <tbody>
            <tr>
              <th class="text-end">Sub Total:</th>
              <td class="text-end fw-semibold" id="subTotal">R0.00</td>
            </tr>
            <tr>
              <th class="text-end">Discount:</th>
              <td class="text-end fw-semibold" id="discount">R0.00</td>
                
              
            </tr>
            <tr>
              <th class="text-end">Shipping:</th>
              <td class="text-end">
                <div class="d-inline-block" style="width: 100px;">
                  <input type="number" step="0.01" min="0" name="shipping" id="shipping" 
                         value="0" class="form-control form-control-sm text-end">
                </div>
              </td>
            </tr>
            <tr>
              <th class="text-end">TAX/VAT:</th>
              <td class="text-end">
                <div class="d-inline-block" style="width: 100px;">
                  <input type="number" step="0.01" min="0" name="tax" id="tax" 
                         value="0" class="form-control form-control-sm text-end">
                </div>
                <div class="form-check mt-1">
                  <input class="form-check-input" type="checkbox" id="removeTax" checked>
                  <label class="form-check-label small" for="removeTax">Remove TAX/VAT</label>
                </div>
              </td>
            </tr>
            <tr class="fw-bold fs-5 table-active">
              <th class="text-end">Total:</th>
              <td class="text-end text-success" id="totalAmount">R0.00</td>
            </tr>
          </tbody>
        </table>
      </div>

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

        <div class="mt-2">
            <button type="submit" class="btn btn-primary">Save Invoice</button>
            <a href="<?= BASE_URL ?>/invoice" class="btn btn-secondary">Cancel</a>
        </div>
        
      </form>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(function(){
    // Auto fill customer details on selection
    $('#customerSelect').change(function(){
      const selected = $(this).find('option:selected');
      if(selected.val() !== ""){
        $('#customer_id').val(selected.val());
        $('#customer_name').val(selected.data('name'));
        $('#customer_email').val(selected.data('email'));
        $('#customer_phone').val(selected.data('phone'));
        $('#address_1').val(selected.data('address_1'));
        $('#address_2').val(selected.data('address_2'));
        $('#city').val(selected.data('city'));
        $('#country').val(selected.data('country'));
        $('#postcode').val(selected.data('postcode'));
        $('#unit_number').val(selected.data('unit_number'));
      } else {
        $('#customer_id').val('');
        $('#customer_name, #customer_email, #customer_phone, #address_1, #address_2, #city, #country, #postcode, #unit_number').val('');
      }
    });

    // Auto fill product details on product select in row
  $('#productsTable').on('change', '.product-select', function(){
    const row = $(this).closest('tr');
    const selected = $(this).find('option:selected');

    if(selected.val() !== ""){
      row.find('.product-name').val(selected.data('name'));
      row.find('.product-price').val(parseFloat(selected.data('price')).toFixed(2));
      row.find('.product-qty').val(1);
      row.find('.product-discount').val(0);
      updateRowTotal(row);
      updateTotals();
    } else {
      row.find('.product-name, .product-price, .product-qty, .product-discount, .product-total').val('');
      updateTotals();
    }
  });

  // Update total when qty, price, or discount changes
  $('#productsTable').on('input', '.product-price, .product-qty, .product-discount', function(){
    const row = $(this).closest('tr');
    updateRowTotal(row);
    updateTotals();
  });

  // Add new product row
  $('#addProductRow').click(function(){
    const newRow = $('#productsTable tbody tr:first').clone();
    newRow.find('select, input').val('');
    newRow.find('.product-qty').val(1);
    newRow.find('.product-discount').val(0);
    $('#productsTable tbody').append(newRow);
  });

  // Remove product row
  $('#productsTable').on('click', '.removeProductRow', function(){
    if($('#productsTable tbody tr').length > 1){
      $(this).closest('tr').remove();
      updateTotals();
    }
  });

  // Remove tax checkbox
  $('#removeTax').change(function(){
    if($(this).is(':checked')){
      $('#tax').val(0);
    }
    updateTotals();
  });

  // Row calculation
  function updateRowTotal(row){
    const price = parseFloat(row.find('.product-price').val()) || 0;
    const qty = parseInt(row.find('.product-qty').val()) || 0;
    const discount = parseFloat(row.find('.product-discount').val()) || 0;

    let total = (price * qty) - discount;
    if(total < 0) total = 0;
    row.find('.product-total').val(total.toFixed(2));
  }

  // Full totals calculation
  function updateTotals(){
  let subtotal = 0;
  let totalDiscount = 0;

  $('.product-total').each(function(){
    subtotal += parseFloat($(this).val()) || 0;
  });

  // Sum all product discounts
  $('.product-discount').each(function(){
    totalDiscount += parseFloat($(this).val()) || 0;
  });

  $('#subTotal').text("R" + subtotal.toFixed(2));
  $('#discount').text("R" + totalDiscount.toFixed(2)); // Show in summary table

  const shipping = parseFloat($('#shipping').val()) || 0;
  const tax = parseFloat($('#tax').val()) || 0;

  const total = subtotal + shipping + tax;
  $('#totalAmount').text("R" + total.toFixed(2));
}


  // Summary section inputs trigger recalculation
  $('#discount, #shipping, #tax').on('input', updateTotals);

  // Initial totals
  updateTotals();
  });
</script>
