<?php
declare(strict_types=1);
require_once __DIR__ . '/../../../app/Models/Ar.php';

header('Content-Type: text/html; charset=utf-8');
$model = new Ar();

// --- HANDLE GET REQUEST: LOAD EDIT FORM ---
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $inv = $model->getById($id);

    if (!$inv) {
        echo '<div class="alert alert-danger m-3">Invoice not found.</div>';
        exit;
    }
?>
<form id="editInvoiceForm">
  <input type="hidden" name="id" value="<?= htmlspecialchars($inv['id']) ?>">

  <div class="form-row">
    <div class="form-group col-md-6">
      <label>Customer Name</label>
      <input type="text" name="customer_name" value="<?= htmlspecialchars($inv['customer_name']) ?>" class="form-control" required>
    </div>
    <div class="form-group col-md-3">
      <label>Invoice Date</label>
      <input type="date" name="invoice_date" value="<?= htmlspecialchars($inv['invoice_date']) ?>" class="form-control" required>
    </div>
    <div class="form-group col-md-3">
      <label>Due Date</label>
      <input type="date" name="due_date" value="<?= htmlspecialchars($inv['due_date']) ?>" class="form-control">
    </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 (SGD)</label>
      <input type="number" step="0.01" name="amount" value="<?= htmlspecialchars($inv['amount']) ?>" class="form-control" required>
    </div>
    <div class="form-group col-md-3">
      <label>Received Amount</label>
      <input type="number" step="0.01" name="received_amount" value="<?= htmlspecialchars($inv['received_amount']) ?>" class="form-control">
    </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>

  <div class="text-right">
    <button type="submit" class="btn btn-warning">
      <i class="fas fa-save mr-1"></i> Update Invoice
    </button>
  </div>
</form>

<script>
$('#editInvoiceForm').on('submit', function(e) {
  e.preventDefault();
  $.post('ajax/ar/edit.php', $(this).serialize())
    .done(function() {
      $('#editInvoiceModal').modal('hide');
      $('<div class="alert alert-success m-3">Invoice updated successfully.</div>')
        .appendTo('.content-wrapper').delay(2000).fadeOut(500, function() { $(this).remove(); });
      setTimeout(() => location.reload(), 800);
    })
    .fail(function() {
      alert('Server error while updating invoice.');
    });
});
</script>
<?php
    exit;
}

// --- HANDLE POST REQUEST: UPDATE INVOICE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($id <= 0) {
        http_response_code(400);
        echo 'Invalid invoice ID';
        exit;
    }

    $updateData = [
        'customer_name'  => $_POST['customer_name'] ?? '',
        'invoice_date'   => $_POST['invoice_date'] ?? '',
        'due_date'       => $_POST['due_date'] ?? null,
        'description'    => $_POST['description'] ?? '',
        'amount'         => (float)($_POST['amount'] ?? 0),
        'received_amount'=> (float)($_POST['received_amount'] ?? 0),
        'payment_method' => $_POST['payment_method'] ?? 'Cash',
        'status'         => $_POST['status'] ?? 'unpaid'
    ];

    $ok = $model->update($id, $updateData);

    if ($ok) {
        echo 'success';
    } else {
        http_response_code(500);
        echo 'Database update failed';
    }
    exit;
}
?>
