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

// ── Handle payment submission ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: purchase_payment.php'); exit;
    }
    $purchaseId = (int)$_POST['purchase_id'];
    $amount     = (float)$_POST['amount'];
    $tdsAmount  = (float)($_POST['tds_amount'] ?? 0);
    $payDate    = $_POST['payment_date'];
    $mode       = trim($_POST['payment_mode']);
    $bankAccId  = (int)$_POST['bank_account_id'];
    $note       = trim($_POST['note'] ?? '');

    $stmt = $pdo->prepare("SELECT p.*, v.vendor_name FROM purchases p JOIN purchase_vendors v ON v.id=p.vendor_id WHERE p.id=?");
    $stmt->execute([$purchaseId]);
    $purchase = $stmt->fetch();

    if (!$purchase) { setFlash('danger','Purchase not found.'); header('Location: purchase_payment.php'); exit; }

    $balanceDue = $purchase['grand_total'] - $purchase['paid_amount'];

    if ($amount <= 0) {
        setFlash('danger','Amount must be greater than zero.');
        header("Location: purchase_payment.php?purchase_id=$purchaseId&vendor_id=".$purchase['vendor_id']); exit;
    }
    if (($amount + $tdsAmount) > $balanceDue + 0.01) {
        setFlash('danger','Amount (' . formatMoney($amount) . ') + TDS (' . formatMoney($tdsAmount) . ') exceeds balance due (' . formatMoney($balanceDue) . ').');
        header("Location: purchase_payment.php?purchase_id=$purchaseId&vendor_id=".$purchase['vendor_id']); exit;
    }

    try {
        $pdo->beginTransaction();

        $newPaid   = $purchase['paid_amount'] + $amount + $tdsAmount;
        $newStatus = ($newPaid >= $purchase['grand_total'] - 0.01) ? 'paid' : 'partial';

        $pdo->prepare("UPDATE purchases SET paid_amount=?, payment_status=? WHERE id=?")
            ->execute([$newPaid, $newStatus, $purchaseId]);

        // Payments log
        recordPayment('outflow','purchase',$purchaseId,$purchase['vendor_name'],$amount,$payDate,$mode,
            "Payment to {$purchase['vendor_name']} for {$purchase['purchase_no']}" . ($note ? " | $note" : "") . ($tdsAmount > 0 ? " | TDS: ".formatMoney($tdsAmount) : ""),
            currentUserId()
        );

        // Accounting journal: DR Accounts Payable  CR Bank/Cash
        if (function_exists('createJournalEntry') && $bankAccId) {
            $apAccId = $pdo->query("SELECT id FROM accounts WHERE account_code='2100' LIMIT 1")->fetchColumn();
            if ($apAccId) {
                createJournalEntry($payDate, 'payment',
                    "Payment to {$purchase['vendor_name']} — {$purchase['purchase_no']} via $mode" . ($tdsAmount > 0 ? " (TDS: ".formatMoney($tdsAmount).")" : ""),
                    [
                        ['account_id' => $apAccId,   'debit' => ($amount + $tdsAmount), 'credit' => 0,       'narration' => 'Clearing payable'],
                        ['account_id' => $bankAccId, 'debit' => 0,                      'credit' => $amount, 'narration' => $mode],
                    ],
                    'purchase', $purchaseId, currentUserId()
                );
            }
        }

        $pdo->commit();

        if ($newStatus === 'paid') {
            setFlash('success', "✅ Payment of " . formatMoney($amount) . " recorded. Purchase {$purchase['purchase_no']} is now FULLY PAID!");
        } else {
            $remaining = $purchase['grand_total'] - $newPaid;
            setFlash('success', "Payment of " . formatMoney($amount) . " recorded. Remaining balance: " . formatMoney($remaining));
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger','Error: '.$e->getMessage());
    }
    header("Location: purchase_payment.php?purchase_id=$purchaseId&vendor_id=".$purchase['vendor_id']); exit;
}

// ── Load data ─────────────────────────────────────────────────
$selectedPurchaseId = (int)($_GET['purchase_id'] ?? 0);
$selectedVendorId   = (int)($_GET['vendor_id']   ?? 0);

$vendors = $pdo->query("SELECT DISTINCT pv.id, pv.vendor_name FROM purchase_vendors pv
    JOIN purchases p ON p.vendor_id=pv.id WHERE pv.status=1 ORDER BY pv.vendor_name")->fetchAll();

$vendorPurchases  = [];
$selectedPurchase = null;
$paymentHistory   = [];
$purchaseItems    = [];

if ($selectedVendorId) {
    $stmt = $pdo->prepare("SELECT * FROM purchases WHERE vendor_id=? ORDER BY purchase_date DESC");
    $stmt->execute([$selectedVendorId]);
    $vendorPurchases = $stmt->fetchAll();
}

if ($selectedPurchaseId) {
    $stmt = $pdo->prepare("SELECT p.*, v.vendor_name FROM purchases p
        JOIN purchase_vendors v ON v.id=p.vendor_id WHERE p.id=?");
    $stmt->execute([$selectedPurchaseId]);
    $selectedPurchase = $stmt->fetch();

    if ($selectedPurchase && !$selectedVendorId) {
        $selectedVendorId = $selectedPurchase['vendor_id'];
        $stmt = $pdo->prepare("SELECT * FROM purchases WHERE vendor_id=? ORDER BY purchase_date DESC");
        $stmt->execute([$selectedVendorId]);
        $vendorPurchases = $stmt->fetchAll();
    }

    // Payment history from payments table
    $stmt = $pdo->prepare("SELECT p.*, u.name as marked_by_name
        FROM payments p LEFT JOIN users u ON u.id=p.created_by
        WHERE p.reference_type='purchase' AND p.reference_id=?
        ORDER BY p.payment_date DESC");
    $stmt->execute([$selectedPurchaseId]);
    $paymentHistory = $stmt->fetchAll();

    // Purchase items breakdown
    $stmt = $pdo->prepare("SELECT pi.*, i.item_name, i.item_code, i.unit
        FROM purchase_items pi JOIN items i ON i.id=pi.item_id
        WHERE pi.purchase_id=?");
    $stmt->execute([$selectedPurchaseId]);
    $purchaseItems = $stmt->fetchAll();
}

$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();

$csrf      = generateCSRFToken();
$pageTitle = 'Purchase Payments';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Stock</div><h2 class="mb-0">Purchase Payments</h2></div>
    <a href="purchases.php" class="btn"><?= icon('arrow-left') ?> Back to Purchases</a>
</div>

<!-- Step 1: Select Vendor -->
<div class="card">
    <div class="card-title"><?= icon('truck-delivery') ?> Step 1 — Select Vendor</div>
    <form method="GET" class="flex gap-8">
        <select name="vendor_id" onchange="this.form.submit()" style="max-width:360px;">
            <option value="">-- Select Vendor --</option>
            <?php foreach ($vendors as $v): ?>
            <option value="<?= $v['id'] ?>" <?= $selectedVendorId==$v['id']?'selected':'' ?>><?= sanitize($v['vendor_name']) ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</div>

<?php if ($vendorPurchases): ?>
<!-- Step 2: Select Purchase -->
<div class="card">
    <div class="card-title"><?= icon('list') ?> Step 2 — Select Purchase Order</div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Purchase No</th>
                    <th>Date</th>
                    <th>Vendor Invoice</th>
                    <th class="text-right">Subtotal</th>
                    <th class="text-right">GST</th>
                    <th class="text-right">Grand Total</th>
                    <th class="text-right">Paid</th>
                    <th class="text-right">Balance</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($vendorPurchases as $p):
                $bal = $p['grand_total'] - $p['paid_amount'];
            ?>
            <tr class="<?= $selectedPurchaseId==$p['id']?'highlighted-row':'' ?>">
                <td class="mono"><?= sanitize($p['purchase_no']) ?></td>
                <td><?= formatDate($p['purchase_date']) ?></td>
                <td class="text-sm"><?= sanitize($p['invoice_no']) ?></td>
                <td class="num"><?= formatMoney($p['total_amount']) ?></td>
                <td class="num"><?= formatMoney($p['gst_amount']) ?></td>
                <td class="num"><strong><?= formatMoney($p['grand_total']) ?></strong></td>
                <td class="num text-success"><?= formatMoney($p['paid_amount']) ?></td>
                <td class="num <?= $bal>0.01?'text-danger':'text-success' ?>">
                    <strong><?= formatMoney($bal) ?></strong>
                </td>
                <td>
                    <span class="badge badge-<?= $p['payment_status']==='paid'?'success':($p['payment_status']==='partial'?'warning':'danger') ?>">
                        <?= strtoupper($p['payment_status']) ?>
                    </span>
                </td>
                <td>
                    <?php if ($bal > 0.01): ?>
                    <a href="?vendor_id=<?= $selectedVendorId ?>&purchase_id=<?= $p['id'] ?>" class="btn btn-sm btn-primary"><?= icon('cash') ?> Pay</a>
                    <?php else: ?>
                    <a href="?vendor_id=<?= $selectedVendorId ?>&purchase_id=<?= $p['id'] ?>" class="btn btn-sm"><?= icon('eye') ?> History</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php if ($selectedPurchase):
    $balanceDue  = $selectedPurchase['grand_total'] - $selectedPurchase['paid_amount'];
    $totalPaid   = $selectedPurchase['paid_amount'];
    $isFullyPaid = $balanceDue <= 0.01;
?>

<!-- Purchase Summary + Items -->
<div class="card" style="border-color:var(--color-primary);">
    <div class="card-title flex-between">
        <span><?= icon('receipt') ?> <?= sanitize($selectedPurchase['purchase_no']) ?> — <?= sanitize($selectedPurchase['vendor_name']) ?></span>
        <span class="badge badge-<?= $selectedPurchase['payment_status']==='paid'?'success':($selectedPurchase['payment_status']==='partial'?'warning':'danger') ?>" style="font-size:13px;">
            <?= strtoupper($selectedPurchase['payment_status']) ?>
        </span>
    </div>

    <!-- Amount Summary -->
    <div class="form-grid" style="margin-bottom:16px;">
        <div style="background:var(--color-surface-2);padding:12px;border-radius:var(--radius-md);">
            <div class="text-sm text-muted">Subtotal (excl. GST)</div>
            <strong class="mono" style="font-size:18px;"><?= formatMoney($selectedPurchase['total_amount']) ?></strong>
        </div>
        <div style="background:var(--color-surface-2);padding:12px;border-radius:var(--radius-md);">
            <div class="text-sm text-muted">GST Amount</div>
            <strong class="mono" style="font-size:18px;"><?= formatMoney($selectedPurchase['gst_amount']) ?></strong>
        </div>
        <div style="background:var(--color-surface-2);padding:12px;border-radius:var(--radius-md);">
            <div class="text-sm text-muted">Grand Total</div>
            <strong class="mono" style="font-size:18px;"><?= formatMoney($selectedPurchase['grand_total']) ?></strong>
        </div>
        <div style="background:#e8f5e9;padding:12px;border-radius:var(--radius-md);">
            <div class="text-sm text-muted">Total Paid</div>
            <strong class="mono text-success" style="font-size:18px;"><?= formatMoney($totalPaid) ?></strong>
        </div>
        <div style="background:<?= $isFullyPaid?'#e8f5e9':'#fdecea' ?>;padding:12px;border-radius:var(--radius-md);">
            <div class="text-sm text-muted">Balance Due</div>
            <strong class="mono <?= $isFullyPaid?'text-success':'text-danger' ?>" style="font-size:20px;">
                <?= $isFullyPaid ? '✅ FULLY PAID' : formatMoney($balanceDue) ?>
            </strong>
        </div>
    </div>

    <!-- Progress Bar -->
    <?php $pct = $selectedPurchase['grand_total'] > 0 ? min(100, ($totalPaid / $selectedPurchase['grand_total']) * 100) : 0; ?>
    <div style="background:#eee;border-radius:99px;height:10px;margin-bottom:16px;overflow:hidden;">
        <div style="height:100%;width:<?= $pct ?>%;background:<?= $pct>=100?'var(--color-success)':'var(--color-primary)' ?>;border-radius:99px;transition:width 0.3s;"></div>
    </div>
    <div class="text-sm text-muted" style="margin-bottom:16px;"><?= number_format($pct,1) ?>% paid</div>

    <!-- Items Breakdown -->
    <?php if ($purchaseItems): ?>
    <div class="divider"></div>
    <div class="card-title" style="margin-bottom:8px;"><?= icon('package') ?> Items in this Purchase</div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>#</th><th>Item</th><th>Code</th><th class="text-right">Qty</th><th class="text-right">Purchase Price</th><th class="text-right">GST%</th><th class="text-right">GST Amt</th><th class="text-right">Line Total</th></tr></thead>
            <tbody>
            <?php foreach ($purchaseItems as $i => $pi): ?>
            <tr>
                <td><?= $i+1 ?></td>
                <td><?= sanitize($pi['item_name']) ?></td>
                <td class="mono"><?= sanitize($pi['item_code']) ?></td>
                <td class="num"><?= $pi['qty'] ?> <?= sanitize($pi['unit']) ?></td>
                <td class="num"><?= formatMoney($pi['purchase_price']) ?></td>
                <td class="num"><?= number_format($pi['gst_percent'],1) ?>%</td>
                <td class="num"><?= formatMoney($pi['gst_amount']) ?></td>
                <td class="num"><strong><?= formatMoney($pi['line_total']) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- Payment Form -->
<?php if (!$isFullyPaid): ?>
<div class="card" style="border-color:var(--color-success);">
    <div class="card-title"><?= icon('cash') ?> Record Payment</div>
    <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="purchase_id" value="<?= $selectedPurchase['id'] ?>">
        <div class="form-grid">
            <div class="form-group">
                <label>Amount Paying <span class="req">*</span></label>
                <input type="number" step="0.01" name="amount" id="payAmount"
                       value="<?= number_format($balanceDue,2,'.','') ?>"
                       max="<?= $balanceDue ?>" min="0.01" required
                       oninput="updatePaySummary()">
                <div class="text-sm text-muted">Balance: <?= formatMoney($balanceDue) ?></div>
            </div>
            <div class="form-group">
                <label>TDS Deducted (if any)</label>
                <input type="number" step="0.01" name="tds_amount" id="tdsAmount" value="0" min="0" oninput="updatePaySummary()">
            </div>
            <div class="form-group">
                <label>Payment Date <span class="req">*</span></label>
                <input type="date" name="payment_date" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="form-group">
                <label>Mode of Payment <span class="req">*</span></label>
                <select name="payment_mode" required>
                    <option value="">-- Select Mode --</option>
                    <option value="Bank Transfer">Bank Transfer</option>
                    <option value="Cash">Cash</option>
                    <option value="UPI">UPI</option>
                    <option value="Cheque">Cheque</option>
                    <option value="NEFT">NEFT</option>
                    <option value="RTGS">RTGS</option>
                    <option value="IMPS">IMPS</option>
                </select>
            </div>
            <div class="form-group">
                <label>Paid From Account <span class="req">*</span></label>
                <select name="bank_account_id" required>
                    <option value="">-- Select Account --</option>
                    <?php foreach ($bankAccounts as $ba): ?>
                    <option value="<?= $ba['id'] ?>">
                        <?= sanitize($ba['account_name']) ?> — Balance: <?= formatMoney($ba['current_balance']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Reference / Note</label>
                <input type="text" name="note" placeholder="Cheque no, UTR no, transaction ID...">
            </div>
        </div>

        <!-- Payment Preview -->
        <div style="background:var(--color-surface-2);border-radius:var(--radius-md);padding:14px;margin-bottom:16px;">
            <div class="flex-between" style="margin-bottom:6px;">
                <span class="text-sm text-muted">Paying Now</span>
                <strong class="mono" id="previewAmount"><?= formatMoney($balanceDue) ?></strong>
            </div>
            <div class="flex-between" style="margin-bottom:6px;">
                <span class="text-sm text-muted">TDS</span>
                <strong class="mono" id="previewTds">₹0.00</strong>
            </div>
            <div class="divider" style="margin:8px 0;"></div>
            <div class="flex-between">
                <span class="text-sm" style="font-weight:700;">Remaining After Payment</span>
                <strong class="mono text-danger" id="previewRemaining"><?= formatMoney($balanceDue) ?></strong>
            </div>
        </div>

        <div class="flex-end">
            <button type="submit" class="btn btn-primary btn-lg" onclick="return confirm('Record this payment?')">
                <?= icon('check') ?> Record Payment
            </button>
        </div>
    </form>
</div>
<?php else: ?>
<div class="alert alert-success" style="max-width:700px;">
    <?= icon('circle-check') ?> <strong>This purchase is fully paid.</strong> No further payments needed.
</div>
<?php endif; ?>

<!-- Payment History -->
<div class="card">
    <div class="card-title"><?= icon('history') ?> Payment History</div>
    <?php if ($paymentHistory): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Date & Time</th>
                    <th class="text-right">Amount</th>
                    <th>Mode of Payment</th>
                    <th>Reference / Remarks</th>
                    <th>Marked By</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $runningTotal = 0;
            foreach ($paymentHistory as $i => $ph):
                $runningTotal += $ph['amount'];
            ?>
            <tr>
                <td><?= $i+1 ?></td>
                <td class="mono"><?= date('d-M-Y H:i', strtotime($ph['payment_date'])) ?></td>
                <td class="num text-danger"><strong><?= formatMoney($ph['amount']) ?></strong></td>
                <td>
                    <span class="badge badge-secondary"><?= sanitize($ph['payment_mode'] ?: 'N/A') ?></span>
                </td>
                <td class="text-sm text-muted"><?= sanitize($ph['remarks']) ?></td>
                <td class="text-sm"><?= sanitize($ph['marked_by_name'] ?? '-') ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background:var(--color-surface-2);">
                    <td colspan="2"><strong>Total Paid</strong></td>
                    <td class="num text-success"><strong><?= formatMoney($runningTotal) ?></strong></td>
                    <td colspan="3">
                        <?php if ($isFullyPaid): ?>
                        <span class="badge badge-success">✅ Fully Paid</span>
                        <?php else: ?>
                        <span class="text-sm text-danger">Balance remaining: <?= formatMoney($balanceDue) ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('history') ?> No payment recorded yet for this purchase.</div>
    <?php endif; ?>
</div>

<script>
const grandTotal   = <?= $selectedPurchase['grand_total'] ?>;
const alreadyPaid  = <?= $selectedPurchase['paid_amount'] ?>;
const balanceDue   = <?= $balanceDue ?>;

function fmt(n) { return '₹' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g,','); }

function updatePaySummary() {
    const amount = parseFloat(document.getElementById('payAmount').value) || 0;
    const tds    = parseFloat(document.getElementById('tdsAmount').value)  || 0;
    const remaining = Math.max(0, balanceDue - amount - tds);
    document.getElementById('previewAmount').textContent   = fmt(amount);
    document.getElementById('previewTds').textContent      = fmt(tds);
    document.getElementById('previewRemaining').textContent = remaining < 0.01 ? '✅ Fully Paid' : fmt(remaining);
    document.getElementById('previewRemaining').style.color = remaining < 0.01 ? 'var(--color-success)' : 'var(--color-danger)';
}
updatePaySummary();
</script>

<?php endif; ?>

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