| Server IP : 72.60.21.38 / Your IP : 216.73.217.140 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
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/mailer.php';
header('Content-Type: application/json');
$companyId = function_exists('getCurrentCompanyId') ? getCurrentCompanyId() : 0;
global $pdo;
if (!($pdo instanceof PDO) && function_exists('getPDO')) {
try {
// Assume getPDO() is defined in includes/db.php which was required above
if (function_exists('getPDO')) {
$pdo = new PDO('mysql:host=' . $_ENV['DB_HOST'] . ';dbname=' . $_ENV['DB_NAME'], $_ENV['DB_USER'], $_ENV['DB_PASS']);
} else {
throw new RuntimeException('getPDO function not found');
}
} catch (\Throwable $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'db_unavailable']);
exit;
}
}
$role = strtolower($_SESSION['user_role'] ?? '');
if (!in_array($role, ['chairman_ceo','chairman','ceo','super_admin','admin','management'], true)) {
http_response_code(403);
echo json_encode(['success'=>false, 'error'=>'Forbidden']);
exit;
}
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
$allocIdStr = isset($data['allocation_id']) ? trim($data['allocation_id']) : '';
$allocId = $allocIdStr !== '' ? (int)$allocIdStr : 0;
$b64 = $data['pdf_base64'] ?? '';
if (is_string($b64)) {
$b64 = trim($b64);
$pos = strpos($b64, ',');
if ($pos !== false) { $b64 = substr($b64, $pos + 1); }
}
if (!$allocId || !$b64) {
echo json_encode(['success'=>false, 'error'=>'Missing params']);
exit;
}
if (!$pdo) {
http_response_code(500);
echo json_encode(['success'=>false, 'error'=>'db_unavailable']);
exit;
}
try {
$st = $pdo->prepare("SELECT status, signed FROM allocations WHERE id = ?");
$st->execute([$allocId]);
$row = $st->fetch(PDO::FETCH_ASSOC);
$st = null;
if ($row) {
$status = strtolower((string)($row['status'] ?? ''));
$signed = intval($row['signed'] ?? 0);
if (($status === 'approved' || $status === 'completed') && $signed === 1) {
try {
$pdo->query("DESCRIBE audit_logs");
$ins = $pdo->prepare("INSERT INTO audit_logs (action, details, ip_address, user_id, created_at) VALUES (?, ?, ?, ?, NOW())");
$ins->execute([
'allocation_prevent_edit',
'Attempt to overwrite approved PDF prevented. Allocation #'.$allocId,
$_SERVER['REMOTE_ADDR'] ?? '',
$_SESSION['user_id'] ?? null
]);
} catch (\Throwable $e) {}
echo json_encode(['success'=>false, 'error'=>'already_approved']);
exit;
}
}
} catch (\Throwable $e) {}
try {
$pdf = base64_decode($b64, true);
if ($pdf === false) { throw new Exception('Decode failed'); }
$dir = __DIR__ . '/uploads/letters/generated';
if (!is_dir($dir)) { @mkdir($dir, 0755, true); }
$fname = 'allocation_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', $allocIdStr) . '_' . date('Ymd_His') . '.pdf';
$path = $dir . '/' . $fname;
file_put_contents($path, $pdf, LOCK_EX);
$rel = 'uploads/letters/generated/' . $fname;
// Try to link to documents table if it exists
try {
$userIdSession = $_SESSION['user_id'] ?? null;
// Update allocation status/approval/sign flags if columns exist
try {
$cols = $pdo->query("DESCRIBE allocations")->fetchAll(PDO::FETCH_ASSOC);
$have = [];
foreach ($cols as $c) { $have[$c['Field']] = true; }
$set = [];
$paramsUpd = [];
if (!empty($have['status'])) { $set[] = "status = ?"; $paramsUpd[] = 'approved'; }
if (!empty($have['approved_by'])) { $set[] = "approved_by = ?"; $paramsUpd[] = $userIdSession; }
if (!empty($have['approved_at'])) { $set[] = "approved_at = CURRENT_TIMESTAMP"; }
if (!empty($have['signed'])) { $set[] = "signed = 1"; }
if (!empty($have['letter_path'])) { $set[] = "letter_path = ?"; $paramsUpd[] = $rel; }
if (!empty($have['pdf_path'])) { $set[] = "pdf_path = ?"; $paramsUpd[] = $rel; }
if (!empty($have['letter_file'])) { $set[] = "letter_file = ?"; $paramsUpd[] = $rel; }
if (!empty($have['pdf_file'])) { $set[] = "pdf_file = ?"; $paramsUpd[] = $rel; }
if ($set) {
$sqlUpd = "UPDATE allocations SET " . implode(', ', $set) . " WHERE id = ?";
$paramsUpd[] = $allocId;
$stUpd = $pdo->prepare($sqlUpd);
$stUpd->execute($paramsUpd);
}
} catch (\Throwable $e) {
// ignore
}
// Audit log if table exists
try {
$pdo->query("DESCRIBE audit_logs");
$insLog = $pdo->prepare("INSERT INTO audit_logs (action, details, ip_address, user_id, created_at) VALUES (?, ?, ?, ?, NOW())");
$insLog->execute([
'allocation_signed',
'Chairman approved and digitally signed Allocation #' . $allocId,
$_SERVER['REMOTE_ADDR'] ?? '',
$userIdSession
]);
} catch (\Throwable $e) {
// ignore if audit_logs doesn't exist
}
// Lookup allocation to find user_id/property_id if possible
$stmt = $pdo->prepare("SELECT user_id, property_id FROM allocations WHERE id = ?");
$stmt->execute([$allocId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userId = $row['user_id'] ?? null;
$propertyId = $row['property_id'] ?? null;
// Build insert dynamically depending on columns
$cols = [];
try {
$res = $pdo->query("DESCRIBE documents");
if ($res) { $cols = $res->fetchAll(PDO::FETCH_ASSOC) ?: []; }
} catch (\Throwable $e) { $cols = []; }
if (!$cols) {
try {
$res = $pdo->query("PRAGMA table_info(documents)");
if ($res) { $cols = $res->fetchAll(PDO::FETCH_ASSOC) ?: []; }
} catch (\Throwable $e) { $cols = []; }
}
$have = [];
foreach ($cols as $c) {
$name = $c['name'] ?? ($c['Field'] ?? null);
if ($name) $have[$name] = true;
}
$fields = [];
$params = [];
$fileCol = !empty($have['file_path']) ? 'file_path' : (!empty($have['path']) ? 'path' : (!empty($have['file_url']) ? 'file_url' : (!empty($have['file']) ? 'file' : (!empty($have['url']) ? 'url' : null))));
$titleCol = !empty($have['title']) ? 'title' : (!empty($have['name']) ? 'name' : null);
$typeCol = !empty($have['type']) ? 'type' : (!empty($have['doc_type']) ? 'doc_type' : (!empty($have['category']) ? 'category' : null));
if ($titleCol) { $fields[] = $titleCol; $params[] = 'Signed Allocation Letter'; }
if ($typeCol) { $fields[] = $typeCol; $params[] = 'allocation_letter'; }
if ($fileCol) { $fields[] = $fileCol; $params[] = $rel; }
if (!empty($have['created_at'])) { $fields[]='created_at'; $params[]=date('Y-m-d H:i:s'); }
if (!empty($have['user_id'])) { $fields[]='user_id'; $params[]=$userId; }
if (!empty($have['property_id'])) { $fields[]='property_id'; $params[]=$propertyId; }
if (!empty($have['allocation_id'])) { $fields[]='allocation_id'; $params[]=$allocId; }
if ($companyId && !empty($have['company_id'])) { $fields[]='company_id'; $params[]=$companyId; }
if (!empty($have['created_by'])) { $fields[]='created_by'; $params[]=$userIdSession; }
if ($fields) {
$sql = "INSERT INTO documents (".implode(',',$fields).") VALUES(".implode(',', array_fill(0,count($fields),'?')).")";
$ins = $pdo->prepare($sql);
$ins->execute($params);
}
// Notify client that their allocation letter is available
if (!empty($userId)) {
$scheme = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) === 'on') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
$fileUrl = $scheme . '://' . $host . ($base ? $base : '') . '/' . ltrim($rel, '/');
$message = "Your allocation letter has been signed and is now available. You can download it here: " . $fileUrl;
sendNotification($userId, 'allocation_letter_signed', $message, $pdo);
}
} catch (\Throwable $e) {
// Ignore if documents table not present
}
echo json_encode(['success'=>true, 'path'=>$rel]);
} catch (\Throwable $e) {
http_response_code(500);
echo json_encode(['success'=>false, 'error'=>'Save failed']);
}
?>