<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// ── Handle new payment submission ──────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'record_payment') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header('Location: payments.php?customer_id=' . (int)($_POST['customer_id'] ?? 0)); exit;
    }

    $invoiceId      = (int)$_POST['invoice_id'];
    $amount         = (float)$_POST['amount'];
    $tdsAmount      = (float)($_POST['tds_amount'] ?? 0);
    $paymentDT      = $_POST['payment_datetime'];
    $mode           = trim($_POST['payment_mode']);
    $note           = trim($_POST['reference_note'] ?? '');
    $customerId     = (int)$_POST['customer_id'];
    $bankAccountId  = (int)($_POST['bank_account_id'] ?? 0);

    // Validate against balance due
    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE id=?");
    $stmt->execute([$invoiceId]);
    $inv = $stmt->fetch();

    if (!$inv) {
        setFlash('danger', 'Invoice not found.');
        header("Location: payments.php?customer_id=$customerId"); exit;
    }

    $balanceDue = $inv['grand_total'] - $inv['paid_amount'] - $inv['tds_amount'];
    if (($amount + $tdsAmount) > $balanceDue + 0.01) {
        setFlash('danger', 'Amount + TDS exceeds the balance due (' . formatMoney($balanceDue) . '). Please re-check.');
        header("Location: payments.php?customer_id=$customerId&invoice_id=$invoiceId"); exit;
    }
    if ($amount <= 0 && $tdsAmount <= 0) {
        setFlash('danger', 'Enter a payment amount or TDS amount greater than zero.');
        header("Location: payments.php?customer_id=$customerId&invoice_id=$invoiceId"); exit;
    }

    try {
        $pdo->beginTransaction();
        $result = recordInvoicePayment($invoiceId, $amount, $tdsAmount, $paymentDT, $mode, $note, currentUserId(), $bankAccountId);
        $pdo->commit();

        if ($result['fully_paid']) {
            setFlash('success', "Full payment received! Invoice {$inv['invoice_no']} is now marked PAID and stock has moved from Freeze to Sold.");
        } else {
            setFlash('success', "Payment of " . formatMoney($amount) . ($tdsAmount > 0 ? " + TDS " . formatMoney($tdsAmount) : "") . " recorded. Remaining balance updated.");
        }
    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error recording payment: ' . $e->getMessage());
    }

    header("Location: payments.php?customer_id=$customerId&invoice_id=$invoiceId"); exit;
}

// ── Load data for display ──────────────────────────────────────
$customers = $pdo->query("SELECT * FROM sale_vendors WHERE status=1 ORDER BY customer_name")->fetchAll();

$selectedCustomerId = (int)($_GET['customer_id'] ?? 0);
$selectedInvoiceId  = (int)($_GET['invoice_id'] ?? 0);

$customerInvoices = [];
$selectedCustomer = null;
$totals = ['total_billed' => 0, 'total_paid' => 0, 'total_tds' => 0, 'total_due' => 0];

$bankAccounts = $pdo->query("SELECT id, account_name, account_subtype, current_balance FROM accounts WHERE account_subtype IN ('bank','cash') AND is_active=1 ORDER BY account_code")->fetchAll();

if ($selectedCustomerId) {
    $stmt = $pdo->prepare("SELECT * FROM sale_vendors WHERE id=?");
    $stmt->execute([$selectedCustomerId]);
    $selectedCustomer = $stmt->fetch();

    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE customer_id=? ORDER BY invoice_date DESC, id DESC");
    $stmt->execute([$selectedCustomerId]);
    $customerInvoices = $stmt->fetchAll();

    foreach ($customerInvoices as $inv) {
        $totals['total_billed'] += $inv['grand_total'];
        $totals['total_paid']   += $inv['paid_amount'];
        $totals['total_tds']    += $inv['tds_amount'];
    }
    $totals['total_due'] = $totals['total_billed'] - $totals['total_paid'] - $totals['total_tds'];
}

$selectedInvoice = null;
$paymentHistory  = [];
if ($selectedInvoiceId) {
    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE id=?");
    $stmt->execute([$selectedInvoiceId]);
    $selectedInvoice = $stmt->fetch();
    $paymentHistory  = getInvoicePaymentHistory($selectedInvoiceId);
}

$csrf = generateCSRFToken();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Payments';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Billing</div>
        <h2 class="mb-0">Payments</h2>
    </div>
</div>

<div class="card">
    <div class="card-title">Step 1: Select Customer</div>
    <form method="GET" class="flex gap-8">
        <select name="customer_id" onchange="this.form.submit()" style="max-width:360px;">
            <option value="">-- Select Customer --</option>
            <?php foreach ($customers as $c): ?>
            <option value="<?= $c['id'] ?>" <?= $selectedCustomerId==$c['id']?'selected':'' ?>>
                <?= sanitize($c['customer_name']) ?> (<?= sanitize($c['customer_code']) ?>)
            </option>
            <?php endforeach; ?>
        </select>
        <noscript><button class="btn btn-primary">Load</button></noscript>
    </form>
</div>

<?php if ($selectedCustomer): ?>

<div class="stat-grid">
    <div class="stat-card info">
        <div class="stat-label">Total Billed</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totals['total_billed']) ?></div>
    </div>
    <div class="stat-card success">
        <div class="stat-label">Total Received</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totals['total_paid']) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Total TDS Deducted</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totals['total_tds']) ?></div>
    </div>
    <div class="stat-card <?= $totals['total_due']>0?'danger':'success' ?>">
        <div class="stat-label">Balance Due</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totals['total_due']) ?></div>
    </div>
</div>

<div class="card">
    <div class="card-title">
        Invoices for <?= sanitize($selectedCustomer['customer_name']) ?>
    </div>
    <?php if ($customerInvoices): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Invoice #</th><th>Date</th><th class="text-right">Total</th>
                    <th class="text-right">Paid</th><th class="text-right">TDS</th>
                    <th class="text-right">Balance</th><th>Status</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($customerInvoices as $inv):
                $bal = $inv['grand_total'] - $inv['paid_amount'] - $inv['tds_amount'];
            ?>
            <tr class="<?= $selectedInvoiceId==$inv['id']?'highlighted-row':'' ?>" style="<?= $selectedInvoiceId==$inv['id']?'background:var(--color-surface-2);':'' ?>">
                <td class="mono"><?= sanitize($inv['invoice_no']) ?></td>
                <td><?= formatDate($inv['invoice_date']) ?></td>
                <td class="num"><?= formatMoney($inv['grand_total']) ?></td>
                <td class="num text-success"><?= formatMoney($inv['paid_amount']) ?></td>
                <td class="num"><?= formatMoney($inv['tds_amount']) ?></td>
                <td class="num <?= $bal>0?'text-danger':'' ?>"><strong><?= formatMoney($bal) ?></strong></td>
                <td><span class="badge badge-<?= $inv['payment_status']=='paid'?'success':($inv['payment_status']=='partial'?'warning':'danger') ?>"><?= $inv['payment_status'] ?></span></td>
                <td>
                    <?php if ($bal > 0.01): ?>
                    <a href="?customer_id=<?= $selectedCustomerId ?>&invoice_id=<?= $inv['id'] ?>" class="btn btn-sm btn-primary"><?= icon('cash') ?> Pay</a>
                    <?php else: ?>
                    <a href="?customer_id=<?= $selectedCustomerId ?>&invoice_id=<?= $inv['id'] ?>" class="btn btn-sm"><?= icon('eye') ?> History</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('receipt') ?> No invoices found for this customer.</div>
    <?php endif; ?>
</div>

<?php endif; ?>

<?php if ($selectedInvoice):
    $balanceDue = $selectedInvoice['grand_total'] - $selectedInvoice['paid_amount'] - $selectedInvoice['tds_amount'];
?>
<div class="card" style="border-color:var(--color-primary);">
    <div class="card-title flex-between">
        <span>Invoice <?= sanitize($selectedInvoice['invoice_no']) ?> — Payment Details</span>
        <a href="../invoice/invoice_view.php?id=<?= $selectedInvoice['id'] ?>" class="btn btn-sm"><?= icon('eye') ?> View Full Invoice</a>
    </div>

    <div class="form-grid" style="margin-bottom:16px;">
        <div><div class="text-sm text-muted">Grand Total</div><strong class="mono" style="font-size:16px;"><?= formatMoney($selectedInvoice['grand_total']) ?></strong></div>
        <div><div class="text-sm text-muted">Paid So Far</div><strong class="mono text-success" style="font-size:16px;"><?= formatMoney($selectedInvoice['paid_amount']) ?></strong></div>
        <div><div class="text-sm text-muted">TDS Deducted</div><strong class="mono" style="font-size:16px;"><?= formatMoney($selectedInvoice['tds_amount']) ?></strong></div>
        <div><div class="text-sm text-muted">Balance Due</div><strong class="mono <?= $balanceDue>0?'text-danger':'text-success' ?>" style="font-size:16px;"><?= formatMoney($balanceDue) ?></strong></div>
    </div>

    <?php if ($balanceDue > 0.01): ?>
    <fieldset>
        <legend>Record New Payment</legend>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="record_payment">
            <input type="hidden" name="invoice_id" value="<?= $selectedInvoice['id'] ?>">
            <input type="hidden" name="customer_id" value="<?= $selectedCustomerId ?>">

            <div class="form-grid">
                <div class="form-group">
                    <label>Amount Received <span class="req">*</span></label>
                    <input type="number" step="0.01" name="amount" id="payAmount" value="<?= number_format($balanceDue,2,'.','') ?>" oninput="recalcBalance()" required>
                    <div class="text-sm text-faint">Balance due: <?= formatMoney($balanceDue) ?></div>
                </div>
                <div class="form-group">
                    <label>TDS Deducted (if any)</label>
                    <input type="number" step="0.01" name="tds_amount" id="payTds" value="0" oninput="recalcBalance()">
                    <div class="text-sm text-faint">Tax Deducted at Source by customer, counted toward settlement</div>
                </div>
                <div class="form-group">
                    <label>Payment Date &amp; Time <span class="req">*</span></label>
                    <input type="datetime-local" name="payment_datetime" value="<?= date('Y-m-d\TH:i') ?>" required>
                </div>
                <div class="form-group">
                    <label>Payment Mode <span class="req">*</span></label>
                    <select name="payment_mode" required>
                        <option value="Cash">Cash</option>
                        <option value="Bank Transfer">Bank Transfer</option>
                        <option value="UPI">UPI</option>
                        <option value="Cheque">Cheque</option>
                        <option value="Card">Card</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Received Into Account <span class="req">*</span></label>
                    <select name="bank_account_id" required>
                        <option value="">-- Select Bank/Cash Account --</option>
                        <?php foreach ($bankAccounts as $ba): ?>
                        <option value="<?= $ba['id'] ?>">
                            <?= sanitize($ba['account_name']) ?> (<?= formatMoney($ba['current_balance']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="text-sm text-faint">Which bank/cash account did you receive this payment into?</div>
                </div>
                <div class="form-group full">
                    <label>Reference Note</label>
                    <input type="text" name="reference_note" placeholder="e.g. Cheque no. 123456, UTR number, etc.">
                </div>
            </div>

            <div style="background:var(--color-surface-2);border-radius:var(--radius-md);padding:12px 14px;margin:12px 0;">
                <div class="flex-between">
                    <span class="text-sm text-muted">This payment + TDS settles</span>
                    <strong class="mono" id="settleAmt"><?= formatMoney($balanceDue) ?></strong>
                </div>
                <div class="flex-between">
                    <span class="text-sm text-muted">Remaining balance after this</span>
                    <strong class="mono" id="remainAmt">₹0.00</strong>
                </div>
            </div>

            <div class="flex-end gap-8">
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Record Payment</button>
            </div>
        </form>
    </fieldset>
    <script>
    function recalcBalance() {
        const balance = <?= $balanceDue ?>;
        const amt = parseFloat(document.getElementById('payAmount').value) || 0;
        const tds = parseFloat(document.getElementById('payTds').value) || 0;
        const settle = amt + tds;
        const remain = Math.max(0, balance - settle);
        document.getElementById('settleAmt').textContent = '₹' + settle.toFixed(2);
        document.getElementById('remainAmt').textContent = '₹' + remain.toFixed(2);
    }
    recalcBalance();
    </script>
    <?php else: ?>
    <div class="alert alert-success"><?= icon('circle-check') ?> This invoice is fully settled. No balance remaining.</div>
    <?php endif; ?>
</div>

<div class="card">
    <div class="card-title">Payment History</div>
    <?php if ($paymentHistory): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Date/Time</th><th class="text-right">Amount</th><th class="text-right">TDS</th>
                    <th>Mode</th><th>Reference</th><th>Marked By</th></tr>
            </thead>
            <tbody>
            <?php foreach ($paymentHistory as $p): ?>
            <tr>
                <td><?= formatDateTime($p['payment_date']) ?></td>
                <td class="num text-success"><?= formatMoney($p['amount']) ?></td>
                <td class="num"><?= formatMoney($p['tds_amount']) ?></td>
                <td><?= sanitize($p['payment_mode']) ?></td>
                <td><?= sanitize($p['reference_note']) ?: '-' ?></td>
                <td><?= sanitize($p['marked_by_name']) ?: '-' ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('history') ?> No payments recorded yet for this invoice.</div>
    <?php endif; ?>
</div>

<?php endif; ?>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
