To integrate an advertising module into your existing PHP-based workspace management system, we'll create a new ads folder that includes all necessary functionalities for managing advertisements on posts and stories. This comprehensive guide includes database schema modifications, PHP backend scripts, and frontend components using Tailwind CSS and Bootstrap Icons to ensure a seamless and visually appealing user experience.
Table of Contents
- Database Schema Additions
- Folder Structure
- Creating the Ads Module
- Integrating Ads with Posts and Stories
- Frontend Enhancements
- Spending and Budget Tracking
- Final Integration with Existing Dashboard
Database Schema Additions
To support the Ads module, we'll introduce two new tables: ads and ad_spend_logs. These tables will help manage advertisements, track their budgets, and monitor spending.
1. ads Table
This table stores information about each advertisement, including its association with posts or stories, budget details, and status.
-- Table structure for table `ads`
CREATE TABLE `ads` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`ad_type` ENUM('Post', 'Story') NOT NULL,
`related_id` INT(11) NOT NULL, -- References `workspace_posts`.`id`
`budget` DECIMAL(10,2) NOT NULL,
`total_spent` DECIMAL(10,2) DEFAULT 0.00,
`start_date` DATE NOT NULL,
`end_date` DATE NOT NULL,
`status` ENUM('Active', 'Paused', 'Completed') DEFAULT 'Active',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `related_id` (`related_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Foreign key constraint
ALTER TABLE `ads`
ADD CONSTRAINT `fk_ads_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_ads_related_id` FOREIGN KEY (`related_id`) REFERENCES `workspace_posts` (`id`) ON DELETE CASCADE;
2. ad_spend_logs Table
This table logs each spending instance related to an advertisement, allowing detailed tracking of expenditures.
-- Table structure for table `ad_spend_logs`
CREATE TABLE `ad_spend_logs` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`ad_id` INT(11) NOT NULL,
`amount` DECIMAL(10,2) NOT NULL,
`spend_date` DATETIME DEFAULT CURRENT_TIMESTAMP,
`description` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ad_id` (`ad_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Foreign key constraint
ALTER TABLE `ad_spend_logs`
ADD CONSTRAINT `fk_ad_spend_logs_ad_id` FOREIGN KEY (`ad_id`) REFERENCES `ads` (`id`) ON DELETE CASCADE;
Applying the Schema
Execute the above SQL statements in your database (via phpMyAdmin or any MySQL client) to create the necessary tables.
Folder Structure
Create a new folder named ads within your existing project structure. The recommended structure is as follows:
/public
└── /workspace
├── index.php
├── /ads
│ ├── index.php
│ ├── create_ad.php
│ ├── edit_ad.php
│ ├── delete_ad.php
│ └── view_ad.php
└── [other existing files and folders]
Creating the Ads Module
We'll create five main PHP scripts within the ads folder to handle different aspects of advertisement management.
1. ads/index.php - List All Ads
This page lists all advertisements, allowing users to view, edit, or delete them.
<?php
// /public/workspace/ads/index.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering
ob_start();
// Include necessary files
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
$ads = [];
$errors = [];
// Fetch Ads
try {
if ($user_role === 'admin') {
$ads_sql = "SELECT a.*, wp.title AS post_title, u.username
FROM ads a
JOIN workspace_posts wp ON a.related_id = wp.id
JOIN users u ON a.user_id = u.id
ORDER BY a.created_at DESC";
$stmt = $conn->prepare($ads_sql);
} else {
$ads_sql = "SELECT a.*, wp.title AS post_title, u.username
FROM ads a
JOIN workspace_posts wp ON a.related_id = wp.id
JOIN users u ON a.user_id = u.id
WHERE a.user_id = ?
ORDER BY a.created_at DESC";
$stmt = $conn->prepare($ads_sql);
$stmt->bind_param("i", $user_id);
}
if ($stmt) {
$stmt->execute();
$result = $stmt->get_result();
while ($ad = $result->fetch_assoc()) {
$ads[] = $ad;
}
$stmt->close();
} else {
throw new Exception("Failed to prepare statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Ads - Kaak Alia Management System</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<!-- Header -->
<?php include __DIR__ . '/../../includes/header.php'; ?>
<!-- Main Content -->
<main class="container mx-auto p-6 mt-24 mb-20">
<h1 class="text-3xl font-bold mb-6">Manage Ads</h1>
<!-- Display Errors -->
<?php if (!empty($errors)): ?>
<div class="mb-6">
<?php foreach ($errors as $error): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-2">
<?= htmlspecialchars($error) ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Add New Ad Button -->
<div class="mb-4">
<a href="create_ad.php" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded inline-flex items-center">
<i class="bi bi-plus-lg mr-2"></i> Create New Ad
</a>
</div>
<!-- Ads Table -->
<div class="overflow-x-auto">
<table class="min-w-full bg-white rounded-lg shadow">
<thead>
<tr>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Ad Name</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Type</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Related Post/Story</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Budget ($)</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Spent ($)</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Status</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Actions</th>
</tr>
</thead>
<tbody>
<?php if (empty($ads)): ?>
<tr>
<td colspan="7" class="text-center py-4">No ads found.</td>
</tr>
<?php else: ?>
<?php foreach ($ads as $ad): ?>
<tr class="border-t">
<td class="py-3 px-6"><?= htmlspecialchars($ad['name']) ?></td>
<td class="py-3 px-6"><?= htmlspecialchars($ad['ad_type']) ?></td>
<td class="py-3 px-6"><?= htmlspecialchars($ad['post_title']) ?></td>
<td class="py-3 px-6"><?= number_format($ad['budget'], 2) ?></td>
<td class="py-3 px-6"><?= number_format($ad['total_spent'], 2) ?></td>
<td class="py-3 px-6">
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?=
$ad['status'] === 'Active' ? 'bg-green-100 text-green-800' :
($ad['status'] === 'Paused' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800')
?>">
<?= htmlspecialchars($ad['status']) ?>
</span>
</td>
<td class="py-3 px-6">
<a href="view_ad.php?id=<?= $ad['id'] ?>" class="text-blue-500 hover:text-blue-700 mr-2">
<i class="bi bi-eye"></i>
</a>
<a href="edit_ad.php?id=<?= $ad['id'] ?>" class="text-yellow-500 hover:text-yellow-700 mr-2">
<i class="bi bi-pencil-square"></i>
</a>
<a href="delete_ad.php?id=<?= $ad['id'] ?>" class="text-red-500 hover:text-red-700"
onclick="return confirm('Are you sure you want to delete this ad?');">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</main>
<!-- Footer -->
<footer class="fixed bottom-0 left-0 w-full bg-gray-800 text-white text-center p-4">
© 2024 Kaak Alia Bakery. All rights reserved.
</footer>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
2. ads/create_ad.php - Create a New Ad
This page provides a form for creating a new advertisement by assigning it to an existing post or story.
<?php
// /public/workspace/ads/create_ad.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering
ob_start();
// Include necessary files
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
$errors = [];
$success = "";
// Fetch user's posts/stories to assign to the ad
$related_items = [];
try {
if ($user_role === 'admin') {
$items_sql = "SELECT id, title, platform FROM workspace_posts ORDER BY created_at DESC";
$stmt = $conn->prepare($items_sql);
} else {
$items_sql = "SELECT id, title, platform FROM workspace_posts WHERE user_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $user_id);
}
if ($stmt) {
$stmt->execute();
$result = $stmt->get_result();
while ($item = $result->fetch_assoc()) {
$related_items[] = $item;
}
$stmt->close();
} else {
throw new Exception("Failed to prepare statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize and validate input
$name = sanitize_input($_POST['name'] ?? '');
$ad_type = sanitize_input($_POST['ad_type'] ?? '');
$related_id = intval($_POST['related_id'] ?? 0);
$budget = floatval($_POST['budget'] ?? 0.00);
$start_date = sanitize_input($_POST['start_date'] ?? '');
$end_date = sanitize_input($_POST['end_date'] ?? '');
$status = sanitize_input($_POST['status'] ?? 'Active');
// Validation
if (empty($name)) {
$errors[] = "Ad name is required.";
}
if (!in_array($ad_type, ['Post', 'Story'])) {
$errors[] = "Invalid ad type selected.";
}
if ($related_id <= 0) {
$errors[] = "Please select a valid related post/story.";
}
if ($budget <= 0) {
$errors[] = "Budget must be greater than zero.";
}
if (empty($start_date) || empty($end_date)) {
$errors[] = "Start date and end date are required.";
}
if (strtotime($start_date) > strtotime($end_date)) {
$errors[] = "Start date cannot be later than end date.";
}
// If no errors, insert the ad
if (empty($errors)) {
try {
$insert_sql = "INSERT INTO ads (user_id, name, ad_type, related_id, budget, start_date, end_date, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insert_sql);
if ($stmt) {
$stmt->bind_param("issidsss", $user_id, $name, $ad_type, $related_id, $budget, $start_date, $end_date, $status);
if ($stmt->execute()) {
$success = "Ad created successfully.";
// Reset form fields
$name = $ad_type = $related_id = $budget = $start_date = $end_date = $status = "";
} else {
throw new Exception("Failed to create ad: " . $stmt->error);
}
$stmt->close();
} else {
throw new Exception("Failed to prepare insert statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create New Ad - Kaak Alia Management System</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<!-- Datepicker CSS (optional for better date selection) -->
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<!-- Header -->
<?php include __DIR__ . '/../../includes/header.php'; ?>
<!-- Main Content -->
<main class="container mx-auto p-6 mt-24 mb-20">
<h1 class="text-3xl font-bold mb-6">Create New Ad</h1>
<!-- Display Success Message -->
<?php if (!empty($success)): ?>
<div class="mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
<?= htmlspecialchars($success) ?>
</div>
<?php endif; ?>
<!-- Display Errors -->
<?php if (!empty($errors)): ?>
<div class="mb-6">
<?php foreach ($errors as $error): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-2">
<?= htmlspecialchars($error) ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Ad Creation Form -->
<form method="POST" action="create_ad.php" class="bg-white p-6 rounded-lg shadow-md">
<div class="mb-4">
<label for="name" class="block text-gray-700">Ad Name</label>
<input type="text" id="name" name="name" value="<?= htmlspecialchars($name ?? '') ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="ad_type" class="block text-gray-700">Ad Type</label>
<select id="ad_type" name="ad_type" class="w-full mt-2 p-2 border rounded" required>
<option value="">Select Ad Type</option>
<option value="Post" <?= isset($ad_type) && $ad_type === 'Post' ? 'selected' : '' ?>>Post</option>
<option value="Story" <?= isset($ad_type) && $ad_type === 'Story' ? 'selected' : '' ?>>Story</option>
</select>
</div>
<div class="mb-4">
<label for="related_id" class="block text-gray-700">Select Related Post/Story</label>
<select id="related_id" name="related_id" class="w-full mt-2 p-2 border rounded" required>
<option value="">Select Post/Story</option>
<?php foreach ($related_items as $item): ?>
<option value="<?= $item['id'] ?>" <?= isset($related_id) && $related_id == $item['id'] ? 'selected' : '' ?>>
<?= htmlspecialchars($item['title']) ?> (<?= htmlspecialchars($item['platform']) ?>)
</option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-4">
<label for="budget" class="block text-gray-700">Budget ($)</label>
<input type="number" step="0.01" id="budget" name="budget" value="<?= htmlspecialchars($budget ?? '') ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="start_date" class="block text-gray-700">Start Date</label>
<input type="date" id="start_date" name="start_date" value="<?= htmlspecialchars($start_date ?? '') ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="end_date" class="block text-gray-700">End Date</label>
<input type="date" id="end_date" name="end_date" value="<?= htmlspecialchars($end_date ?? '') ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="status" class="block text-gray-700">Status</label>
<select id="status" name="status" class="w-full mt-2 p-2 border rounded" required>
<option value="Active" <?= isset($status) && $status === 'Active' ? 'selected' : '' ?>>Active</option>
<option value="Paused" <?= isset($status) && $status === 'Paused' ? 'selected' : '' ?>>Paused</option>
<option value="Completed" <?= isset($status) && $status === 'Completed' ? 'selected' : '' ?>>Completed</option>
</select>
</div>
<div class="flex justify-between">
<button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">
<i class="bi bi-save mr-2"></i> Save Ad
</button>
<a href="index.php" class="text-gray-700 hover:text-gray-900"><i class="bi bi-arrow-left mr-2"></i> Back to Ads</a>
</div>
</form>
</main>
<!-- Footer -->
<footer class="fixed bottom-0 left-0 w-full bg-gray-800 text-white text-center p-4">
© 2024 Kaak Alia Bakery. All rights reserved.
</footer>
<!-- Optional: Flatpickr JS for enhanced date selection -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
// Initialize Flatpickr
flatpickr("#start_date", {
dateFormat: "Y-m-d"
});
flatpickr("#end_date", {
dateFormat: "Y-m-d"
});
</script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
3. ads/edit_ad.php - Edit an Existing Ad
This page allows users to modify the details of an existing advertisement.
<?php
// /public/workspace/ads/edit_ad.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering
ob_start();
// Include necessary files
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
$errors = [];
$success = "";
// Get Ad ID from GET parameter
$ad_id = intval($_GET['id'] ?? 0);
if ($ad_id <= 0) {
header("Location: index.php");
exit();
}
// Fetch Ad Details
$ad = null;
$related_items = [];
try {
if ($user_role === 'admin') {
$ad_sql = "SELECT a.* FROM ads a WHERE a.id = ?";
$stmt = $conn->prepare($ad_sql);
$stmt->bind_param("i", $ad_id);
} else {
$ad_sql = "SELECT a.* FROM ads a WHERE a.id = ? AND a.user_id = ?";
$stmt = $conn->prepare($ad_sql);
$stmt->bind_param("ii", $ad_id, $user_id);
}
if ($stmt) {
$stmt->execute();
$result = $stmt->get_result();
$ad = $result->fetch_assoc();
$stmt->close();
if (!$ad) {
header("Location: index.php");
exit();
}
} else {
throw new Exception("Failed to prepare ad fetch statement: " . $conn->error);
}
// Fetch related posts/stories
if ($user_role === 'admin') {
$items_sql = "SELECT id, title, platform FROM workspace_posts ORDER BY created_at DESC";
$stmt = $conn->prepare($items_sql);
} else {
$items_sql = "SELECT id, title, platform FROM workspace_posts WHERE user_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $user_id);
}
if ($stmt) {
$stmt->execute();
$result = $stmt->get_result();
while ($item = $result->fetch_assoc()) {
$related_items[] = $item;
}
$stmt->close();
} else {
throw new Exception("Failed to prepare related items fetch statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize and validate input
$name = sanitize_input($_POST['name'] ?? '');
$ad_type = sanitize_input($_POST['ad_type'] ?? '');
$related_id = intval($_POST['related_id'] ?? 0);
$budget = floatval($_POST['budget'] ?? 0.00);
$start_date = sanitize_input($_POST['start_date'] ?? '');
$end_date = sanitize_input($_POST['end_date'] ?? '');
$status = sanitize_input($_POST['status'] ?? 'Active');
// Validation
if (empty($name)) {
$errors[] = "Ad name is required.";
}
if (!in_array($ad_type, ['Post', 'Story'])) {
$errors[] = "Invalid ad type selected.";
}
if ($related_id <= 0) {
$errors[] = "Please select a valid related post/story.";
}
if ($budget <= 0) {
$errors[] = "Budget must be greater than zero.";
}
if (empty($start_date) || empty($end_date)) {
$errors[] = "Start date and end date are required.";
}
if (strtotime($start_date) > strtotime($end_date)) {
$errors[] = "Start date cannot be later than end date.";
}
// If no errors, update the ad
if (empty($errors)) {
try {
$update_sql = "UPDATE ads SET name = ?, ad_type = ?, related_id = ?, budget = ?, start_date = ?, end_date = ?, status = ?, updated_at = NOW()
WHERE id = ?";
$stmt = $conn->prepare($update_sql);
if ($stmt) {
$stmt->bind_param("ssidsssi", $name, $ad_type, $related_id, $budget, $start_date, $end_date, $status, $ad_id);
if ($stmt->execute()) {
$success = "Ad updated successfully.";
// Refresh ad data
$ad['name'] = $name;
$ad['ad_type'] = $ad_type;
$ad['related_id'] = $related_id;
$ad['budget'] = $budget;
$ad['start_date'] = $start_date;
$ad['end_date'] = $end_date;
$ad['status'] = $status;
} else {
throw new Exception("Failed to update ad: " . $stmt->error);
}
$stmt->close();
} else {
throw new Exception("Failed to prepare update statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Ad - Kaak Alia Management System</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<!-- Datepicker CSS (optional for better date selection) -->
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<!-- Header -->
<?php include __DIR__ . '/../../includes/header.php'; ?>
<!-- Main Content -->
<main class="container mx-auto p-6 mt-24 mb-20">
<h1 class="text-3xl font-bold mb-6">Edit Ad</h1>
<!-- Display Success Message -->
<?php if (!empty($success)): ?>
<div class="mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
<?= htmlspecialchars($success) ?>
</div>
<?php endif; ?>
<!-- Display Errors -->
<?php if (!empty($errors)): ?>
<div class="mb-6">
<?php foreach ($errors as $error): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-2">
<?= htmlspecialchars($error) ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Ad Edit Form -->
<?php if ($ad): ?>
<form method="POST" action="edit_ad.php?id=<?= $ad_id ?>" class="bg-white p-6 rounded-lg shadow-md">
<div class="mb-4">
<label for="name" class="block text-gray-700">Ad Name</label>
<input type="text" id="name" name="name" value="<?= htmlspecialchars($ad['name']) ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="ad_type" class="block text-gray-700">Ad Type</label>
<select id="ad_type" name="ad_type" class="w-full mt-2 p-2 border rounded" required>
<option value="Post" <?= $ad['ad_type'] === 'Post' ? 'selected' : '' ?>>Post</option>
<option value="Story" <?= $ad['ad_type'] === 'Story' ? 'selected' : '' ?>>Story</option>
</select>
</div>
<div class="mb-4">
<label for="related_id" class="block text-gray-700">Select Related Post/Story</label>
<select id="related_id" name="related_id" class="w-full mt-2 p-2 border rounded" required>
<?php foreach ($related_items as $item): ?>
<option value="<?= $item['id'] ?>" <?= $ad['related_id'] == $item['id'] ? 'selected' : '' ?>>
<?= htmlspecialchars($item['title']) ?> (<?= htmlspecialchars($item['platform']) ?>)
</option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-4">
<label for="budget" class="block text-gray-700">Budget ($)</label>
<input type="number" step="0.01" id="budget" name="budget" value="<?= htmlspecialchars($ad['budget']) ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="start_date" class="block text-gray-700">Start Date</label>
<input type="date" id="start_date" name="start_date" value="<?= htmlspecialchars($ad['start_date']) ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="end_date" class="block text-gray-700">End Date</label>
<input type="date" id="end_date" name="end_date" value="<?= htmlspecialchars($ad['end_date']) ?>"
class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="mb-4">
<label for="status" class="block text-gray-700">Status</label>
<select id="status" name="status" class="w-full mt-2 p-2 border rounded" required>
<option value="Active" <?= $ad['status'] === 'Active' ? 'selected' : '' ?>>Active</option>
<option value="Paused" <?= $ad['status'] === 'Paused' ? 'selected' : '' ?>>Paused</option>
<option value="Completed" <?= $ad['status'] === 'Completed' ? 'selected' : '' ?>>Completed</option>
</select>
</div>
<div class="flex justify-between">
<button type="submit" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">
<i class="bi bi-save mr-2"></i> Update Ad
</button>
<a href="index.php" class="text-gray-700 hover:text-gray-900"><i class="bi bi-arrow-left mr-2"></i> Back to Ads</a>
</div>
</form>
<?php endif; ?>
</main>
<!-- Footer -->
<footer class="fixed bottom-0 left-0 w-full bg-gray-800 text-white text-center p-4">
© 2024 Kaak Alia Bakery. All rights reserved.
</footer>
<!-- Optional: Flatpickr JS for enhanced date selection -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
// Initialize Flatpickr
flatpickr("#start_date", {
dateFormat: "Y-m-d"
});
flatpickr("#end_date", {
dateFormat: "Y-m-d"
});
</script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
4. ads/delete_ad.php - Delete an Ad
This script handles the deletion of an advertisement after user confirmation.
<?php
// /public/workspace/ads/delete_ad.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering
ob_start();
// Include necessary files
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
// Get Ad ID from GET parameter
$ad_id = intval($_GET['id'] ?? 0);
if ($ad_id <= 0) {
header("Location: index.php");
exit();
}
$errors = [];
// Delete the Ad
try {
if ($user_role === 'admin') {
$delete_sql = "DELETE FROM ads WHERE id = ?";
$stmt = $conn->prepare($delete_sql);
$stmt->bind_param("i", $ad_id);
} else {
$delete_sql = "DELETE FROM ads WHERE id = ? AND user_id = ?";
$stmt = $conn->prepare($delete_sql);
$stmt->bind_param("ii", $ad_id, $user_id);
}
if ($stmt) {
if ($stmt->execute()) {
// Redirect back with success message
header("Location: index.php?message=Ad+deleted+successfully.");
exit();
} else {
throw new Exception("Failed to delete ad: " . $stmt->error);
}
$stmt->close();
} else {
throw new Exception("Failed to prepare delete statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
// Redirect back with error message
header("Location: index.php?error=" . urlencode($e->getMessage()));
exit();
}
?>
5. ads/view_ad.php - View Ad Details
This page displays detailed information about a specific advertisement, including spending logs.
<?php
// /public/workspace/ads/view_ad.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering
ob_start();
// Include necessary files
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Contains sanitize_input()
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
$ad = null;
$spend_logs = [];
$errors = [];
// Get Ad ID from GET parameter
$ad_id = intval($_GET['id'] ?? 0);
if ($ad_id <= 0) {
header("Location: index.php");
exit();
}
// Fetch Ad Details and Spend Logs
try {
// Fetch Ad Details
if ($user_role === 'admin') {
$ad_sql = "SELECT a.*, wp.title AS post_title, u.username
FROM ads a
JOIN workspace_posts wp ON a.related_id = wp.id
JOIN users u ON a.user_id = u.id
WHERE a.id = ?";
$stmt = $conn->prepare($ad_sql);
$stmt->bind_param("i", $ad_id);
} else {
$ad_sql = "SELECT a.*, wp.title AS post_title, u.username
FROM ads a
JOIN workspace_posts wp ON a.related_id = wp.id
JOIN users u ON a.user_id = u.id
WHERE a.id = ? AND a.user_id = ?";
$stmt = $conn->prepare($ad_sql);
$stmt->bind_param("ii", $ad_id, $user_id);
}
if ($stmt) {
$stmt->execute();
$result = $stmt->get_result();
$ad = $result->fetch_assoc();
$stmt->close();
if (!$ad) {
header("Location: index.php");
exit();
}
} else {
throw new Exception("Failed to prepare ad fetch statement: " . $conn->error);
}
// Fetch Spend Logs
$spend_sql = "SELECT * FROM ad_spend_logs WHERE ad_id = ? ORDER BY spend_date DESC";
$stmt = $conn->prepare($spend_sql);
if ($stmt) {
$stmt->bind_param("i", $ad_id);
$stmt->execute();
$result = $stmt->get_result();
while ($log = $result->fetch_assoc()) {
$spend_logs[] = $log;
}
$stmt->close();
} else {
throw new Exception("Failed to prepare spend logs fetch statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
// Handle Add Spend Log Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_spend'])) {
$amount = floatval($_POST['amount'] ?? 0.00);
$description = sanitize_input($_POST['description'] ?? '');
if ($amount <= 0) {
$errors[] = "Amount must be greater than zero.";
}
if (empty($description)) {
$errors[] = "Description is required.";
}
if (empty($errors)) {
try {
$insert_spend_sql = "INSERT INTO ad_spend_logs (ad_id, amount, description) VALUES (?, ?, ?)";
$stmt = $conn->prepare($insert_spend_sql);
if ($stmt) {
$stmt->bind_param("ids", $ad_id, $amount, $description);
if ($stmt->execute()) {
// Update total_spent in ads table
$update_ad_sql = "UPDATE ads SET total_spent = total_spent + ? WHERE id = ?";
$update_stmt = $conn->prepare($update_ad_sql);
if ($update_stmt) {
$update_stmt->bind_param("di", $amount, $ad_id);
$update_stmt->execute();
$update_stmt->close();
}
// Redirect to refresh data
header("Location: view_ad.php?id=$ad_id");
exit();
} else {
throw new Exception("Failed to add spend log: " . $stmt->error);
}
$stmt->close();
} else {
throw new Exception("Failed to prepare spend log insert statement: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Ad - Kaak Alia Management System</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<!-- Chart.js for visualizing spending (optional) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-100">
<!-- Header -->
<?php include __DIR__ . '/../../includes/header.php'; ?>
<!-- Main Content -->
<main class="container mx-auto p-6 mt-24 mb-20">
<h1 class="text-3xl font-bold mb-6">Ad Details</h1>
<!-- Back Button -->
<div class="mb-4">
<a href="index.php" class="text-gray-700 hover:text-gray-900"><i class="bi bi-arrow-left mr-2"></i> Back to Ads</a>
</div>
<!-- Display Errors -->
<?php if (!empty($errors)): ?>
<div class="mb-6">
<?php foreach ($errors as $error): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-2">
<?= htmlspecialchars($error) ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Ad Information -->
<?php if ($ad): ?>
<div class="bg-white p-6 rounded-lg shadow-md mb-6">
<h2 class="text-2xl font-semibold mb-4"><?= htmlspecialchars($ad['name']) ?></h2>
<p><strong>Type:</strong> <?= htmlspecialchars($ad['ad_type']) ?></p>
<p><strong>Related Post/Story:</strong> <?= htmlspecialchars($ad['post_title']) ?> (<?= htmlspecialchars($ad['platform']) ?>)</p>
<p><strong>Budget:</strong> $<?= number_format($ad['budget'], 2) ?></p>
<p><strong>Total Spent:</strong> $<?= number_format($ad['total_spent'], 2) ?></p>
<p><strong>Start Date:</strong> <?= htmlspecialchars(date("d M Y", strtotime($ad['start_date']))) ?></p>
<p><strong>End Date:</strong> <?= htmlspecialchars(date("d M Y", strtotime($ad['end_date']))) ?></p>
<p><strong>Status:</strong> <?= htmlspecialchars($ad['status']) ?></p>
<p><strong>Created By:</strong> <?= htmlspecialchars($ad['username']) ?></p>
<p><strong>Created At:</strong> <?= htmlspecialchars(date("d M Y, h:i A", strtotime($ad['created_at']))) ?></p>
</div>
<!-- Spending Visualization (Optional) -->
<div class="bg-white p-6 rounded-lg shadow-md mb-6">
<h3 class="text-xl font-semibold mb-4">Spending Overview</h3>
<canvas id="spendingChart" width="400" height="200"></canvas>
</div>
<!-- Add Spend Log Form -->
<div class="bg-white p-6 rounded-lg shadow-md mb-6">
<h3 class="text-xl font-semibold mb-4">Add Spend Log</h3>
<form method="POST" action="view_ad.php?id=<?= $ad_id ?>" class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label for="amount" class="block text-gray-700">Amount ($)</label>
<input type="number" step="0.01" id="amount" name="amount" class="w-full mt-2 p-2 border rounded" required>
</div>
<div>
<label for="description" class="block text-gray-700">Description</label>
<input type="text" id="description" name="description" class="w-full mt-2 p-2 border rounded" required>
</div>
<div class="md:col-span-2 flex justify-end">
<button type="submit" name="add_spend" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">
<i class="bi bi-plus-lg mr-2"></i> Add Spend
</button>
</div>
</form>
</div>
<!-- Spend Logs Table -->
<div class="bg-white p-6 rounded-lg shadow-md mb-6">
<h3 class="text-xl font-semibold mb-4">Spending Logs</h3>
<div class="overflow-x-auto">
<table class="min-w-full bg-white rounded-lg shadow">
<thead>
<tr>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Amount ($)</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Description</th>
<th class="py-3 px-6 bg-gray-200 font-semibold text-left">Date</th>
</tr>
</thead>
<tbody>
<?php if (empty($spend_logs)): ?>
<tr>
<td colspan="3" class="text-center py-4">No spend logs found.</td>
</tr>
<?php else: ?>
<?php foreach ($spend_logs as $log): ?>
<tr class="border-t">
<td class="py-3 px-6"><?= number_format($log['amount'], 2) ?></td>
<td class="py-3 px-6"><?= htmlspecialchars($log['description']) ?></td>
<td class="py-3 px-6"><?= htmlspecialchars(date("d M Y, h:i A", strtotime($log['spend_date']))) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<!-- Chart.js Script -->
<script>
const ctx = document.getElementById('spendingChart').getContext('2d');
const spendData = {
labels: <?= json_encode(array_map(function($log) {
return date("d M", strtotime($log['spend_date']));
}, $spend_logs)) ?>,
datasets: [{
label: 'Amount Spent ($)',
data: <?= json_encode(array_map(function($log) {
return floatval($log['amount']);
}, $spend_logs)) ?>,
backgroundColor: 'rgba(59, 130, 246, 0.6)', // Tailwind blue-500
borderColor: 'rgba(59, 130, 246, 1)',
borderWidth: 1
}]
};
const spendingChart = new Chart(ctx, {
type: 'bar',
data: spendData,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
<?php endif; ?>
</main>
<!-- Footer -->
<footer class="fixed bottom-0 left-0 w-full bg-gray-800 text-white text-center p-4">
© 2024 Kaak Alia Bakery. All rights reserved.
</footer>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
6. ads/delete_ad.php - Delete an Ad
Note: This file was covered in the previous section as ads/delete_ad.php. Ensure it's placed correctly in the ads folder.
Integrating Ads with Posts and Stories
To assign posts and stories to ads, the ads/create_ad.php and ads/edit_ad.php forms include a dropdown that lists existing posts or stories from the workspace_posts table. By selecting a post or story, the ad is linked via the related_id field in the ads table.
Assigning Stories:
If "stories" are treated as different types of posts, ensure that the workspace_posts table includes a distinguishing field (e.g., type or platform) to filter stories if necessary.
Example:
-- Adding a 'type' field to differentiate between posts and stories
ALTER TABLE `workspace_posts` ADD COLUMN `type` ENUM('Post', 'Story') DEFAULT 'Post';
Then, adjust the create_ad.php and edit_ad.php to filter or display based on the type field if required.
Frontend Enhancements
To ensure a cool and user-friendly interface, we utilize Tailwind CSS for styling and Bootstrap Icons for visual cues. Additional enhancements include:
1. Responsive Design
Tailwind's utility-first classes make it easy to create responsive layouts. Ensure all components are mobile-friendly by utilizing classes like md:grid-cols-3 and overflow-x-auto.
2. Visual Indicators
Use color-coded status badges to indicate the status of ads (Active, Paused, Completed):
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
Active
</span>
3. Charts for Spending Overview
Integrate Chart.js to visualize ad spending, providing users with a quick overview of their budget usage.
<canvas id="spendingChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('spendingChart').getContext('2d');
// Chart configuration...
</script>
4. Interactive Elements
In ads/index.php, icons within action buttons (view, edit, delete) provide intuitive interactions.
<a href="view_ad.php?id=<?= $ad['id'] ?>" class="text-blue-500 hover:text-blue-700 mr-2">
<i class="bi bi-eye"></i>
</a>
Spending and Budget Tracking
1. Ad Budget
Each ad has a defined budget (budget field in ads table). The system tracks the total amount spent (total_spent) by adding entries to the ad_spend_logs table.
2. Adding Spend Logs
Users can add spend logs via the view_ad.php page. Each log increases the total_spent for the corresponding ad.
3. Visualization
Using Chart.js, display a bar chart showing daily or weekly spending, helping users monitor their budgets effectively.
4. Alerts (Optional)
Implement alerts or warnings when the total_spent approaches or exceeds the budget. This can be achieved by comparing these two values and displaying appropriate messages or changing the status of the ad automatically.
Example:
if ($ad['total_spent'] >= $ad['budget']) {
// Optionally update ad status to 'Completed' or alert the user
}
Final Integration with Existing Dashboard
Ensure that the Ads module integrates seamlessly with your existing workspace dashboard (/public/workspace/index.php). You can add quick links or summary cards similar to other sections like Plans, Posts, and Notes.
Example: Adding Ads Summary Card
<!-- Summary Cards -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
<!-- Existing Cards -->
<!-- ... -->
<!-- Ads Summary Card -->
<div class="flex items-center p-4 bg-red-500 text-white rounded-lg shadow hover:bg-red-600 transition">
<i class="bi bi-megaphone text-4xl mr-4"></i>
<div>
<h2 class="text-xl font-semibold">Total Ads</h2>
<p class="text-2xl"><?= htmlspecialchars(number_format($ads_count)) ?></p>
</div>
</div>
</div>
<!-- Quick Links -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
<!-- Existing Links -->
<!-- ... -->
<!-- Ads Quick Link -->
<a href="ads/index.php" class="block p-6 bg-red-400 text-white rounded-lg shadow hover:bg-red-500 transition">
<i class="bi bi-megaphone text-3xl"></i>
<h2 class="mt-2 text-xl font-semibold">Manage Ads</h2>
</a>
</div>
Updating workspace/index.php
Modify your existing index.php to include counts for ads and quick links.
<?php
// ... [Existing code above]
// Fetch total ads count
try {
if ($user_role === 'admin') {
$ads_count_sql = "SELECT COUNT(*) AS total FROM ads";
} else {
$ads_count_sql = "SELECT COUNT(*) AS total FROM ads WHERE user_id = ?";
}
if ($stmt = $conn->prepare($ads_count_sql)) {
if ($user_role !== 'admin') {
$stmt->bind_param("i", $user_id);
}
$stmt->execute();
$result = $stmt->get_result();
$ads_count = $result->fetch_assoc()['total'] ?? 0;
$stmt->close();
} else {
throw new Exception("Prepare statement failed for ads count: " . $conn->error);
}
} catch (Exception $e) {
$errors[] = $e->getMessage();
$ads_count = 0; // Default value in case of error
}
?>
Then, incorporate the summary card and quick link as shown above.
Conclusion
By following the above steps, you've successfully integrated a comprehensive Ads module into your existing workspace management system. This module allows users to create, manage, and track advertisements on posts and stories, ensuring effective budget management and enhanced visibility of promotional activities.
Key Features Implemented:
- Database Integration: New tables to manage ads and their spend logs.
- User Interface: Intuitive and responsive forms for creating and editing ads.
- Spending Tracking: Detailed logs and visualization for budget management.
- Integration with Existing System: Seamless addition of ads to the existing dashboard with summary cards and quick links.
Future Enhancements:
- Automated Status Updates: Automatically change ad status based on spending or date.
- Payment Integration: Integrate payment gateways for real monetary transactions.
- Advanced Analytics: Provide more detailed insights into ad performance.
- Role-Based Access Control: Enhance permissions based on user roles for ad management.
Feel free to customize and expand this module further to suit your specific needs and elevate the functionality of your Kaak Alia Management System.