Compare commits

..

2 Commits

Author SHA1 Message Date
Flatlogic Bot
79236554fd UB 2025-11-09 01:47:20 +00:00
Flatlogic Bot
b3bb8a479f UBPay 2025-11-08 19:46:15 +00:00
14 changed files with 1246 additions and 144 deletions

0
.perm_test_apache Normal file
View File

0
.perm_test_exec Normal file
View File

311
ai/LocalAIApi.php Normal file
View File

@ -0,0 +1,311 @@
<?php
// LocalAIApi — proxy client for the Responses API.
// Usage:
// require_once __DIR__ . '/ai/LocalAIApi.php';
// $response = LocalAIApi::createResponse([
// 'input' => [
// ['role' => 'system', 'content' => 'You are a helpful assistant.'],
// ['role' => 'user', 'content' => 'Tell me a bedtime story.'],
// ],
// ]);
// if (!empty($response['success'])) {
// $decoded = LocalAIApi::decodeJsonFromResponse($response);
// }
class LocalAIApi
{
/** @var array<string,mixed>|null */
private static ?array $configCache = null;
/**
* Signature compatible with the OpenAI Responses API.
*
* @param array<string,mixed> $params Request body (model, input, text, reasoning, metadata, etc.).
* @param array<string,mixed> $options Extra options (timeout, verify_tls, headers, path, project_uuid).
* @return array{
* success:bool,
* status?:int,
* data?:mixed,
* error?:string,
* response?:mixed,
* message?:string
* }
*/
public static function createResponse(array $params, array $options = []): array
{
$cfg = self::config();
$payload = $params;
if (empty($payload['input']) || !is_array($payload['input'])) {
return [
'success' => false,
'error' => 'input_missing',
'message' => 'Parameter "input" is required and must be an array.',
];
}
if (!isset($payload['model']) || $payload['model'] === '') {
$payload['model'] = $cfg['default_model'];
}
return self::request($options['path'] ?? null, $payload, $options);
}
/**
* Snake_case alias for createResponse (matches the provided example).
*
* @param array<string,mixed> $params
* @param array<string,mixed> $options
* @return array<string,mixed>
*/
public static function create_response(array $params, array $options = []): array
{
return self::createResponse($params, $options);
}
/**
* Perform a raw request to the AI proxy.
*
* @param string $path Endpoint (may be an absolute URL).
* @param array<string,mixed> $payload JSON payload.
* @param array<string,mixed> $options Additional request options.
* @return array<string,mixed>
*/
public static function request(?string $path = null, array $payload = [], array $options = []): array
{
if (!function_exists('curl_init')) {
return [
'success' => false,
'error' => 'curl_missing',
'message' => 'PHP cURL extension is missing. Install or enable it on the VM.',
];
}
$cfg = self::config();
$projectUuid = $cfg['project_uuid'];
if (empty($projectUuid)) {
return [
'success' => false,
'error' => 'project_uuid_missing',
'message' => 'PROJECT_UUID is not defined; aborting AI request.',
];
}
$defaultPath = $cfg['responses_path'] ?? null;
$resolvedPath = $path ?? ($options['path'] ?? $defaultPath);
if (empty($resolvedPath)) {
return [
'success' => false,
'error' => 'project_id_missing',
'message' => 'PROJECT_ID is not defined; cannot resolve AI proxy endpoint.',
];
}
$url = self::buildUrl($resolvedPath, $cfg['base_url']);
$baseTimeout = isset($cfg['timeout']) ? (int) $cfg['timeout'] : 30;
$timeout = isset($options['timeout']) ? (int) $options['timeout'] : $baseTimeout;
if ($timeout <= 0) {
$timeout = 30;
}
$baseVerifyTls = array_key_exists('verify_tls', $cfg) ? (bool) $cfg['verify_tls'] : true;
$verifyTls = array_key_exists('verify_tls', $options)
? (bool) $options['verify_tls']
: $baseVerifyTls;
$projectHeader = $cfg['project_header'];
$headers = [
'Content-Type: application/json',
'Accept: application/json',
];
$headers[] = $projectHeader . ': ' . $projectUuid;
if (!empty($options['headers']) && is_array($options['headers'])) {
foreach ($options['headers'] as $header) {
if (is_string($header) && $header !== '') {
$headers[] = $header;
}
}
}
if (!empty($projectUuid) && !array_key_exists('project_uuid', $payload)) {
$payload['project_uuid'] = $projectUuid;
}
$body = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($body === false) {
return [
'success' => false,
'error' => 'json_encode_failed',
'message' => 'Failed to encode request body to JSON.',
];
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verifyTls);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verifyTls ? 2 : 0);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
$responseBody = curl_exec($ch);
if ($responseBody === false) {
$error = curl_error($ch) ?: 'Unknown cURL error';
curl_close($ch);
return [
'success' => false,
'error' => 'curl_error',
'message' => $error,
];
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decoded = null;
if ($responseBody !== '' && $responseBody !== null) {
$decoded = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$decoded = null;
}
}
if ($status >= 200 && $status < 300) {
return [
'success' => true,
'status' => $status,
'data' => $decoded ?? $responseBody,
];
}
$errorMessage = 'AI proxy request failed';
if (is_array($decoded)) {
$errorMessage = $decoded['error'] ?? $decoded['message'] ?? $errorMessage;
} elseif (is_string($responseBody) && $responseBody !== '') {
$errorMessage = $responseBody;
}
return [
'success' => false,
'status' => $status,
'error' => $errorMessage,
'response' => $decoded ?? $responseBody,
];
}
/**
* Extract plain text from a Responses API payload.
*
* @param array<string,mixed> $response Result of LocalAIApi::createResponse|request.
* @return string
*/
public static function extractText(array $response): string
{
$payload = $response['data'] ?? $response;
if (!is_array($payload)) {
return '';
}
if (!empty($payload['output']) && is_array($payload['output'])) {
$combined = '';
foreach ($payload['output'] as $item) {
if (!isset($item['content']) || !is_array($item['content'])) {
continue;
}
foreach ($item['content'] as $block) {
if (is_array($block) && ($block['type'] ?? '') === 'output_text' && !empty($block['text'])) {
$combined .= $block['text'];
}
}
}
if ($combined !== '') {
return $combined;
}
}
if (!empty($payload['choices'][0]['message']['content'])) {
return (string) $payload['choices'][0]['message']['content'];
}
return '';
}
/**
* Attempt to decode JSON emitted by the model (handles markdown fences).
*
* @param array<string,mixed> $response
* @return array<string,mixed>|null
*/
public static function decodeJsonFromResponse(array $response): ?array
{
$text = self::extractText($response);
if ($text === '') {
return null;
}
$decoded = json_decode($text, true);
if (is_array($decoded)) {
return $decoded;
}
$stripped = preg_replace('/^```json|```$/m', '', trim($text));
if ($stripped !== null && $stripped !== $text) {
$decoded = json_decode($stripped, true);
if (is_array($decoded)) {
return $decoded;
}
}
return null;
}
/**
* Load configuration from ai/config.php.
*
* @return array<string,mixed>
*/
private static function config(): array
{
if (self::$configCache === null) {
$configPath = __DIR__ . '/config.php';
if (!file_exists($configPath)) {
throw new RuntimeException('AI config file not found: ai/config.php');
}
$cfg = require $configPath;
if (!is_array($cfg)) {
throw new RuntimeException('Invalid AI config format: expected array');
}
self::$configCache = $cfg;
}
return self::$configCache;
}
/**
* Build an absolute URL from base_url and a path.
*/
private static function buildUrl(string $path, string $baseUrl): string
{
$trimmed = trim($path);
if ($trimmed === '') {
return $baseUrl;
}
if (str_starts_with($trimmed, 'http://') || str_starts_with($trimmed, 'https://')) {
return $trimmed;
}
if ($trimmed[0] === '/') {
return $baseUrl . $trimmed;
}
return $baseUrl . '/' . $trimmed;
}
}
// Legacy alias for backward compatibility with the previous class name.
if (!class_exists('OpenAIService')) {
class_alias(LocalAIApi::class, 'OpenAIService');
}

52
ai/config.php Normal file
View File

@ -0,0 +1,52 @@
<?php
// OpenAI proxy configuration (workspace scope).
// Reads values from environment variables or executor/.env.
$projectUuid = getenv('PROJECT_UUID');
$projectId = getenv('PROJECT_ID');
if (
($projectUuid === false || $projectUuid === null || $projectUuid === '') ||
($projectId === false || $projectId === null || $projectId === '')
) {
$envPath = realpath(__DIR__ . '/../../.env'); // executor/.env
if ($envPath && is_readable($envPath)) {
$lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') {
continue;
}
if (!str_contains($line, '=')) {
continue;
}
[$key, $value] = array_map('trim', explode('=', $line, 2));
if ($key === '') {
continue;
}
$value = trim($value, "\"' ");
if (getenv($key) === false || getenv($key) === '') {
putenv("{$key}={$value}");
}
}
$projectUuid = getenv('PROJECT_UUID');
$projectId = getenv('PROJECT_ID');
}
}
$projectUuid = ($projectUuid === false) ? null : $projectUuid;
$projectId = ($projectId === false) ? null : $projectId;
$baseUrl = 'https://flatlogic.com';
$responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null;
return [
'base_url' => $baseUrl,
'responses_path' => $responsesPath,
'project_id' => $projectId,
'project_uuid' => $projectUuid,
'project_header' => 'project-uuid',
'default_model' => 'gpt-5',
'timeout' => 30,
'verify_tls' => true,
];

47
assets/css/custom.css Normal file
View File

@ -0,0 +1,47 @@
/* UBPay Custom Styles */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap');
:root {
--bs-primary: #00A859;
--bs-secondary: #FFC107;
--bs-light: #F8F9FA;
--bs-dark: #212529;
--bs-font-sans-serif: 'Poppins', sans-serif;
--bs-border-radius: 0.5rem;
--bs-border-radius-lg: 1rem;
}
body {
background-color: var(--bs-light);
font-family: var(--bs-font-sans-serif);
}
.btn-primary {
background-color: var(--bs-primary);
border-color: var(--bs-primary);
}
.btn-primary:hover {
background-color: #008245;
border-color: #00733d;
}
.form-control:focus {
border-color: var(--bs-primary);
box-shadow: 0 0 0 0.25rem rgba(0, 168, 89, 0.25);
}
.navbar-brand {
font-weight: 700;
color: var(--bs-primary) !important;
}
.brand-gradient {
background: linear-gradient(135deg, #00A859 0%, #007B5F 100%);
color: white;
}
.registration-card {
border: none;
box-shadow: 0 0.5rem 1rem rgba(0,0,0,.15);
}

159
dashboard.php Normal file
View File

@ -0,0 +1,159 @@
<?php
session_start();
// If user is not logged in, redirect to login page
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
require_once 'db/config.php';
$user_id = $_SESSION['user_id'];
$user = null;
$balance = 0;
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT full_name, balance FROM users WHERE id = :id");
$stmt->execute(['id' => $user_id]);
$user = $stmt->fetch();
$balance = $user['balance'] ?? 0;
} catch (PDOException $e) {
// Handle db error
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UBPay Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="assets/css/custom.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="index.php">
<i class="bi bi-wallet2"></i> UBPay
</a>
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-person-circle"></i> <?php echo htmlspecialchars($user['full_name'] ?? 'User'); ?>
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Profile</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="logout.php">Logout</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<main class="container mt-4">
<div class="row">
<div class="col-12">
<h1 class="h3 mb-4">Welcome, <?php echo htmlspecialchars(explode(' ', $user['full_name'])[0] ?? 'User'); ?>!</h1>
</div>
</div>
<div class="row">
<!-- Wallet Balance -->
<div class="col-md-6 col-lg-4 mb-4">
<div class="card text-white" style="background: linear-gradient(135deg, #00A859 0%, #007B5F 100%);">
<div class="card-body">
<h5 class="card-title">Wallet Balance</h5>
<p class="display-4 fw-bold">R<?php echo number_format($balance, 2); ?></p>
<p class="card-text text-white-50">Available Funds</p>
</div>
</div>
</div>
<!-- Quick Actions -->
<div class="col-md-6 col-lg-8 mb-4">
<div class="card">
<div class="card-body">
<h5 class="card-title mb-3">Quick Actions</h5>
<div class="d-grid gap-2 d-sm-flex">
<a href="send-money.php" class="btn btn-primary flex-fill"><i class="bi bi-send"></i> Send Money</a>
<a href="pay-merchant.php" class="btn btn-secondary flex-fill"><i class="bi bi-shop"></i> Pay Merchant</a>
<button class="btn btn-info flex-fill"><i class="bi bi-phone"></i> Buy Airtime</button>
</div>
</div>
</div>
</div>
</div>
<!-- Recent Transactions -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h5 class="card-title">Recent Transactions</h5>
<?php
try {
$pdo = db();
// Create table if not exists
$pdo->exec("CREATE TABLE IF NOT EXISTS transactions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
description VARCHAR(255) NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
type VARCHAR(50) NOT NULL,
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)");
// Fetch transactions for the logged-in user
$stmt = $pdo->prepare("SELECT description, amount, type, notes, created_at FROM transactions WHERE user_id = :user_id ORDER BY created_at DESC LIMIT 10");
$stmt->execute(['user_id' => $user_id]);
$transactions = $stmt->fetchAll();
if (count($transactions) > 0) {
echo '<ul class="list-group list-group-flush">';
foreach ($transactions as $tx) {
$amount_class = $tx['amount'] > 0 ? 'text-success' : 'text-danger';
$icon = $tx['amount'] > 0 ? 'bi-arrow-down-circle-fill' : 'bi-arrow-up-circle-fill';
$amount_prefix = $tx['amount'] > 0 ? '+' : '-';
$formatted_amount = 'R' . number_format(abs($tx['amount']), 2);
echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
echo '<div>';
echo '<i class="bi ' . $icon . ' ' . $amount_class . '"></i>';
echo '<strong class="ms-2">' . htmlspecialchars($tx['description']) . '</strong>';
echo '<small class="d-block text-muted">' . htmlspecialchars($tx['type']) . '</small>';
if (!empty($tx['notes'])) {
echo '<small class="d-block text-muted fst-italic">' . htmlspecialchars($tx['notes']) . '</small>';
}
echo '</div>';
echo '<span class="' . $amount_class . ' fw-bold">' . $amount_prefix . ' ' . $formatted_amount . '</span>';
echo '</li>';
}
echo '</ul>';
} else {
echo '<p class="text-muted">No recent transactions.</p>';
}
} catch (PDOException $e) {
echo '<p class="text-danger">Database error: Could not fetch transactions.</p>';
}
?>
</div>
</div>
</div>
</div>
</main>
<footer class="text-center text-muted py-4">
&copy; 2025 UBPay. All Rights Reserved.
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

280
index.php
View File

@ -1,150 +1,142 @@
<?php <!DOCTYPE html>
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
$phpVersion = PHP_VERSION;
$now = date('Y-m-d H:i:s');
?>
<!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Style</title>
<?php <!-- SEO and Meta Tags -->
// Read project preview data from environment <title>UBPay - Welcome</title>
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? ''; <meta name="description" content="Join UBPay, the future of payments in Southern Africa. Built with Flatlogic Generator.">
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? ''; <meta name="keywords" content="fintech africa, mobile payments, p2p transfer, merchant services, financial inclusion, unbanked, cross-border payments, digital wallet, south africa fintech, Built with Flatlogic Generator">
?>
<?php if ($projectDescription): ?> <!-- Open Graph / Facebook -->
<!-- Meta description --> <meta property="og:type" content="website">
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' /> <meta property="og:title" content="UBPay - Secure & Instant Payments">
<!-- Open Graph meta tags --> <meta property="og:description" content="The leading fintech platform for Southern Africa, enabling financial inclusion for everyone.">
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<!-- Twitter meta tags --> <!-- Twitter -->
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" /> <meta name="twitter:card" content="summary_large_image">
<?php endif; ?>
<?php if ($projectImageUrl): ?> <!-- Platform-managed Meta Tags -->
<!-- Open Graph image --> <?php if (getenv('PROJECT_IMAGE_URL')): ?>
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" /> <meta property="og:image" content="<?= htmlspecialchars(getenv('PROJECT_IMAGE_URL')) ?>">
<!-- Twitter image --> <meta name="twitter:image" content="<?= htmlspecialchars(getenv('PROJECT_IMAGE_URL')) ?>">
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" /> <?php endif; ?>
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com"> <!-- Stylesheets -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet"> <link href="assets/css/custom.css?v=<?php echo time(); ?>" rel="stylesheet">
<style>
:root {
--bg-color-start: #6a11cb;
--bg-color-end: #2575fc;
--text-color: #ffffff;
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1);
}
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
text-align: center;
overflow: hidden;
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
animation: bg-pan 20s linear infinite;
z-index: -1;
}
@keyframes bg-pan {
0% { background-position: 0% 0%; }
100% { background-position: 100% 100%; }
}
main {
padding: 2rem;
}
.card {
background: var(--card-bg-color);
border: 1px solid var(--card-border-color);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
}
.loader {
margin: 1.25rem auto 1.25rem;
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.25);
border-top-color: #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hint {
opacity: 0.9;
}
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0 0 1rem;
letter-spacing: -1px;
}
p {
margin: 0.5rem 0;
font-size: 1.1rem;
}
code {
background: rgba(0,0,0,0.2);
padding: 2px 6px;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
opacity: 0.7;
}
</style>
</head> </head>
<body> <body>
<main>
<div class="card"> <!-- Toast Container -->
<h1>Analyzing your requirements and generating your website…</h1> <div class="toast-container position-fixed top-0 end-0 p-3">
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes"> <div id="notificationToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<span class="sr-only">Loading…</span> <div class="toast-header">
</div> <strong class="me-auto" id="toastTitle"></strong>
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
<p class="hint">This page will update automatically as the plan is implemented.</p> </div>
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p> <div class="toast-body" id="toastBody">
</div>
</div>
</div> </div>
</main>
<footer> <!-- Navbar -->
Page updated: <?= htmlspecialchars($now) ?> (UTC) <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
</footer> <div class="container">
<a class="navbar-brand" href="#">UBPay</a>
</div>
</nav>
<!-- Main Content -->
<main class="container my-5">
<div class="row align-items-center g-5">
<!-- Left Column: Welcome Text -->
<div class="col-lg-6">
<h1 class="display-4 fw-bold lh-1 mb-3">The Future of Payments in Southern Africa</h1>
<p class="lead">Join UBPay for fast, secure, and low-cost payments. Built for everyone, from street vendors to cross-border businesses. Financial inclusion starts here.</p>
</div>
<!-- Right Column: Registration Form -->
<div class="col-lg-6">
<div class="card registration-card p-4 p-md-5">
<form action="register.php" method="POST">
<h3 class="fw-bold mb-4 text-center">Create Your Account</h3>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="fullName" name="full_name" placeholder="John Doe" required>
<label for="fullName">Full Name</label>
</div>
<div class="form-floating mb-3">
<input type="tel" class="form-control" id="mobileNumber" name="mobile_number" placeholder="+27721234567" required>
<label for="mobileNumber">Mobile Number</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
<label for="password">Password</label>
</div>
<div class="form-check mb-4">
<input class="form-check-input" type="checkbox" value="" id="agreeTerms" name="agree_terms" required>
<label class="form-check-label" for="agreeTerms">
I agree to the <a href="#">Terms and Conditions</a>
</label>
</div>
<div class="d-grid">
<button class="btn btn-primary btn-lg" type="submit">Create Account</button>
</div>
</form>
<p class="text-center mt-3">
Already have an account? <a href="login.php">Login</a>
</p>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="container py-4 mt-5 border-top">
<p class="text-center text-muted">&copy; <?php echo date("Y"); ?> UBPay. All rights reserved.</p>
</footer>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const urlParams = new URLSearchParams(window.location.search);
const successMessage = urlParams.get('success');
const errorMessage = urlParams.get('error');
const toastEl = document.getElementById('notificationToast');
if (!toastEl) return;
const toast = new bootstrap.Toast(toastEl);
const toastTitle = document.getElementById('toastTitle');
const toastBody = document.getElementById('toastBody');
if (successMessage) {
toastTitle.textContent = 'Success';
toastTitle.classList.add('text-success');
toastBody.textContent = successMessage;
toast.show();
} else if (errorMessage) {
toastTitle.textContent = 'Error';
toastTitle.classList.add('text-danger');
toastBody.textContent = errorMessage;
toast.show();
}
// Clean URL after showing toast
if(successMessage || errorMessage) {
window.history.replaceState({}, document.title, window.location.pathname);
}
});
</script>
</body> </body>
</html> </html>

84
login.php Normal file
View File

@ -0,0 +1,84 @@
<?php
session_start();
ini_set('display_errors', 0);
// If user is already logged in, redirect to dashboard
if (isset($_SESSION['user_id'])) {
header("Location: dashboard.php");
exit();
}
require_once 'db/config.php';
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$mobile_number = trim($_POST['mobile_number'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($mobile_number) || empty($password)) {
$error_message = 'Please enter both mobile number and password.';
} else {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, password_hash FROM users WHERE mobile_number = :mobile_number");
$stmt->execute(['mobile_number' => $mobile_number]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
// Password is correct, start session
$_SESSION['user_id'] = $user['id'];
header("Location: dashboard.php");
exit();
} else {
$error_message = 'Invalid mobile number or password.';
}
} catch (PDOException $e) {
$error_message = 'An internal error occurred. Please try again later.';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - UBPay</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css">
</head>
<body>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-6 col-lg-4">
<div class="card mt-5">
<div class="card-body">
<h3 class="card-title text-center mb-4">Login to UBPay</h3>
<?php if (!empty($error_message)): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<form action="login.php" method="post">
<div class="mb-3">
<label for="mobile_number" class="form-label">Mobile Number</label>
<input type="text" class="form-control" id="mobile_number" name="mobile_number" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Login</button>
</div>
<p class="text-center mt-3">
Don't have an account? <a href="index.php">Register</a>
</p>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

22
logout.php Normal file
View File

@ -0,0 +1,22 @@
<?php
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
// Redirect to login page
header("Location: login.php");
exit();

59
pay-merchant.php Normal file
View File

@ -0,0 +1,59 @@
<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$user_id]);
$user = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pay Merchant - UBPay</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card mt-5">
<div class="card-body">
<h3 class="card-title text-center mb-4">Pay Merchant</h3>
<div class="text-center mb-4">
<p class="text-muted mb-0">Your current balance:</p>
<h4 class="fw-bold">$<?php echo number_format($user['balance'], 2); ?></h4>
</div>
<form action="process-pay-merchant.php" method="post">
<div class="mb-3">
<label for="merchant-code" class="form-label">Merchant Code</label>
<input type="text" class="form-control" id="merchant-code" name="merchant_code" required>
</div>
<div class="mb-3">
<label for="amount" class="form-label">Amount</label>
<input type="number" class="form-control" id="amount" name="amount" step="0.01" required>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Pay Now</button>
</div>
<p class="text-center mt-3">
<a href="dashboard.php">Back to Dashboard</a>
</p>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

76
process-pay-merchant.php Normal file
View File

@ -0,0 +1,76 @@
<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
// For demonstration, we'll ensure a merchant user exists.
// In a real app, merchants would register separately.
$merchant_email = 'merchant@ubpay.com';
$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
$stmt->execute([$merchant_email]);
$merchant = $stmt->fetch();
if (!$merchant) {
$stmt = $pdo->prepare('INSERT INTO users (name, email, password, balance) VALUES (?, ?, ?, ?)');
$stmt->execute(['Default Merchant', $merchant_email, password_hash('password', PASSWORD_DEFAULT), 10000]);
$merchant_id = $pdo->lastInsertId();
} else {
$merchant_id = $merchant['id'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user_id = $_SESSION['user_id'];
$merchant_code = $_POST['merchant_code']; // In a real app, this would be validated more thoroughly
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
if (!$merchant_code || !$amount || $amount <= 0) {
$_SESSION['error_message'] = 'Invalid input. Please check the merchant code and amount.';
header('Location: pay-merchant.php');
exit;
}
try {
$pdo->beginTransaction();
// Get sender's balance
$stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ? FOR UPDATE');
$stmt->execute([$user_id]);
$sender = $stmt->fetch();
if ($sender['balance'] < $amount) {
$_SESSION['error_message'] = 'Insufficient funds.';
header('Location: pay-merchant.php');
$pdo->rollBack();
exit;
}
// Debit sender
$stmt = $pdo->prepare('UPDATE users SET balance = balance - ? WHERE id = ?');
$stmt->execute([$amount, $user_id]);
// Credit merchant (using the dummy merchant for this example)
$stmt = $pdo->prepare('UPDATE users SET balance = balance + ? WHERE id = ?');
$stmt->execute([$amount, $merchant_id]);
// Record transaction
$stmt = $pdo->prepare('INSERT INTO transactions (sender_id, receiver_id, amount, type, description) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$user_id, $merchant_id, $amount, 'merchant_payment', 'Payment to merchant ' . htmlspecialchars($merchant_code)]);
$pdo->commit();
$_SESSION['success_message'] = 'Payment of $' . number_format($amount, 2) . ' to merchant ' . htmlspecialchars($merchant_code) . ' was successful.';
header('Location: dashboard.php');
exit;
} catch (Exception $e) {
$pdo->rollBack();
$_SESSION['error_message'] = 'An error occurred. Please try again.';
error_log('Merchant Payment Error: ' . $e->getMessage());
header('Location: pay-merchant.php');
exit;
}
}

91
process-send-money.php Normal file
View File

@ -0,0 +1,91 @@
<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
// Check if 'notes' column exists and add it if not
try {
$pdo->query("SELECT notes FROM transactions LIMIT 1");
} catch (PDOException $e) {
if ($e->getCode() == '42S22') { // Column not found
$pdo->exec("ALTER TABLE transactions ADD COLUMN notes TEXT");
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sender_id = $_SESSION['user_id'];
$recipient_mobile = $_POST['recipient'];
$amount = (float)$_POST['amount'];
$notes = !empty($_POST['notes']) ? trim($_POST['notes']) : null;
// Validate amount
if ($amount <= 0) {
$_SESSION['message'] = "Invalid amount.";
$_SESSION['message_type'] = "danger";
header("Location: send-money.php");
exit;
}
try {
$pdo->beginTransaction();
// Get sender
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? FOR UPDATE");
$stmt->execute([$sender_id]);
$sender = $stmt->fetch();
// Get recipient
$stmt = $pdo->prepare("SELECT * FROM users WHERE mobile = ? FOR UPDATE");
$stmt->execute([$recipient_mobile]);
$recipient = $stmt->fetch();
if (!$recipient) {
throw new Exception("Recipient not found.");
}
if ($sender['id'] === $recipient['id']) {
throw new Exception("You cannot send money to yourself.");
}
if ($sender['balance'] < $amount) {
throw new Exception("Insufficient funds.");
}
// Perform transaction
$new_sender_balance = $sender['balance'] - $amount;
$stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_sender_balance, $sender_id]);
$new_recipient_balance = $recipient['balance'] + $amount;
$stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
$stmt->execute([$new_recipient_balance, $recipient['id']]);
// Record transaction
$stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, notes) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$sender_id, 'debit', $amount, "Sent money to {$recipient['name']}", $notes]);
$stmt->execute([$recipient['id'], 'credit', $amount, "Received money from {$sender['name']}", $notes]);
$pdo->commit();
$_SESSION['message'] = "Money sent successfully!";
$_SESSION['message_type'] = "success";
header("Location: dashboard.php");
exit;
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
$_SESSION['message'] = "Error: " . $e->getMessage();
$_SESSION['message_type'] = "danger";
header("Location: send-money.php");
exit;
}
} else {
header("Location: send-money.php");
exit;
}

80
register.php Normal file
View File

@ -0,0 +1,80 @@
<?php
// register.php
ini_set('display_errors', 0); // Do not display errors to the user
require_once 'db/config.php';
function redirect_with_message($type, $message) {
header("Location: index.php?$type=" . urlencode($message));
exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect_with_message('error', 'Invalid request method.');
}
// --- Input Validation ---
$full_name = trim($_POST['full_name'] ?? '');
$mobile_number = trim($_POST['mobile_number'] ?? '');
$password = $_POST['password'] ?? '';
$agree_terms = isset($_POST['agree_terms']);
if (empty($full_name) || empty($mobile_number) || empty($password)) {
redirect_with_message('error', 'All fields are required.');
}
if (!$agree_terms) {
redirect_with_message('error', 'You must agree to the terms and conditions.');
}
if (strlen($password) < 8) {
redirect_with_message('error', 'Password must be at least 8 characters long.');
}
// Basic mobile number validation (doesn't cover all edge cases)
if (!preg_match('/^\+?[1-9]\d{1,14}$/', $mobile_number)) {
redirect_with_message('error', 'Invalid mobile number format.');
}
try {
$pdo = db();
// --- Idempotent Table Creation ---
$pdo->exec("
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
full_name VARCHAR(255) NOT NULL,
mobile_number VARCHAR(20) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
");
// --- Check if user already exists ---
$stmt = $pdo->prepare("SELECT id FROM users WHERE mobile_number = :mobile_number");
$stmt->execute(['mobile_number' => $mobile_number]);
if ($stmt->fetch()) {
redirect_with_message('error', 'A user with this mobile number already exists.');
}
// --- Create User ---
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare(
"INSERT INTO users (full_name, mobile_number, password_hash) VALUES (:full_name, :mobile_number, :password_hash)"
);
$stmt->execute([
':full_name' => $full_name,
':mobile_number' => $mobile_number,
':password_hash' => $password_hash
]);
redirect_with_message('success', 'Registration successful! You can now log in.');
} catch (PDOException $e) {
// In a real app, you would log this error.
// error_log("Registration failed: " . $e->getMessage());
redirect_with_message('error', 'An internal error occurred. Please try again later.');
}

129
send-money.php Normal file
View File

@ -0,0 +1,129 @@
<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send Money - UBPay</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.css">
</head>
<body style="background-color: #F8F9FA;">
<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
<div class="container">
<a class="navbar-brand" href="dashboard.php" style="color: #00A859; font-weight: bold;">
<i data-feather="dollar-sign" class="me-2"></i>UBPay
</a>
<div class="d-flex">
<a href="dashboard.php" class="btn btn-light">Back to Dashboard</a>
</div>
</div>
</nav>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card shadow-sm" style="border-radius: 0.5rem;">
<div class="card-body p-4">
<h2 class="card-title text-center mb-4" style="color: #00A859; font-weight: 600;">Send Money</h2>
<div class="alert alert-info">
Your current balance is: <strong>$<?php echo htmlspecialchars(number_format($user['balance'], 2)); ?></strong>
</div>
<?php if (isset($_SESSION['message'])): ?>
<div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show" role="alert">
<?php echo $_SESSION['message']; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php unset($_SESSION['message']); unset($_SESSION['message_type']); ?>
<?php endif; ?>
<form id="send-money-form" action="process-send-money.php" method="POST">
<div class="mb-3">
<label for="recipient" class="form-label">Recipient's Mobile Number</label>
<input type="text" class="form-control" id="recipient" name="recipient" placeholder="Enter mobile number" required>
</div>
<div class="mb-3">
<label for="amount" class="form-label">Amount</label>
<div class="input-group">
<span class="input-group-text" style="color: #00A859;">$</span>
<input type="number" class="form-control" id="amount" name="amount" placeholder="0.00" step="0.01" min="0.01" max="<?php echo $user['balance']; ?>" required>
</div>
</div>
<div class="mb-3">
<label for="notes" class="form-label">Notes (Optional)</label>
<textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Add a note..."></textarea>
</div>
<div class="d-grid">
<button type="button" class="btn btn-primary btn-lg" style="background-color: #00A859; border-color: #00A859;" data-bs-toggle="modal" data-bs-target="#confirmationModal">Send Money</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Confirmation Modal -->
<div class="modal fade" id="confirmationModal" tabindex="-1" aria-labelledby="confirmationModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="confirmationModalLabel">Confirm Transaction</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Please confirm the details of your transaction:</p>
<ul class="list-group">
<li class="list-group-item"><strong>Recipient:</strong> <span id="confirm-recipient"></span></li>
<li class="list-group-item"><strong>Amount:</strong> $<span id="confirm-amount"></span></li>
<li class="list-group-item"><strong>Notes:</strong> <span id="confirm-notes"></span></li>
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="confirm-send-button" style="background-color: #00A859; border-color: #00A859;">Confirm & Send</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script>
feather.replace();
const confirmationModal = document.getElementById('confirmationModal');
confirmationModal.addEventListener('show.bs.modal', function (event) {
const recipient = document.getElementById('recipient').value;
const amount = document.getElementById('amount').value;
const notes = document.getElementById('notes').value;
document.getElementById('confirm-recipient').textContent = recipient;
document.getElementById('confirm-amount').textContent = parseFloat(amount).toFixed(2);
document.getElementById('confirm-notes').textContent = notes || 'N/A';
});
document.getElementById('confirm-send-button').addEventListener('click', function () {
document.getElementById('send-money-form').submit();
});
</script>
</body>
</html>