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

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT inv.*, c.name customer_name, coa.account_code, coa.description acc_desc
                        FROM ar_invoices inv JOIN ar_customers c ON c.id=inv.customer_id
                        JOIN chart_of_accounts coa ON coa.id = inv.revenue_account_id
                        WHERE inv.id = ?");
$stmt->execute([$id]);
$invoice = $stmt->fetch();
if (!$invoice) { flash('error', 'Invoice not found.'); redirect('accounts_receivable/list.php'); }

$accounts = get_chart_of_accounts($pdo);
$receivablesAccount = get_control_account($pdo, 'Trade Receivables');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $depositAccountId = $_POST['deposit_account_id'] ?? '';
    $amount = (float)($_POST['amount'] ?? 0);
    $receiptDate = $_POST['receipt_date'] ?: date('Y-m-d');
    $method = trim($_POST['payment_method'] ?? '');
    $reference = trim($_POST['reference'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    $remaining = $invoice['amount'] - $invoice['amount_received'];
    if (!$receivablesAccount) {
        flash('error', 'No active "Trade Receivables" account found in the Chart of Accounts.');
    } elseif (!$depositAccountId || $amount <= 0) {
        flash('error', 'Please choose a cash/bank account and a positive amount.');
    } elseif ($amount > $remaining + 0.005) {
        flash('error', 'Receipt amount exceeds the remaining balance of ₦' . number_format($remaining,2) . '.');
    } else {
        $pdo->beginTransaction();
        try {
            [$ok, $entryResult] = post_journal_entry(
                $pdo, $receiptDate, "Receipt for {$invoice['invoice_number']}",
                [
                    ['account_id' => $depositAccountId, 'debit' => $amount, 'credit' => 0, 'description' => "Receipt for {$invoice['invoice_number']}"],
                    ['account_id' => $receivablesAccount['id'], 'debit' => 0, 'credit' => $amount, 'description' => $notes],
                ],
                $u['id'], 'AR_RECEIPT', $id
            );
            if (!$ok) throw new Exception($entryResult);
            $entryId = $entryResult;

            $pdo->prepare("INSERT INTO ar_receipts (invoice_id, deposit_account_id, receipt_date, amount, payment_method, reference, notes, journal_entry_id, created_by)
                           VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$id, $depositAccountId, $receiptDate, $amount, $method, $reference, $notes, $entryId, $u['id']]);

            $newReceived = $invoice['amount_received'] + $amount;
            $newStatus = $newReceived >= $invoice['amount'] - 0.005 ? 'received' : 'partially_received';
            $pdo->prepare("UPDATE ar_invoices SET amount_received=?, status=? WHERE id=?")->execute([$newReceived, $newStatus, $id]);

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

$recStmt = $pdo->prepare("SELECT r.*, coa.account_code, coa.description acc_desc FROM ar_receipts r
                           JOIN chart_of_accounts coa ON coa.id = r.deposit_account_id
                           WHERE r.invoice_id = ? ORDER BY r.receipt_date");
$recStmt->execute([$id]);
$receipts = $recStmt->fetchAll();
$remaining = $invoice['amount'] - $invoice['amount_received'];

$pageTitle = 'Invoice ' . $invoice['invoice_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($invoice['invoice_number']) ?></h1>
    <p class="text-slate-500 text-sm">Customer: <?= e($invoice['customer_name']) ?> · <?= e($invoice['account_code']) ?> - <?= e($invoice['acc_desc']) ?></p>
  </div>
  <?php $badge = ['open'=>'bg-amber-100 text-amber-700','partially_received'=>'bg-blue-100 text-blue-700','received'=>'bg-emerald-100 text-emerald-700','void'=>'bg-slate-200 text-slate-500'][$invoice['status']]; ?>
  <span class="px-3 py-1 rounded-full text-sm <?= $badge ?> capitalize"><?= str_replace('_',' ',$invoice['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($invoice['amount'],2) ?></p></div>
      <div><p class="text-slate-500 text-xs">Received</p><p class="font-semibold">₦<?= number_format($invoice['amount_received'],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">Receipt 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">Deposited To</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 ($receipts as $r): ?>
          <tr class="border-t border-slate-100">
            <td class="px-5 py-2.5"><?= date('M j, Y', strtotime($r['receipt_date'])) ?></td>
            <td class="px-5 py-2.5">₦<?= number_format($r['amount'],2) ?></td>
            <td class="px-5 py-2.5"><?= e($r['account_code']) ?> - <?= e($r['acc_desc']) ?></td>
            <td class="px-5 py-2.5"><?= e($r['payment_method']) ?></td>
            <td class="px-5 py-2.5"><?= e($r['reference']) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($receipts)): ?><tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">No receipts recorded yet.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
    </div>
  </div>

  <div>
    <?php if ($invoice['status'] !== 'received' && $invoice['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 Receipt</p>
      <form method="POST" class="space-y-3">
        <div>
          <label class="text-xs text-slate-500 block mb-1">Deposit To</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="deposit_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="receipt_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 Receipt</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'; ?>
