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

$suppliers = $pdo->query("SELECT id, name FROM suppliers WHERE is_active=1 ORDER BY name")->fetchAll();
$accounts = get_chart_of_accounts($pdo);
$payablesAccount = get_control_account($pdo, 'Trade Payables');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplierId = $_POST['supplier_id'] ?? '';
    $expenseAccountId = $_POST['expense_account_id'] ?? '';
    $billDate = $_POST['bill_date'] ?: date('Y-m-d');
    $dueDate = $_POST['due_date'] ?: null;
    $amount = (float)($_POST['amount'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');

    if (!$payablesAccount) {
        flash('error', 'No active "Trade Payables" account found in the Chart of Accounts. Add one first.');
    } elseif (!$supplierId || !$expenseAccountId || $amount <= 0) {
        flash('error', 'Supplier, account, and a positive amount are all required.');
    } else {
        $pdo->beginTransaction();
        try {
            $billNumber = generate_doc_number($pdo, 'ap_bills', 'bill_number', 'BILL');

            [$ok, $entryResult] = post_journal_entry(
                $pdo, $billDate, "Bill $billNumber",
                [
                    ['account_id' => $expenseAccountId, 'debit' => $amount, 'credit' => 0, 'description' => $notes],
                    ['account_id' => $payablesAccount['id'], 'debit' => 0, 'credit' => $amount, 'description' => "Bill $billNumber"],
                ],
                $u['id'], 'AP_BILL', null
            );
            if (!$ok) throw new Exception($entryResult);
            $entryId = $entryResult;

            $pdo->prepare("INSERT INTO ap_bills (bill_number, supplier_id, expense_account_id, bill_date, due_date, amount, notes, journal_entry_id, created_by)
                           VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$billNumber, $supplierId, $expenseAccountId, $billDate, $dueDate, $amount, $notes, $entryId, $u['id']]);
            $billId = $pdo->lastInsertId();

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

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

$pageTitle = 'New Bill';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">New Accounts Payable Bill</h1>
<p class="text-slate-500 text-sm mb-6">Posts: Debit the account below, Credit
  <?= $payablesAccount ? e($payablesAccount['account_code'] . ' - ' . $payablesAccount['description']) : '⚠ no Trade Payables account found' ?>.
</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">Supplier</label>
    <select name="supplier_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <option value="">-- Select supplier --</option>
      <?php foreach ($suppliers as $s): ?><option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
    </select>
  </div>
  <div>
    <label class="text-sm font-medium block mb-1">Expense / Asset Account (what was purchased)</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="expense_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">Bill Date</label>
      <input type="date" name="bill_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 Bill</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'; ?>
