<?php
require_once __DIR__ . '/../../Config/functions.php';
require_login();

// Defensive fallback
if (!isset($invoice) || !$invoice) {
  echo "<div class='alert alert-danger m-3'>Invoice not found.</div>";
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice <?= htmlspecialchars($invoice['invoice_no']) ?> | SGAccount</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">

<?php include __DIR__ . '/../layouts/header.php'; ?>
<?php include __DIR__ . '/../layouts/sidebar.php'; ?>

<div class="content-wrapper p-4">
  <section class="content-header d-flex justify-content-between align-items-center">
    <h1><i class="fas fa-file-invoice-dollar mr-2"></i>Invoice #<?= htmlspecialchars($invoice['invoice_no']) ?></h1>
    <a href="router.php?page=ar" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back to List</a>
  </section>

  <section class="content mt-3">
    <div class="card">
      <div class="card-header bg-primary text-white">
        <h5 class="mb-0"><i class="fas fa-user mr-2"></i>Customer: <?= htmlspecialchars($invoice['customer_name']) ?></h5>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-md-4">
            <strong>Invoice Date:</strong><br><?= htmlspecialchars($invoice['invoice_date']) ?>
          </div>
          <div class="col-md-4">
            <strong>Due Date:</strong><br><?= htmlspecialchars($invoice['due_date']) ?: '-' ?>
          </div>
          <div class="col-md-4">
            <strong>Status:</strong><br>
            <span class="badge badge-<?= $invoice['status']=='paid'?'success':($invoice['status']=='partial'?'warning':($invoice['status']=='cancelled'?'danger':'secondary')) ?>">
              <?= ucfirst($invoice['status']) ?>
            </span>
          </div>
        </div>

        <div class="mb-3">
          <strong>Description:</strong>
          <p><?= nl2br(htmlspecialchars($invoice['description'])) ?: '<em>No description provided.</em>' ?></p>
        </div>

        <table class="table table-bordered">
          <thead class="bg-light">
            <tr><th>Field</th><th class="text-right">Amount (SGD)</th></tr>
          </thead>
          <tbody>
            <tr>
              <td>Total Invoice Amount</td>
              <td class="text-right"><?= number_format($invoice['amount'],2) ?></td>
            </tr>
            <tr>
              <td>Received Amount</td>
              <td class="text-right"><?= number_format($invoice['received_amount'],2) ?></td>
            </tr>
            <tr>
              <td><strong>Balance Due</strong></td>
              <td class="text-right font-weight-bold text-<?= ($invoice['amount'] - $invoice['received_amount']) > 0 ? 'danger':'success' ?>">
                <?= number_format($invoice['amount'] - $invoice['received_amount'],2) ?>
              </td>
            </tr>
          </tbody>
        </table>

        <div class="mt-4 d-flex justify-content-between">
          <button class="btn btn-success" data-toggle="modal" data-target="#recordPaymentModal">
            <i class="fas fa-money-check-alt mr-2"></i>Record Payment
          </button>
          <button onclick="window.print()" class="btn btn-outline-secondary">
            <i class="fas fa-print mr-2"></i>Print Invoice
          </button>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- Record Payment Modal -->
<div class="modal fade" id="recordPaymentModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="recordPaymentForm">
        <div class="modal-header bg-success text-white">
          <h5 class="modal-title"><i class="fas fa-money-bill-wave mr-2"></i>Record Payment</h5>
          <button class="close text-white" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="id" value="<?= $invoice['id'] ?>">
          <div class="form-group">
            <label>Amount Received (SGD)</label>
            <input type="number" step="0.01" name="received_amount" value="<?= $invoice['received_amount'] ?>" class="form-control" required>
          </div>
          <div class="form-group">
            <label>Payment Method</label>
            <select name="payment_method" class="form-control">
              <?php foreach(['Cash','Cheque','Bank Transfer','Others'] as $pm): ?>
              <option value="<?= $pm ?>" <?= $pm==$invoice['payment_method']?'selected':'' ?>><?= $pm ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Status</label>
            <select name="status" class="form-control">
              <?php foreach(['unpaid','partial','paid','cancelled'] as $st): ?>
              <option value="<?= $st ?>" <?= $st==$invoice['status']?'selected':'' ?>><?= ucfirst($st) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-success"><i class="fas fa-save mr-1"></i>Update</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../layouts/footer.php'; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
$('#recordPaymentForm').on('submit', function(e){
  e.preventDefault();
  $.post('ajax/ar/edit.php', $(this).serialize(), function(){
    alert('Payment record updated successfully!');
    location.reload();
  });
});
</script>
</body>
</html>
