Feature/users #6

Merged
Corpintech merged 7 commits from feature/users into main 2025-08-23 17:04:45 -04:00
21 changed files with 1011 additions and 68 deletions

View File

@@ -1 +0,0 @@
APIKEY=123

118
ai_email.sql Normal file
View File

@@ -0,0 +1,118 @@
-- phpMyAdmin SQL Dump
-- version 6.0.0-dev+20250817.7816c49805
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Aug 23, 2025 at 08:49 PM
-- Server version: 8.4.3
-- PHP Version: 8.3.16
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `ai_email`
--
-- --------------------------------------------------------
--
-- Table structure for table `saved_emails`
--
CREATE TABLE `saved_emails` (
`id` int UNSIGNED NOT NULL,
`user_id` int UNSIGNED NOT NULL,
`subject` varchar(255) DEFAULT NULL,
`body` text NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
--
-- Dumping data for table `saved_emails`
--
INSERT INTO `saved_emails` (`id`, `user_id`, `subject`, `body`, `created_at`) VALUES
(1, 1, 'Welcome to AI Email Generator', 'This is your first saved email 🎉', '2025-08-20 00:14:01'),
(2, 1, 'saved', 'Dear [Recipient\'s Name],\r\n\r\nI am writing to express my interest in purchasing the car listed for sale at $60,000. I am prepared to offer $50,000 for the vehicle. Please let me know if this offer is acceptable to you.\r\n\r\nThank you for your time and consideration.\r\n\r\nSincerely,\r\n[Your Name]', '2025-08-20 01:02:02');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int UNSIGNED NOT NULL,
`username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`dob` date NOT NULL,
`uniqueid` char(32) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `email`, `password`, `dob`, `uniqueid`, `created_at`) VALUES
(1, 'DreamRage', 'test@gmail.com', '$2y$12$8EafDAPFoXdNsx6jWM6NIOAtF8dumXCA//Yl2B/NdNkd6vss2qDhW', '1997-02-08', '5924447ab071c6526f1f76ef53127ffa', '2025-08-19 23:03:58');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `saved_emails`
--
ALTER TABLE `saved_emails`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `uniqueid` (`uniqueid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `saved_emails`
--
ALTER TABLE `saved_emails`
MODIFY `id` int UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `saved_emails`
--
ALTER TABLE `saved_emails`
ADD CONSTRAINT `saved_emails_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View File

@@ -1,11 +1,12 @@
<?php
// config.php
function getApi(){
function getApi() {
$api_key = getenv('APIKEY');
if($api_key){
return array('openai_api_key' => $api_key);
}else{
return false;
if ($api_key) {
return $api_key;
} else {
// fallback hardcoded key for testing
return "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";
}
}
?>
?>

9
database_schema.sql Normal file
View File

@@ -0,0 +1,9 @@
-- Creates the users table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
uniqueid VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

23
db.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
function getConnection() {
$host = '127.0.0.1'; // Force TCP/IP, avoids socket issues
$port = 3306; // XAMPP default port
$db = 'ai_email';
$user = 'root';
$pass = ''; // XAMPP default has no password
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
return new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
?>

View File

@@ -1,9 +1,73 @@
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');?>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin(); // only logged-in users can pass
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$conn = getConnection();
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
?>
<body>
<div class="container">
<h1>AI Email Generator</h1>
<p>Effortlessly craft polished, professional emails in seconds.</p>
<a href="/"><button>Start Generating Emails</button></a>
<button id="darkModeBtn">Toggle Dark Mode</button>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php');
<div class="dashboard">
<!-- Sidebar -->
<aside class="sidebar">
<h2 class="logo">📧 AI Email</h2>
<nav>
<ul>
<li><a href="/inc/php/generate.php">✍️ Generate</a></li>
<li><a href="/saved_emails.php">💾 Saved Emails</a></li>
<li><a href="/settings.php">⚙️ Settings</a></li>
<li><a href="/logout.php">🚪 Logout</a></li>
</ul>
</nav>
</aside>
<!-- Main Content -->
<main class="main-content">
<header>
<h1>Welcome to AI Email Generator</h1>
<p>Effortlessly craft polished, professional emails in seconds.</p>
<button id="darkModeBtn">🌙 Toggle Dark Mode</button>
</header>
<section class="quick-actions">
<h2>⚡ Quick Actions</h2>
<div class="actions">
<a href="/inc/php/generate.php"><button>Start Generating Emails</button></a>
</div>
</section>
<section class="connected-accounts">
<h2>📧 Connected Accounts</h2>
<p>Link your email provider to read & send directly:</p>
<div class="connect-buttons">
<a href="/connect/gmail.php"><button>Connect Gmail</button></a>
<a href="/connect/outlook.php"><button>Connect Outlook</button></a>
<a href="/connect/imap.php"><button>Other (IMAP/SMTP)</button></a>
</div>
</section>
<section class="inbox">
<h2>📥 Inbox</h2>
<p>(This will show your connected emails once integration is done)</p>
<table>
<tr><th>From</th><th>Subject</th><th>Date</th><th>Action</th></tr>
<tr>
<td>Alice</td>
<td>Hello about our meeting</td>
<td>2025-08-20</td>
<td><a href="/inbox/view.php?id=1"><button>View</button></a></td>
</tr>
<tr>
<td>Bob</td>
<td>Invoice Reminder</td>
<td>2025-08-19</td>
<td><a href="/inbox/view.php?id=2"><button>View</button></a></td>
</tr>
</table>
</section>
</main>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>

View File

@@ -151,3 +151,195 @@ button + button {
white-space: pre-wrap;
word-wrap: break-word;
}
.auth-box {
max-width: 400px;
margin: auto;
padding: 20px;
border-radius: 10px;
background: #fff;
transition: all 0.5s ease;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
.auth-box.hidden {
display: none;
}
.auth-box h2 {
text-align: center;
}
.auth-box .error {
color: red;
text-align: center;
margin-bottom: 10px;
}
.auth-box input, .auth-box button {
display: block;
width: 100%;
margin: 10px 0;
}
/* Navbar styling */
.navbar {
display: flex;
justify-content: space-between; /* logo left, links right */
align-items: center;
background-color: #fff;
padding: 15px 30px;
border-bottom: 1px solid #ddd;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.navbar .logo {
font-size: 1.5em;
font-weight: bold;
color: #333;
}
.navbar .nav-links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
gap: 20px;
}
.navbar .nav-links li {
display: inline;
}
.navbar .nav-links a {
text-decoration: none;
color: #333;
font-weight: 500;
transition: color 0.2s ease;
}
.navbar .nav-links a:hover,
.navbar .nav-links a.active {
color: #007bff; /* highlight */
}
.connect-buttons button {
margin: 8px;
padding: 10px 18px;
font-size: 14px;
border-radius: 8px;
border: none;
cursor: pointer;
background: #444;
color: #fff;
transition: background 0.2s;
}
.connect-buttons button:hover {
background: #666;
}
table.inbox {
width: 100%;
margin-top: 15px;
border-collapse: collapse;
}
table.inbox th, table.inbox td {
padding: 10px;
border-bottom: 1px solid #333;
text-align: left;
}
table.inbox tr:hover {
background: #222;
}
/* Dashboard Layout */
.dashboard {
display: flex;
min-height: 100vh;
}
/* Sidebar */
.sidebar {
width: 220px;
background: #111827; /* dark slate */
color: #fff;
padding: 20px;
display: flex;
flex-direction: column;
}
.sidebar .logo {
font-size: 20px;
font-weight: bold;
margin-bottom: 30px;
text-align: center;
}
.sidebar ul {
list-style: none;
padding: 0;
margin: 0;
}
.sidebar ul li {
margin: 15px 0;
}
.sidebar ul li a {
color: #d1d5db;
text-decoration: none;
font-size: 16px;
display: block;
padding: 8px;
border-radius: 8px;
transition: 0.2s;
}
.sidebar ul li a:hover {
background: #374151;
color: #fff;
}
/* Main Content */
.main-content {
flex: 1;
padding: 40px;
background: #f3f4f6;
}
.dark-mode .main-content {
background: #1f2937;
color: #f3f4f6;
}
/* Force full-width flex layout */
body, html {
margin: 0;
padding: 0;
height: 100%;
}
/* Dashboard wrapper */
.dashboard {
display: flex;
min-height: 100vh;
}
/* Sidebar */
.sidebar {
width: 220px;
background: #0f172a;
color: #fff;
padding: 20px;
margin: 0; /* REMOVE spacing */
position: fixed; /* Stick to left */
top: 0;
left: 0;
bottom: 0;
}
/* Main content area */
.main-content {
margin-left: 220px; /* Push content to the right of sidebar */
padding: 30px;
flex: 1;
}

View File

@@ -1,9 +1,61 @@
document.addEventListener('DOMContentLoaded', () =>{
document.addEventListener('DOMContentLoaded', () => {
// Dark mode toggle
const toggleBtn = document.getElementById('darkModeBtn');
if(toggleBtn){
toggleBtn.addEventListener('click', (e) =>{
if (toggleBtn) {
toggleBtn.addEventListener('click', (e) => {
e.preventDefault();
document.body.classList.toggle('dark-mode');
})
});
}
})
// Copy email button
const copyBtn = document.getElementById('copyBtn');
if (copyBtn) {
copyBtn.addEventListener('click', () => {
const text = document.getElementById('aiEmail')?.innerText;
if (text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
// Modern way (requires HTTPS or localhost)
navigator.clipboard.writeText(text).then(() => {
showToast();
}).catch(err => {
alert("Failed to copy: " + err);
});
} else {
// Fallback for HTTP
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
showToast();
}
}
});
}
// Save email button
const saveBtn = document.getElementById('saveBtn');
if (saveBtn) {
saveBtn.addEventListener('click', () => {
const text = document.getElementById('aiEmail')?.innerText;
if (text) {
const blob = new Blob([text], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'email.txt';
link.click();
}
});
}
// Toast helper
function showToast() {
const toast = document.getElementById('toast');
if (toast) {
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2000);
}
}
});

32
inc/php/auth.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
function isAuthenticated() {
if (empty($_SESSION['user_id']) || empty($_SESSION['uniqueid'])) {
return false;
}
try {
$conn = getConnection();
$stmt = $conn->prepare("SELECT id FROM users WHERE id = :id AND uniqueid = :uniqueid");
$stmt->execute([
'id' => $_SESSION['user_id'],
'uniqueid' => $_SESSION['uniqueid'],
]);
return $stmt->fetch() !== false;
} catch (PDOException $e) {
return false; // fail safe
}
}
function requireLogin() {
if (!isAuthenticated()) {
header("Location: /landing.php");
exit();
}
}

18
inc/php/delete_email.php Normal file
View File

@@ -0,0 +1,18 @@
<?php
// /inc/php/delete_email.php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$conn = getConnection();
$user_id = $_SESSION['user_id'] ?? null;
$id = intval($_GET['id'] ?? 0);
$stmt = $conn->prepare("DELETE FROM saved_emails WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $id, $user_id);
$stmt->execute();
header("Location: /inc/php/saved.php?deleted=1");
exit;

37
inc/php/generate.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/resources.php'); // load languages
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
?>
<body>
<div class="container">
<h1>Generate an Email</h1>
<!-- adjust action depending on vhost/subfolder -->
<form action="/process.php" method="POST">
<label for="email_input">Your rough text:</label><br>
<textarea name="email_input" rows="6" cols="50" required></textarea><br><br>
<label for="tone">Select tone:</label>
<select name="tone" required>
<option value="formal">Formal</option>
<option value="casual">Casual</option>
<option value="persuasive">Persuasive</option>
</select><br><br>
<label for="language">Language:</label>
<select name="language" required>
<?php foreach (getLanguages() as $lang): ?>
<option value="<?= htmlspecialchars($lang) ?>"><?= htmlspecialchars($lang) ?></option>
<?php endforeach; ?>
</select><br><br>
<button type="submit">Generate Email</button>
</form>
<br>
<a href="/home.php"><button type="button">🏠 Back to Home</button></a>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>

View File

@@ -3,5 +3,5 @@
<head>
<meta charset="UTF-8">
<title>AI Email Generator - Result</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="/inc/css/style.css">
</head>

91
inc/php/login.php Normal file
View File

@@ -0,0 +1,91 @@
<?php
// Always start session safely
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Load DB
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = trim($_POST['login_email'] ?? '');
$password = $_POST['login_password'] ?? '';
$captcha = $_POST['g-recaptcha-response'] ?? '';
// 1. Input validation
if (empty($user) || empty($password)) {
$errors[] = "All fields are required.";
}
// 2. CAPTCHA validation
$captcha_success = false;
$localHosts = ['127.0.0.1', 'localhost'];
if (in_array($_SERVER['SERVER_NAME'], $localHosts) || str_contains($_SERVER['HTTP_HOST'], '.test')) {
$captcha_success = true; // Skip CAPTCHA locally
} else {
if (!empty($captcha)) {
$captcha_secret = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'; // test key
$ch = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $captcha_secret,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR'] ?? null
]);
$captcha_response = curl_exec($ch);
curl_close($ch);
$captcha_data = json_decode($captcha_response, true);
$captcha_success = !empty($captcha_data['success']);
}
}
if (!$captcha_success) {
$errors[] = "CAPTCHA verification failed.";
}
// 3. Authentication
if (empty($errors)) {
try {
$conn = getConnection();
$stmt = $conn->prepare("
SELECT id, username, password, uniqueid
FROM users
WHERE email = :email OR username = :username
LIMIT 1
");
$stmt->execute([
'email' => $user,
'username' => $user
]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result && password_verify($password, $result['password'])) {
// Regenerate session ID on login (security)
session_regenerate_id(true);
$_SESSION['user_id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['uniqueid'] = $result['uniqueid'];
header("Location: /home.php");
exit;
} else {
$errors[] = "Invalid email/username or password.";
}
} catch (Exception $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
// If failed
$_SESSION['login_error'] = implode("<br>", $errors);
header("Location: /landing.php");
exit;
}
?>

99
inc/php/register.php Normal file
View File

@@ -0,0 +1,99 @@
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$confirm_email = trim($_POST['confirm_email'] ?? '');
$password = $_POST['password'] ?? '';
$dob = $_POST['dob'] ?? ''; // from <input type="date" name="dob">
$captcha = $_POST['g-recaptcha-response'] ?? '';
// Basic validation
if (empty($username) || empty($email) || empty($confirm_email) || empty($password) || empty($dob)) {
$errors[] = "All fields are required.";
}
if ($email !== $confirm_email) {
$errors[] = "Emails do not match.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters.";
}
// Date of Birth validation
if ($dob) {
try {
$birthDate = new DateTime($dob);
$today = new DateTime();
if ($birthDate > $today) {
$errors[] = "Date of birth cannot be in the future.";
}
if ($birthDate < new DateTime('1900-01-01')) {
$errors[] = "Please enter a valid birth year (1900 or later).";
}
$age = $today->diff($birthDate)->y;
if ($age < 16) {
$errors[] = "You must be at least 16 years old to register.";
}
} catch (Exception $e) {
$errors[] = "Invalid date of birth.";
}
}
// CAPTCHA validation
$captcha_secret = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'; // Google's test secret key
$captcha_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$captcha_secret}&response={$captcha}");
$captcha_data = json_decode($captcha_response);
if (!$captcha_data->success) {
$errors[] = "CAPTCHA verification failed.";
}
if (empty($errors)) {
$conn = getConnection();
// Check for existing user
$stmt = $conn->prepare("SELECT id FROM users WHERE email = :email OR username = :username");
$stmt->execute(['email' => $email, 'username' => $username]);
if ($stmt->fetch()) {
$errors[] = "Email or username already in use.";
} else {
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$uniqueId = bin2hex(random_bytes(16));
$insert = $conn->prepare("INSERT INTO users (username, email, password, dob, uniqueid)
VALUES (:username, :email, :password, :dob, :uniqueid)");
$insert->execute([
'username' => $username,
'email' => $email,
'password' => $hash,
'dob' => $dob,
'uniqueid' => $uniqueId,
]);
$_SESSION['user_id'] = $conn->lastInsertId();
$_SESSION['uniqueid'] = $uniqueId;
header("Location: /home.php");
exit();
}
}
$_SESSION['register_error'] = implode("<br>", $errors);
header("Location: /landing.php");
exit();
}
?>

39
inc/php/save_email.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
// /inc/php/save_email.php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin(); // block guests
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$conn = getConnection();
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
die("Unauthorized. Please log in.");
}
// Get and sanitize inputs
$subject = trim($_POST['subject'] ?? '');
$email_body = trim($_POST['email_body'] ?? '');
if (empty($email_body)) {
die("No email content provided.");
}
$stmt = $conn->prepare("
INSERT INTO saved_emails (user_id, subject, body, created_at)
VALUES (:user_id, :subject, :body, NOW())
");
if ($stmt->execute([
':user_id' => $user_id,
':subject' => $subject,
':body' => $email_body
])) {
header("Location: /home.php?success=1");
exit;
} else {
$error = $stmt->errorInfo();
echo "Error saving email: " . $error[2];
}

33
inc/php/view_email.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
// /inc/php/view_email.php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$conn = getConnection();
$user_id = $_SESSION['user_id'] ?? null;
$id = intval($_GET['id'] ?? 0);
$stmt = $conn->prepare("SELECT subject, body, created_at FROM saved_emails WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$email = $result->fetch_assoc();
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
?>
<body>
<div class="container">
<?php if ($email): ?>
<h1><?= htmlspecialchars($email['subject'] ?: '(No Subject)') ?></h1>
<p><em>Saved on <?= $email['created_at'] ?></em></p>
<pre><?= htmlspecialchars($email['body']) ?></pre>
<a href="/inc/php/saved.php"><button>⬅ Back</button></a>
<?php else: ?>
<p>Email not found ❌</p>
<?php endif; ?>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>

View File

@@ -1,31 +1,3 @@
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/resources.php');
$languages = getLanguages();
?>
<body>
<div class="container">
<h1>AI Email Generator</h1>
<form action="process.php" method="POST">
<label for="email_input">Your Rough Email:</label>
<textarea name="email_input" id="email_input" rows="8" required></textarea>
<label for="tone">Select Tone:</label>
<select name="tone" id="tone" required>
<option value="formal">Formal</option>
<option value="casual">Casual</option>
<option value="persuasive">Persuasive</option>
</select>
<label for="language">Select Language:</label>
<select name="language" id="language" required>
<?php foreach($languages as $language) :?>
<option value="<?=$language;?>"><?=$language;?></option>
<?php endforeach;?>
</select>
<button type="submit">Generate Email</button>
<button id="darkModeBtn" type="button">Toggle Dark Mode</button>
</form>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php');
header("Location: /landing.php");
exit();

96
landing.php Normal file
View File

@@ -0,0 +1,96 @@
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/config.php');
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
?>
<link rel="stylesheet" href="/inc/css/style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<body>
<nav class="navbar">
<div class="logo">MailGenius</div>
<ul class="nav-links">
<li><a href="#" class="active" onclick="showLogin(); highlightTab(this)">Login</a></li>
<li><a href="#" onclick="showRegister(); highlightTab(this)">Create Account</a></li>
<li><a href="#" onclick="alert('About us content coming soon!')">About Us</a></li>
</ul>
</nav>
<div class="container" id="auth-container">
<h1>AI Email Generator</h1>
<!-- Login Form -->
<div id="login-box" class="auth-box">
<form action="/inc/php/login.php" method="POST">
<h2>Login</h2>
<?php if (isset($_SESSION['login_error'])): ?>
<p class="error"><?= $_SESSION['login_error']; unset($_SESSION['login_error']); ?></p>
<?php endif; ?>
<label for="login_email">Email or Username</label>
<input type="text" name="login_email" required>
<label for="login_password">Password</label>
<input type="password" name="login_password" required>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<button type="submit">Login</button>
</form>
</div>
<!-- Register Form -->
<div id="register-box" class="auth-box hidden">
<form action="/inc/php/register.php" method="POST">
<h2>Create Account</h2>
<?php if (isset($_SESSION['register_error'])): ?>
<p class="error"><?= $_SESSION['register_error']; unset($_SESSION['register_error']); ?></p>
<?php endif; ?>
<label for="username">Username</label>
<input type="text" name="username" required>
<label for="email">Email</label>
<input type="email" name="email" required>
<label for="confirm_email">Confirm Email</label>
<input type="email" name="confirm_email" required>
<label for="password">Password</label>
<input type="password" name="password" required>
<label for="dob">Date of Birth</label>
<input type="date" name="dob" required
min="1900-01-01"
max="<?php echo date('Y-m-d'); ?>">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<button type="submit">Register</button>
</form>
</div>
</div>
<script>
function showRegister() {
document.getElementById("login-box").classList.add("hidden");
document.getElementById("register-box").classList.remove("hidden");
}
function showLogin() {
document.getElementById("register-box").classList.add("hidden");
document.getElementById("login-box").classList.remove("hidden");
}
function highlightTab(el) {
document.querySelectorAll('.nav-links a').forEach(link => link.classList.remove('active'));
el.classList.add('active');
}
</script>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>

6
logout.php Normal file
View File

@@ -0,0 +1,6 @@
<?php
session_start();
session_unset();
session_destroy();
header('Location: login.php');
exit;

View File

@@ -1,18 +1,24 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/config.php');
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/config.php');
include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
$conn = getConnection();
$user_id = $_SESSION['user_id'] ?? null;
?>
<body>
<div class="container">
<?php
// Load API key from config
// Load API key
$apikey = getApi();
// Sanitize and validate user inputs
// Sanitize inputs
$emailInput = trim($_POST['email_input'] ?? '');
$tone = htmlspecialchars($_POST['tone']) ?? '';
$language = htmlspecialchars($_POST['language']) ?? 'English'; // Language selector
$tone = isset($_POST['tone']) ? htmlspecialchars($_POST['tone']) : '';
$language = isset($_POST['language']) ? htmlspecialchars($_POST['language']) : 'English';
$allowedTones = [
'formal' => 'Write this email in a formal tone',
@@ -24,12 +30,11 @@
die('Invalid Input.');
}
// Improved Prompt with strict language response
// Build prompt
$prompt = $allowedTones[$tone] . ". Transform this rough text into a polished, professional email in " . $language . ". ONLY reply in " . $language . ":\n\n" . $emailInput;
// Prepare API request
// API call
$apiurl = 'https://api.openai.com/v1/chat/completions';
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => [
@@ -44,7 +49,6 @@
'Authorization: Bearer ' . $apikey,
];
// Make API request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@@ -55,18 +59,31 @@
$response = curl_exec($ch);
curl_close($ch);
// Handle response
$result = json_decode($response, true);
if (isset($result['choices'][0]['message']['content'])) {
$aiEmail = htmlspecialchars($result['choices'][0]['message']['content']);
$aiEmail = trim($result['choices'][0]['message']['content']);
$safeEmail = htmlspecialchars($aiEmail);
echo "<h2>Your AI-Generated Email:</h2>";
echo "<div class='email-output'>";
echo "<pre>$aiEmail</pre>";
echo "<pre>$safeEmail</pre>";
// Copy / Save / Navigation
echo "<button id='copyBtn'>Copy Email</button>";
echo "<button id='saveBtn'>Save Email as .txt</button>";
echo "<button id='darkModeBtn'>Toggle Dark Mode</button>";
echo "<a href='index.php' class='back-link'>← Generate Another Email</a>";
echo "<a href='/home.php'><button>🏠 Back to Home</button></a>";
echo "<a href='/inc/php/generate.php' class='back-link'>← Generate Another Email</a>";
// NEW: Save to DB form
if ($user_id) {
echo "<form method='POST' action='/inc/php/save_email.php' style='margin-top:15px;'>";
echo "<input type='hidden' name='email_body' value=\"" . htmlspecialchars($aiEmail, ENT_QUOTES) . "\">";
echo "<input type='text' name='subject' placeholder='Subject (optional)'>";
echo "<button type='submit'>💾 Save to My Account</button>";
echo "</form>";
}
echo "</div>";
} else {
echo "Error: Failed to generate email. Try again later.";
@@ -78,7 +95,6 @@
<script>
const copyBtn = document.getElementById('copyBtn');
const saveBtn = document.getElementById('saveBtn');
const darkBtn = document.getElementById('darkModeBtn');
if (copyBtn) {
copyBtn.onclick = function () {
@@ -104,4 +120,4 @@
};
}
</script>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php');
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>

46
saved_emails.php Normal file
View File

@@ -0,0 +1,46 @@
<?php
// /saved_emails.php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/php/auth.php');
requireLogin();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$conn = getConnection();
$user_id = $_SESSION['user_id'] ?? null;
$stmt = $conn->prepare("
SELECT id, subject, body, created_at
FROM saved_emails
WHERE user_id = :user_id
ORDER BY created_at DESC
");
$stmt->execute([':user_id' => $user_id]);
$emails = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/header.php'); ?>
<body>
<div class="container">
<h1>📑 Saved Emails</h1>
<?php if (!empty($emails)): ?>
<table>
<tr><th>Subject</th><th>Preview</th><th>Date</th><th>Action</th></tr>
<?php foreach ($emails as $email): ?>
<tr>
<td><?= htmlspecialchars($email['subject'] ?: '(No Subject)') ?></td>
<td><?= htmlspecialchars(substr($email['body'], 0, 50)) ?>...</td>
<td><?= $email['created_at'] ?></td>
<td>
<a href="/view_email.php?id=<?= $email['id'] ?>"><button>View</button></a>
<a href="/inc/php/delete_email.php?id=<?= $email['id'] ?>" onclick="return confirm('Delete this email?')"><button>Delete</button></a>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<p>No saved emails yet.</p>
<?php endif; ?>
</div>
<?php include($_SERVER['DOCUMENT_ROOT'] . '/inc/php/footer.php'); ?>