<?php
require_once __DIR__ . '/../../../app/Models/Ar.php';
$model = new Ar();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $inv = $model->getById((int)$_GET['id']);
    if (!$inv) { echo "Invoice not found"; exit; }
?>
<form id="editInvoiceForm">
  <input type="hidden" name="id" value="<?= $inv['id'] ?>">
  <div class="form-row">
    <div class="form-group col-md-6"><label>Customer Name</label><input name="customer_name" class="form-control" value="<?= htmlspecialchars($inv['customer_name']) ?>"></div>
    <div class="form-group col-md-3"><label>Invoice Date</label><input type="date" name="invoice_date" class="form-control" value="<?= $inv['invoice_date'] ?>"></div>
    <div class="form-group col-md-3"><label>Due Date</label><input type="date" name="due_date" class="form-control" value="<?= $inv['due_date'] ?>"></div>
  </div>
  <div class="form-group"><label>Description</label><textarea name="description" rows="2" class="form-control"><?= htmlspecialchars($inv['description']) ?></textarea></div>
  <div class="form-row">
    <div class="form-group col-md-3"><label>Amount</label><input type="number" step="0.01" name="amount" class="form-control" value="<?= $inv['amount'] ?>"></div>
    <div class="form-group col-md-3"><label>Received</label><input type="number" step="0.01" name="received_amount" class="form-control" value="<?= $inv['received_amount'] ?>"></div>
    <div class="form-group col-md-3"><label>Payment Method</label>
      <select name="payment_method" class="form-control">
        <?php foreach(['Cash','Cheque','Bank Transfer','Others'] as $pm): ?>
          <option value="<?= $pm ?>" <?= $pm==$inv['payment_method']?'selected':'' ?>><?= $pm ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="form-group col-md-3"><label>Status</label>
      <select name="status" class="form-control">
        <?php foreach(['unpaid','partial','paid','cancelled'] as $st): ?>
          <option value="<?= $st ?>" <?= $st==$inv['status']?'selected':'' ?>><?= ucfirst($st) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
  </div>
  <button type="submit" class="btn btn-warning btn-block">Update</button>
</form>
<script>
$('#editInvoiceForm').on('submit', function(e){
  e.preventDefault();
  $.post('ajax/ar/edit.php', $(this).serialize(), function(){ location.reload(); });
});
</script>
<?php
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $model->update((int)$_POST['id'], $_POST);
    echo 'updated';
}
