| Current Path : /home/users/unlimited/www/nigeria.codeskitter.site/admin/ |
| Current File : /home/users/unlimited/www/nigeria.codeskitter.site/admin/courses.php |
<?php
include '../includes/config.php';
// Check if user is admin
if(!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
header("Location: login.php");
exit();
}
// Handle form submissions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['add_course'])) {
$title = $_POST['title'];
$description = $_POST['description'];
$category_id = $_POST['category_id'];
$instructor_id = $_POST['instructor_id'];
$old_price = $_POST['old_price'];
$current_price = $_POST['current_price'];
$content = $_POST['content'];
$is_popular = isset($_POST['is_popular']) ? 1 : 0;
// Enhanced image upload handling
$image = '';
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
$target_dir = "../assets/images/courses/";
// Create directory if it doesn't exist
if (!file_exists($target_dir)) {
mkdir($target_dir, 0777, true);
}
$original_name = $_FILES["image"]["name"];
$file_size = $_FILES["image"]["size"];
$file_tmp = $_FILES["image"]["tmp_name"];
$file_type = $_FILES["image"]["type"];
// Get file extension
$file_ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
// Allowed file types
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg');
// Validate file type
if (in_array($file_ext, $allowed_extensions)) {
// Validate file size (10MB max)
if ($file_size <= 10485760) {
// Generate unique filename to prevent conflicts
$image = uniqid('course_', true) . '.' . $file_ext;
$target_file = $target_dir . $image;
// Move uploaded file
if (move_uploaded_file($file_tmp, $target_file)) {
// Success - image uploaded
$_SESSION['success'] = "Course added successfully with image!";
} else {
$image = '';
$_SESSION['error'] = "Error uploading image file.";
}
} else {
$_SESSION['error'] = "File size too large. Maximum size is 10MB.";
}
} else {
$_SESSION['error'] = "Invalid file type. Allowed: JPG, JPEG, PNG, GIF, WEBP, SVG";
}
} else {
// No image uploaded or upload error
if ($_FILES['image']['error'] != 4) { // Error 4 means no file uploaded
$upload_errors = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.'
);
$_SESSION['error'] = "Upload error: " . ($upload_errors[$_FILES['image']['error']] ?? 'Unknown error');
}
}
// Insert course into database
$sql = "INSERT INTO courses (title, description, category_id, instructor_id, old_price, current_price, image, content, is_popular)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssiiddssi", $title, $description, $category_id, $instructor_id, $old_price, $current_price, $image, $content, $is_popular);
if($stmt->execute()) {
if (!isset($_SESSION['error'])) {
$_SESSION['success'] = "Course added successfully!";
}
header("Location: courses.php");
exit();
} else {
$_SESSION['error'] = "Error adding course to database!";
}
}
// Handle update course
if(isset($_POST['update_course'])) {
$course_id = $_POST['course_id'];
$title = $_POST['title'];
$description = $_POST['description'];
$category_id = $_POST['category_id'];
$instructor_id = $_POST['instructor_id'];
$old_price = $_POST['old_price'];
$current_price = $_POST['current_price'];
$content = $_POST['content'];
$is_popular = isset($_POST['is_popular']) ? 1 : 0;
// Handle image upload if new image is provided
$image_update = '';
if(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
$target_dir = "../assets/images/courses/";
// Create directory if it doesn't exist
if (!file_exists($target_dir)) {
mkdir($target_dir, 0777, true);
}
$original_name = $_FILES["image"]["name"];
$file_size = $_FILES["image"]["size"];
$file_tmp = $_FILES["image"]["tmp_name"];
$file_type = $_FILES["image"]["type"];
// Get file extension
$file_ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
// Allowed file types
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg');
// Validate file type
if (in_array($file_ext, $allowed_extensions)) {
// Validate file size (10MB max)
if ($file_size <= 10485760) {
// Generate unique filename to prevent conflicts
$new_image = uniqid('course_', true) . '.' . $file_ext;
$target_file = $target_dir . $new_image;
// Move uploaded file
if (move_uploaded_file($file_tmp, $target_file)) {
// Delete old image if exists
$old_image_sql = "SELECT image FROM courses WHERE id = ?";
$old_stmt = $conn->prepare($old_image_sql);
$old_stmt->bind_param("i", $course_id);
$old_stmt->execute();
$old_course = $old_stmt->get_result()->fetch_assoc();
if ($old_course['image'] && file_exists("../assets/images/courses/" . $old_course['image'])) {
unlink("../assets/images/courses/" . $old_course['image']);
}
$image_update = ", image = ?";
} else {
$_SESSION['error'] = "Error uploading image file.";
}
} else {
$_SESSION['error'] = "File size too large. Maximum size is 10MB.";
}
} else {
$_SESSION['error'] = "Invalid file type. Allowed: JPG, JPEG, PNG, GIF, WEBP, SVG";
}
}
// Update course in database
if ($image_update) {
$sql = "UPDATE courses SET title = ?, description = ?, category_id = ?, instructor_id = ?,
old_price = ?, current_price = ?, content = ?, is_popular = ?, image = ?
WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssiiddsssi", $title, $description, $category_id, $instructor_id,
$old_price, $current_price, $content, $is_popular, $new_image, $course_id);
} else {
$sql = "UPDATE courses SET title = ?, description = ?, category_id = ?, instructor_id = ?,
old_price = ?, current_price = ?, content = ?, is_popular = ?
WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssiiddssi", $title, $description, $category_id, $instructor_id,
$old_price, $current_price, $content, $is_popular, $course_id);
}
if($stmt->execute()) {
$_SESSION['success'] = "Course updated successfully!";
header("Location: courses.php");
exit();
} else {
$_SESSION['error'] = "Error updating course!";
}
}
if(isset($_POST['delete_course'])) {
$course_id = $_POST['course_id'];
// Get course image to delete it from server
$course_sql = "SELECT image FROM courses WHERE id = ?";
$stmt = $conn->prepare($course_sql);
$stmt->bind_param("i", $course_id);
$stmt->execute();
$course = $stmt->get_result()->fetch_assoc();
// Delete image file if exists
if ($course['image'] && file_exists("../assets/images/courses/" . $course['image'])) {
unlink("../assets/images/courses/" . $course['image']);
}
$sql = "DELETE FROM courses WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $course_id);
if($stmt->execute()) {
$_SESSION['success'] = "Course deleted successfully!";
} else {
$_SESSION['error'] = "Error deleting course!";
}
header("Location: courses.php");
exit();
}
}
// Get categories and instructors for dropdowns
$categories = $conn->query("SELECT * FROM categories");
$instructors = $conn->query("SELECT * FROM instructors");
$courses = $conn->query("SELECT c.*, cat.name as category_name, i.name as instructor_name
FROM courses c
LEFT JOIN categories cat ON c.category_id = cat.id
LEFT JOIN instructors i ON c.instructor_id = i.id");
// Get course data for editing if course_id is provided
$edit_course = null;
if(isset($_GET['edit_id'])) {
$edit_id = $_GET['edit_id'];
$edit_sql = "SELECT * FROM courses WHERE id = ?";
$edit_stmt = $conn->prepare($edit_sql);
$edit_stmt->bind_param("i", $edit_id);
$edit_stmt->execute();
$edit_course = $edit_stmt->get_result()->fetch_assoc();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Courses - Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
<style>
.image-preview {
max-width: 200px;
max-height: 150px;
border: 2px dashed #ddd;
border-radius: 5px;
padding: 5px;
margin-top: 10px;
}
.image-preview img {
max-width: 100%;
max-height: 140px;
object-fit: contain;
}
.file-info {
font-size: 0.875rem;
color: #6c757d;
margin-top: 5px;
}
.upload-area {
border: 2px dashed #dee2e6;
border-radius: 5px;
padding: 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
background: #f8f9fa;
}
.upload-area:hover {
border-color: #0d6efd;
background: #e9ecef;
}
.upload-area.dragover {
border-color: #0d6efd;
background: #e7f1ff;
}
.word-picker {
max-height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
margin-top: 5px;
background: white;
display: none;
}
.word-item {
padding: 5px 10px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.word-item:hover {
background-color: #f8f9fa;
}
.word-item:last-child {
border-bottom: none;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<?php include 'sidebar.php'; ?>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Manage Courses</h1>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCourseModal">
<i class="bi bi-plus-circle"></i> Add New Course
</button>
</div>
<!-- Success/Error Messages -->
<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if(isset($_SESSION['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<!-- Courses Table -->
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Category</th>
<th>Instructor</th>
<th>Price</th>
<th>Popular</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php while($course = $courses->fetch_assoc()):
// Fix image display path
$image_path = '';
if (!empty($course['image'])) {
if (strpos($course['image'], 'http') === 0 || strpos($course['image'], '/') === 0) {
$image_path = $course['image'];
} else {
$image_path = '../assets/images/courses/' . $course['image'];
}
} else {
$image_path = '../assets/images/course-placeholder.jpg';
}
?>
<tr>
<td><?php echo $course['id']; ?></td>
<td>
<img src="<?php echo $image_path; ?>"
alt="<?php echo htmlspecialchars($course['title']); ?>"
style="width: 50px; height: 30px; object-fit: cover;"
onerror="this.src='../assets/images/course-placeholder.jpg'">
</td>
<td><?php echo htmlspecialchars($course['title']); ?></td>
<td><?php echo htmlspecialchars($course['category_name']); ?></td>
<td><?php echo htmlspecialchars($course['instructor_name']); ?></td>
<td>
<?php if($course['old_price'] > 0): ?>
<span class="text-decoration-line-through text-muted">$<?php echo number_format($course['old_price'], 2); ?></span>
<?php endif; ?>
<span class="fw-bold">$<?php echo number_format($course['current_price'], 2); ?></span>
</td>
<td>
<?php if($course['is_popular']): ?>
<span class="badge bg-success">Yes</span>
<?php else: ?>
<span class="badge bg-secondary">No</span>
<?php endif; ?>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-primary edit-btn"
data-course-id="<?php echo $course['id']; ?>"
data-bs-toggle="modal" data-bs-target="#editCourseModal">
<i class="bi bi-pencil"></i> Edit
</button>
<form method="POST" class="d-inline">
<input type="hidden" name="course_id" value="<?php echo $course['id']; ?>">
<button type="submit" name="delete_course" class="btn btn-sm btn-outline-danger"
onclick="return confirm('Are you sure you want to delete this course?')">
<i class="bi bi-trash"></i> Delete
</button>
</form>
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
</div>
</main>
</div>
</div>
<!-- Add Course Modal -->
<div class="modal fade" id="addCourseModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Course</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<form method="POST" enctype="multipart/form-data" id="courseForm">
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Course Title *</label>
<input type="text" class="form-control" name="title" required>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Course Image</label>
<!-- Enhanced File Upload -->
<div class="upload-area" onclick="document.getElementById('imageInput').click()">
<i class="bi bi-cloud-upload fs-1 text-muted"></i>
<p class="mb-1">Click to upload or drag and drop</p>
<small class="text-muted">PNG, JPG, GIF, WEBP, SVG (Max 10MB)</small>
</div>
<input type="file" class="form-control d-none" id="imageInput" name="image" accept="image/*">
<!-- File Info Display -->
<div class="file-info" id="fileInfo"></div>
<!-- Image Preview -->
<div class="image-preview mt-2" id="imagePreview"></div>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Description *</label>
<textarea class="form-control" name="description" rows="3" required></textarea>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Category *</label>
<select class="form-select" name="category_id" required>
<option value="">Select Category</option>
<?php
$categories->data_seek(0); // Reset pointer
while($category = $categories->fetch_assoc()): ?>
<option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
<?php endwhile; ?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Instructor *</label>
<select class="form-select" name="instructor_id" required>
<option value="">Select Instructor</option>
<?php
$instructors->data_seek(0); // Reset pointer
while($instructor = $instructors->fetch_assoc()): ?>
<option value="<?php echo $instructor['id']; ?>"><?php echo htmlspecialchars($instructor['name']); ?></option>
<?php endwhile; ?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Old Price</label>
<input type="number" class="form-control" name="old_price" step="0.01" min="0" placeholder="0.00">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Current Price *</label>
<input type="number" class="form-control" name="current_price" step="0.01" min="0" required placeholder="0.00">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Course Content *</label>
<textarea class="form-control word-picker-target" name="content" rows="6" required placeholder="Enter course content, modules, or learning objectives..."></textarea>
<div class="word-picker" id="wordPicker"></div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" name="is_popular" id="is_popular">
<label class="form-check-label" for="is_popular">
Mark as Popular Course
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" name="add_course" class="btn btn-primary">Add Course</button>
</div>
</form>
</div>
</div>
</div>
<!-- Edit Course Modal -->
<div class="modal fade" id="editCourseModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Course</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<form method="POST" enctype="multipart/form-data" id="editCourseForm">
<input type="hidden" name="course_id" id="edit_course_id">
<input type="hidden" name="update_course" value="1">
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Course Title *</label>
<input type="text" class="form-control" name="title" id="edit_title" required>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Course Image</label>
<!-- Current Image -->
<div id="currentImageContainer" class="mb-2">
<small class="text-muted">Current Image:</small>
<img id="currentImage" src="" class="image-preview" style="display: none;">
</div>
<!-- Enhanced File Upload -->
<div class="upload-area" onclick="document.getElementById('edit_imageInput').click()">
<i class="bi bi-cloud-upload fs-1 text-muted"></i>
<p class="mb-1">Click to upload or drag and drop</p>
<small class="text-muted">PNG, JPG, GIF, WEBP, SVG (Max 10MB)</small>
</div>
<input type="file" class="form-control d-none" id="edit_imageInput" name="image" accept="image/*">
<!-- File Info Display -->
<div class="file-info" id="edit_fileInfo"></div>
<!-- Image Preview -->
<div class="image-preview mt-2" id="edit_imagePreview"></div>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Description *</label>
<textarea class="form-control" name="description" id="edit_description" rows="3" required></textarea>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Category *</label>
<select class="form-select" name="category_id" id="edit_category_id" required>
<option value="">Select Category</option>
<?php
$categories->data_seek(0); // Reset pointer
while($category = $categories->fetch_assoc()): ?>
<option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
<?php endwhile; ?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Instructor *</label>
<select class="form-select" name="instructor_id" id="edit_instructor_id" required>
<option value="">Select Instructor</option>
<?php
$instructors->data_seek(0); // Reset pointer
while($instructor = $instructors->fetch_assoc()): ?>
<option value="<?php echo $instructor['id']; ?>"><?php echo htmlspecialchars($instructor['name']); ?></option>
<?php endwhile; ?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Old Price</label>
<input type="number" class="form-control" name="old_price" id="edit_old_price" step="0.01" min="0" placeholder="0.00">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Current Price *</label>
<input type="number" class="form-control" name="current_price" id="edit_current_price" step="0.01" min="0" required placeholder="0.00">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Course Content *</label>
<textarea class="form-control word-picker-target" name="content" id="edit_content" rows="6" required placeholder="Enter course content, modules, or learning objectives..."></textarea>
<div class="word-picker" id="edit_wordPicker"></div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" name="is_popular" id="edit_is_popular">
<label class="form-check-label" for="edit_is_popular">
Mark as Popular Course
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update Course</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Common words for word picker
const commonWords = [
"Introduction", "Overview", "Fundamentals", "Advanced", "Basic",
"Getting Started", "Conclusion", "Summary", "Practice", "Exercise",
"Project", "Assignment", "Quiz", "Test", "Assessment",
"Module", "Lesson", "Chapter", "Section", "Part",
"Video", "Tutorial", "Guide", "Walkthrough", "Demonstration",
"Hands-on", "Practical", "Theoretical", "Conceptual", "Technical",
"Beginner", "Intermediate", "Expert", "Professional", "Master",
"Skills", "Knowledge", "Understanding", "Application", "Analysis",
"Development", "Implementation", "Deployment", "Maintenance", "Support"
];
// Initialize word picker for all textareas with class 'word-picker-target'
function initializeWordPicker(textarea, picker) {
textarea.addEventListener('input', function(e) {
const value = e.target.value;
const lastWord = value.split(/\s+/).pop().toLowerCase();
if (lastWord.length > 1) {
const matches = commonWords.filter(word =>
word.toLowerCase().startsWith(lastWord)
);
if (matches.length > 0) {
picker.innerHTML = matches.map(word =>
`<div class="word-item" onclick="insertWord('${textarea.id}', '${word}')">${word}</div>`
).join('');
picker.style.display = 'block';
} else {
picker.style.display = 'none';
}
} else {
picker.style.display = 'none';
}
});
// Hide picker when clicking outside
document.addEventListener('click', function(e) {
if (!picker.contains(e.target) && e.target !== textarea) {
picker.style.display = 'none';
}
});
}
// Global function to insert word
window.insertWord = function(textareaId, word) {
const textarea = document.getElementById(textareaId);
const picker = document.getElementById(textareaId === 'content' ? 'wordPicker' : 'edit_wordPicker');
const words = textarea.value.split(/\s+/);
words.pop(); // Remove the partially typed word
words.push(word);
textarea.value = words.join(' ') + ' ';
picker.style.display = 'none';
textarea.focus();
};
// Initialize word pickers
const contentTextarea = document.querySelector('textarea[name="content"]');
const wordPicker = document.getElementById('wordPicker');
if (contentTextarea && wordPicker) {
initializeWordPicker(contentTextarea, wordPicker);
}
const editContentTextarea = document.getElementById('edit_content');
const editWordPicker = document.getElementById('edit_wordPicker');
if (editContentTextarea && editWordPicker) {
initializeWordPicker(editContentTextarea, editWordPicker);
}
// File upload functionality for add modal
const imageInput = document.getElementById('imageInput');
const imagePreview = document.getElementById('imagePreview');
const fileInfo = document.getElementById('fileInfo');
const uploadArea = document.querySelector('.upload-area');
// File upload functionality for edit modal
const editImageInput = document.getElementById('edit_imageInput');
const editImagePreview = document.getElementById('edit_imagePreview');
const editFileInfo = document.getElementById('edit_fileInfo');
const editUploadArea = document.querySelectorAll('.upload-area')[1];
// Initialize file upload for both modals
initializeFileUpload(imageInput, imagePreview, fileInfo, uploadArea);
initializeFileUpload(editImageInput, editImagePreview, editFileInfo, editUploadArea);
function initializeFileUpload(input, preview, info, area) {
// Click to upload
area.addEventListener('click', function() {
input.click();
});
// Drag and drop functionality
area.addEventListener('dragover', function(e) {
e.preventDefault();
area.classList.add('dragover');
});
area.addEventListener('dragleave', function() {
area.classList.remove('dragover');
});
area.addEventListener('drop', function(e) {
e.preventDefault();
area.classList.remove('dragover');
if (e.dataTransfer.files.length) {
input.files = e.dataTransfer.files;
handleFileSelect(input.files[0], preview, info);
}
});
// File input change
input.addEventListener('change', function(e) {
if (this.files && this.files[0]) {
handleFileSelect(this.files[0], preview, info);
}
});
function handleFileSelect(file, previewElement, infoElement) {
// Validate file type
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
if (!allowedTypes.includes(file.type)) {
alert('Please select a valid image file (JPEG, PNG, GIF, WEBP, SVG)');
input.value = '';
return;
}
// Validate file size (10MB)
if (file.size > 10485760) {
alert('File size must be less than 10MB');
input.value = '';
return;
}
// Display file info
infoElement.innerHTML = `
<strong>Selected file:</strong> ${file.name}<br>
<strong>Size:</strong> ${(file.size / 1024 / 1024).toFixed(2)} MB<br>
<strong>Type:</strong> ${file.type}
`;
// Preview image
const reader = new FileReader();
reader.onload = function(e) {
previewElement.innerHTML = `<img src="${e.target.result}" alt="Preview">`;
previewElement.style.display = 'block';
};
reader.readAsDataURL(file);
}
}
// Edit button functionality
const editButtons = document.querySelectorAll('.edit-btn');
editButtons.forEach(button => {
button.addEventListener('click', function() {
const courseId = this.getAttribute('data-course-id');
// Fetch course data via AJAX
fetch(`get_course.php?id=${courseId}`)
.then(response => response.json())
.then(course => {
// Populate edit form
document.getElementById('edit_course_id').value = course.id;
document.getElementById('edit_title').value = course.title;
document.getElementById('edit_description').value = course.description;
document.getElementById('edit_category_id').value = course.category_id;
document.getElementById('edit_instructor_id').value = course.instructor_id;
document.getElementById('edit_old_price').value = course.old_price;
document.getElementById('edit_current_price').value = course.current_price;
document.getElementById('edit_content').value = course.content;
document.getElementById('edit_is_popular').checked = course.is_popular == 1;
// Handle current image
const currentImage = document.getElementById('currentImage');
const currentImageContainer = document.getElementById('currentImageContainer');
if (course.image) {
currentImage.src = '../assets/images/courses/' + course.image;
currentImage.style.display = 'block';
currentImageContainer.style.display = 'block';
} else {
currentImage.style.display = 'none';
currentImageContainer.style.display = 'none';
}
})
.catch(error => {
console.error('Error fetching course data:', error);
alert('Error loading course data');
});
});
});
// Form validation
const courseForm = document.getElementById('courseForm');
const editCourseForm = document.getElementById('editCourseForm');
[courseForm, editCourseForm].forEach(form => {
if (form) {
form.addEventListener('submit', function(e) {
const currentPrice = this.querySelector('input[name="current_price"]');
if (currentPrice && parseFloat(currentPrice.value) < 0) {
e.preventDefault();
alert('Current price cannot be negative');
return false;
}
});
}
});
});
// Format file size
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
</script>
</body>
</html>