Sindbad~EG File Manager
<?php
require_once '../config/config.php';
// Check if user is logged in
if (!isLoggedIn()) {
redirect('login.php');
}
$db = new Database();
$conn = $db->getConnection();
$success_message = '';
$error_message = '';
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
$error_message = 'Invalid security token. Please try again.';
} else {
$action = $_POST['action'] ?? '';
if ($action === 'update_registration_status') {
$program_id = (int)$_POST['program_id'];
$registration_status = sanitizeInput($_POST['registration_status'] ?? 'open');
$registration_open_date = !empty($_POST['registration_open_date']) ? $_POST['registration_open_date'] : null;
$registration_close_date = !empty($_POST['registration_close_date']) ? $_POST['registration_close_date'] : null;
$registration_message = sanitizeInput($_POST['registration_message'] ?? '');
try {
$query = "UPDATE programs SET
registration_status = ?,
registration_open_date = ?,
registration_close_date = ?,
registration_message = ?
WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->execute([$registration_status, $registration_open_date, $registration_close_date, $registration_message, $program_id]);
logActivity($_SESSION['user_id'], 'update_registration_status', "Updated registration status for program ID: $program_id");
$success_message = 'Registration status updated successfully.';
} catch (Exception $e) {
$error_message = 'An error occurred while updating registration status.';
}
} elseif ($action === 'create' || $action === 'update') {
$name = sanitizeInput($_POST['name'] ?? '');
$description = sanitizeInput($_POST['description'] ?? '');
$fields = $_POST['fields'] ?? '[]';
$is_active = isset($_POST['is_active']) ? 1 : 0;
if (empty($name)) {
$error_message = 'Form template name is required.';
} else {
try {
if ($action === 'create') {
$query = "INSERT INTO form_templates (name, description, fields, is_active, created_by)
VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute([$name, $description, $fields, $is_active, $_SESSION['user_id']]);
logActivity($_SESSION['user_id'], 'create_form_template', "Created form template: $name");
$success_message = 'Form template created successfully.';
} else {
$template_id = (int)$_POST['template_id'];
$query = "UPDATE form_templates SET name = ?, description = ?, fields = ?, is_active = ?
WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->execute([$name, $description, $fields, $is_active, $template_id]);
logActivity($_SESSION['user_id'], 'update_form_template', "Updated form template: $name");
$success_message = 'Form template updated successfully.';
}
} catch (Exception $e) {
$error_message = 'An error occurred while saving the form template.';
}
}
} elseif ($action === 'duplicate') {
$template_id = (int)$_POST['template_id'];
try {
// Get original template
$query = "SELECT * FROM form_templates WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->execute([$template_id]);
$original = $stmt->fetch();
if ($original) {
$new_name = $original['name'] . ' (Copy)';
$query = "INSERT INTO form_templates (name, description, fields, is_active, created_by)
VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute([$new_name, $original['description'], $original['fields'], 0, $_SESSION['user_id']]);
logActivity($_SESSION['user_id'], 'duplicate_form_template', "Duplicated form template: $new_name");
$success_message = 'Form template duplicated successfully.';
} else {
$error_message = 'Template not found.';
}
} catch (Exception $e) {
$error_message = 'An error occurred while duplicating the template.';
}
} elseif ($action === 'delete' && hasRole('superuser')) {
$template_id = (int)$_POST['template_id'];
try {
$query = "DELETE FROM form_templates WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->execute([$template_id]);
logActivity($_SESSION['user_id'], 'delete_form_template', "Deleted form template ID: $template_id");
$success_message = 'Form template deleted successfully.';
} catch (Exception $e) {
$error_message = 'Cannot delete form template. It may be in use.';
}
}
}
}
// Get form templates
$query = "SELECT ft.*, u.full_name as created_by_name
FROM form_templates ft
LEFT JOIN users u ON ft.created_by = u.id
ORDER BY ft.created_at DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$templates = $stmt->fetchAll();
// Get programs with registration status
$programs_query = "SELECT p.*,
CASE
WHEN p.registration_status = 'scheduled' AND p.registration_open_date > NOW() THEN 'scheduled_closed'
WHEN p.registration_status = 'scheduled' AND p.registration_close_date < NOW() THEN 'scheduled_closed'
WHEN p.registration_status = 'scheduled' THEN 'scheduled_open'
ELSE p.registration_status
END as current_status
FROM programs p
WHERE p.is_active = 1
ORDER BY p.name";
$programs_stmt = $conn->prepare($programs_query);
$programs_stmt->execute();
$programs = $programs_stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Management - Admin Panel</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#3B82F6',
secondary: '#F59E0B',
accent: '#6B7280'
}
}
}
}
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
.gradient-bg {
background: linear-gradient(135deg, #3B82F6 0%, #F59E0B 50%, #6B7280 100%);
}
</style>
</head>
<body class="bg-gray-50">
<!-- Include Sidebar -->
<?php include 'includes/sidebar.php'; ?>
<!-- Main Content -->
<div class="md:ml-64">
<!-- Header -->
<header class="bg-white shadow-sm border-b">
<div class="px-6 py-4">
<div class="flex items-center justify-between">
<h1 class="text-2xl font-bold text-gray-900">Form Management</h1>
<button onclick="showCreateModal()" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
<i class="fas fa-plus mr-2"></i>
Create Form Template
</button>
</div>
</div>
</header>
<!-- Content -->
<main class="p-6">
<!-- Success/Error Messages -->
<?php if ($success_message): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
<div class="flex items-center">
<i class="fas fa-check-circle mr-2"></i>
<span><?php echo $success_message; ?></span>
</div>
</div>
<?php endif; ?>
<?php if ($error_message): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
<div class="flex items-center">
<i class="fas fa-exclamation-circle mr-2"></i>
<span><?php echo $error_message; ?></span>
</div>
</div>
<?php endif; ?>
<!-- Program Registration Status Management -->
<div class="bg-white rounded-lg shadow mb-8">
<div class="px-6 py-4 border-b border-gray-200">
<div class="flex items-center justify-between">
<h2 class="text-xl font-semibold text-gray-900">Program Registration Status</h2>
<div class="text-sm text-gray-500">
<i class="fas fa-info-circle mr-1"></i>
Control when users can register for programs
</div>
</div>
</div>
<div class="p-6">
<?php if (empty($programs)): ?>
<div class="text-center py-8">
<i class="fas fa-calendar-times text-4xl text-gray-400 mb-4"></i>
<h3 class="text-lg font-semibold text-gray-700 mb-2">No Active Programs Found</h3>
<p class="text-gray-500">Create some programs first to manage registration status.</p>
</div>
<?php else: ?>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Program</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Current Status</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Registration Dates</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<?php foreach ($programs as $program): ?>
<tr class="hover:bg-gray-50">
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div>
<div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($program['name']); ?></div>
<div class="text-sm text-gray-500"><?php echo htmlspecialchars($program['description'] ?? ''); ?></div>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<?php
$status_class = '';
$status_text = '';
$status_icon = '';
switch ($program['current_status']) {
case 'open':
case 'scheduled_open':
$status_class = 'bg-green-100 text-green-800';
$status_text = 'Open';
$status_icon = 'fas fa-check-circle';
break;
case 'closed':
case 'scheduled_closed':
$status_class = 'bg-red-100 text-red-800';
$status_text = 'Closed';
$status_icon = 'fas fa-times-circle';
break;
default:
$status_class = 'bg-gray-100 text-gray-800';
$status_text = 'Unknown';
$status_icon = 'fas fa-question-circle';
}
?>
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
<i class="<?php echo $status_icon; ?> mr-1"></i>
<?php echo $status_text; ?>
<?php if ($program['registration_status'] === 'scheduled'): ?>
<span class="ml-1">(Scheduled)</span>
<?php endif; ?>
</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<?php if ($program['registration_open_date'] || $program['registration_close_date']): ?>
<div class="space-y-1">
<?php if ($program['registration_open_date']): ?>
<div><strong>Opens:</strong> <?php echo date('M j, Y g:i A', strtotime($program['registration_open_date'])); ?></div>
<?php endif; ?>
<?php if ($program['registration_close_date']): ?>
<div><strong>Closes:</strong> <?php echo date('M j, Y g:i A', strtotime($program['registration_close_date'])); ?></div>
<?php endif; ?>
</div>
<?php else: ?>
<span class="text-gray-400">No scheduled dates</span>
<?php endif; ?>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<button onclick="editRegistrationStatus(<?php echo $program['id']; ?>)"
class="text-primary hover:text-blue-700 mr-3">
<i class="fas fa-edit mr-1"></i>
Edit Status
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
<!-- Form Templates -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<?php foreach ($templates as $template): ?>
<div class="bg-white rounded-lg shadow overflow-hidden">
<div class="<?php echo $template['is_active'] ? 'gradient-bg' : 'bg-gray-400'; ?> p-4">
<div class="flex items-center justify-between">
<h3 class="text-lg font-bold text-white">
<?php echo htmlspecialchars($template['name']); ?>
</h3>
<div class="flex space-x-2">
<button onclick="editTemplate(<?php echo $template['id']; ?>)"
class="text-white hover:text-yellow-200">
<i class="fas fa-edit"></i>
</button>
<button onclick="previewTemplate(<?php echo $template['id']; ?>)"
class="text-white hover:text-green-200">
<i class="fas fa-eye"></i>
</button>
<?php if (hasRole('superuser')): ?>
<button onclick="deleteTemplate(<?php echo $template['id']; ?>)"
class="text-white hover:text-red-200">
<i class="fas fa-trash"></i>
</button>
<?php endif; ?>
</div>
</div>
</div>
<div class="p-4">
<?php if ($template['description']): ?>
<p class="text-gray-600 mb-3"><?php echo htmlspecialchars($template['description']); ?></p>
<?php endif; ?>
<?php
$fields = json_decode($template['fields'], true);
$field_count = is_array($fields) ? count($fields) : 0;
?>
<div class="space-y-2 text-sm text-gray-500">
<div class="flex items-center">
<i class="fas fa-list mr-2"></i>
<span><?php echo $field_count; ?> form fields</span>
</div>
<div class="flex items-center">
<i class="fas fa-user mr-2"></i>
<span>Created by: <?php echo htmlspecialchars($template['created_by_name'] ?? 'Unknown'); ?></span>
</div>
<div class="flex items-center">
<i class="fas fa-calendar mr-2"></i>
<span><?php echo date('M j, Y', strtotime($template['created_at'])); ?></span>
</div>
</div>
<div class="mt-4 pt-4 border-t">
<div class="flex items-center justify-between">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $template['is_active'] ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
<?php echo $template['is_active'] ? 'Active' : 'Inactive'; ?>
</span>
<button onclick="duplicateTemplate(<?php echo $template['id']; ?>)"
class="text-primary hover:text-blue-700 text-sm font-medium">
<i class="fas fa-copy mr-1"></i>
Duplicate
</button>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<?php if (empty($templates)): ?>
<div class="col-span-full text-center py-12">
<i class="fas fa-edit text-6xl text-gray-400 mb-4"></i>
<h3 class="text-xl font-semibold text-gray-700 mb-2">No Form Templates Found</h3>
<p class="text-gray-500 mb-4">Create your first form template to get started.</p>
<button onclick="showCreateModal()" class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
<i class="fas fa-plus mr-2"></i>
Create Form Template
</button>
</div>
<?php endif; ?>
</div>
</main>
</div>
<!-- Create/Edit Template Modal -->
<div id="templateModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
<div class="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-screen overflow-y-auto">
<div class="flex items-center justify-between mb-4">
<h3 id="modalTitle" class="text-lg font-semibold text-gray-900">Create Form Template</h3>
<button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
<i class="fas fa-times"></i>
</button>
</div>
<form method="POST" id="templateForm">
<input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
<input type="hidden" name="action" id="formAction" value="create">
<input type="hidden" name="template_id" id="templateId">
<div class="space-y-4">
<div>
<label for="name" class="block text-sm font-medium text-gray-700 mb-2">
Template Name <span class="text-red-500">*</span>
</label>
<input type="text" id="name" name="name" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
</div>
<div>
<label for="description" class="block text-sm font-medium text-gray-700 mb-2">
Description
</label>
<textarea id="description" name="description" rows="2"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">
Form Fields
</label>
<div class="bg-gray-50 rounded-lg p-4">
<p class="text-sm text-gray-600 mb-4">
The system includes default fields: District Name, Assembly Name, Full Name, Email, and Phone.
You can add additional custom fields below.
</p>
<div id="customFields">
<!-- Custom fields will be added here -->
</div>
<button type="button" onclick="addCustomField()"
class="mt-2 text-primary hover:text-blue-700 text-sm">
<i class="fas fa-plus mr-1"></i>
Add Custom Field
</button>
</div>
<input type="hidden" name="fields" id="fieldsJson">
</div>
<div class="flex items-center">
<input type="checkbox" id="is_active" name="is_active" checked
class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
<label for="is_active" class="ml-2 block text-sm text-gray-700">
Active (available for use)
</label>
</div>
</div>
<div class="flex justify-end space-x-4 mt-6">
<button type="button" onclick="closeModal()"
class="px-4 py-2 text-gray-600 hover:text-gray-800">
Cancel
</button>
<button type="submit"
class="px-4 py-2 bg-primary text-white rounded hover:bg-blue-700">
<span id="submitText">Create Template</span>
</button>
</div>
</form>
</div>
</div>
<!-- Registration Status Modal -->
<div id="registrationModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
<div class="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-semibold text-gray-900">Edit Registration Status</h3>
<button onclick="closeRegistrationModal()" class="text-gray-400 hover:text-gray-600">
<i class="fas fa-times"></i>
</button>
</div>
<form method="POST" id="registrationForm">
<input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
<input type="hidden" name="action" value="update_registration_status">
<input type="hidden" name="program_id" id="regProgramId">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Program</label>
<div id="regProgramName" class="text-lg font-semibold text-gray-900"></div>
</div>
<div>
<label for="registration_status" class="block text-sm font-medium text-gray-700 mb-2">
Registration Status <span class="text-red-500">*</span>
</label>
<select id="registration_status" name="registration_status" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
onchange="toggleDateFields()">
<option value="open">Open - Registration is always open</option>
<option value="closed">Closed - Registration is always closed</option>
<option value="scheduled">Scheduled - Registration opens/closes automatically</option>
</select>
</div>
<div id="dateFields" class="hidden space-y-4">
<div>
<label for="registration_open_date" class="block text-sm font-medium text-gray-700 mb-2">
Registration Opens
</label>
<input type="datetime-local" id="registration_open_date" name="registration_open_date"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
</div>
<div>
<label for="registration_close_date" class="block text-sm font-medium text-gray-700 mb-2">
Registration Closes
</label>
<input type="datetime-local" id="registration_close_date" name="registration_close_date"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
</div>
</div>
<div>
<label for="registration_message" class="block text-sm font-medium text-gray-700 mb-2">
Custom Message (shown when registration is closed)
</label>
<textarea id="registration_message" name="registration_message" rows="3"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
placeholder="e.g., Registration for this program is currently closed. Please check back later."></textarea>
</div>
</div>
<div class="flex justify-end space-x-4 mt-6">
<button type="button" onclick="closeRegistrationModal()"
class="px-4 py-2 text-gray-600 hover:text-gray-800">
Cancel
</button>
<button type="submit"
class="px-4 py-2 bg-primary text-white rounded hover:bg-blue-700">
Update Status
</button>
</div>
</form>
</div>
</div>
<script>
let customFieldCount = 0;
function showCreateModal() {
document.getElementById('modalTitle').textContent = 'Create Form Template';
document.getElementById('formAction').value = 'create';
document.getElementById('submitText').textContent = 'Create Template';
document.getElementById('templateForm').reset();
document.getElementById('customFields').innerHTML = '';
document.getElementById('is_active').checked = true;
customFieldCount = 0;
document.getElementById('templateModal').classList.remove('hidden');
document.getElementById('templateModal').classList.add('flex');
}
function addCustomField() {
customFieldCount++;
const fieldHtml = `
<div class="border rounded-lg p-4 mb-4" id="field_${customFieldCount}">
<div class="flex justify-between items-center mb-3">
<h4 class="font-medium text-gray-900">Custom Field #${customFieldCount}</h4>
<button type="button" onclick="removeCustomField(${customFieldCount})"
class="text-red-600 hover:text-red-800">
<i class="fas fa-trash"></i>
</button>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Field Name</label>
<input type="text" class="field-name w-full px-2 py-1 border border-gray-300 rounded text-sm"
placeholder="e.g., age_group">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Field Label</label>
<input type="text" class="field-label w-full px-2 py-1 border border-gray-300 rounded text-sm"
placeholder="e.g., Age Group">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Field Type</label>
<select class="field-type w-full px-2 py-1 border border-gray-300 rounded text-sm"
onchange="toggleOptions(${customFieldCount})">
<option value="text">Text</option>
<option value="email">Email</option>
<option value="tel">Phone</option>
<option value="select">Dropdown</option>
<option value="radio">Radio Buttons</option>
<option value="textarea">Textarea</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Required</label>
<input type="checkbox" class="field-required mt-2">
</div>
</div>
<div class="field-options mt-3 hidden">
<label class="block text-sm font-medium text-gray-700 mb-1">Options (one per line)</label>
<textarea class="field-options-text w-full px-2 py-1 border border-gray-300 rounded text-sm"
rows="3" placeholder="Option 1\nOption 2\nOption 3"></textarea>
</div>
</div>
`;
document.getElementById('customFields').insertAdjacentHTML('beforeend', fieldHtml);
}
function removeCustomField(id) {
document.getElementById(`field_${id}`).remove();
}
function toggleOptions(id) {
const fieldType = document.querySelector(`#field_${id} .field-type`).value;
const optionsDiv = document.querySelector(`#field_${id} .field-options`);
if (fieldType === 'select' || fieldType === 'radio') {
optionsDiv.classList.remove('hidden');
} else {
optionsDiv.classList.add('hidden');
}
}
function collectFormFields() {
const fields = [];
// Add default fields
fields.push(
{name: 'district_name', label: 'District Name', type: 'text', required: false},
{name: 'assembly_name', label: 'Assembly Name', type: 'text', required: false},
{name: 'full_name', label: 'Full Name', type: 'text', required: true},
{name: 'email', label: 'Email Address', type: 'email', required: false},
{name: 'telephone', label: 'Phone Number', type: 'tel', required: false}
);
// Add custom fields
document.querySelectorAll('#customFields > div').forEach(fieldDiv => {
const name = fieldDiv.querySelector('.field-name').value;
const label = fieldDiv.querySelector('.field-label').value;
const type = fieldDiv.querySelector('.field-type').value;
const required = fieldDiv.querySelector('.field-required').checked;
if (name && label) {
const field = {name, label, type, required};
if (type === 'select' || type === 'radio') {
const optionsText = fieldDiv.querySelector('.field-options-text').value;
field.options = optionsText.split('\n').filter(opt => opt.trim());
}
fields.push(field);
}
});
return fields;
}
// Update form submission to collect fields
document.getElementById('templateForm').addEventListener('submit', function(e) {
const fields = collectFormFields();
document.getElementById('fieldsJson').value = JSON.stringify(fields);
});
function editTemplate(id) {
// Fetch template data via AJAX
fetch('get_form_template.php?id=' + id)
.then(response => response.json())
.then(data => {
if (data.success) {
const template = data.template;
// Populate form fields
document.getElementById('modalTitle').textContent = 'Edit Form Template';
document.getElementById('formAction').value = 'update';
document.getElementById('submitText').textContent = 'Update Template';
document.getElementById('templateId').value = template.id;
document.getElementById('name').value = template.name;
document.getElementById('description').value = template.description || '';
document.getElementById('is_active').checked = template.is_active == 1;
// Clear existing custom fields
document.getElementById('customFields').innerHTML = '';
// Load custom fields (excluding default ones)
const fields = JSON.parse(template.fields || '[]');
const defaultFields = ['district_name', 'assembly_name', 'full_name', 'email', 'telephone'];
fields.forEach(field => {
if (!defaultFields.includes(field.name)) {
addCustomFieldWithData(field);
}
});
// Show modal
document.getElementById('templateModal').classList.remove('hidden');
document.getElementById('templateModal').classList.add('flex');
} else {
alert('Error loading template data: ' + data.message);
}
})
.catch(error => {
alert('Error loading template data');
console.error('Error:', error);
});
}
function addCustomFieldWithData(fieldData) {
customFieldCount++;
const fieldHtml = `
<div id="field_${customFieldCount}" class="border border-gray-300 rounded p-3 mb-3">
<div class="flex justify-between items-start mb-2">
<h4 class="font-medium text-gray-900">Custom Field ${customFieldCount}</h4>
<button type="button" onclick="removeCustomField(${customFieldCount})"
class="text-red-600 hover:text-red-800">
<i class="fas fa-trash"></i>
</button>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Field Name</label>
<input type="text" class="field-name w-full px-2 py-1 border border-gray-300 rounded text-sm"
placeholder="field_name" value="${fieldData.name || ''}">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Label</label>
<input type="text" class="field-label w-full px-2 py-1 border border-gray-300 rounded text-sm"
placeholder="Field Label" value="${fieldData.label || ''}">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Type</label>
<select class="field-type w-full px-2 py-1 border border-gray-300 rounded text-sm"
onchange="toggleOptions(${customFieldCount})">
<option value="text" ${fieldData.type === 'text' ? 'selected' : ''}>Text</option>
<option value="email" ${fieldData.type === 'email' ? 'selected' : ''}>Email</option>
<option value="tel" ${fieldData.type === 'tel' ? 'selected' : ''}>Phone</option>
<option value="select" ${fieldData.type === 'select' ? 'selected' : ''}>Dropdown</option>
<option value="radio" ${fieldData.type === 'radio' ? 'selected' : ''}>Radio Buttons</option>
<option value="textarea" ${fieldData.type === 'textarea' ? 'selected' : ''}>Textarea</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Required</label>
<input type="checkbox" class="field-required mt-2" ${fieldData.required ? 'checked' : ''}>
</div>
</div>
<div class="field-options mt-3 ${(fieldData.type === 'select' || fieldData.type === 'radio') ? '' : 'hidden'}">
<label class="block text-sm font-medium text-gray-700 mb-1">Options (one per line)</label>
<textarea class="field-options-text w-full px-2 py-1 border border-gray-300 rounded text-sm"
rows="3" placeholder="Option 1\nOption 2\nOption 3">${fieldData.options ? fieldData.options.join('\n') : ''}</textarea>
</div>
</div>
`;
document.getElementById('customFields').insertAdjacentHTML('beforeend', fieldHtml);
}
function previewTemplate(id) {
// Open preview in new window
window.open('preview_form_template.php?id=' + id, '_blank', 'width=800,height=600,scrollbars=yes');
}
function duplicateTemplate(id) {
if (confirm('Are you sure you want to duplicate this form template?')) {
// Create and submit duplicate form
const form = document.createElement('form');
form.method = 'POST';
form.innerHTML = `
<input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
<input type="hidden" name="action" value="duplicate">
<input type="hidden" name="template_id" value="${id}">
`;
document.body.appendChild(form);
form.submit();
}
}
function deleteTemplate(id) {
if (confirm('Are you sure you want to delete this form template?')) {
// Create and submit delete form
const form = document.createElement('form');
form.method = 'POST';
form.innerHTML = `
<input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="template_id" value="${id}">
`;
document.body.appendChild(form);
form.submit();
}
}
function closeModal() {
document.getElementById('templateModal').classList.add('hidden');
document.getElementById('templateModal').classList.remove('flex');
}
// Close modal when clicking outside
document.getElementById('templateModal').addEventListener('click', function(e) {
if (e.target === this) closeModal();
});
// Registration Status Management Functions
const programsData = <?php echo json_encode($programs); ?>;
function editRegistrationStatus(programId) {
const program = programsData.find(p => p.id == programId);
if (!program) return;
// Populate modal with program data
document.getElementById('regProgramId').value = program.id;
document.getElementById('regProgramName').textContent = program.name;
document.getElementById('registration_status').value = program.registration_status || 'open';
// Handle dates
if (program.registration_open_date) {
const openDate = new Date(program.registration_open_date);
document.getElementById('registration_open_date').value = formatDateForInput(openDate);
} else {
document.getElementById('registration_open_date').value = '';
}
if (program.registration_close_date) {
const closeDate = new Date(program.registration_close_date);
document.getElementById('registration_close_date').value = formatDateForInput(closeDate);
} else {
document.getElementById('registration_close_date').value = '';
}
document.getElementById('registration_message').value = program.registration_message || '';
// Show/hide date fields based on status
toggleDateFields();
// Show modal
document.getElementById('registrationModal').classList.remove('hidden');
document.getElementById('registrationModal').classList.add('flex');
}
function toggleDateFields() {
const status = document.getElementById('registration_status').value;
const dateFields = document.getElementById('dateFields');
if (status === 'scheduled') {
dateFields.classList.remove('hidden');
} else {
dateFields.classList.add('hidden');
}
}
function closeRegistrationModal() {
document.getElementById('registrationModal').classList.add('hidden');
document.getElementById('registrationModal').classList.remove('flex');
}
function formatDateForInput(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
// Close registration modal when clicking outside
document.getElementById('registrationModal').addEventListener('click', function(e) {
if (e.target === this) closeRegistrationModal();
});
</script>
</body>
</html>
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists