<?php
require_once __DIR__ . '/../config/config.php';
require_permission('accounting.ar_manage');
$u = current_user();

$customers = $pdo->query("SELECT id, name FROM ar_customers WHERE is_active=1 ORDER BY name")->fetchAll();
$accounts = get_chart_of_accounts($pdo);
$receivablesAccount = get_control_account($pdo, 'Trade Receivables');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customerId = $_POST['customer_id'] ?? '';
    $revenueAccountId = $_POST['revenue_account_id'] ?? '';
    $invoiceDate = $_POST['invoice_date'] ?: date('Y-m-d');
    $dueDate = $_POST['due_date'] ?: null;
    $amount = (float)($_POST['amount'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');

    if (!$receivablesAccount) {
        flash('error', 'No active "Trade Receivables" account found in the Chart of Accounts. Add one first.');
    } elseif (!$customerId || !$revenueAccountId || $amount <= 0) {
        flash('error', 'Customer, income account, and a positive amount are all required.');
    } else {
        $pdo->beginTransaction();
        try {
            $invoiceNumber = generate_doc_number($pdo, 'ar_invoices', 'invoice_number', 'INV');

            [$ok, $entryResult] = post_journal_entry(
                $pdo, $invoiceDate, "Invoice $invoiceNumber",
                [
                    ['account_id' => $receivablesAccount['id'], 'debit' => $amount, 'credit' => 0, 'description' => "Invoice $invoiceNumber"],
                    ['account_id' => $revenueAccountId, 'debit' => 0, 'credit' => $amount, 'description' => $notes],
                ],
                $u['id'], 'AR_INVOICE', null
            );
            if (!$ok) throw new Exception($entryResult);
            $entryId = $entryResult;

            $pdo->prepare("INSERT INTO ar_invoices (invoice_number, customer_id, revenue_account_id, invoice_date, due_date, amount, notes, journal_entry_id, created_by)
                           VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$invoiceNumber, $customerId, $revenueAccountId, $invoiceDate, $dueDate, $amount, $notes, $entryId, $u['id']]);
            $invoiceId = $pdo->lastInsertId();

            $pdo->prepare("UPDATE journal_entries SET reference_id=? WHERE id=?")->execute([$invoiceId, $entryId]);

            $pdo->commit();
            flash('success', "Invoice $invoiceNumber recorded.");
            redirect('accounts_receivable/view.php?id=' . $invoiceId);
        } catch (Exception $ex) {
            $pdo->rollBack();
            flash('error', 'Failed: ' . $ex->getMessage());
        }
    }
}

$pageTitle = 'New Invoice';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">New Accounts Receivable Invoice</h1>
<p class="text-slate-500 text-sm mb-6">Posts: Debit
  <?= $receivablesAccount ? e($receivablesAccount['account_code'] . ' - ' . $receivablesAccount['description']) : '⚠ no Trade Receivables account found' ?>,
  Credit the income account below.
</p>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 max-w-xl space-y-4">
  <div>
    <label class="text-sm font-medium block mb-1">Customer</label>
    <select name="customer_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <option value="">-- Select customer --</option>
      <?php foreach ($customers as $c): ?><option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option><?php endforeach; ?>
    </select>
    <p class="text-xs text-slate-400 mt-1">Don't see them? <a href="customers.php" class="text-blue-600 hover:underline">Add a customer first</a>.</p>
  </div>
  <div>
    <label class="text-sm font-medium block mb-1">Income Account (what this invoice is for)</label>
    <div class="account-autocomplete relative">
      <input type="text" class="account-search w-full border border-slate-300 rounded-lg px-3 py-2 text-sm" placeholder="Type to search account..." autocomplete="off" required>
      <input type="hidden" class="account-id-input" name="revenue_account_id">
      <div class="account-dropdown hidden absolute z-20 bg-white border border-slate-200 rounded-lg mt-1 max-h-48 overflow-y-auto w-full shadow-lg"></div>
    </div>
  </div>
  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
    <div>
      <label class="text-sm font-medium block mb-1">Invoice Date</label>
      <input type="date" name="invoice_date" value="<?= date('Y-m-d') ?>" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div>
      <label class="text-sm font-medium block mb-1">Due Date</label>
      <input type="date" name="due_date" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
  </div>
  <div>
    <label class="text-sm font-medium block mb-1">Amount</label>
    <input type="number" step="0.01" name="amount" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>
  <div>
    <label class="text-sm font-medium block mb-1">Notes</label>
    <textarea name="notes" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"></textarea>
  </div>
  <button type="submit" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Save Invoice</button>
</form>

<script>
window.ACCOUNTS_DATA = <?= json_encode(array_map(fn($a) => ['id' => $a['id'], 'code' => $a['account_code'], 'name' => $a['description']], $accounts)) ?>;
</script>
<?php include __DIR__ . '/../includes/account_autocomplete.php'; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
