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

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT b.*, s.name supplier_name, coa.account_code, coa.description acc_desc
                        FROM ap_bills b JOIN suppliers s ON s.id=b.supplier_id
                        JOIN chart_of_accounts coa ON coa.id = b.expense_account_id
                        WHERE b.id = ?");
$stmt->execute([$id]);
$bill = $stmt->fetch();
if (!$bill) { flash('error', 'Bill not found.'); redirect('accounts_payable/list.php'); }

$accounts = get_chart_of_accounts($pdo);
$payablesAccount = get_control_account($pdo, 'Trade Payables');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cashAccountId = $_POST['cash_account_id'] ?? '';
    $amount = (float)($_POST['amount'] ?? 0);
    $paymentDate = $_POST['payment_date'] ?: date('Y-m-d');
    $method = trim($_POST['payment_method'] ?? '');
    $reference = trim($_POST['reference'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    $remaining = $bill['amount'] - $bill['amount_paid'];
    if (!$cashAccountId || $amount <= 0) {
        flash('error', 'Please choose a cash/bank account and a positive amount.');
    } elseif ($amount > $remaining + 0.005) {
        flash('error', 'Payment amount exceeds the remaining balance of ₦' . number_format($remaining,2) . '.');
    } else {
        $pdo->beginTransaction();
        try {
            $payNumber = generate_doc_number($pdo, 'ap_payments', 'id', 'PMT'); // note: numeric id-based table, just for uniqueness of description
            [$ok, $entryResult] = post_journal_entry(
                $pdo, $paymentDate, "Payment for {$bill['bill_number']}",
                [
                    ['account_id' => $payablesAccount['id'], 'debit' => $amount, 'credit' => 0, 'description' => $notes],
                    ['account_id' => $cashAccountId, 'debit' => 0, 'credit' => $amount, 'description' => "Payment for {$bill['bill_number']}"],
                ],
                $u['id'], 'AP_PAYMENT', $id
            );
            if (!$ok) throw new Exception($entryResult);
            $entryId = $entryResult;

            $pdo->prepare("INSERT INTO ap_payments (bill_id, payment_date, amount, cash_account_id, payment_method, reference, notes, journal_entry_id, created_by)
                           VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$id, $paymentDate, $amount, $cashAccountId, $method, $reference, $notes, $entryId, $u['id']]);

            $newPaid = $bill['amount_paid'] + $amount;
            $newStatus = $newPaid >= $bill['amount'] - 0.005 ? 'paid' : 'partially_paid';
            $pdo->prepare("UPDATE ap_bills SET amount_paid=?, status=? WHERE id=?")->execute([$newPaid, $newStatus, $id]);

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

$payStmt = $pdo->prepare("SELECT p.*, coa.account_code, coa.description acc_desc FROM ap_payments p
                           JOIN chart_of_accounts coa ON coa.id = p.cash_account_id
                           WHERE p.bill_id = ? ORDER BY p.payment_date");
$payStmt->execute([$id]);
$payments = $payStmt->fetchAll();
$remaining = $bill['amount'] - $bill['amount_paid'];

$pageTitle = 'Bill ' . $bill['bill_number'];
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6">
  <div>
    <h1 class="text-2xl font-bold"><?= e($bill['bill_number']) ?></h1>
    <p class="text-slate-500 text-sm">Supplier: <?= e($bill['supplier_name']) ?> · <?= e($bill['account_code']) ?> - <?= e($bill['acc_desc']) ?></p>
  </div>
  <?php $badge = ['open'=>'bg-amber-100 text-amber-700','partially_paid'=>'bg-blue-100 text-blue-700','paid'=>'bg-emerald-100 text-emerald-700','void'=>'bg-slate-200 text-slate-500'][$bill['status']]; ?>
  <span class="px-3 py-1 rounded-full text-sm <?= $badge ?> capitalize"><?= str_replace('_',' ',$bill['status']) ?></span>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
  <div class="lg:col-span-2 space-y-6">
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5 grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-4 text-sm">
      <div><p class="text-slate-500 text-xs">Amount</p><p class="font-semibold">₦<?= number_format($bill['amount'],2) ?></p></div>
      <div><p class="text-slate-500 text-xs">Paid</p><p class="font-semibold">₦<?= number_format($bill['amount_paid'],2) ?></p></div>
      <div><p class="text-slate-500 text-xs">Remaining</p><p class="font-semibold">₦<?= number_format($remaining,2) ?></p></div>
    </div>

    <div class="overflow-x-auto">
    <div class="bg-white rounded-xl shadow-sm border border-slate-200">
      <div class="px-5 py-4 border-b border-slate-200 font-semibold">Payment History</div>
      <table class="w-full text-sm">
        <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
          <th class="text-left px-5 py-2">Date</th><th class="text-left px-5 py-2">Amount</th>
          <th class="text-left px-5 py-2">Paid From</th><th class="text-left px-5 py-2">Method</th>
          <th class="text-left px-5 py-2">Reference</th></tr></thead>
        <tbody>
        <?php foreach ($payments as $p): ?>
          <tr class="border-t border-slate-100">
            <td class="px-5 py-2.5"><?= date('M j, Y', strtotime($p['payment_date'])) ?></td>
            <td class="px-5 py-2.5">₦<?= number_format($p['amount'],2) ?></td>
            <td class="px-5 py-2.5"><?= e($p['account_code']) ?> - <?= e($p['acc_desc']) ?></td>
            <td class="px-5 py-2.5"><?= e($p['payment_method']) ?></td>
            <td class="px-5 py-2.5"><?= e($p['reference']) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($payments)): ?><tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">No payments recorded yet.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
    </div>
  </div>

  <div>
    <?php if ($bill['status'] !== 'paid' && $bill['status'] !== 'void'): ?>
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
      <p class="text-sm font-semibold mb-3">Record Payment</p>
      <form method="POST" class="space-y-3">
        <div>
          <label class="text-xs text-slate-500 block mb-1">Paid From</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 cash/bank account..." autocomplete="off" required>
            <input type="hidden" class="account-id-input" name="cash_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>
        <input type="date" name="payment_date" value="<?= date('Y-m-d') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <input type="number" step="0.01" name="amount" max="<?= $remaining ?>" value="<?= $remaining ?>" required placeholder="Amount" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <input name="payment_method" placeholder="Payment method (e.g. Bank Transfer)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <input name="reference" placeholder="Reference (e.g. transaction ID)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <textarea name="notes" placeholder="Notes" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"></textarea>
        <button class="w-full bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Save Payment</button>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>

<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'; ?>
