| Server IP : 72.60.21.38 / Your IP : 216.73.216.25 Web Server : LiteSpeed System : Linux uk-fast-web1372.main-hosting.eu 4.18.0-553.121.1.lve.el8.x86_64 #1 SMP Thu Apr 30 16:40:41 UTC 2026 x86_64 User : u390967363 ( 390967363) PHP Version : 8.2.30 Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail MySQL : OFF | cURL : ON | WGET : ON | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /home/u390967363/domains/aibenproperties.com/public_html/app/ |
Upload File : |
<?php
session_start();
require_once 'includes/db.php';
require_once 'includes/functions.php';
// Check login and role
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'client') {
header("Location: dashboard.php");
exit;
}
$user_id = $_SESSION['user_id'];
$companyId = getCurrentCompanyId();
$query = "
SELECT i.*, p.title as property_title
FROM invoices i
JOIN leases l ON i.lease_id = l.id
JOIN properties p ON l.property_id = p.id
WHERE i.tenant_id = ?
";
$params = [$user_id];
if ($companyId) {
$query .= " AND l.company_id = ?";
$params[] = $companyId;
}
$query .= " ORDER BY i.due_date DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$invoices = $stmt->fetchAll();
// KPIs and auxiliary data
$sumQuery = "
SELECT COALESCE(SUM(i.amount),0) as total_invoiced,
MIN(CASE WHEN i.status IN ('unpaid','overdue') THEN i.due_date END) as next_due
FROM invoices i
JOIN leases l ON i.lease_id = l.id
WHERE i.tenant_id = ?
";
$sumParams = [$user_id];
if ($companyId) {
$sumQuery .= " AND l.company_id = ?";
$sumParams[] = $companyId;
}
$stmtSum = $pdo->prepare($sumQuery);
$stmtSum->execute($sumParams);
$sumRow = $stmtSum->fetch(PDO::FETCH_ASSOC);
$total_invoiced = (float)($sumRow['total_invoiced'] ?? 0);
$next_due_date = $sumRow['next_due'] ?? null;
$okStatuses = ['verified','approved','completed','paid','success'];
$hasCompanyCol = tableHasColumn('payments','company_id');
$paidQuery = "SELECT COALESCE(SUM(amount),0) FROM payments WHERE user_id = ? AND LOWER(status) IN ('" . implode("','", array_map('strtolower', $okStatuses)) . "')";
$paidParams = [$user_id];
if ($companyId && $hasCompanyCol) {
$paidQuery .= " AND company_id = ?";
$paidParams[] = $companyId;
}
$stmtPaid = $pdo->prepare($paidQuery);
$stmtPaid->execute($paidParams);
$total_paid = (float)$stmtPaid->fetchColumn();
$outstanding = max($total_invoiced - $total_paid, 0);
$progress = $total_invoiced > 0 ? min(100, round(($total_paid / $total_invoiced) * 100)) : 0;
// Installments
$plotCol = 'NULL as plot_number';
if (function_exists('tableHasColumn')) {
if (tableHasColumn('allocations', 'plot_number')) {
$plotCol = 'a.plot_number';
} elseif (tableHasColumn('allocations', 'unit_number')) {
$plotCol = 'a.unit_number as plot_number';
} elseif (tableHasColumn('allocations', 'plot_no')) {
$plotCol = 'a.plot_no as plot_number';
} elseif (tableHasColumn('allocations', 'property_code')) {
$plotCol = 'a.property_code as plot_number';
}
}
$instSql = "SELECT i.*, $plotCol
FROM installments i
JOIN allocations a ON i.allocation_id = a.id
WHERE a.user_id = ?";
$instParams = [$user_id];
if ($companyId) {
$instSql .= " AND a.company_id = ?";
$instParams[] = $companyId;
}
$instSql .= " ORDER BY i.due_date ASC";
$inst_stmt = $pdo->prepare($instSql);
$inst_stmt->execute($instParams);
$installments = $inst_stmt->fetchAll();
// Payment history
$pdParts = [];
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'created_at')) $pdParts[] = 'payment_date'; // actually 'created_at' in some schemas
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'created_at')) $pdParts[] = 'p.created_at';
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'updated_at')) $pdParts[] = 'p.updated_at';
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'date')) $pdParts[] = 'p.date';
$pdExpr = !empty($pdParts) ? 'COALESCE(' . implode(', ', $pdParts) . ')' : 'NULL';
$hasReceiptsTbl = $pdo->query("SHOW TABLES LIKE 'receipts'")->rowCount() > 0;
$receiptJoin = '';
$receiptSel = ', 0 AS receipt_id';
if ($hasReceiptsTbl && function_exists('tableHasColumn') && tableHasColumn('receipts', 'payment_id')) {
$receiptJoin = " LEFT JOIN receipts r ON r.payment_id = p.id ";
$receiptSel = ", COALESCE(r.id, 0) AS receipt_id";
}
$paySql = "SELECT p.*, $pdExpr as pd $receiptSel FROM payments p $receiptJoin WHERE p.user_id = ?";
$payParams = [$user_id];
if ($companyId && $hasCompanyCol) {
$paySql .= " AND p.company_id = ?";
$payParams[] = $companyId;
}
$paySql .= " ORDER BY pd DESC";
$stmtPay = $pdo->prepare($paySql);
$stmtPay->execute($payParams);
$payments = $stmtPay->fetchAll();
// Client bank transfer submission
$success_msg = null;
$error_msg = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['client_payment'])) {
$amount = (float)($_POST['amount'] ?? 0);
$ref = trim($_POST['reference'] ?? '');
$invoice_id = !empty($_POST['invoice_id']) ? (int)$_POST['invoice_id'] : null;
$method = 'bank_transfer';
$pay_date = $_POST['payment_date'] ?? date('Y-m-d');
if ($amount > 0) {
try {
$proofPath = null;
if (isset($_FILES['proof_file'])) {
$proofPath = handleFileUpload('proof_file', 'uploads/payments/');
}
$cols = ['user_id','amount','method','status'];
$vals = [$user_id, $amount, $method, 'pending_confirmation'];
$place = ['?','?','?','?'];
if (!empty($ref)) {
if (tableHasColumn('payments','reference')) {
$cols[] = 'reference';
$vals[] = $ref;
$place[] = '?';
} elseif (tableHasColumn('payments','reference_number')) {
$cols[] = 'reference_number';
$vals[] = $ref;
$place[] = '?';
}
}
if ($invoice_id && tableHasColumn('payments','invoice_id')) {
$cols[] = 'invoice_id';
$vals[] = $invoice_id;
$place[] = '?';
}
if ($proofPath && tableHasColumn('payments','proof_file')) {
$cols[] = 'proof_file';
$vals[] = $proofPath;
$place[] = '?';
}
if (tableHasColumn('payments','payment_date')) {
$cols[] = 'payment_date';
$vals[] = $pay_date;
$place[] = '?';
} elseif (tableHasColumn('payments','date')) {
$cols[] = 'date';
$vals[] = $pay_date;
$place[] = '?';
}
if ($companyId && tableHasColumn('payments','company_id')) {
$cols[] = 'company_id';
$vals[] = $companyId;
$place[] = '?';
}
if (tableHasColumn('payments','created_at')) {
$cols[] = 'created_at';
$vals[] = date('Y-m-d H:i:s');
$place[] = '?';
}
$sql = "INSERT INTO payments (" . implode(',', $cols) . ") VALUES (" . implode(',', $place) . ")";
$stmtIns = $pdo->prepare($sql);
$ok = $stmtIns->execute($vals);
if ($ok) {
$success_msg = 'Payment submitted for review.';
} else {
$error_msg = 'Failed to submit payment.';
}
} catch (Exception $e) {
$error_msg = 'Upload error.';
}
} else {
$error_msg = 'Enter a valid amount.';
}
}
// Statement generator
if (isset($_GET['download_statement']) && $_GET['download_statement'] == '1') {
$clientName = $_SESSION['user_name'] ?? 'Client';
$clientEmail = $_SESSION['user_email'] ?? '';
header('Content-Type: text/html; charset=UTF-8');
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Statement of Account</title><style>
body{font-family:Arial,Helvetica,sans-serif;color:#333;max-width:900px;margin:40px auto;padding:0 20px}
.header{display:flex;justify-content:space-between;align-items:center;border-bottom:2px solid #001F3F;padding-bottom:12px;margin-bottom:24px}
.brand{font-size:22px;font-weight:bold;color:#001F3F}
.title{font-size:28px;font-weight:800;color:#777;text-transform:uppercase}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin:16px 0}
.label{font-size:12px;text-transform:uppercase;color:#666;margin-bottom:4px}
.value{font-size:16px;font-weight:600}
.kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:16px 0}
.kpi{border:1px solid #eee;border-radius:10px;padding:12px;background:#fafafa}
.kpi .label{margin:0;color:#888}
.kpi .value{font-size:20px}
table{width:100%;border-collapse:collapse;margin-top:16px}
th,td{padding:10px;border-bottom:1px solid #eee}
thead th{background:#f8f9fa;text-align:left}
.right{text-align:right}
.footer{text-align:center;font-size:12px;color:#888;margin-top:32px}
</style></head><body>';
echo '<div class="header"><div><div class="brand">Aiben Properties</div><div style="font-size:12px;margin-top:4px">Client Statement of Account</div></div><div class="title">Statement</div></div>';
echo '<div class="grid"><div><div class="label">Client</div><div class="value">'.htmlspecialchars($clientName).'</div><div style="font-size:13px;color:#666">'.htmlspecialchars($clientEmail).'</div></div><div style="text-align:right"><div class="label">Generated</div><div class="value">'.date('M d, Y').'</div></div></div>';
echo '<div class="kpis">
<div class="kpi"><div class="label">Total Invoiced</div><div class="value">'.formatCurrency($total_invoiced).'</div></div>
<div class="kpi"><div class="label">Total Paid</div><div class="value">'.formatCurrency($total_paid).'</div></div>
<div class="kpi"><div class="label">Outstanding</div><div class="value">'.formatCurrency($outstanding).'</div></div>
</div>';
$invListQuery = "
SELECT i.id, i.amount, i.due_date, i.status, p.title as property_title
FROM invoices i
JOIN leases l ON i.lease_id = l.id
JOIN properties p ON l.property_id = p.id
WHERE i.tenant_id = ?
";
$invListParams = [$user_id];
if ($companyId) {
$invListQuery .= " AND l.company_id = ?";
$invListParams[] = $companyId;
}
$invListQuery .= " ORDER BY i.due_date ASC";
$stmtInv = $pdo->prepare($invListQuery);
$stmtInv->execute($invListParams);
$invRows = $stmtInv->fetchAll(PDO::FETCH_ASSOC);
echo '<h3 style="margin-top:24px">Invoices</h3><table><thead><tr><th>ID</th><th>Property</th><th class=\"right\">Amount</th><th>Due</th><th>Status</th></tr></thead><tbody>';
foreach ($invRows as $r) {
echo '<tr><td>#'.htmlspecialchars($r['id']).'</td><td>'.htmlspecialchars($r['property_title']).'</td><td class="right">'.formatCurrency($r['amount']).'</td><td>'.date('M d, Y', strtotime($r['due_date'])).'</td><td>'.ucfirst($r['status']).'</td></tr>';
}
if (empty($invRows)) {
echo '<tr><td colspan="5" style="text-align:center;color:#777">No invoices</td></tr>';
}
echo '</tbody></table>';
$pdPartsX = [];
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'payment_date')) $pdPartsX[] = 'payment_date';
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'date')) $pdPartsX[] = 'date';
if (function_exists('tableHasColumn') && tableHasColumn('payments', 'created_at')) $pdPartsX[] = 'created_at';
$pdExprX = !empty($pdPartsX) ? 'COALESCE(' . implode(', ', $pdPartsX) . ')' : 'NULL';
$payQuery = "SELECT reference, reference_number, amount, method, status, $pdExprX as pd, proof_file FROM payments WHERE user_id = ?";
$payParamsX = [$user_id];
if ($companyId && $hasCompanyCol) {
$payQuery .= " AND company_id = ?";
$payParamsX[] = $companyId;
}
$payQuery .= " ORDER BY pd DESC";
$stmtPayX = $pdo->prepare($payQuery);
$stmtPayX->execute($payParamsX);
$payRows = $stmtPayX->fetchAll(PDO::FETCH_ASSOC);
echo '<h3 style="margin-top:24px">Payments</h3><table><thead><tr><th>Date</th><th>Reference</th><th>Method</th><th class=\"right\">Amount</th><th>Status</th></tr></thead><tbody>';
foreach ($payRows as $p) {
$dt = $p['pd'] ? date('M d, Y', strtotime($p['pd'])) : '';
$refShow = $p['reference'] ?? ($p['reference_number'] ?? '');
echo '<tr><td>'.$dt.'</td><td>'.htmlspecialchars($refShow).'</td><td>'.htmlspecialchars($p['method'] ?? '').'</td><td class="right">'.formatCurrency($p['amount']).'</td><td>'.ucfirst($p['status']).'</td></tr>';
}
if (empty($payRows)) {
echo '<tr><td colspan="5" style="text-align:center;color:#777">No payments</td></tr>';
}
echo '</tbody></table><div class="footer">This statement was generated electronically on '.date('c').'</div></body></html>';
exit;
}
include 'includes/header.php';
?>
<div class="main-content">
<div class="container-fluid">
<div class="d-flex justify-content-between align-items-center mb-3">
<h1 class="h3 mb-0 text-gray-800"><i class="fa-solid fa-file-invoice-dollar me-2"></i>My Payments</h1>
<div class="d-flex gap-2">
<a href="?download_statement=1" class="btn btn-outline-secondary"><i class="fa-solid fa-download me-2"></i>Download Statement</a>
<button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#makePaymentModal"><i class="fa-regular fa-credit-card me-2"></i>Make Payment</button>
</div>
</div>
<?php if ($success_msg): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= htmlspecialchars($success_msg) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if ($error_msg): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= htmlspecialchars($error_msg) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small">Outstanding Balance</div>
<div class="fs-4 fw-bold"><?= formatCurrency($outstanding) ?></div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small">Total Paid</div>
<div class="fs-4 fw-bold"><?= formatCurrency($total_paid) ?></div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small">Total Invoiced</div>
<div class="fs-4 fw-bold"><?= formatCurrency($total_invoiced) ?></div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="text-muted small">Next Due Date</div>
<div class="fs-6 fw-semibold"><?= $next_due_date ? date('M d, Y', strtotime($next_due_date)) : '—' ?></div>
<div class="mt-2">
<div class="progress" style="height:6px; background:#f3f4f6;">
<div class="progress-bar" style="width: <?= $progress ?>%; background: linear-gradient(90deg,#fb923c,#f97316);"></div>
</div>
<div class="small text-muted mt-1"><?= $progress ?>% Paid</div>
</div>
</div>
</div>
</div>
</div>
<style>
@media print {
.sidebar, .topbar, .nav, .btn, .icon-btn, .alert, .toast-container { display: none !important; }
.main-content > :not(.print-invoice-container.active) { display: none !important; }
.print-invoice-container.active { display: block !important; }
}
</style>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Installment Plan</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-hover align-middle">
<thead class="table-light">
<tr>
<th>Due Date</th>
<th>Description</th>
<th>Amount</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php if (empty($installments)): ?>
<tr><td colspan="5" class="text-center text-muted">No active installment plans.</td></tr>
<?php else: ?>
<?php foreach ($installments as $inst): ?>
<tr>
<td>
<?php
$is_past = strtotime($inst['due_date']) < time();
$text_class = ($inst['status'] == 'pending' && $is_past) ? 'text-danger fw-bold' : '';
?>
<span class="<?= $text_class ?>"><?= date('M d, Y', strtotime($inst['due_date'])) ?></span>
</td>
<td><?= htmlspecialchars($inst['description'] ?? ('Installment for Plot ' . ($inst['plot_number'] ?? ''))) ?></td>
<td class="fw-bold"><?= formatCurrency($inst['amount']) ?></td>
<td><span class="badge <?= getStatusBadgeClass($inst['status']) ?>"><?= ucfirst($inst['status']) ?></span></td>
<td>
<?php if (in_array(strtolower($inst['status']), ['pending','overdue'])): ?>
<button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#makePaymentModal">Pay</button>
<?php else: ?>
<span class="text-muted small">—</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Invoice History</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" width="100%" cellspacing="0">
<thead class="table-light">
<tr>
<th>Invoice #</th>
<th>Property</th>
<th>Amount</th>
<th>Due Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php if (count($invoices) > 0): ?>
<?php foreach ($invoices as $inv): ?>
<tr>
<td>#<?= $inv['id'] ?></td>
<td>
<i class="fa-solid fa-building me-1 text-secondary"></i> <?= htmlspecialchars($inv['property_title']) ?>
</td>
<td class="fw-bold text-dark"><?= formatCurrency($inv['amount']) ?></td>
<td>
<?php
$due = new DateTime($inv['due_date']);
$now = new DateTime();
$is_overdue = $now > $due && $inv['status'] == 'unpaid';
?>
<span class="<?= $is_overdue ? 'text-danger fw-bold' : '' ?>">
<?= $due->format('M d, Y') ?>
</span>
</td>
<td>
<span class="badge <?= getStatusBadgeClass($inv['status']) ?>">
<?= ucfirst($inv['status']) ?>
</span>
</td>
<td>
<button class="btn btn-outline-primary btn-sm me-1" data-action="print-invoice" data-invoice-id="<?= $inv['id'] ?>">
<i class="fa-solid fa-print me-1"></i> Print Invoice
</button>
<?php if ($inv['status'] === 'unpaid' || $inv['status'] === 'overdue'): ?>
<button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#makePaymentModal">
<i class="fa-regular fa-credit-card me-1"></i>Pay Now
</button>
<?php else: ?>
<?php
$proofFile = null;
try {
$payStmt = $pdo->prepare("SELECT proof_file FROM payments WHERE invoice_id = ? AND proof_file IS NOT NULL AND proof_file != '' AND (LOWER(status) IN ('verified','approved','completed','paid','success')) ORDER BY created_at DESC LIMIT 1");
$payStmt->execute([$inv['id']]);
$pf = $payStmt->fetch();
if ($pf && !empty($pf['proof_file'])) {
$proofFile = $pf['proof_file'];
}
} catch (Exception $e) {
$proofFile = null;
}
?>
<?php if ($proofFile): ?>
<a class="btn btn-outline-secondary btn-sm me-1" target="_blank" href="<?= htmlspecialchars($proofFile) ?>">View Receipt</a>
<a class="btn btn-outline-primary btn-sm me-1" href="<?= htmlspecialchars($proofFile) ?>" download>Download Receipt</a>
<button class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#printInvoiceReceiptModal<?= $inv['id'] ?>">Print Receipt</button>
<div class="modal fade" id="printInvoiceReceiptModal<?= $inv['id'] ?>" tabindex="-1" aria-labelledby="printInvoiceReceiptModalLabel<?= $inv['id'] ?>" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="printInvoiceReceiptModalLabel<?= $inv['id'] ?>">Print Receipt for Invoice #<?= $inv['id'] ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<iframe id="printFrame-<?= $inv['id'] ?>" src="<?= htmlspecialchars($proofFile) ?>" width="100%" height="500px"></iframe>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="document.getElementById('printFrame-<?= $inv['id'] ?>').contentWindow.print()">Print</button>
</div>
</div>
</div>
</div>
<?php else: ?>
<button class="btn btn-secondary btn-sm" disabled>
<i class="fa-solid fa-check me-1"></i>Paid
</button>
<?php endif; ?>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="6" class="text-center py-4">No invoices found.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<div class="card shadow mb-5">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Payment History</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<th>Date</th>
<th>Reference</th>
<th>Amount</th>
<th>Method</th>
<th>Status</th>
<th>Receipt</th>
</tr>
</thead>
<tbody>
<?php if (empty($payments)): ?>
<tr><td colspan="6" class="text-center py-4 text-muted">No payment history found.</td></tr>
<?php else: ?>
<?php foreach ($payments as $pay): ?>
<tr>
<td><?= $pay['pd'] ? date('M d, Y', strtotime($pay['pd'])) : '' ?></td>
<td><span class="font-monospace small"><?= htmlspecialchars($pay['reference'] ?? ($pay['reference_number'] ?? '')) ?></span></td>
<td class="fw-bold text-success"><?= formatCurrency($pay['amount']) ?></td>
<td><?= ucfirst($pay['payment_method'] ?? ($pay['method'] ?? 'transfer')) ?></td>
<td><span class="badge <?= getStatusBadgeClass($pay['status']) ?>"><?= htmlspecialchars(paymentStatusLabel($pay['status'])) ?></span></td>
<td>
<?php
$proof = $pay['proof_file'] ?? '';
$rcpId = (int)($pay['receipt_id'] ?? 0);
$viewUrl = ($rcpId > 0) ? "receipt_view.php?id=$rcpId" : "payment-receipt.php?id=" . (int)$pay['id'];
$downloadUrl = ($rcpId > 0) ? "receipt_view.php?id=$rcpId&download=1" : (!empty($proof) ? htmlspecialchars($proof) : "");
$isSystemReceipt = ($rcpId > 0);
$canShow = in_array(strtolower($pay['status']), ['verified','approved','completed','paid','success']);
?>
<?php if ($canShow): ?>
<div class="dropdown d-inline-block">
<button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Actions
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="<?= $viewUrl ?>" target="_blank"><i class="fa-solid fa-receipt me-2"></i>View Receipt</a></li>
<?php if ($isSystemReceipt): ?>
<li><a class="dropdown-item" href="<?= $downloadUrl ?>"><i class="fa-solid fa-download me-2"></i>Download Receipt</a></li>
<li><a class="dropdown-item" href="#" onclick="var w=window.open('<?= $viewUrl ?>','_blank'); if(w){ w.addEventListener('load', function(){ try{ w.print(); }catch(e){} }, {once:true}); } return false;"><i class="fa-solid fa-print me-2"></i>Print Receipt</a></li>
<?php elseif (!empty($proof)): ?>
<li><a class="dropdown-item" href="<?= htmlspecialchars($proof) ?>" download><i class="fa-solid fa-download me-2"></i>Download Proof</a></li>
<?php endif; ?>
<?php if ($isSystemReceipt && !empty($proof)): ?>
<li class="dropdown-divider"></li>
<li><a class="dropdown-item text-muted small" href="<?= htmlspecialchars($proof) ?>" target="_blank"><i class="fa-solid fa-file-invoice me-2"></i>View Uploaded Proof</a></li>
<?php endif; ?>
</ul>
</div>
<?php elseif (!empty($proof)): ?>
<a class="btn btn-sm btn-outline-secondary" target="_blank" href="<?= htmlspecialchars($proof) ?>">View Proof</a>
<?php else: ?>
<span class="text-muted small">—</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="makePaymentModal" tabindex="-1" aria-labelledby="makePaymentModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="makePaymentModalLabel">Make a Payment</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<ul class="nav nav-tabs" id="payTab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="transfer-tab" data-bs-toggle="tab" data-bs-target="#transfer" type="button" role="tab">Bank Transfer</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="online-tab" data-bs-toggle="tab" data-bs-target="#online" type="button" role="tab">Online Gateway</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="wallet-tab" data-bs-toggle="tab" data-bs-target="#wallet" type="button" role="tab">Wallet</button>
</li>
</ul>
<div class="tab-content pt-3">
<div class="tab-pane fade show active" id="transfer" role="tabpanel">
<div class="mb-3 small text-muted">Transfer to Aiben Properties, Account: 0000000000. Upload proof after payment.</div>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="client_payment" value="1">
<div class="mb-3">
<label class="form-label">Amount</label>
<input type="number" step="0.01" name="amount" class="form-control" required>
</div>
<div class="mb-3">
<label class="form-label">Reference</label>
<input type="text" name="reference" class="form-control" placeholder="Optional">
</div>
<div class="mb-3">
<label class="form-label">Invoice</label>
<select name="invoice_id" class="form-select">
<option value="">Not linked to an invoice</option>
<?php foreach ($invoices as $iv): ?>
<?php if (in_array($iv['status'], ['unpaid','overdue'])): ?>
<option value="<?= $iv['id'] ?>">#<?= $iv['id'] ?> — <?= htmlspecialchars($iv['property_title']) ?> (<?= formatCurrency($iv['amount']) ?>)</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label class="form-label">Payment Date</label>
<input type="date" name="payment_date" class="form-control" value="<?= date('Y-m-d') ?>">
</div>
<div class="mb-3">
<label class="form-label">Upload Proof</label>
<input type="file" name="proof_file" class="form-control" accept="image/*,.pdf">
</div>
<div class="d-grid">
<button type="submit" class="btn btn-success">Submit Payment</button>
</div>
</form>
</div>
<div class="tab-pane fade" id="online" role="tabpanel">
<div class="text-muted small">Online gateway integration is coming soon.</div>
</div>
<div class="tab-pane fade" id="wallet" role="tabpanel">
<div class="text-muted small">Wallet payments are not yet available.</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php if (count($invoices) > 0): ?>
<?php foreach ($invoices as $inv): ?>
<div id="print-invoice-<?= $inv['id'] ?>" class="print-invoice-container" style="display:none;">
<div class="container px-4">
<div class="d-flex justify-content-between align-items-start mt-3">
<div>
<div class="fw-bold" style="font-size:1.25rem;">INVOICE</div>
<div class="text-muted small">INV-<?= str_pad($inv['id'], 5, '0', STR_PAD_LEFT) ?></div>
</div>
<div class="text-end">
<div class="text-muted small">Date: <?= htmlspecialchars(date('F j, Y', strtotime($inv['created_at'] ?? ($inv['due_date'] ?? date('Y-m-d'))))) ?></div>
<div class="text-muted small">Due: <?= htmlspecialchars(date('F j, Y', strtotime($inv['due_date']))) ?></div>
</div>
</div>
<div class="row mt-3">
<div class="col-6">
<div class="fw-semibold mb-1">Bill To</div>
<div><?= htmlspecialchars($_SESSION['user_name'] ?? 'Client') ?></div>
<div class="text-muted small"><?= htmlspecialchars($_SESSION['user_email'] ?? '') ?></div>
</div>
<div class="col-6 text-end">
<div class="fw-semibold mb-1">From</div>
<div><?= htmlspecialchars(getSetting('company_name', 'Your Company')) ?></div>
<div class="text-muted small"><?= htmlspecialchars(getSetting('company_email', 'info@company.com')) ?></div>
</div>
</div>
<div class="table-responsive mt-3">
<table class="table table-sm align-middle">
<thead class="table-light">
<tr>
<th>Description</th>
<th class="text-end">Qty</th>
<th class="text-end">Rate</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><?= htmlspecialchars($inv['description'] ?? ('Invoice for ' . $inv['property_title'])) ?></td>
<td class="text-end">1</td>
<td class="text-end"><?= htmlspecialchars(getSetting('currency_symbol', '₦')) . number_format((float)$inv['amount'], 2) ?></td>
<td class="text-end"><?= htmlspecialchars(getSetting('currency_symbol', '₦')) . number_format((float)$inv['amount'], 2) ?></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="3" class="text-end">Subtotal</th>
<th class="text-end"><?= htmlspecialchars(getSetting('currency_symbol', '₦')) . number_format((float)$inv['amount'], 2) ?></th>
</tr>
<tr>
<th colspan="3" class="text-end">Tax (<?= htmlspecialchars(getSetting('tax_rate', '0')) ?>%)</th>
<th class="text-end"><?= htmlspecialchars(getSetting('currency_symbol', '₦')) . number_format(0, 2) ?></th>
</tr>
<tr>
<th colspan="3" class="text-end">Total</th>
<th class="text-end"><?= htmlspecialchars(getSetting('currency_symbol', '₦')) . number_format((float)$inv['amount'], 2) ?></th>
</tr>
</tfoot>
</table>
</div>
<div class="mt-4 text-muted small">Thank you for your business.</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
<script>
(function(){
document.addEventListener('click', function(e){
var btn = e.target.closest && e.target.closest('[data-action="print-invoice"]');
if (!btn) return;
var id = btn.getAttribute('data-invoice-id');
var container = document.getElementById('print-invoice-' + id);
if (!container) return;
container.style.display = 'block';
container.classList.add('active');
setTimeout(function(){
window.print();
setTimeout(function(){
container.classList.remove('active');
container.style.display = 'none';
}, 300);
}, 50);
}, true);
})();
</script>
<?php include 'includes/footer.php'; ?>