Files

3670 lines
184 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Plugin Name: Sige Events
* Plugin URI: https://www.sige.ita.br
* Description: Sige Event is a simple and easy to use plugin that allows you to manage enrollments in short-courses and events in general.
* Version: 0.0.1
* Author: Leandro Geraldo da Costa and Thales the Mileto
* Author URI: http://lattes.cnpq.br/7216945611788146 and http://lattes.cnpq.br/7216945611788146
* Text Domain: ITA
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
// check if file is available by user accessing it, otherwise kill process
if (! defined('ABSPATH')){
die;
}
// Enqueue the HTML5 QR Code library
function sige_enqueue_qrcode_library() {
wp_enqueue_script( 'html5-qrcode', plugin_dir_url( __FILE__ ) . 'js/html5-qrcode.min.js', array(), '2.3.8', true );
}
add_action( 'admin_enqueue_scripts', 'sige_enqueue_qrcode_library' );
function sige_enqueue_tinymce() {
wp_enqueue_script('tinymce');
wp_enqueue_script('wp-tinymce');
}
add_action('admin_enqueue_scripts', 'sige_enqueue_tinymce');
register_activation_hook(__FILE__, 'sige_events_install');
register_deactivation_hook(__FILE__, 'sige_events_uninstall');
function sige_events_install() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// SQL to create necessary tables
$sql = "
CREATE TABLE {$wpdb->prefix}sige_place (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
place TINYTEXT NOT NULL,
comments TEXT NOT NULL,
PRIMARY KEY (id)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_speakers (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
research_degree VARCHAR(50) NOT NULL,
full_name TINYTEXT NOT NULL,
email VARCHAR(100) NOT NULL,
institution TINYTEXT NOT NULL,
PRIMARY KEY (id)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_event_names (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
acronym VARCHAR(50) NOT NULL,
name TINYTEXT NOT NULL,
responsible_for TINYTEXT NOT NULL,
PRIMARY KEY (id)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_meta_keys (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
meta_key VARCHAR(255) NOT NULL,
status TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY meta_key (meta_key)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_activities (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
description TEXT NOT NULL,
start_date DATE NOT NULL,
start_time TIME NOT NULL,
end_date DATE NOT NULL,
end_time TIME NOT NULL,
type VARCHAR(50) NOT NULL,
modality VARCHAR(50) NOT NULL,
status VARCHAR(50) NOT NULL,
curriculum TEXT NOT NULL,
comment TEXT NOT NULL,
place_id MEDIUMINT(9) NOT NULL,
speaker_id MEDIUMINT(9) NOT NULL,
event_name_id MEDIUMINT(9),
security_credential VARCHAR(20) NOT NULL,
chair TINYTEXT NOT NULL,
target_audience VARCHAR(50) NOT NULL,
attendance_control ENUM('yes', 'no') NOT NULL DEFAULT 'no',
PRIMARY KEY (id),
KEY place_id (place_id),
KEY speaker_id (speaker_id),
KEY event_name_id (event_name_id),
CONSTRAINT fk_place FOREIGN KEY (place_id) REFERENCES {$wpdb->prefix}sige_place(id) ON DELETE CASCADE,
CONSTRAINT fk_speaker FOREIGN KEY (speaker_id) REFERENCES {$wpdb->prefix}sige_speakers(id) ON DELETE CASCADE,
CONSTRAINT fk_event_name FOREIGN KEY (event_name_id) REFERENCES {$wpdb->prefix}sige_event_names(id) ON DELETE SET NULL
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_enrollments (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
activity_id MEDIUMINT(9) NOT NULL,
user_id BIGINT(20) UNSIGNED NOT NULL,
enrollment_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
status VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (activity_id) REFERENCES {$wpdb->prefix}sige_activities(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_cancellation_record (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
activity_id MEDIUMINT(9) NOT NULL,
user_id BIGINT(20) UNSIGNED NOT NULL,
date_of_cancelation DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
reasons VARCHAR(50) NULL,
PRIMARY KEY (id),
FOREIGN KEY (activity_id) REFERENCES {$wpdb->prefix}sige_activities(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_activity_notices (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
type VARCHAR(50) NOT NULL,
notice TEXT NOT NULL,
PRIMARY KEY (id)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_display_options (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
field_name VARCHAR(50) NOT NULL,
display TINYINT(1) NOT NULL DEFAULT 1,
PRIMARY KEY (id)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_enrollment_button_style (
button_action VARCHAR(50) NOT NULL,
button_label VARCHAR(50) NOT NULL,
background_color VARCHAR(7) NOT NULL,
font_size VARCHAR(10) NOT NULL,
font_family VARCHAR(100) NOT NULL,
font_weight VARCHAR(10) NOT NULL,
PRIMARY KEY (button_action)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_enrollment_status_style (
status_action VARCHAR(50) NOT NULL,
status_label VARCHAR(50) NOT NULL,
font_color VARCHAR(7) NOT NULL,
font_size VARCHAR(10) NOT NULL,
font_family VARCHAR(100) NOT NULL,
font_weight VARCHAR(10) NOT NULL,
PRIMARY KEY (status_action)
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_email_messages (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
email_sender VARCHAR(100) NOT NULL,
email_subject VARCHAR(255) NOT NULL,
email_message TEXT NOT NULL,
status_action VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (status_action) REFERENCES {$wpdb->prefix}sige_enrollment_status_style(status_action) ON DELETE CASCADE
) $charset_collate;
CREATE TABLE {$wpdb->prefix}sige_enrollment_attendance_control (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
enrollment_id MEDIUMINT(9) NOT NULL,
attended ENUM('yes', 'no') DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (enrollment_id) REFERENCES {$wpdb->prefix}sige_enrollments(id) ON DELETE CASCADE
) $charset_collate;
";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// Insert default display options
$default_options = [
'Notices',
'Speaker',
'Curriculum Vitae',
'Data',
'Place',
'Enrollment Status',
'Comment',
'Security Credential',
'Target Audience',
'Chair'
];
foreach ($default_options as $option) {
if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}sige_display_options WHERE field_name = %s", $option))) {
$wpdb->insert("{$wpdb->prefix}sige_display_options", ['field_name' => $option, 'display' => 1]);
}
}
// Insert default button styles
$default_styles = [
['button_action' => 'request_enrollment', 'button_label' => 'Request Enrollment', 'background_color' => '#0073aa', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['button_action' => 'cancel_enrollment', 'button_label' => 'Cancel Enrollment', 'background_color' => '#ac1226', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal']
];
foreach ($default_styles as $style) {
$wpdb->insert("{$wpdb->prefix}sige_enrollment_button_style", $style);
}
// Insert default status styles
$default_status_styles = [
['status_action' => 'Not Requested', 'status_label' => 'Not Requested', 'font_color' => '#000000', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['status_action' => 'Enrollment Canceled by User', 'status_label' => 'Enrollment Canceled by User', 'font_color' => '#ac1226', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['status_action' => 'Under Analysis', 'status_label' => 'Under Analysis', 'font_color' => '#0073aa', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['status_action' => 'Approved', 'status_label' => 'Approved', 'font_color' => '#008000', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['status_action' => 'Waiting List', 'status_label' => 'Waiting List', 'font_color' => '#CC9900', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal'],
['status_action' => 'Not Approved', 'status_label' => 'Not Approved', 'font_color' => '#bc97cd', 'font_size' => '14px', 'font_family' => 'Arial, sans-serif', 'font_weight' => 'normal']
];
foreach ($default_status_styles as $style) {
$wpdb->insert("{$wpdb->prefix}sige_enrollment_status_style", $style);
}
// Insert default email messages
$default_email_messages = [
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Not Requested', 'email_message' => 'Your enrollment status is Not Requested.', 'status_action' => 'Not Requested'],
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Enrollment Canceled by User', 'email_message' => 'Your enrollment has been canceled by user.', 'status_action' => 'Enrollment Canceled by User'],
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Under Analysis', 'email_message' => 'Your enrollment is under analysis.', 'status_action' => 'Under Analysis'],
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Approved', 'email_message' => 'Your enrollment has been approved.', 'status_action' => 'Approved'],
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Waiting List', 'email_message' => 'You have been placed on the waiting list.', 'status_action' => 'Waiting List'],
['email_sender' => get_bloginfo('admin_email'), 'email_subject' => 'Not Approved', 'email_message' => 'Your enrollment has not been approved.', 'status_action' => 'Not Approved']
];
foreach ($default_email_messages as $message) {
$wpdb->insert("{$wpdb->prefix}sige_email_messages", $message);
}
// Ensure wp_usermeta has specified meta_keys
$required_meta_keys = [
'forca',
'full_name',
'posto',
'militar',
'instituição',
'nacionalidade',
'efetivo_dcta',
'cidade',
'estado',
'areaatividadeprincipal',
'setordeatuacao',
'cargofuncao',
'ehativa',
'circulo hierárquico',
'telefone',
'passaporte',
'pais',
'formacao_academica',
'regiao_do_brasil'
];
foreach ($required_meta_keys as $meta_key) {
if (!$wpdb->get_var($wpdb->prepare("SELECT meta_key FROM {$wpdb->prefix}usermeta WHERE meta_key = %s", $meta_key))) {
$wpdb->insert("{$wpdb->prefix}usermeta", ['meta_key' => $meta_key, 'meta_value' => '']);
}
}
// Check if the JSON file with saved data exists and restore data if available
$json_file_path = plugin_dir_path(__FILE__) . 'sige_events_data.json';
if (file_exists($json_file_path)) {
$json_data = json_decode(file_get_contents($json_file_path), true);
if ($json_data) {
$tables_to_replace = [
'sige_enrollment_status_style',
'sige_email_messages',
'sige_enrollment_button_style',
'sige_display_options',
'sige_activities',
'sige_enrollments',
'sige_cancellation_record',
'sige_enrollment_attendance_control'
];
// Restore the non-replacement tables first
foreach ($json_data as $table => $records) {
if (!in_array($table, $tables_to_replace)) {
foreach ($records as $record) {
$wpdb->insert("{$wpdb->prefix}$table", $record);
}
}
}
// Restore the replacement tables last
foreach ($tables_to_replace as $table) {
if (isset($json_data[$table])) {
foreach ($json_data[$table] as $record) {
$wpdb->replace("{$wpdb->prefix}$table", $record);
}
}
}
}
}
}
function sige_events_uninstall() {
global $wpdb;
// Export data to JSON file before dropping tables
$tables = [
'sige_activity_notices',
'sige_display_options',
'sige_enrollment_button_style',
'sige_meta_keys',
'sige_email_messages',
'sige_enrollment_status_style',
'sige_event_names',
'sige_place',
'sige_speakers',
'sige_activities',
'sige_enrollments',
'sige_cancellation_record',
'sige_enrollment_attendance_control'
];
$data = [];
// Save non-replacement tables first
foreach ($tables as $table) {
if (!in_array($table, ['sige_activities', 'sige_enrollments', 'sige_enrollment_attendance_control','sige_cancellation_record'])) {
$data[$table] = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}$table", ARRAY_A);
}
}
// Save replacement tables last
foreach (['sige_activities', 'sige_enrollments', 'sige_enrollment_attendance_control','sige_cancellation_record'] as $table) {
$data[$table] = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}$table", ARRAY_A);
}
$json_file_path = plugin_dir_path(__FILE__) . 'sige_events_data.json';
file_put_contents($json_file_path, json_encode($data));
// Drop the tables
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_activity_notices");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_display_options");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_enrollment_button_style");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_meta_keys");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_email_messages");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_enrollment_status_style");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_enrollment_attendance_control");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_enrollments");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_cancellation_record");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_activities");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_event_names");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_place");
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sige_speakers");
}
add_action('admin_menu', 'addAdminPageContent');
function addAdminPageContent() {
add_menu_page('SIGE Events', 'SIGE Events', 'manage_options', 'sige-events', 'SigeEventmenuPage', 'dashicons-wordpress');
add_submenu_page('sige-events', 'Dashboard', 'Dashboard', 'manage_options', 'dashboard-submenu', 'dashboardSubmenuPage');
add_submenu_page('sige-events', 'Available Activities', 'Available Activities', 'manage_options', 'available-activities-submenu', 'availableActivitiesSubmenuPage');
add_submenu_page('sige-events', 'Enrollment Control', 'Enrollment Control', 'manage_options', 'enrollment-submenu', 'enrollmentSubmenuPage');
add_submenu_page('sige-events', 'Attendance Control', 'Attendance Control', 'manage_options', 'attendance-control-submenu', 'attendanceControlSubmenuPage');
add_submenu_page('sige-events', 'Settings', 'Settings', 'manage_options', 'settings-submenu', 'settingsSubmenuPage');
}
function SigeEventmenuPage() {
echo '<div class="wrap">';
echo '<h2>Welcome to Sige Events</h2>';
// Main Purpose Section
echo '<div class="sige-box">';
echo '<h3>Main Purpose</h3>';
echo '<p>Sige Events is a comprehensive plugin designed to facilitate the management of enrollments for short courses and events. It offers a user-friendly interface and a variety of features that help administrators efficiently handle all aspects of event management.</p>';
echo '<p><strong>Key Features:</strong></p>';
echo '<ul>';
echo '<li><strong>Event Creation and Management:</strong> Easily create and manage different types of activities, including presentations, short courses, lectures, workshops, and more.</li>';
echo '<li><strong>Enrollment Handling:</strong> Manage enrollments, track participant status, and handle approvals and cancellations.</li>';
echo '<li><strong>Email Notifications:</strong> Set up and customize email notifications to keep participants informed about their enrollment status and event updates.</li>';
echo '<li><strong>Data Export:</strong> Export activity and enrollment data to CSV for reporting and analysis purposes.</li>';
echo '<li><strong>Customizable Display Options:</strong> Choose which fields to display on the frontend and customize notices for different types of activities.</li>';
echo '</ul>';
echo '<p>This plugin is an ideal solution for institutions, organizations, or individuals who need a reliable and efficient system to manage their educational or informational events.</p>';
echo '</div>'; // End Main Purpose Section
// Development Team Section
echo '<div class="sige-box">';
echo '<h3>Development Team</h3>';
echo '<p>The development of Sige Events was a collaborative effort involving the following contributors:</p>';
echo '<ul>';
echo '<li><strong>Leandro Geraldo da Costa:</strong> Project Lead and Developer.</li>';
echo '<li><strong>Caio:</strong> Frontend Specialist.</li>';
echo '<li><strong>Munho:</strong> Backend Developer.</li>';
echo '<li><strong>Thales the Mileto:</strong> User Experience and Interface Designer.</li>';
echo '</ul>';
echo '</div>'; // End Development Team Section
// Shortcode Usage Section
echo '<div class="sige-box">';
echo '<h3>Shortcode Usage</h3>';
echo '<p>To display the open activities on any page or post, use the following shortcode:</p>';
echo '<code>[open_activities]</code>';
echo '<p>To display the enrollments on any page or post, use the following shortcode:</p>';
echo '<code>[enrollments]</code>';
echo '<p>To manage attendance control on any page or post, use the following shortcode:</p>';
echo '<code>[frontend_attendance_control]</code>';
echo '<p>To generate the QR CODE for user purpose, use the following shortcode:</p>';
echo '<code>[userbadge_qr_code]</code>';
echo '</div>'; // End Shortcode Usage Section
// Available Functions Section
echo '<div class="sige-box">';
echo '<h3>Available Functions and Their Purposes</h3>';
echo '<ul>';
echo '<li><strong>sige_events_install:</strong> Function to create the necessary database tables and insert default options when the plugin is activated.</li>';
echo '<li><strong>sige_events_uninstall:</strong> Function to drop the database tables when the plugin is deactivated.</li>';
echo '<li><strong>addAdminPageContent:</strong> Function to add the admin menu and submenu pages for managing the plugin.</li>';
echo '<li><strong>SigeEventmenuPage:</strong> Function to display the main content of the SIGE Events submenu page.</li>';
echo '<li><strong>dashboardSubmenuPage:</strong> Function to display the content of the Dashboard submenu page.</li>';
echo '<li><strong>availableActivitiesSubmenuPage:</strong> Function to display and manage available activities in the Available Activities submenu page.</li>';
echo '<li><strong>enrollmentSubmenuPage:</strong> Function to display and manage enrollments in the Enrollments submenu page.</li>';
echo '<li><strong>emailSettingsSubmenuPage:</strong> Function to manage email settings in the Email Settings submenu page.</li>';
echo '<li><strong>attendanceControlSubmenuPage:</strong> Function to manage attendance control in the Attendance Control submenu page.</li>';
echo '<li><strong>export_activities_to_csv:</strong> Function to export activities to a CSV file.</li>';
echo '<li><strong>enqueue_datatables_assets_admin:</strong> Function to enqueue DataTables assets for enhanced table interactions in the admin area.</li>';
echo '<li><strong>frontendDisplayOpenActivities:</strong> Shortcode function to display open activities on the frontend. Usage: <code>[open_activities]</code></li>';
echo '<li><strong>frontendEnrollmentControl:</strong> Shortcode function to display enrollments on the frontend. Usage: <code>[enrollments]</code></li>';
echo '<li><strong>frontendAttendanceControl:</strong> Shortcode function to display attendance control on the frontend. Usage: <code>[frontend_attendance_control]</code></li>';
echo '<li><strong>displayMainOptions:</strong> Function to display the Main Options tab in the Settings submenu page.</li>';
echo '<li><strong>displayDashboardOptions:</strong> Function to display the Dashboard Options tab in the Settings submenu page.</li>';
echo '<li><strong>displayActivityOptions:</strong> Function to display and manage activity-related options in the Activity Options tab in the Settings submenu page.</li>';
echo '<li><strong>displayEnrollmentOptions:</strong> Function to display and manage enrollment-related options in the Enrollment Options tab in the Settings submenu page.</li>';
echo '<li><strong>displayEmailOptions:</strong> Function to display the Email Options tab in the Settings submenu page.</li>';
echo '<li><strong>displayMiscellaneous:</strong> Function to display the Miscellaneous tab in the Settings submenu page.</li>';
echo '<li><strong>settingsSubmenuPage:</strong> Function to display the content of the Settings submenu page and handle tab navigation.</li>';
echo '</ul>';
echo '</div>'; // End Available Functions Section
echo '</div>';
}
// Add this CSS to your plugin to apply the styles
function sige_events_admin_styles() {
echo '<style>
.sige-box {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background: #f9f9f9;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
margin-bottom: 20px;
}
</style>';
}
add_action('admin_head', 'sige_events_admin_styles');
function dashboardSubmenuPage() {
echo '<div class="wrap"><h2>Dashboard</h2><p>Content for the Dashboard submenu page.</p></div>';
}
function availableActivitiesSubmenuPage() {
global $wpdb;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['new_activity'])) {
$name = sanitize_text_field($_POST['activity_name']);
$description = sanitize_textarea_field($_POST['activity_description']);
$start_date = sanitize_text_field($_POST['start_date']);
$start_time = sanitize_text_field($_POST['start_time']);
$end_date = sanitize_text_field($_POST['end_date']);
$end_time = sanitize_text_field($_POST['end_time']);
$type = sanitize_text_field($_POST['activity_type']);
$modality = sanitize_text_field($_POST['activity_modality']);
$status = sanitize_text_field($_POST['activity_status']);
$curriculum = esc_url_raw($_POST['curriculum']);
$comment = sanitize_textarea_field($_POST['comment']);
$place_id = intval($_POST['place']);
$speaker_id = intval($_POST['speaker']);
$event_name_id = intval($_POST['event_name']);
$security_credential = sanitize_text_field($_POST['security_credential']);
$chair = sanitize_text_field($_POST['chair']);
$target_audience = sanitize_text_field($_POST['target_audience']);
$attendance_control = sanitize_text_field($_POST['attendance_control']);
if (strtotime($end_date) < strtotime($start_date)) {
echo '<div class="notice notice-error"><p>The end date cannot be before the start date.</p></div>';
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_activities",
[
'name' => $name,
'description' => $description,
'start_date' => $start_date,
'start_time' => $start_time,
'end_date' => $end_date,
'end_time' => $end_time,
'type' => $type,
'modality' => $modality,
'status' => $status,
'curriculum' => $curriculum,
'comment' => $comment,
'place_id' => $place_id,
'speaker_id' => $speaker_id,
'event_name_id' => $event_name_id,
'security_credential' => $security_credential,
'chair' => $chair,
'target_audience' => $target_audience,
'attendance_control' => $attendance_control
]
);
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_activity'])) {
$id = intval($_POST['activity_id']);
$name = sanitize_text_field($_POST['activity_name']);
$description = sanitize_textarea_field($_POST['activity_description']);
$start_date = sanitize_text_field($_POST['start_date']);
$start_time = sanitize_text_field($_POST['start_time']);
$end_date = sanitize_text_field($_POST['end_date']);
$end_time = sanitize_text_field($_POST['end_time']);
$type = sanitize_text_field($_POST['activity_type']);
$modality = sanitize_text_field($_POST['activity_modality']);
$status = sanitize_text_field($_POST['activity_status']);
$curriculum = esc_url_raw($_POST['curriculum']);
$comment = sanitize_textarea_field($_POST['comment']);
$place_id = intval($_POST['place']);
$speaker_id = intval($_POST['speaker']);
$event_name_id = intval($_POST['event_name']);
$security_credential = sanitize_text_field($_POST['security_credential']);
$chair = sanitize_text_field($_POST['chair']);
$target_audience = sanitize_text_field($_POST['target_audience']);
$attendance_control = sanitize_text_field($_POST['attendance_control']);
if (strtotime($end_date) < strtotime($start_date)) {
echo '<div class="notice notice-error"><p>The end date cannot be before the start date.</p></div>';
} else {
$wpdb->update(
"{$wpdb->prefix}sige_activities",
[
'name' => $name,
'description' => $description,
'start_date' => $start_date,
'start_time' => $start_time,
'end_date' => $end_date,
'end_time' => $end_time,
'type' => $type,
'modality' => $modality,
'status' => $status,
'curriculum' => $curriculum,
'comment' => $comment,
'place_id' => $place_id,
'speaker_id' => $speaker_id,
'event_name_id' => $event_name_id,
'security_credential' => $security_credential,
'chair' => $chair,
'target_audience' => $target_audience,
'attendance_control' => $attendance_control
],
['id' => $id]
);
$redirect_url = admin_url('admin.php?page=available-activities-submenu');
echo '<script>window.location.href="' . $redirect_url . '";</script>';
exit;
}
}
if (isset($_GET['delete_activity'])) {
$id = intval($_GET['delete_activity']);
$wpdb->delete("{$wpdb->prefix}sige_activities", ['id' => $id]);
}
$edit_activity = null;
if (isset($_GET['edit_activity'])) {
$edit_id = intval($_GET['edit_activity']);
$edit_activity = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}sige_activities WHERE id = $edit_id");
}
$places = $wpdb->get_results("SELECT id, place FROM {$wpdb->prefix}sige_place");
$speakers = $wpdb->get_results("SELECT id, full_name FROM {$wpdb->prefix}sige_speakers");
$event_names = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}sige_event_names");
echo '<div class="wrap"><h2>Available Activities</h2>
<form method="post" style="box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; padding: 20px; border-radius: 8px;">
<style>
.sige-activity-form th,
.sige-activity-form td {
padding: 10px 5px;
vertical-align: bottom;
}
.sige-activity-form th {
text-align: left;
padding-right: 10px;
}
.sige-activity-form td {
width: 50%;
}
.sige-activity-form input[type="text"],
.sige-activity-form input[type="date"],
.sige-activity-form input[type="time"],
.sige-activity-form select,
.sige-activity-form textarea {
width: 100%;
box-sizing: border-box;
}
.sige-activity-form select[name="activity_type"],
.sige-activity-form select[name="activity_modality"],
.sige-activity-form select[name="activity_status"] {
max-width: none;
}
.sige-activity-form .full-width {
width: 100%;
}
.button-edit,
.button-delete {
width: 70px; /* Adjust this to your desired width */
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
const startDate = document.querySelector("input[name=\'start_date\']");
const endDate = document.querySelector("input[name=\'end_date\']");
startDate.addEventListener("focus", function() {
const today = new Date().toISOString().split("T")[0];
if (startDate.value ==="") {
startDate.value = today;
}
});
endDate.addEventListener("focus", function() {
if (endDate.value ==="") {
endDate.value = startDate.value;
}
});
startDate.addEventListener("change", function() {
if (endDate.value < startDate.value || endDate.value ==="") {
endDate.value = startDate.value;
}
});
document.querySelector("form").addEventListener("submit", function(event) {
if (new Date(endDate.value) < new Date(startDate.value)) {
event.preventDefault();
alert("The end date cannot be before the start date.");
}
});
});
</script>';
if ($edit_activity) {
echo '<input type="hidden" name="activity_id" value="' . esc_attr($edit_activity->id) . '" />';
echo '<input type="hidden" name="update_activity" value="1" />';
} else {
echo '<input type="hidden" name="new_activity" value="1" />';
}
echo '
<table class="form-table sige-activity-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Activity Name</th>
<td><input type="text" name="activity_name" value="' . ($edit_activity ? esc_attr($edit_activity->name) : '') . '" required /></td>
<th scope="row">Activity Description</th>
<td><textarea rows="1" name="activity_description" required>' . ($edit_activity ? esc_textarea($edit_activity->description) : '') . '</textarea></td>
</tr>
<tr valign="top">
<th scope="row">Start Date</th>
<td><input type="date" name="start_date" value="' . ($edit_activity ? esc_attr($edit_activity->start_date) : '') . '" required /></td>
<th scope="row">Start Time</th>
<td><input type="time" name="start_time" value="' . ($edit_activity ? esc_attr($edit_activity->start_time) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">End Date</th>
<td><input type="date" name="end_date" value="' . ($edit_activity ? esc_attr($edit_activity->end_date) : '') . '" required /></td>
<th scope="row">End Time</th>
<td><input type="time" name="end_time" value="' . ($edit_activity ? esc_attr($edit_activity->end_time) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">Activity Type</th>
<td>
<select name="activity_type" required>
<option value="Presentation"' . ($edit_activity && $edit_activity->type == 'Presentation' ? ' selected' : '') . '>Presentation</option>
<option value="Short-course"' . ($edit_activity && $edit_activity->type == 'Short-course' ? ' selected' : '') . '>Short-course</option>
<option value="Lecture"' . ($edit_activity && $edit_activity->type == 'Lecture' ? ' selected' : '') . '>Lecture</option>
<option value="Workshop"' . ($edit_activity && $edit_activity->type == 'Workshop' ? ' selected' : '') . '>Workshop</option>
<option value="Others"' . ($edit_activity && $edit_activity->type == 'Others' ? ' selected' : '') . '>Others</option>
</select>
</td>
<th scope="row">Activity Modality</th>
<td>
<select name="activity_modality" required>
<option value="Online"' . ($edit_activity && $edit_activity->modality == 'Online' ? ' selected' : '') . '>Online</option>
<option value="In-person"' . ($edit_activity && $edit_activity->modality == 'In-person' ? ' selected' : '') . '>In-person</option>
<option value="Hybrid"' . ($edit_activity && $edit_activity->modality == 'Hybrid' ? ' selected' : '') . '>Hybrid</option>
<option value="Others"' . ($edit_activity && $edit_activity->modality == 'Others' ? ' selected' : '') . '>Others</option>
</select>
</td>
</tr>
<tr valign="top">
<th scope="row">Subscription Status</th>
<td>
<select name="activity_status" required>
<option value="Open"' . ($edit_activity && $edit_activity->status == 'Open' ? ' selected' : '') . '>Open</option>
<option value="Closed"' . ($edit_activity && $edit_activity->status == 'Closed' ? ' selected' : '') . '>Closed</option>
<option value="Not applicable"' . ($edit_activity && $edit_activity->status == 'Not applicable' ? ' selected' : '') . '>Not applicable</option>
</select>
</td>
<th scope="row">Place</th>
<td>
<select name="place" required>';
foreach ($places as $place) {
echo '<option value="' . esc_attr($place->id) . '"' . ($edit_activity && $edit_activity->place_id == $place->id ? ' selected' : '') . '>' . esc_html($place->place) . '</option>';
}
echo ' </select>
</td>
</tr>
<tr valign="top">
<th scope="row">Speaker</th>
<td>
<select name="speaker" required>';
foreach ($speakers as $speaker) {
echo '<option value="' . esc_attr($speaker->id) . '"' . ($edit_activity && $edit_activity->speaker_id == $speaker->id ? ' selected' : '') . '>' . esc_html($speaker->full_name) . '</option>';
}
echo ' </select>
</td>
<th scope="row">Event Name</th>
<td>
<select name="event_name" required>';
foreach ($event_names as $event_name) {
echo '<option value="' . esc_attr($event_name->id) . '"' . ($edit_activity && $edit_activity->event_name_id == $event_name->id ? ' selected' : '') . '>' . esc_html($event_name->name) . '</option>';
}
echo ' </select>
</td>
</tr>
<tr valign="top">
<th scope="row">Chair</th>
<td><input type="text" name="chair" value="' . ($edit_activity ? esc_attr($edit_activity->chair) : '') . '" required /></td>
<th scope="row">Curriculum</th>
<td><input type="url" name="curriculum" class="full-width" placeholder="https://curriculumsite.yourdomain.country" value="' . ($edit_activity ? esc_url($edit_activity->curriculum) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">Security Credential</th>
<td>
<select name="security_credential" required>
<option value="Required"' . ($edit_activity && $edit_activity->security_credential == 'Required' ? ' selected' : '') . '>Required</option>
<option value="Not Required"' . ($edit_activity && $edit_activity->security_credential == 'Not Required' ? ' selected' : '') . '>Not Required</option>
</select>
</td>
<th scope="row">Target Audience</th>
<td>
<select name="target_audience" required>
<option value="Military"' . ($edit_activity && $edit_activity->target_audience == 'Military' ? ' selected' : '') . '>Military</option>
<option value="Civilian"' . ($edit_activity && $edit_activity->target_audience == 'Civilian' ? ' selected' : '') . '>Civilian</option>
<option value="Military and Civilian"' . ($edit_activity && $edit_activity->target_audience == 'Military and Civilian' ? ' selected' : '') . '>Military and Civilian</option>
</select>
</td>
</tr>
<tr valign="top">
<th scope="row">Attendance Control</th>
<td>
<select name="attendance_control" required>
<option value="yes"' . ($edit_activity && $edit_activity->attendance_control == 'yes' ? ' selected' : '') . '>Yes</option>
<option value="no"' . ($edit_activity && $edit_activity->attendance_control == 'no' ? ' selected' : '') . '>No</option>
</select>
</td>
<th scope="row">Comment</th>
<td colspan="3"><textarea rows="1" textarea name="comment" required>' . ($edit_activity ? esc_textarea($edit_activity->comment) : '') . '</textarea></td>
</tr>
</table>
<input type="submit" name="' . ($edit_activity ? 'update_activity' : 'new_activity') . '" value="' . ($edit_activity ? 'Update Activity' : 'Add Activity') . '" class="button button-primary" />
</form></div>';
$activities = $wpdb->get_results("
SELECT a.*, p.place, s.full_name as speaker, e.name as event_name
FROM {$wpdb->prefix}sige_activities a
LEFT JOIN {$wpdb->prefix}sige_place p ON a.place_id = p.id
LEFT JOIN {$wpdb->prefix}sige_speakers s ON a.speaker_id = s.id
LEFT JOIN {$wpdb->prefix}sige_event_names e ON a.event_name_id = e.id
");
if ($activities) {
$types = ['Presentation', 'Short-course', 'Lecture', 'Workshop', 'Others'];
$modalities = ['Online', 'In-person', 'Hybrid', 'Others'];
$statuses = ['Open', 'Closed', 'Not applicable'];
if ($activities) {
echo '<form method="post" action="">
<input type="hidden" name="export_activities_csv" value="1" />
<input type="submit" value="Export to CSV" class="button button-secondary" />
</form>';
}
echo '<h3>Existing Activities</h3>';
echo '<div style="max-width: 100%; overflow-x: auto; padding-right: 20px;">';
echo '<table id="activities-table" class="display" style="width: 100%; min-width: 1000px;">
<thead>
<tr>
<th style="width: 100px;">Activity Name</th>
<th style="min-width: 200px;">Activity Description</th>
<th style="width: 70px;">Start Date</th>
<th style="width: 70px;">Start Time</th>
<th style="width: 70px;">End Date</th>
<th style="width: 70px;">End Time</th>
<th style="width: 70px;">Type</th>
<th style="width: 90px;">Modality</th>
<th style="width: 70px;">Status</th>
<th style="width: 100px;">Place</th>
<th style="width: 100px;">Speaker</th>
<th style="width: 70px;">Event Name</th>
<th style="width: 80px;">Chair</th>
<th style="min-width: 100px;">Curriculum</th>
<th style="min-width: 100px;">Security Credential</th>
<th style="min-width: 100px;">Target Audience</th>
<th style="min-width: 100px;">Attendance Control</th>
<th style="min-width: 200px;">Comment</th>
<th style="width: 70px;"></th>
<th style="width: 70px;"></th>
</tr>
</thead>
<tbody>';
foreach ($activities as $activity) {
echo '<tr>
<td>' . esc_html($activity->name) . '</td>
<td>' . esc_html($activity->description) . '</td>
<td>' . esc_html($activity->start_date) . '</td>
<td>' . esc_html($activity->start_time) . '</td>
<td>' . esc_html($activity->end_date) . '</td>
<td>' . esc_html($activity->end_time) . '</td>
<td>' . esc_html($activity->type) . '</td>
<td>' . esc_html($activity->modality) . '</td>
<td>' . esc_html($activity->status) . '</td>
<td>' . esc_html($activity->place) . '</td>
<td>' . esc_html($activity->speaker) . '</td>
<td>' . esc_html($activity->event_name) . '</td>
<td>' . esc_html($activity->chair) . '</td>
<td>' . esc_html($activity->curriculum) . '</td>
<td>' . esc_html($activity->security_credential) . '</td>
<td>' . esc_html($activity->target_audience) . '</td>
<td>' . esc_html($activity->attendance_control) . '</td>
<td>' . esc_html($activity->comment) . '</td>
<td><a href="' . admin_url('admin.php?page=available-activities-submenu&edit_activity=' . $activity->id) . '" class="button button-edit">Edit</a></td>
<td><a href="' . admin_url('admin.php?page=available-activities-submenu&delete_activity=' . $activity->id) . '" class="button button-delete" onclick="return confirm(\'Are you sure you want to delete this activity?\')">Delete</a></td>
</tr>';
}
echo '</tbody>
</table>
</div>';
echo '<script>
jQuery(document).ready(function($) {
$("#activities-table").DataTable({
"pagingType": "full_numbers",
"lengthMenu": [10, 25, 50, 100],
"pageLength": 10,
"language": {
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"lengthMenu": "Show _MENU_ entries"
}
});
});
</script>';
}
}
function enrollmentSubmenuPage() {
global $wpdb;
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
// Define the additional meta keys
$additional_meta_keys = [
'forca',
'full_name',
'posto',
'militar',
'instituição',
'nacionalidade',
'efetivo_dcta',
'cidade',
'estado',
'areaatividadeprincipal',
'setordeatuacao',
'cargofuncao',
'ehativa',
'circulo_hierárquico',
'pais',
'formacao_academica',
'regiao_do_brasil'
];
// Handle saving additional features selection
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['additional_features'])) {
$selected_meta_keys = array_intersect($additional_meta_keys, $_POST['additional_features']);
update_user_meta($user_id, 'selected_additional_features', $selected_meta_keys);
} else {
$selected_meta_keys = get_user_meta($user_id, 'selected_additional_features', true);
if (!$selected_meta_keys) {
$selected_meta_keys = [];
}
}
// Handle status update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['apply_status']) && isset($_POST['selected_enrollments'])) {
$new_status = sanitize_text_field($_POST['new_status']);
$selected_enrollments = array_map('intval', $_POST['selected_enrollments']);
if (!empty($selected_enrollments)) {
foreach ($selected_enrollments as $enrollment_id) {
$updated = $wpdb->update(
"{$wpdb->prefix}sige_enrollments",
['status' => $new_status],
['id' => $enrollment_id]
);
if ($updated === false) {
echo '<div class="notice notice-error"><p>Error updating enrollment ID ' . $enrollment_id . '.</p></div>';
}
}
echo '<div class="notice notice-success"><p>Enrollment status updated successfully.</p></div>';
} else {
echo '<div class="notice notice-error"><p>Please select at least one enrollment.</p></div>';
}
}
// Fetch enrollments with additional meta data if selected
$meta_selects = '';
$meta_joins = '';
foreach ($selected_meta_keys as $meta_key) {
$meta_selects .= ", um_$meta_key.meta_value as $meta_key";
$meta_joins .= " LEFT JOIN {$wpdb->prefix}usermeta um_$meta_key ON um_$meta_key.user_id = u.ID AND um_$meta_key.meta_key = '$meta_key'";
}
$query = "
SELECT e.*, a.name as activity_name, u.user_email $meta_selects
FROM {$wpdb->prefix}sige_enrollments e
LEFT JOIN {$wpdb->prefix}sige_activities a ON e.activity_id = a.id
LEFT JOIN {$wpdb->prefix}users u ON e.user_id = u.ID
$meta_joins
";
$enrollments = $wpdb->get_results($query);
// Display additional features form
echo '<h3>Additional Features</h3>';
echo '<button id="toggle-features" class="button button-secondary">Expand Features</button>';
echo '<div id="features-container" style="display: none; width: 100%; margin-top: 20px;">';
echo '<form method="post" action="" style="width: 100%;">';
foreach ($additional_meta_keys as $meta_key) {
$checked = in_array($meta_key, $selected_meta_keys) ? 'checked' : '';
echo '<label style="display: block; margin-bottom: 10px;"><input type="checkbox" name="additional_features[]" value="' . $meta_key . '" ' . $checked . '> ' . ucfirst(str_replace('_', ' ', $meta_key)) . '</label>';
}
echo '<input type="submit" value="Apply" class="button button-primary" style="margin-top: 20px;">';
echo '</form>';
echo '</div>';
// Display the enrollments table
echo '<h3>Existing Enrollments</h3>';
echo '<div style="padding-right: 20px;">';
echo '<form method="post" action="">';
echo '<input type="hidden" id="selected-meta-keys" value="' . esc_attr(json_encode(array_values($selected_meta_keys))) . '">';
echo '<button id="export-csv" class="button button-secondary" style="margin-bottom: 20px;">Export to CSV</button>';
echo '<table id="enrollments-table" class="display">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="select_all"> Select All</th>
<th>Activity Name</th>
<th>User Email</th>
<th>Enrollment Date</th>
<th>Status</th>';
foreach ($selected_meta_keys as $meta_key) {
echo '<th>' . ucfirst(str_replace('_', ' ', $meta_key)) . '</th>';
}
echo '</tr></thead><tbody>';
if ($enrollments) {
foreach ($enrollments as $enrollment) {
$row_style = '';
$checkbox_disabled = '';
if ($enrollment->status == 'Enrollment Canceled by User') {
$row_style = 'style="background-color: #f38d8d;"';
$checkbox_disabled = 'disabled';
} elseif ($enrollment->status == 'Waiting List') {
$row_style = 'style="background-color: #e3db69;"';
} elseif ($enrollment->status == 'Approved') {
$row_style = 'style="background-color: green;"';
} elseif ($enrollment->status == 'Not Approved') {
$row_style = 'style="background-color: #bc97cd;"';
} elseif ($enrollment->status == 'Under Analysis') {
$row_style = 'style="background-color: #5ecac7;"';
}
$formatted_date = date('d-m-Y', strtotime($enrollment->enrollment_date));
echo "<tr $row_style>
<td style='text-align: center;'><input type='checkbox' name='selected_enrollments[]' value='{$enrollment->id}' $checkbox_disabled></td>
<td style='font-weight: bold;'>{$enrollment->activity_name}</td>
<td style='font-weight: bold;'>{$enrollment->user_email}</td>
<td style='font-weight: bold;'>$formatted_date</td>
<td style='font-weight: bold;'>{$enrollment->status}</td>";
foreach ($selected_meta_keys as $meta_key) {
echo '<td style="font-weight: bold;">' . esc_html($enrollment->$meta_key) . '</td>';
}
echo '</tr>';
}
} else {
echo '<tr><td colspan="5" style="text-align: center; font-weight: bold;">No enrollments found</td></tr>';
}
echo '</tbody></table>';
if ($enrollments) {
echo '<div style="margin-top: 20px;">
<select name="new_status" required>
<option value="Waiting List">Waiting List</option>
<option value="Not Approved">Not Approved</option>
<option value="Approved">Approved</option>
</select>
<input type="submit" name="apply_status" value="Apply" class="button button-primary">';
echo '</div>';
}
echo '</form>';
echo '</div>';
// Add the color legend
echo '<div style="margin-top: 20px; display: flex; align-items: center;">
<h3 style="margin-right: 20px;">Legend:</h3>';
echo '<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<span style="background-color: #f38d8d; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Enrollment Canceled by User</span>
<span style="background-color: #e3db69; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Waiting List</span>
<span style="background-color: green; padding: 5px; border-radius: 3px; color: white; width: 150px; text-align: center;">Approved</span>
<span style="background-color: #bc97cd; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Not Approved</span>
<span style="background-color: #5ecac7; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Under Analysis</span>
</div></div>';
echo '<script>
jQuery(document).ready(function($) {
$("#enrollments-table").DataTable();
$("#select_all").click(function() {
$("input[type=checkbox]").prop("checked", this.checked);
});
$("#toggle-features").click(function() {
$("#features-container").slideToggle();
$(this).text(function(i, text){
return text === "Expand Features" ? "Collapse Features" : "Expand Features";
});
});
$("#export-csv").click(function(e) {
e.preventDefault();
const selectedMetaKeys = JSON.parse($("#selected-meta-keys").val());
const now = new Date();
const formattedDate = `${("0" + now.getDate()).slice(-2)}_${("0" + (now.getMonth() + 1)).slice(-2)}_${now.getFullYear()}_${("0" + now.getHours()).slice(-2)}_${("0" + now.getMinutes()).slice(-2)}_${("0" + now.getSeconds()).slice(-2)}`;
const filename = `enrollments_${formattedDate}.csv`;
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Activity Name,User Email,Enrollment Date,Status";
// Add selected meta keys to CSV header
if (selectedMetaKeys.length > 0) {
selectedMetaKeys.forEach(function(metaKey) {
csvContent += "," + metaKey.charAt(0).toUpperCase() + metaKey.slice(1).replace(/_/g, " ");
});
}
csvContent += "\n";
$("#enrollments-table tbody tr").each(function() {
const row = $(this);
const activityName = row.find("td:nth-child(2)").text().trim();
const userEmail = row.find("td:nth-child(3)").text().trim();
const enrollmentDate = row.find("td:nth-child(4)").text().trim();
const status = row.find("td:nth-child(5)").text().trim();
let rowData = `${activityName},${userEmail},${enrollmentDate},${status}`;
if (selectedMetaKeys.length > 0) {
selectedMetaKeys.forEach(function(metaKey, index) {
rowData += "," + row.find("td:nth-child(" + (6 + index) + ")").text().trim();
});
}
csvContent += rowData + "\n";
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
</script>';
}
// Function to display Email Options content
function emailSettingsSubmenuPage() {
global $wpdb;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_email_settings'])) {
$id = intval($_POST['id']);
$email_sender = sanitize_email($_POST['email_sender']);
$email_subject = sanitize_text_field($_POST['email_subject']);
$email_message = wp_kses_post($_POST['email_message']); // Use wp_kses_post to allow basic HTML
$wpdb->update(
"{$wpdb->prefix}sige_email_messages",
[
'email_sender' => $email_sender,
'email_subject' => $email_subject,
'email_message' => $email_message
],
['id' => $id]
);
echo '<div class="notice notice-success"><p>Email settings saved successfully.</p></div>';
}
$email_messages = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_email_messages", ARRAY_A);
$status_actions = array_column($email_messages, 'status_action', 'id');
echo '<div class="wrap"><h2>Email Settings</h2><form method="post" id="email_settings_form"><table class="form-table">';
echo '<tr valign="top">
<th scope="row">Choose Status Action</th>
<td>
<select name="id" id="status_action_select" required>';
foreach ($status_actions as $id => $status_action) {
echo '<option value="' . esc_attr($id) . '">' . esc_html($status_action) . '</option>';
}
echo ' </select>
</td>
</tr>';
// Default values for the form fields
$default_email_sender = $email_messages[0]['email_sender'];
$default_email_subject = $email_messages[0]['email_subject'];
$default_email_message = $email_messages[0]['email_message'];
echo '<tr valign="top">
<th scope="row">Email Sender</th>
<td><input type="email" name="email_sender" id="email_sender" value="' . esc_attr($default_email_sender) . '" style="width: 100%;" required /></td>
</tr>
<tr valign="top">
<th scope="row">Email Subject</th>
<td><input type="text" name="email_subject" id="email_subject" value="' . esc_attr($default_email_subject) . '" style="width: 100%;" required /></td>
</tr>
<tr valign="top">
<th scope="row">Email Message</th>
<td><textarea name="email_message" id="email_message" rows="15" style="width: 100%;" required>' . wp_kses_post($default_email_message) . '</textarea></td>
</tr>
</table><input type="submit" name="save_email_settings" value="Save Settings" class="button button-primary" /></form></div>';
echo '<script>
document.addEventListener("DOMContentLoaded", function() {
const emailMessages = ' . json_encode($email_messages) . ';
const selectElement = document.getElementById("status_action_select");
const emailSenderInput = document.getElementById("email_sender");
const emailSubjectInput = document.getElementById("email_subject");
const emailMessageTextarea = document.getElementById("email_message");
selectElement.addEventListener("change", function() {
const selectedId = this.value;
const selectedMessage = emailMessages.find(message => message.id == selectedId);
if (selectedMessage) {
emailSenderInput.value = selectedMessage.email_sender;
emailSubjectInput.value = selectedMessage.email_subject;
emailMessageTextarea.value = selectedMessage.email_message;
tinymce.get("email_message").setContent(selectedMessage.email_message); // Set TinyMCE content
}
});
tinymce.init({
selector: "#email_message",
height: 300,
menubar: false,
plugins: "lists link image charmap textcolor colorpicker",
toolbar: "undo redo | formatselect | bold italic underline backcolor forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat",
content_css: "//www.tiny.cloud/css/codepen.min.css"
});
});
</script>';
}
function export_activities_to_csv() {
if (isset($_POST['export_activities_csv'])) {
global $wpdb;
$activities = $wpdb->get_results("
SELECT a.*, p.place, s.full_name as speaker, e.name as event_name
FROM {$wpdb->prefix}sige_activities a
LEFT JOIN {$wpdb->prefix}sige_place p ON a.place_id = p.id
LEFT JOIN {$wpdb->prefix}sige_speakers s ON a.speaker_id = s.id
LEFT JOIN {$wpdb->prefix}sige_event_names e ON a.event_name_id = e.id
");
if ($activities) {
$filename = "activities_" . date('Ymd_His') . ".csv";
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=' . $filename);
$output = fopen('php://output', 'w');
// Set the column headers
fputcsv($output, array(
'Activity Name', 'Description', 'Start Date', 'Start Time', 'End Date', 'End Time',
'Type', 'Modality', 'Status', 'Speaker', 'Curriculum', 'Place', 'Event Name',
'Security Credential', 'Chair', 'Target Audience'
));
// Output each row of the data
foreach ($activities as $activity) {
fputcsv($output, array(
$activity->name,
$activity->description,
$activity->start_date,
$activity->start_time,
$activity->end_date,
$activity->end_time,
$activity->type,
$activity->modality,
$activity->status,
$activity->speaker,
$activity->curriculum,
$activity->place,
$activity->event_name,
$activity->security_credential,
$activity->chair,
$activity->target_audience
));
}
fclose($output);
exit;
}
}
}
add_action('admin_init', 'export_activities_to_csv');
function enqueue_jquery_ui() {
wp_enqueue_script('jquery-ui-tabs');
wp_enqueue_style('jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery_ui');
function enqueue_datatables_assets_admin() {
wp_enqueue_script('jquery');
wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js', array('jquery'), null, true);
wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css');
wp_enqueue_script('datatables-fixedcolumns-js', 'https://cdn.datatables.net/fixedcolumns/3.3.3/js/dataTables.fixedColumns.min.js', array('datatables-js'), null, true);
wp_enqueue_style('datatables-fixedcolumns-css', 'https://cdn.datatables.net/fixedcolumns/3.3.3/css/fixedColumns.dataTables.min.css');
}
add_action('admin_enqueue_scripts', 'enqueue_datatables_assets_admin');
function enqueue_datatables_assets_frontend() {
wp_enqueue_script('jquery');
wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js', array('jquery'), null, true);
wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css');
wp_enqueue_script('datatables-fixedcolumns-js', 'https://cdn.datatables.net/fixedcolumns/3.3.3/js/dataTables.fixedColumns.min.js', array('datatables-js'), null, true);
wp_enqueue_style('datatables-fixedcolumns-css', 'https://cdn.datatables.net/fixedcolumns/3.3.3/css/fixedColumns.dataTables.min.css');
}
add_action('wp_enqueue_scripts', 'enqueue_datatables_assets_frontend');
function enqueue_html5_qrcode_script() {
wp_enqueue_script('html5-qrcode', 'https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js', [], null, true);
}
add_action('admin_enqueue_scripts', 'enqueue_html5_qrcode_script');
add_action('wp_enqueue_scripts', 'enqueue_html5_qrcode_script');
function frontendDisplayOpenActivities() {
if (!is_user_logged_in()) {
return '<p>You must be logged in to view the available activities.</p>';
}
global $wpdb;
$current_user_id = get_current_user_id();
// Fetch the required meta keys from wp_sige_meta_keys excluding specific keys
$required_meta_keys = $wpdb->get_col("
SELECT meta_key FROM {$wpdb->prefix}sige_meta_keys
WHERE status = 1 AND meta_key NOT IN ('militar', 'forca', 'posto', 'efetivo_dcta', 'ehativa', 'circulo hierárquico')
");
// Check if all required meta keys are filled
$user_meta = get_user_meta($current_user_id);
$missing_keys = [];
foreach ($required_meta_keys as $meta_key) {
if (empty($user_meta[$meta_key][0])) {
$missing_keys[] = $meta_key;
}
}
// Check if 'militar' meta key is set to '1', if so, check additional meta keys
if (!empty($user_meta['militar'][0]) && $user_meta['militar'][0] == '1') {
$additional_keys = ['forca', 'posto', 'efetivo_dcta', 'ehativa', 'circulo hierárquico'];
foreach ($additional_keys as $key) {
if (empty($user_meta[$key][0])) {
$missing_keys[] = $key;
}
}
}
if (!empty($missing_keys)) {
echo '<div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
<div style="box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; padding: 20px; border-radius: 8px; text-align: center;">
<p>You need to update your profile information to view the available activities. Please make sure all required fields are filled out.</p>
</div>
</div>';
echo '<script>
setTimeout(function() {
window.location.href = "' . home_url() . '";
}, 10000);
</script>';
return '';
}
$current_year = date('Y');
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && isset($_POST['activity_id'])) {
$activity_id = intval($_POST['activity_id']);
$action = sanitize_text_field($_POST['action']);
if ($action == 'request_enrollment') {
$existing_enrollment = $wpdb->get_var($wpdb->prepare("
SELECT id FROM {$wpdb->prefix}sige_enrollments
WHERE activity_id = %d AND user_id = %d
", $activity_id, $current_user_id));
if ($existing_enrollment) {
$wpdb->update(
"{$wpdb->prefix}sige_enrollments",
['status' => 'Under Analysis'],
['id' => $existing_enrollment]
);
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_enrollments",
[
'activity_id' => $activity_id,
'user_id' => $current_user_id,
'enrollment_date' => current_time('mysql'),
'status' => 'Under Analysis'
]
);
}
} elseif ($action == 'cancel_enrollment') {
$reason = isset($_POST['cancel_reason']) ? sanitize_text_field($_POST['cancel_reason']) : '';
if (!empty($reason)) {
$wpdb->insert(
"{$wpdb->prefix}sige_cancellation_record",
[
'activity_id' => $activity_id,
'user_id' => $current_user_id,
'reasons' => $reason,
'date_of_cancelation' => current_time('mysql')
]
);
}
$wpdb->update(
"{$wpdb->prefix}sige_enrollments",
['status' => 'Enrollment Canceled by User'],
[
'activity_id' => $activity_id,
'user_id' => $current_user_id
]
);
}
// Reload the page to show updated status
echo '<script>window.location.href="' . esc_url($_SERVER['REQUEST_URI']) . '";</script>';
exit;
}
$activities = $wpdb->get_results($wpdb->prepare("
SELECT a.*, p.place, s.full_name as speaker, e.name as event_name
FROM {$wpdb->prefix}sige_activities a
LEFT JOIN {$wpdb->prefix}sige_place p ON a.place_id = p.id
LEFT JOIN {$wpdb->prefix}sige_speakers s ON a.speaker_id = s.id
LEFT JOIN {$wpdb->prefix}sige_event_names e ON a.event_name_id = e.id
WHERE (a.status = 'Open' OR a.status = 'Closed')
AND YEAR(a.start_date) = %d
AND a.attendance_control = 'yes'
", $current_year));
if (empty($activities)) {
return '<p>No open activities available for this year.</p>';
}
$display_options = $wpdb->get_results("SELECT field_name, display FROM {$wpdb->prefix}sige_display_options", OBJECT_K);
// CSS for tabbed interface and active tab highlighting
echo '<style>
.tab-container {
display: flex;
flex-direction: column;
}
.tab-links {
display: flex;
margin-bottom: 10px;
}
.tab-links a {
padding: 10px 20px;
text-decoration: none;
background-color: #f1f1f1;
border: 1px solid #ccc;
margin-right: 5px;
border-radius: 4px 4px 0 0;
}
.tab-links a.active {
background-color: #c3c4c7;
color: black;
border-bottom: none;
}
.tab-content {
display: none;
padding: 20px;
background-color: #c3c4c7;
border: 1px solid #ccc;
border-top: none;
border-radius: 0 4px 4px 4px;
}
.tab-content.active {
display: block;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 500px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>';
ob_start();
echo '<div class="tab-container">';
echo '<div class="tab-links">';
$event_names = $wpdb->get_results("SELECT DISTINCT e.name FROM {$wpdb->prefix}sige_event_names e INNER JOIN {$wpdb->prefix}sige_activities a ON e.id = a.event_name_id WHERE a.status IN ('Open', 'Closed')");
foreach ($event_names as $index => $event_name) {
$active_class = $index == 0 ? 'active' : '';
echo '<a href="#tab-' . sanitize_title($event_name->name) . '" class="tab-link ' . $active_class . '">' . esc_html($event_name->name) . '</a>';
}
echo '</div>';
foreach ($event_names as $index => $event_name) {
$active_class = $index == 0 ? 'active' : '';
echo '<div id="tab-' . sanitize_title($event_name->name) . '" class="tab-content ' . $active_class . '">';
$event_activities = array_filter($activities, function($activity) use ($event_name) {
return $activity->event_name == $event_name->name;
});
if (empty($event_activities)) {
echo '<p>No open activities available for this event.</p>';
} else {
foreach (['Presentation', 'Short-course', 'Lecture', 'Workshop', 'Others'] as $type_name) {
$grouped_activities = array_filter($event_activities, function($activity) use ($type_name) {
return $activity->type == $type_name;
});
if (!empty($grouped_activities)) {
$notice = $wpdb->get_var($wpdb->prepare("SELECT notice FROM {$wpdb->prefix}sige_activity_notices WHERE type = %s", $type_name));
echo '<h2>' . $type_name . '</h2>';
if ($display_options['Notices']->display) {
echo '<h3>Notices</h3>';
echo '<p>' . ($notice ? esc_html($notice) : 'No notice available for this type.') . '</p>';
}
foreach ($grouped_activities as $activity) {
$formatted_start_date = date('d-m-Y', strtotime($activity->start_date));
$formatted_end_date = date('d-m-Y', strtotime($activity->end_date));
$end_date = $activity->end_date == $activity->start_date ? '' : ' to ' . $formatted_end_date;
$enrollment_status_action = $wpdb->get_var($wpdb->prepare("
SELECT status FROM {$wpdb->prefix}sige_enrollments
WHERE activity_id = %d AND user_id = %d
", $activity->id, $current_user_id));
if (!$enrollment_status_action) {
$enrollment_status_action = 'Not Requested';
}
echo '<p><strong>' . esc_html($activity->type) . ':</strong> ' . $activity->name . '</p>';
if ($display_options['Comment']->display) {
echo '<p style="text-align: justify;"><strong>Comment:</strong> ' . esc_html($activity->comment) . '</p>';
}
if ($display_options['Speaker']->display) {
echo '<p><strong>Speaker:</strong> ' . $activity->speaker . '</p>';
}
if ($display_options['Curriculum Vitae']->display) {
echo '<p><strong>Curriculum Vitae:</strong> <a href="' . esc_url($activity->curriculum) . '" target="_blank">' . esc_url($activity->curriculum) . '</a></p>';
}
if ($display_options['Data']->display) {
echo '<p><strong>Data:</strong> ' . esc_html($formatted_start_date) . $end_date . '</p>';
}
if ($display_options['Place']->display) {
echo '<p><strong>Place:</strong> ' . esc_html($activity->place) . '</p>';
}
if ($display_options['Security Credential']->display) {
echo '<p><strong>Security Credential:</strong> ' . esc_html($activity->security_credential) . '</p>';
}
if ($display_options['Target Audience']->display) {
echo '<p><strong>Target Audience:</strong> ' . esc_html($activity->target_audience) . '</p>';
}
if ($display_options['Chair']->display) {
echo '<p><strong>Chair:</strong> ' . esc_html($activity->chair) . '</p>';
}
// Display the activity status
echo '<p><strong>Activity Status:</strong> ' . esc_html($activity->status) . '</p>';
if ($activity->status != 'Not applicable' && $display_options['Enrollment Status']->display) {
$status_style = $wpdb->get_row($wpdb->prepare("
SELECT * FROM {$wpdb->prefix}sige_enrollment_status_style
WHERE status_action = %s
", $enrollment_status_action));
$font_color = $status_style->font_color;
$font_size = $status_style->font_size;
$font_family = $status_style->font_family;
$font_weight = $status_style->font_weight;
$status_label = $status_style->status_label;
echo '<p><strong>Enrollment Status:</strong> <strong style="color: ' . esc_attr($font_color) . '; font-size: ' . esc_attr($font_size) . '; font-family: ' . esc_attr($font_family) . '; font-weight: ' . esc_attr($font_weight) . ';">' . esc_html($status_label) . '</strong></p>';
}
if ($activity->status != 'Closed') {
// Determine button label, action, and style
if ($enrollment_status_action == 'Not Requested' || $enrollment_status_action == 'Enrollment Canceled by User') {
$button_action = 'request_enrollment';
} elseif ($enrollment_status_action == 'Under Analysis' || $enrollment_status_action == 'Waiting List' || $enrollment_status_action == 'Approved') {
$button_action = 'cancel_enrollment';
}
if ($enrollment_status_action != 'Not Approved') {
// Get button styles
$button_style = $wpdb->get_row($wpdb->prepare("
SELECT * FROM {$wpdb->prefix}sige_enrollment_button_style
WHERE button_action = %s
", $button_action));
$button_label = $button_style->button_label;
$button_background_color = $button_style->background_color;
$button_font_size = $button_style->font_size;
$button_font_family = $button_style->font_family;
$button_font_weight = $button_style->font_weight;
echo '<form method="post" action="" onsubmit="return handleFormSubmission(event, this);">
<input type="hidden" name="activity_id" value="' . esc_attr($activity->id) . '">
<button type="submit" name="action" value="' . esc_attr($button_action) . '" class="button button-primary" style="
background-color: ' . esc_attr($button_background_color) . ';
font-size: ' . esc_attr($button_font_size) . ';
font-family: ' . esc_attr($button_font_family) . ';
font-weight: ' . esc_attr($button_font_weight) . ';
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
filter: brightness(1);
">' . esc_html($button_label) . '</button>
</form>';
}
}
echo '<hr style="border: 3px solid black; margin: 20px 0;">';
}
}
}
echo '</div>';
}
}
echo '</div>';
echo '<div id="cancelModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>Cancel Enrollment</h2>
<p>Please provide a reason for cancellation (optional):</p>
<textarea id="cancelReason" placeholder="Reason for cancellation (optional)"></textarea>
<button id="confirmCancel" class="button button-primary">Confirm</button>
</div>
</div>';
echo '<form id="cancelForm" method="post" style="display:none;">
<input type="hidden" name="activity_id" id="cancelActivityId">
<input type="hidden" name="action" value="cancel_enrollment">
<input type="hidden" name="cancel_reason" id="cancelReasonInput">
</form>';
echo '<script>
document.addEventListener("DOMContentLoaded", function() {
const tabs = document.querySelectorAll(".tab-link");
const tabContents = document.querySelectorAll(".tab-content");
tabs.forEach(tab => {
tab.addEventListener("click", function(e) {
e.preventDefault();
tabs.forEach(t => t.classList.remove("active"));
tabContents.forEach(tc => tc.classList.remove("active"));
tab.classList.add("active");
document.querySelector(tab.getAttribute("href")).classList.add("active");
});
});
// Set the initial active tab
const initialActiveTab = document.querySelector(".tab-link.active");
if (initialActiveTab) {
document.querySelector(initialActiveTab.getAttribute("href")).classList.add("active");
}
// Modal functionality
const modal = document.getElementById("cancelModal");
const closeModal = modal.querySelector(".close");
const confirmCancelBtn = modal.querySelector("#confirmCancel");
let currentForm;
window.handleFormSubmission = function(event, form) {
const action = form.querySelector("button[name=\'action\']").value;
if (action === "cancel_enrollment") {
event.preventDefault();
currentForm = form;
modal.style.display = "block";
document.getElementById("cancelActivityId").value = form.querySelector("input[name=\'activity_id\']").value;
return false;
} else {
return true;
}
};
closeModal.onclick = function() {
modal.style.display = "none";
};
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
confirmCancelBtn.onclick = function() {
const reason = document.getElementById("cancelReason").value;
document.getElementById("cancelReasonInput").value = reason;
modal.style.display = "none";
document.getElementById("cancelForm").submit();
};
});
</script>';
return ob_get_clean();
}
add_shortcode('open_activities', 'frontendDisplayOpenActivities');
function displayMainOptions() {
echo '<div class="wrap"><h2>Main Options</h2><p>Content for Main Options tab.</p></div>';
}
function displayDashboardOptions() {
echo '<div class="wrap"><h2>Dashboard Options</h2><p>Content for Dashboard Options tab.</p></div>';
}
function displayActivityOptions() {
global $wpdb;
echo '<div class="wrap"><h2>Activity Options</h2>';
// Wrap all sections in a single div for unified scroll
echo '<div style="overflow-x: auto;">';
// Places Options
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_place'])) {
$place = sanitize_text_field($_POST['place']);
$comments = sanitize_textarea_field($_POST['comments']);
$place_id = isset($_POST['place_id']) ? intval($_POST['place_id']) : 0;
if ($place_id > 0) {
$wpdb->update(
"{$wpdb->prefix}sige_place",
['place' => $place, 'comments' => $comments],
['id' => $place_id]
);
$redirect_url = admin_url('admin.php?page=settings-submenu&tab=activity_options');
echo '<script>window.location.href="' . $redirect_url . '";</script>';
exit;
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_place",
['place' => $place, 'comments' => $comments]
);
}
echo '<div class="notice notice-success"><p>Place saved successfully.</p></div>';
}
if (isset($_GET['edit_place'])) {
$edit_place_id = intval($_GET['edit_place']);
$edit_place = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}sige_place WHERE id = %d", $edit_place_id));
}
if (isset($_GET['delete_place'])) {
$delete_place_id = intval($_GET['delete_place']);
$wpdb->delete("{$wpdb->prefix}sige_place", ['id' => $delete_place_id]);
echo '<div class="notice notice-success"><p>Place deleted successfully.</p></div>';
}
echo '<h3>Places Options</h3>';
echo '<form method="post" style="width: fit-content; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; border-radius: 8px; padding: 20px;">
<style>
.sige-places-form th,
.sige-places-form td {
padding: 10px 5px;
vertical-align: top;
}
.sige-places-form th {
text-align: left;
padding-right: 10px;
}
.sige-places-form td {
width: 100%;
}
.sige-places-form textarea {
width: 100%;
box-sizing: border-box;
}
.actions-cell {
text-align: right;
}
</style>
<table class="form-table sige-places-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Place</th>
<td><input type="text" name="place" value="' . (isset($edit_place) ? esc_attr($edit_place->place) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">Comments</th>
<td><textarea name="comments" required>' . (isset($edit_place) ? esc_textarea($edit_place->comments) : '') . '</textarea></td>
</tr>
</table>';
if (isset($edit_place)) {
echo '<input type="hidden" name="place_id" value="' . esc_attr($edit_place->id) . '" />';
}
echo '<input type="submit" name="save_place" value="' . (isset($edit_place) ? 'Update Place' : 'Save Place') . '" class="button button-primary" />
</form>';
$places = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_place");
if ($places) {
echo '<h3>Existing Places</h3>';
echo '<table id="places-table" class="display" style="width: 100%;">
<thead>
<tr>
<th style="width: 100px;">Place</th>
<th>Comments</th>
<th>Actions</th>
</tr>
</thead>
<tbody>';
foreach ($places as $place) {
echo "<tr>
<td>{$place->place}</td>
<td style='text-align: justify;'>{$place->comments}</td>
<td class='actions-cell'>
<a href='?page=settings-submenu&tab=activity_options&edit_place={$place->id}' class='button button-edit'>Edit</a>
<a href='?page=settings-submenu&tab=activity_options&delete_place={$place->id}' class='button button-delete' onclick='return confirm(\"Are you sure you want to delete this place?\")'>Delete</a>
</td>
</tr>";
}
echo '</tbody></table>';
}
echo '<script>
jQuery(document).ready(function($) {
$("#places-table").DataTable();
});
</script>';
// Add separator line
echo '<hr style="border: 3px solid #000; margin: 20px 0;">';
// Speakers Options
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_speaker'])) {
$research_degree = sanitize_text_field($_POST['research_degree']);
$full_name = sanitize_text_field($_POST['full_name']);
$email = sanitize_email($_POST['email']);
$institution = sanitize_text_field($_POST['institution']);
$speaker_id = isset($_POST['speaker_id']) ? intval($_POST['speaker_id']) : 0;
if ($speaker_id > 0) {
$wpdb->update(
"{$wpdb->prefix}sige_speakers",
[
'research_degree' => $research_degree,
'full_name' => $full_name,
'email' => $email,
'institution' => $institution
],
['id' => $speaker_id]
);
$redirect_url = admin_url('admin.php?page=settings-submenu&tab=activity_options');
echo '<script>window.location.href="' . $redirect_url . '";</script>';
exit;
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_speakers",
[
'research_degree' => $research_degree,
'full_name' => $full_name,
'email' => $email,
'institution' => $institution
]
);
}
echo '<div class="notice notice-success"><p>Speaker saved successfully.</p></div>';
}
if (isset($_GET['edit_speaker'])) {
$edit_speaker_id = intval($_GET['edit_speaker']);
$edit_speaker = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}sige_speakers WHERE id = %d", $edit_speaker_id));
}
if (isset($_GET['delete_speaker'])) {
$delete_speaker_id = intval($_GET['delete_speaker']);
$wpdb->delete("{$wpdb->prefix}sige_speakers", ['id' => $delete_speaker_id]);
echo '<div class="notice notice-success"><p>Speaker deleted successfully.</p></div>';
}
echo '<h3>Register Speakers</h3>';
echo '<form method="post" style="width: fit-content; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; border-radius: 8px; padding: 20px;">
<style>
.sige-speakers-form th,
.sige-speakers-form td {
padding: 10px 5px;
vertical-align: top;
}
.sige-speakers-form th {
text-align: left;
padding-right: 10px;
}
.sige-speakers-form td {
width: 100%;
}
.sige-speakers-form textarea {
width: 100%;
box-sizing: border-box;
}
.actions-cell {
text-align: right;
}
</style>
<table class="form-table sige-speakers-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Research Degree</th>
<td><input type="text" name="research_degree" value="' . (isset($edit_speaker) ? esc_attr($edit_speaker->research_degree) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">Full Name</th>
<td><input type="text" name="full_name" value="' . (isset($edit_speaker) ? esc_attr($edit_speaker->full_name) : '') . '" style="min-width: 500px;" required /></td>
</tr>
<tr valign="top">
<th scope="row">Email</th>
<td><input type="email" name="email" value="' . (isset($edit_speaker) ? esc_attr($edit_speaker->email) : '') . '" placeholder="example@example.com" style="min-width: 500px;" required /></td>
</tr>
<tr valign="top">
<th scope="row">Institution</th>
<td><input type="text" name="institution" value="' . (isset($edit_speaker) ? esc_attr($edit_speaker->institution) : '') . '" style="min-width: 500px;" required /></td>
</tr>
</table>';
if (isset($edit_speaker)) {
echo '<input type="hidden" name="speaker_id" value="' . esc_attr($edit_speaker->id) . '" />';
}
echo '<input type="submit" name="save_speaker" value="' . (isset($edit_speaker) ? 'Update Speaker' : 'Save Speaker') . '" class="button button-primary" />
</form>';
$speakers = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_speakers");
if ($speakers) {
echo '<h3>Existing Speakers</h3>';
echo '<table id="speakers-table" class="display" style="width: 100%;">
<thead>
<tr>
<th style="width: 100px;">Research Degree</th>
<th>Full Name</th>
<th>Email</th>
<th>Institution</th>
<th>Actions</th>
</tr>
</thead>
<tbody>';
foreach ($speakers as $speaker) {
echo "<tr>
<td>{$speaker->research_degree}</td>
<td>{$speaker->full_name}</td>
<td>{$speaker->email}</td>
<td>{$speaker->institution}</td>
<td class='actions-cell'>
<a href='?page=settings-submenu&tab=activity_options&edit_speaker={$speaker->id}' class='button button-edit'>Edit</a>
<a href='?page=settings-submenu&tab=activity_options&delete_speaker={$speaker->id}' class='button button-delete' onclick='return confirm(\"Are you sure you want to delete this speaker?\")'>Delete</a>
</td>
</tr>";
}
echo '</tbody></table>';
}
echo '<script>
jQuery(document).ready(function($) {
$("#speakers-table").DataTable();
});
</script>';
// Add separator line
echo '<hr style="border: 3px solid #000; margin: 20px 0;">';
// Major Event Options
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_major_event'])) {
$acronym = sanitize_text_field($_POST['acronym']);
$name = sanitize_text_field($_POST['name']);
$responsible_for = sanitize_text_field($_POST['responsible_for']);
$major_event_id = isset($_POST['major_event_id']) ? intval($_POST['major_event_id']) : 0;
if ($major_event_id > 0) {
$wpdb->update(
"{$wpdb->prefix}sige_event_names",
[
'acronym' => $acronym,
'name' => $name,
'responsible_for' => $responsible_for
],
['id' => $major_event_id]
);
$redirect_url = admin_url('admin.php?page=settings-submenu&tab=activity_options');
echo '<script>window.location.href="' . $redirect_url . '";</script>';
exit;
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_event_names",
[
'acronym' => $acronym,
'name' => $name,
'responsible_for' => $responsible_for
]
);
}
echo '<div class="notice notice-success"><p>Event Name saved successfully.</p></div>';
}
if (isset($_GET['edit_major_event'])) {
$edit_major_event_id = intval($_GET['edit_major_event']);
$edit_major_event = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}sige_event_names WHERE id = %d", $edit_major_event_id));
}
if (isset($_GET['delete_major_event'])) {
$delete_major_event_id = intval($_GET['delete_major_event']);
$wpdb->delete("{$wpdb->prefix}sige_event_names", ['id' => $delete_major_event_id]);
echo '<div class="notice notice-success"><p>Event Name deleted successfully.</p></div>';
}
echo '<h3>Register Event Name</h3>';
echo '<form method="post" style="width: fit-content; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; border-radius: 8px; padding: 20px;">
<style>
.sige-major-events-form th,
.sige-major-events-form td {
padding: 10px 5px;
vertical-align: top;
}
.sige-major-events-form th {
text-align: left;
padding-right: 10px;
}
.sige-major-events-form td {
width: 100%;
}
.sige-major-events-form textarea {
width: 100%;
box-sizing: border-box;
}
.actions-cell {
text-align: right;
}
</style>
<table class="form-table sige-major-events-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Acronym</th>
<td><input type="text" name="acronym" value="' . (isset($edit_major_event) ? esc_attr($edit_major_event->acronym) : '') . '" required /></td>
</tr>
<tr valign="top">
<th scope="row">Name</th>
<td><input type="text" name="name" value="' . (isset($edit_major_event) ? esc_attr($edit_major_event->name) : '') . '" style="min-width: 500px;" required /></td>
</tr>
<tr valign="top">
<th scope="row">Responsible For</th>
<td><input type="text" name="responsible_for" value="' . (isset($edit_major_event) ? esc_attr($edit_major_event->responsible_for) : '') . '" style="min-width: 500px;" required /></td>
</tr>
</table>';
if (isset($edit_major_event)) {
echo '<input type="hidden" name="major_event_id" value="' . esc_attr($edit_major_event->id) . '" />';
}
echo '<input type="submit" name="save_major_event" value="' . (isset($edit_major_event) ? 'Update Event Name' : 'Save Event Data') . '" class="button button-primary" />
</form>';
$major_events = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_event_names");
if ($major_events) {
echo '<h3>Existing Event Names</h3>';
echo '<table id="major-events-table" class="display" style="width: 100%;">
<thead>
<tr>
<th style="width: 100px;">Acronym</th>
<th>Name</th>
<th>Responsible For</th>
<th>Actions</th>
</tr>
</thead>
<tbody>';
foreach ($major_events as $major_event) {
echo "<tr>
<td>{$major_event->acronym}</td>
<td>{$major_event->name}</td>
<td>{$major_event->responsible_for}</td>
<td class='actions-cell'>
<a href='?page=settings-submenu&tab=activity_options&edit_major_event={$major_event->id}' class='button button-edit'>Edit</a>
<a href='?page=settings-submenu&tab=activity_options&delete_major_event={$major_event->id}' class='button button-delete' onclick='return confirm(\"Are you sure you want to delete this event name?\")'>Delete</a>
</td>
</tr>";
}
echo '</tbody></table>';
}
echo '<script>
jQuery(document).ready(function($) {
$("#major-events-table").DataTable();
});
</script>';
// End of unified div
echo '</div>';
echo '</div>'; // End of Activity Options section
}
function displayEnrollmentOptions() {
global $wpdb;
echo '<div class="wrap"><h2>Enrollment Options</h2>';
// Wrap Display and Notice Options in a single div for unified scroll
echo '<div style="overflow-x: auto;">';
// Display Options
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_display_options'])) {
// Set all display options to 0 first
$wpdb->query("UPDATE {$wpdb->prefix}sige_display_options SET display = 0");
// Update only the checked options to 1
if (!empty($_POST['display_options'])) {
foreach ($_POST['display_options'] as $field_name => $display) {
$wpdb->update(
"{$wpdb->prefix}sige_display_options",
['display' => intval($display)],
['field_name' => sanitize_text_field($field_name)]
);
}
}
echo '<div class="notice notice-success"><p>Display options saved successfully.</p></div>';
}
$display_options = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_display_options");
echo '<h3>Display Options</h3>';
echo '<form method="post" style="width: fit-content;">
<style>
.display-options-container {
display: flex;
flex-direction: column; /* Align checkboxes vertically */
flex-wrap: wrap;
}
.display-options-container p {
padding: 5px;
margin: 0; /* Adjust margin to align properly */
}
</style>
<table class="form-table">
<tr valign="top">
<th scope="row">Display Options</th>
<td>
<div class="display-options-container">';
foreach ($display_options as $option) {
echo '<p>
<label>
<input type="checkbox" name="display_options[' . esc_attr($option->field_name) . ']" value="1"' . checked($option->display, 1, false) . '>
' . esc_html($option->field_name) . '
</label>
</p>';
}
echo ' </div>
</td>
</tr>
</table>
<input type="submit" name="save_display_options" value="Save Display Options" class="button button-primary" />
</form>';
// Add separator line
echo '<hr style="border: 3px solid #000; margin: 20px 0;">';
echo '<div style="display: flex; flex-direction: row; gap: 20px;">';
// Button Style Section
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_button_style'])) {
$selected_button_action = sanitize_text_field($_POST['button_action']);
$button_styles = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_enrollment_button_style", ARRAY_A);
foreach ($button_styles as $style) {
$button_action = $style['button_action'];
$button_label = sanitize_text_field($_POST['button_label'][$button_action]);
$background_color = sanitize_text_field($_POST['background_color'][$button_action]);
$font_size = sanitize_text_field($_POST['font_size'][$button_action]);
$font_family = str_replace('"', '', sanitize_text_field($_POST['font_family'][$button_action]));
$font_weight = sanitize_text_field($_POST['font_weight'][$button_action]);
$wpdb->update(
"{$wpdb->prefix}sige_enrollment_button_style",
[
'button_label' => $button_label,
'background_color' => $background_color,
'font_size' => $font_size,
'font_family' => $font_family,
'font_weight' => $font_weight
],
['button_action' => $button_action]
);
}
echo '<div class="notice notice-success"><p>Button styles saved successfully.</p></div>';
}
$button_styles = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_enrollment_button_style", ARRAY_A);
$selected_button_action = isset($_POST['button_action']) ? sanitize_text_field($_POST['button_action']) : $button_styles[0]['button_action'];
$font_families = [
'Arial, sans-serif' => 'Arial',
'Georgia, serif' => 'Georgia',
'Times New Roman, serif' => 'Times New Roman',
'Courier New, monospace' => 'Courier New',
'Tahoma, sans-serif' => 'Tahoma',
'Verdana, sans-serif' => 'Verdana',
'Lucida Sans, sans-serif' => 'Lucida Sans',
'Impact, sans-serif' => 'Impact',
'Calibri, sans-serif' => 'Calibri',
'Garamond, serif' => 'Garamond',
'Comic Sans MS, cursive, sans-serif' => 'Comic Sans MS',
'Trebuchet MS, sans-serif' => 'Trebuchet MS',
'Arial Black, sans-serif' => 'Arial Black',
'Palatino, serif' => 'Palatino',
'Gill Sans, sans-serif' => 'Gill Sans',
'Helvetica, sans-serif' => 'Helvetica',
'Lucida Bright, serif' => 'Lucida Bright',
'Futura, sans-serif' => 'Futura',
'Franklin Gothic Medium, sans-serif' => 'Franklin Gothic Medium',
'Candara, sans-serif' => 'Candara'
];
$font_sizes = range(8, 42);
echo '<div style="flex: 1;">';
echo '<h3>Button Style</h3>';
echo '<form method="post" style="width: fit-content;">';
echo '<table class="form-table">';
echo '<tr valign="top">
<th scope="row">Button Action</th>
<td>
<select name="button_action" id="button_action">';
foreach ($button_styles as $style) {
echo '<option value="' . esc_attr($style['button_action']) . '"' . selected($style['button_action'], $selected_button_action, false) . '>' . esc_html($style['button_action']) . '</option>';
}
echo '</select>
</td>
</tr>';
echo '<tr valign="top">
<th scope="row">Button Label</th>
<td>';
foreach ($button_styles as $style) {
$display_style = $style['button_action'] === $selected_button_action ? 'display: block;' : 'display: none;';
echo '<input type="text" name="button_label[' . esc_attr($style['button_action']) . ']" value="' . esc_attr($style['button_label']) . '" class="button-label-input" data-action="' . esc_attr($style['button_action']) . '" style="' . $display_style . '" required />';
}
echo '</td>
</tr>';
foreach ($button_styles as $style) {
$display_style = $style['button_action'] === $selected_button_action ? 'display: table-row;' : 'display: none;';
echo '<tr valign="top" class="button-style-row" data-action="' . esc_attr($style['button_action']) . '" style="' . $display_style . '">
<th scope="row">Background Color</th>
<td><input type="color" name="background_color[' . esc_attr($style['button_action']) . ']" value="' . esc_attr($style['background_color']) . '" required /></td>
</tr>
<tr valign="top" class="button-style-row" data-action="' . esc_attr($style['button_action']) . '" style="' . $display_style . '">
<th scope="row">Font Size</th>
<td>
<select name="font_size[' . esc_attr($style['button_action']) . ']" required>';
foreach ($font_sizes as $size) {
echo '<option value="' . esc_attr($size . 'px') . '" ' . selected($style['font_size'], $size . 'px', false) . '>' . esc_html($size . 'px') . '</option>';
}
echo '</select></td>
</tr>
<tr valign="top" class="button-style-row" data-action="' . esc_attr($style['button_action']) . '" style="' . $display_style . '">
<th scope="row">Font Family</th>
<td>
<select name="font_family[' . esc_attr($style['button_action']) . ']" class="font-family-dropdown" required size="5">';
foreach ($font_families as $font_value => $font_label) {
$selected = selected(str_replace('"', '', $style['font_family']), $font_value, false);
echo '<option value="' . esc_attr($font_value) . '"' . $selected . '>' . esc_html($font_label) . '</option>';
}
echo '</select>
</td>
</tr>
<tr valign="top" class="button-style-row" data-action="' . esc_attr($style['button_action']) . '" style="' . $display_style . '">
<th scope="row">Font Weight</th>
<td>
<select name="font_weight[' . esc_attr($style['button_action']) . ']" required>
<option value="normal"' . selected($style['font_weight'], 'normal', false) . '>Normal</option>
<option value="bold"' . selected($style['font_weight'], 'bold', false) . '>Bold</option>
</select>
</td>
</tr>';
}
echo '</table>
<input type="submit" name="save_button_style" value="Save Button Style" class="button button-primary" />
</form>';
echo '</div>';
// Status Style Section
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_status_style'])) {
$status_styles = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_enrollment_status_style", ARRAY_A);
foreach ($status_styles as $style) {
$status_action = $style['status_action'];
$status_label = sanitize_text_field($_POST['status_label'][$status_action]);
$font_color = sanitize_text_field($_POST['font_color'][$status_action]);
$font_size = sanitize_text_field($_POST['font_size'][$status_action]);
$font_family = str_replace('"', '', sanitize_text_field($_POST['font_family'][$status_action]));
$font_weight = sanitize_text_field($_POST['font_weight'][$status_action]);
$wpdb->update(
"{$wpdb->prefix}sige_enrollment_status_style",
[
'status_label' => $status_label,
'font_color' => $font_color,
'font_size' => $font_size,
'font_family' => $font_family,
'font_weight' => $font_weight
],
['status_action' => $status_action]
);
}
echo '<div class="notice notice-success"><p>Status styles saved successfully.</p></div>';
}
$status_styles = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_enrollment_status_style", ARRAY_A);
$selected_status_action = isset($_POST['status_action']) ? sanitize_text_field($_POST['status_action']) : $status_styles[0]['status_action'];
echo '<div style="flex: 1;">';
echo '<h3>Status Style</h3>';
echo '<form method="post" style="width: fit-content;">';
echo '<table class="form-table">';
echo '<tr valign="top">
<th scope="row">Status Action</th>
<td>
<select name="status_action" id="status_action">';
foreach ($status_styles as $style) {
echo '<option value="' . esc_attr($style['status_action']) . '"' . selected($style['status_action'], $selected_status_action, false) . '>' . esc_html($style['status_action']) . '</option>';
}
echo '</select>
</td>
</tr>';
echo '<tr valign="top">
<th scope="row">Status Label</th>
<td>';
foreach ($status_styles as $style) {
$display_style = $style['status_action'] === $selected_status_action ? 'display: block;' : 'display: none;';
echo '<input type="text" name="status_label[' . esc_attr($style['status_action']) . ']" value="' . esc_attr($style['status_label']) . '" class="status-label-input" data-action="' . esc_attr($style['status_action']) . '" style="' . $display_style . '" required />';
}
echo '</td>
</tr>';
foreach ($status_styles as $style) {
$display_style = $style['status_action'] === $selected_status_action ? 'display: table-row;' : 'display: none;';
echo '<tr valign="top" class="status-style-row" data-action="' . esc_attr($style['status_action']) . '" style="' . $display_style . '">
<th scope="row">Font Color</th>
<td><input type="color" name="font_color[' . esc_attr($style['status_action']) . ']" value="' . esc_attr($style['font_color']) . '" required /></td>
</tr>
<tr valign="top" class="status-style-row" data-action="' . esc_attr($style['status_action']) . '" style="' . $display_style . '">
<th scope="row">Font Size</th>
<td>
<select name="font_size[' . esc_attr($style['status_action']) . ']" required>';
foreach ($font_sizes as $size) {
echo '<option value="' . esc_attr($size . 'px') . '" ' . selected($style['font_size'], $size . 'px', false) . '>' . esc_html($size . 'px') . '</option>';
}
echo '</select></td>
</tr>
<tr valign="top" class="status-style-row" data-action="' . esc_attr($style['status_action']) . '" style="' . $display_style . '">
<th scope="row">Font Family</th>
<td>
<select name="font_family[' . esc_attr($style['status_action']) . ']" class="font-family-dropdown" required size="5">';
foreach ($font_families as $font_value => $font_label) {
$selected = selected(str_replace('"', '', $style['font_family']), $font_value, false);
echo '<option value="' . esc_attr($font_value) . '"' . $selected . '>' . esc_html($font_label) . '</option>';
}
echo '</select>
</td>
</tr>
<tr valign="top" class="status-style-row" data-action="' . esc_attr($style['status_action']) . '" style="' . $display_style . '">
<th scope="row">Font Weight</th>
<td>
<select name="font_weight[' . esc_attr($style['status_action']) . ']" required>
<option value="normal"' . selected($style['font_weight'], 'normal', false) . '>Normal</option>
<option value="bold"' . selected($style['font_weight'], 'bold', false) . '>Bold</option>
</select>
</td>
</tr>';
}
echo '</table>
<input type="submit" name="save_status_style" value="Save Status Style" class="button button-primary" />
</form>';
echo '</div>';
echo '</div>'; // Close div for flex display
// Add separator line
echo '<hr style="border: 3px solid #000; margin: 20px 0;">';
// Notice Options
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_notice'])) {
$type = sanitize_text_field($_POST['notice_type']);
$notice = sanitize_textarea_field($_POST['notice']);
$existing_notice = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}sige_activity_notices WHERE type = %s", $type));
if ($existing_notice) {
$wpdb->update(
"{$wpdb->prefix}sige_activity_notices",
['notice' => $notice],
['id' => $existing_notice]
);
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_activity_notices",
['type' => $type, 'notice' => $notice]
);
}
echo '<div class="notice notice-success"><p>Notice saved successfully.</p></div>';
}
$types = ['Presentation', 'Short-course', 'Lecture', 'Workshop', 'Others'];
echo '<h3>Register Activity Notices</h3>';
echo '<form method="post" style="width: fit-content; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #f9f9f9; border: 1px solid #ccc; padding: 20px; border-radius: 8px;">
<style>
.sige-notices-form th,
.sige-notices-form td {
padding: 10px 5px;
vertical-align: top;
}
.sige-notices-form th {
text-align: left;
padding-right: 10px;
}
.sige-notices-form td {
width: 100%;
}
.sige-notices-form textarea {
width: 100%;
box-sizing: border-box;
}
</style>
<table class="form-table sige-notices-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Type</th>
<td>
<select name="notice_type" required>';
foreach ($types as $type_name) {
echo '<option value="' . $type_name . '">' . $type_name . '</option>';
}
echo '</select>
</td>
</tr>
<tr valign="top">
<th scope="row">Notice</th>
<td><textarea name="notice" required></textarea></td>
</tr>
</table>
<input type="submit" name="save_notice" value="Save Notice" class="button button-primary" />
</form>';
$notices = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}sige_activity_notices");
if ($notices) {
echo '<h3>Existing Notices</h3>';
echo '<table id="notices-table" class="display" style="width: 100%;">
<thead>
<tr>
<th style="width: 100px;">Type</th>
<th>Notice</th>
</tr>
</thead>
<tbody>';
foreach ($notices as $notice) {
echo "<tr>
<td>{$notice->type}</td>
<td style='text-align: justify;'>{$notice->notice}</td>
</tr>";
}
echo '</tbody></table>';
}
echo '<script>
jQuery(document).ready(function($) {
$("#notices-table").DataTable();
$("#button_action").on("change", function() {
const selectedAction = $(this).val();
$(".button-style-row, .button-label-input").each(function() {
const action = $(this).data("action");
if (action === selectedAction) {
$(this).show();
} else {
$(this).hide();
}
});
}).trigger("change");
$("#status_action").on("change", function() {
const selectedAction = $(this).val();
$(".status-style-row, .status-label-input").each(function() {
const action = $(this).data("action");
if (action === selectedAction) {
$(this).show();
} else {
$(this).hide();
}
});
}).trigger("change");
});
</script>';
}
function displayEmailOptions() {
echo '<div class="wrap"><h2>Email Options</h2><p>Content for Email Options tab.</p></div>';
}
function displayMiscellaneous() {
global $wpdb;
echo '<div class="wrap"><h2>Miscellaneous</h2>';
// Fetch all distinct meta keys from wp_usermeta
$meta_keys = $wpdb->get_col("SELECT DISTINCT meta_key FROM {$wpdb->prefix}usermeta");
// Fetch the saved meta keys and their statuses
$saved_meta_keys = $wpdb->get_results("SELECT meta_key, status FROM {$wpdb->prefix}sige_meta_keys", OBJECT_K);
// Remove saved meta keys from the list of all meta keys
$meta_keys = array_diff($meta_keys, array_keys($saved_meta_keys));
// Handle form submission for saving meta keys
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_meta_keys'])) {
$selected_meta_key = sanitize_text_field($_POST['meta_key']);
$meta_key_status = isset($_POST['meta_key_status']) ? 1 : 0;
// Save or update the selected meta key status
$existing_entry = $wpdb->get_var($wpdb->prepare("
SELECT COUNT(*) FROM {$wpdb->prefix}sige_meta_keys
WHERE meta_key = %s
", $selected_meta_key));
if ($existing_entry) {
$wpdb->update(
"{$wpdb->prefix}sige_meta_keys",
['status' => $meta_key_status],
['meta_key' => $selected_meta_key]
);
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_meta_keys",
['meta_key' => $selected_meta_key, 'status' => $meta_key_status]
);
}
echo '<div class="notice notice-success"><p>Meta Key status saved successfully.</p></div>';
echo '<script>
setTimeout(function() {
window.location.reload();
}, 2000);
</script>';
}
// Handle delete request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_meta_key'])) {
$meta_key_to_delete = sanitize_text_field($_POST['meta_key_to_delete']);
$wpdb->delete(
"{$wpdb->prefix}sige_meta_keys",
['meta_key' => $meta_key_to_delete]
);
echo '<div class="notice notice-success"><p>Meta Key deleted successfully.</p></div>';
echo '<script>
setTimeout(function() {
window.location.reload();
}, 2000);
</script>';
}
echo '<h3>Meta Key Options</h3>';
echo '<form method="post" style="width: fit-content;">
<style>
.meta-key-form th,
.meta-key-form td {
padding: 10px 5px;
vertical-align: top;
}
.meta-key-form th {
text-align: left;
padding-right: 10px;
}
.meta-key-form td {
width: 100%;
}
.meta-key-form select,
.meta-key-form input[type="checkbox"] {
margin-bottom: 20px;
}
</style>
<table class="form-table meta-key-form" style="width: 100%;">
<tr valign="top">
<th scope="row">Meta Key</th>
<td>
<select name="meta_key" required>';
foreach ($meta_keys as $meta_key) {
echo '<option value="' . esc_attr($meta_key) . '">' . esc_html($meta_key) . '</option>';
}
echo ' </select>
</td>
</tr>
<tr valign="top">
<th scope="row">Status</th>
<td>
<label>
<input type="checkbox" name="meta_key_status" value="1">
Enable
</label>
</td>
</tr>
</table>
<input type="submit" name="save_meta_keys" value="Save Meta Key Status" class="button button-primary" />
</form>';
// Display the saved meta keys in a table
if (!empty($saved_meta_keys)) {
echo '<h3>Saved Meta Keys</h3>';
echo '<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>Meta Key</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($saved_meta_keys as $meta_key => $data) {
echo '<tr>
<td>' . esc_html($meta_key) . '</td>
<td>' . ($data->status ? 'Enabled' : 'Disabled') . '</td>
<td>
<form method="post" style="display:inline;">
<input type="hidden" name="meta_key_to_delete" value="' . esc_attr($meta_key) . '" />
<input type="submit" name="delete_meta_key" value="Delete" class="button button-secondary" onclick="return confirm(\'Are you sure you want to delete this meta key?\');" />
</form>
</td>
</tr>';
}
echo '</tbody></table>';
}
echo '<script>
document.addEventListener("DOMContentLoaded", function() {
const metaKeySelect = document.querySelector("select[name=\'meta_key\']");
const metaKeyCheckbox = document.querySelector("input[name=\'meta_key_status\']");
metaKeySelect.addEventListener("change", function() {
const selectedMetaKey = metaKeySelect.value;
const savedMetaKeys = ' . json_encode($saved_meta_keys) . ';
if (savedMetaKeys[selectedMetaKey] && savedMetaKeys[selectedMetaKey].status) {
metaKeyCheckbox.checked = true;
} else {
metaKeyCheckbox.checked = false;
}
});
// Trigger change event on page load to set the initial checkbox state
metaKeySelect.dispatchEvent(new Event("change"));
});
</script>';
echo '</div>';
}
// Update settingsSubmenuPage function to include emailSettingsSubmenuPage
function settingsSubmenuPage() {
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'main_options';
echo '<div class="wrap">
<h2>Settings</h2>
<h2 class="nav-tab-wrapper">
<a href="?page=settings-submenu&tab=main_options" class="nav-tab ' . ($tab == 'main_options' ? 'nav-tab-active' : '') . '">Main Options</a>
<a href="?page=settings-submenu&tab=dashboard_options" class="nav-tab ' . ($tab == 'dashboard_options' ? 'nav-tab-active' : '') . '">Dashboard Options</a>
<a href="?page=settings-submenu&tab=activity_options" class="nav-tab ' . ($tab == 'activity_options' ? 'nav-tab-active' : '') . '">Activity Options</a>
<a href="?page=settings-submenu&tab=enrollment_options" class="nav-tab ' . ($tab == 'enrollment_options' ? 'nav-tab-active' : '') . '">Enrollment Options</a>
<a href="?page=settings-submenu&tab=email_options" class="nav-tab ' . ($tab == 'email_options' ? 'nav-tab-active' : '') . '">Email Options</a>
<a href="?page=settings-submenu&tab=miscellaneous" class="nav-tab ' . ($tab == 'miscellaneous' ? 'nav-tab-active' : '') . '">Miscellaneous</a>
</h2>';
if ($tab == 'main_options') {
displayMainOptions();
} elseif ($tab == 'dashboard_options') {
displayDashboardOptions();
} elseif ($tab == 'activity_options') {
displayActivityOptions();
} elseif ($tab == 'enrollment_options') {
displayEnrollmentOptions();
} elseif ($tab == 'email_options') {
emailSettingsSubmenuPage();
} elseif ($tab == 'miscellaneous') {
displayMiscellaneous();
}
echo '</div>';
}
// Shortcode for displaying enrollments on the front-end
function frontendEnrollmentControl() {
if (!is_user_logged_in()) {
return '<p>You need to be logged in to view the registrations that have been made.</p>';
}
// Check if the user has administrator or contributor role
if (!current_user_can('administrator') && !current_user_can('contributor')) {
return '<p>You do not have the required permissions to handle the attendance control.</p>';
}
global $wpdb;
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
// Define the additional meta keys
$additional_meta_keys = [
'forca',
'full_name',
'posto',
'militar',
'instituição',
'nacionalidade',
'efetivo_dcta',
'cidade',
'estado',
'areaatividadeprincipal',
'setordeatuacao',
'cargofuncao',
'ehativa',
'circulo_hierárquico',
'pais',
'formacao_academica',
'regiao_do_brasil'
];
// Handle saving additional features selection
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['additional_features'])) {
$selected_meta_keys = array_intersect($additional_meta_keys, $_POST['additional_features']);
update_user_meta($user_id, 'selected_additional_features_frontend', $selected_meta_keys);
// Redirect to avoid resubmission
wp_safe_redirect(add_query_arg([], wp_get_referer()));
exit;
} else {
$selected_meta_keys = get_user_meta($user_id, 'selected_additional_features_frontend', true);
if (!$selected_meta_keys) {
$selected_meta_keys = [];
}
}
// Handle form submission for updating enrollment status
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['apply_status']) && isset($_POST['selected_enrollments'])) {
$new_status = sanitize_text_field($_POST['new_status']);
$selected_enrollments = array_map('intval', $_POST['selected_enrollments']);
if (!empty($selected_enrollments)) {
foreach ($selected_enrollments as $enrollment_id) {
$wpdb->update(
"{$wpdb->prefix}sige_enrollments",
['status' => $new_status],
['id' => $enrollment_id]
);
}
// Redirect to the same page to clear POST data
wp_safe_redirect(add_query_arg([], wp_get_referer()));
exit;
} else {
echo '<div class="notice notice-error"><p>Please select at least one enrollment.</p></div>';
}
}
// Fetch enrollments with additional meta data if selected
$meta_selects = '';
$meta_joins = '';
foreach ($selected_meta_keys as $meta_key) {
$meta_selects .= ", um_$meta_key.meta_value as $meta_key";
$meta_joins .= " LEFT JOIN {$wpdb->prefix}usermeta um_$meta_key ON um_$meta_key.user_id = u.ID AND um_$meta_key.meta_key = '$meta_key'";
}
$query = "
SELECT e.*, a.name as activity_name, u.user_email $meta_selects
FROM {$wpdb->prefix}sige_enrollments e
LEFT JOIN {$wpdb->prefix}sige_activities a ON e.activity_id = a.id
LEFT JOIN {$wpdb->prefix}users u ON e.user_id = u.ID
$meta_joins
";
$enrollments = $wpdb->get_results($query);
ob_start();
// Display additional features form
echo '<div class="additional-features-container" style="display: flex; align-items: center; margin-bottom: 20px;">';
echo '<h3 style="margin: 0;">Additional Features</h3>';
echo '<button id="toggle-features" class="button button-secondary" style="margin-left: 10px;">Expand Features</button>';
echo '</div>';
echo '<div id="features-container" style="display: none; width: 100%; margin-top: 20px;">';
echo '<form method="post" action="" style="width: 100%;">';
foreach ($additional_meta_keys as $meta_key) {
$checked = in_array($meta_key, $selected_meta_keys) ? 'checked' : '';
echo '<label style="display: block; margin-bottom: 10px;"><input type="checkbox" name="additional_features[]" value="' . $meta_key . '" ' . $checked . '> ' . ucfirst(str_replace('_', ' ', $meta_key)) . '</label>';
}
echo '<input type="submit" value="Apply" class="button button-primary" style="margin-top: 20px;">';
echo '</form>';
echo '</div>';
// Display the enrollments table
echo '<h3>Existing Enrollments</h3>';
echo '<div style="width: 100%; margin: 0; padding: 0;">';
echo '<form method="post" action="" style="width: 100%; margin: 0; padding: 0;">';
echo '<input type="hidden" id="selected-meta-keys" value="' . esc_attr(json_encode(array_values($selected_meta_keys))) . '">';
echo '<button id="export-csv" class="button button-secondary" style="margin-bottom: 20px;">Export to CSV</button>';
echo '<table id="enrollments-table" class="display" style="width: 100%; margin: 0; padding: 0;">
<thead>
<tr>
<th style="text-align: center;"><input type="checkbox" id="select_all"> Select All</th>
<th>Activity Name</th>
<th>User Email</th>
<th>Enrollment Date</th>
<th>Status</th>';
foreach ($selected_meta_keys as $meta_key) {
echo '<th>' . ucfirst(str_replace('_', ' ', $meta_key)) . '</th>';
}
echo '</tr></thead><tbody>';
if ($enrollments) {
foreach ($enrollments as $enrollment) {
$row_style = '';
$checkbox_disabled = '';
if ($enrollment->status == 'Enrollment Canceled by User') {
$row_style = 'style="background-color: #f38d8d;"';
$checkbox_disabled = 'disabled';
} elseif ($enrollment->status == 'Waiting List') {
$row_style = 'style="background-color: #e3db69;"';
} elseif ($enrollment->status == 'Approved') {
$row_style = 'style="background-color: green;"';
} elseif ($enrollment->status == 'Not Approved') {
$row_style = 'style="background-color: #bc97cd;"';
} elseif ($enrollment->status == 'Under Analysis') {
$row_style = 'style="background-color: #5ecac7;"';
}
$formatted_date = date('d-m-Y', strtotime($enrollment->enrollment_date));
echo "<tr $row_style>
<td style='text-align: center;'><input type='checkbox' name='selected_enrollments[]' value='{$enrollment->id}' $checkbox_disabled></td>
<td style='font-weight: bold;'>{$enrollment->activity_name}</td>
<td style='font-weight: bold;'>{$enrollment->user_email}</td>
<td style='font-weight: bold;'>$formatted_date</td>
<td style='font-weight: bold;'>{$enrollment->status}</td>";
foreach ($selected_meta_keys as $meta_key) {
echo '<td style="font-weight: bold;">' . esc_html($enrollment->$meta_key) . '</td>';
}
echo '</tr>';
}
} else {
echo '<tr><td colspan="5" style="text-align: center;">No enrollments found</td></tr>';
}
echo '</tbody></table>';
if ($enrollments) {
echo '<div style="margin-top: 20px;">
<select name="new_status" required>
<option value="Waiting List">Waiting List</option>
<option value="Not Approved">Not Approved</option>
<option value="Approved">Approved</option>
</select>
<input type="submit" name="apply_status" value="Apply" class="button button-primary">';
echo '</div>';
}
echo '</form>';
echo '</div>';
// Add the color legend
echo '<div style="margin-top: 20px; display: flex; align-items: center;">
<h3 style="margin-right: 20px;">Legend:</h3>';
echo '<div style="display: flex; flex-wrap: wrap; gap: 10px;">
<span style="background-color: #f38d8d; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Enrollment Canceled by User</span>
<span style="background-color: #e3db69; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Waiting List</span>
<span style="background-color: green; padding: 5px; border-radius: 3px; color: white; width: 150px; text-align: center;">Approved</span>
<span style="background-color: #bc97cd; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Not Approved</span>
<span style="background-color: #5ecac7; padding: 5px; border-radius: 3px; width: 150px; text-align: center;">Under Analysis</span>
</div></div>';
echo '<script>
jQuery(document).ready(function($) {
$("#enrollments-table").DataTable({
"scrollX": true,
"autoWidth": false
});
$("#select_all").click(function() {
$("input[type=checkbox]").prop("checked", this.checked);
});
$("#toggle-features").click(function() {
$("#features-container").slideToggle();
$(this).text(function(i, text){
return text === "Expand Features" ? "Collapse Features" : "Expand Features";
});
});
$("#export-csv").click(function(e) {
e.preventDefault();
const selectedMetaKeys = JSON.parse($("#selected-meta-keys").val());
const now = new Date();
const formattedDate = `${("0" + now.getDate()).slice(-2)}_${("0" + (now.getMonth() + 1)).slice(-2)}_${now.getFullYear()}_${("0" + now.getHours()).slice(-2)}_${("0" + now.getMinutes()).slice(-2)}_${("0" + now.getSeconds()).slice(-2)}`;
const filename = `enrollments_${formattedDate}.csv`;
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Activity Name,User Email,Enrollment Date,Status";
// Add selected meta keys to CSV header
if (selectedMetaKeys.length > 0) {
selectedMetaKeys.forEach(function(metaKey) {
csvContent += "," + metaKey.charAt(0).toUpperCase() + metaKey.slice(1).replace(/_/g, " ");
});
}
csvContent += "\n";
$("#enrollments-table tbody tr").each(function() {
const row = $(this);
const activityName = row.find("td:nth-child(2)").text().trim();
const userEmail = row.find("td:nth-child(3)").text().trim();
const enrollmentDate = row.find("td:nth-child(4)").text().trim();
const status = row.find("td:nth-child(5)").text().trim();
let rowData = `${activityName},${userEmail},${enrollmentDate},${status}`;
if (selectedMetaKeys.length > 0) {
selectedMetaKeys.forEach(function(metaKey, index) {
rowData += "," + row.find("td:nth-child(" + (6 + index) + ")").text().trim();
});
}
csvContent += rowData + "\n";
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
</script>';
return ob_get_clean();
}
add_shortcode('enrollments', 'frontendEnrollmentControl');
function attendanceControlSubmenuPage() {
global $wpdb;
$filtered_user_id = isset($_POST['filtered_user_id']) ? sanitize_text_field($_POST['filtered_user_id']) : '';
$qrScannerUsedInput = isset($_POST['qr_scanner_used']) ? sanitize_text_field($_POST['qr_scanner_used']) : '';
// Handle form submission to update attendance
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_attendance'])) {
$enrollment_id = isset($_POST['enrollment_id']) ? intval($_POST['enrollment_id']) : 0;
$attended = isset($_POST['attended']) ? sanitize_text_field($_POST['attended']) : '';
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
if ($enrollment_id && $attended) {
$existing_record = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}sige_enrollment_attendance_control WHERE enrollment_id = %d", $enrollment_id));
if ($existing_record) {
$wpdb->update(
"{$wpdb->prefix}sige_enrollment_attendance_control",
['attended' => $attended],
['id' => $existing_record]
);
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_enrollment_attendance_control",
[
'enrollment_id' => $enrollment_id,
'attended' => $attended
]
);
}
}
}
// Handle QR code verification
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $qrScannerUsedInput === 'true') {
$hashed_user_id = sanitize_text_field($_POST['filtered_user_id']);
$filtered_user_id = verifyUserBasedOnQRCode($hashed_user_id);
}
// Fetch enrollments with status "Approved"
$query = "
SELECT e.id as enrollment_id, e.activity_id, a.name as activity_name, e.user_id, u.user_email, um.meta_value as user_full_name, e.enrollment_date, e.status, ac.attended
FROM {$wpdb->prefix}sige_enrollments e
LEFT JOIN {$wpdb->prefix}sige_activities a ON e.activity_id = a.id
LEFT JOIN {$wpdb->prefix}users u ON e.user_id = u.ID
LEFT JOIN {$wpdb->prefix}usermeta um ON e.user_id = um.user_id AND um.meta_key = 'full_name'
LEFT JOIN {$wpdb->prefix}sige_enrollment_attendance_control ac ON e.id = ac.enrollment_id
WHERE e.status = 'Approved'
";
if ($filtered_user_id) {
$query .= $wpdb->prepare(" AND e.user_id = %d", $filtered_user_id);
}
$enrollments = $wpdb->get_results($query);
echo '<div class="wrap"><h2>Attendance Control</h2>';
// QR Code Scanner container
echo '<div id="qr-reader" style="width:300px;"></div>
<button id="start-qr-reader" class="button button-secondary">Start QR Scanner</button>';
// Filter form
echo '<form method="post" action="" style="margin-top: 20px; margin-bottom: 20px;">
<input type="hidden" name="qr_scanner_used" id="qr_scanner_used" value="' . esc_attr($qrScannerUsedInput) . '" />
<input type="text" name="filtered_user_id" id="filtered_user_id" placeholder="Enter User ID" value="' . esc_attr($filtered_user_id) . '" />
<input type="submit" value="Filter" class="button button-secondary" />
</form>';
echo '<button id="export-csv" class="button button-secondary" style="margin-bottom: 20px;">Export to CSV</button>';
echo '<table id="attendance-table" class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>Activity Name</th>
<th>User ID</th>
<th>User Full Name</th>
<th>Email</th>
<th>Enrollment Date</th>
<th>Status</th>
<th>Attended</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
if ($enrollments) {
foreach ($enrollments as $enrollment) {
echo '<tr>
<td>' . esc_html($enrollment->activity_name) . '</td>
<td>' . esc_html($enrollment->user_id) . '</td>
<td>' . esc_html($enrollment->user_full_name) . '</td>
<td>' . esc_html($enrollment->user_email) . '</td>
<td>' . esc_html($enrollment->enrollment_date) . '</td>
<td>' . esc_html($enrollment->status) . '</td>
<td>' . esc_html($enrollment->attended) . '</td>
<td>
<form method="post" action="">
<input type="hidden" name="enrollment_id" value="' . esc_attr($enrollment->enrollment_id) . '" />
<input type="hidden" name="user_id" value="' . esc_attr($enrollment->user_id) . '" />
<select name="attended">
<option value="yes"' . selected($enrollment->attended, 'yes', false) . '>Yes</option>
<option value="no"' . selected($enrollment->attended, 'no', false) . '>No</option>
</select>
<input type="submit" name="update_attendance" value="Update" class="button button-primary" />
</form>
</td>
</tr>';
}
} else {
echo '<tr><td colspan="8">No approved enrollments found.</td></tr>';
}
echo '</tbody></table></div>';
// Add custom JavaScript directly within the PHP file
echo '<script>
document.addEventListener("DOMContentLoaded", function() {
function initializeQrCodeScanner() {
if (typeof Html5Qrcode !== "undefined") {
const qrReader = new Html5Qrcode("qr-reader");
const startQrReaderBtn = document.getElementById("start-qr-reader");
const userIdInput = document.getElementById("filtered_user_id");
const qrScannerUsedInput = document.getElementById("qr_scanner_used");
startQrReaderBtn.addEventListener("click", function() {
if (startQrReaderBtn.textContent === "Stop QR Scanner") {
qrReader.stop();
startQrReaderBtn.textContent = "Start QR Scanner";
} else {
qrReader.start(
{ facingMode: "environment" },
{
fps: 10,
qrbox: 250
},
qrCodeMessage => {
userIdInput.value = qrCodeMessage;
qrScannerUsedInput.value = "true";
qrReader.stop();
startQrReaderBtn.textContent = "Start QR Scanner";
// Submit the form automatically after setting the hashed user ID
document.querySelector("form").submit();
},
errorMessage => {
console.warn(`QR Code scanning error: ${errorMessage}`);
})
.then(() => {
startQrReaderBtn.textContent = "Stop QR Scanner";
})
.catch(err => {
console.error(`Unable to start QR Code scanning: ${err}`);
});
}
});
} else {
console.error("Html5Qrcode library is not loaded properly.");
}
}
function exportTableToCSV(filename) {
const csv = [];
const rows = document.querySelectorAll("#attendance-table tr");
for (const row of rows) {
const cols = row.querySelectorAll("td, th");
const rowData = [];
for (let i = 0; i < cols.length - 1; i++) { // Exclude the last column (Action)
rowData.push(cols[i].innerText);
}
csv.push(rowData.join(","));
}
// Download CSV
const csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
const downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
document.getElementById("export-csv").addEventListener("click", function() {
const now = new Date();
const formattedDate = `${("0" + now.getDate()).slice(-2)}_${("0" + (now.getMonth() + 1)).slice(-2)}_${now.getFullYear()}_${("0" + now.getHours()).slice(-2)}_${("0" + now.getMinutes()).slice(-2)}_${("0" + now.getSeconds()).slice(-2)}`;
exportTableToCSV(`attendance_${formattedDate}.csv`);
});
initializeQrCodeScanner();
});
</script>';
}
function frontendAttendanceControl() {
ob_start();
if (!is_user_logged_in()) {
return '<p>You must be logged in to handle the attendance control.</p>';
}
// Check if the user has administrator or contributor role
if (!current_user_can('administrator') && !current_user_can('contributor')) {
return '<p>You do not have the required permissions to handle the attendance control.</p>';
}
// Handle form submission to update attendance
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_attendance'])) {
$enrollment_id = isset($_POST['enrollment_id']) ? intval($_POST['enrollment_id']) : 0;
$attended = isset($_POST['attended']) ? sanitize_text_field($_POST['attended']) : '';
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
if ($enrollment_id && $attended) {
global $wpdb;
$existing_record = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}sige_enrollment_attendance_control WHERE enrollment_id = %d", $enrollment_id));
if ($existing_record) {
$wpdb->update(
"{$wpdb->prefix}sige_enrollment_attendance_control",
['attended' => $attended],
['id' => $existing_record]
);
} else {
$wpdb->insert(
"{$wpdb->prefix}sige_enrollment_attendance_control",
[
'enrollment_id' => $enrollment_id,
'attended' => $attended
]
);
}
}
}
// Handle QR code verification
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['qr_scanner_used']) && $_POST['qr_scanner_used'] == '1') {
$hashed_user_id = sanitize_text_field($_POST['filtered_user_id']);
$filtered_user_id = verifyUserBasedOnQRCode($hashed_user_id);
} else {
$filtered_user_id = isset($_POST['filtered_user_id']) ? intval($_POST['filtered_user_id']) : '';
}
} else {
$filtered_user_id = '';
}
// Fetch enrollments with status "Approved"
global $wpdb;
$query = "
SELECT e.id as enrollment_id, e.activity_id, a.name as activity_name, e.user_id, um1.meta_value as full_name, u.user_email, e.enrollment_date, e.status, ac.attended
FROM {$wpdb->prefix}sige_enrollments e
LEFT JOIN {$wpdb->prefix}sige_activities a ON e.activity_id = a.id
LEFT JOIN {$wpdb->prefix}usermeta um1 ON e.user_id = um1.user_id AND um1.meta_key = 'full_name'
LEFT JOIN {$wpdb->prefix}users u ON e.user_id = u.ID
LEFT JOIN {$wpdb->prefix}sige_enrollment_attendance_control ac ON e.id = ac.enrollment_id
WHERE e.status = 'Approved'
";
if ($filtered_user_id) {
$query .= $wpdb->prepare(" AND e.user_id = %d", $filtered_user_id);
}
$enrollments = $wpdb->get_results($query);
?>
<div class="wrap">
<h2>Attendance Control</h2>
<div id="qr-reader" style="width:300px;"></div>
<button id="start-qr-reader" class="button button-secondary">Start QR Scanner</button>
<form method="post" action="" id="attendanceForm" style="margin-top: 20px; margin-bottom: 20px;">
<input type="text" name="filtered_user_id" id="filtered_user_id" placeholder="Enter User ID" value="<?php echo esc_attr($filtered_user_id); ?>" />
<input type="hidden" name="qr_scanner_used" id="qr_scanner_used" value="0" />
<input type="submit" value="Filter" class="button button-secondary" />
</form>
<button id="export-csv" class="button button-secondary" style="margin-bottom: 20px;">Export to CSV</button>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>Activity Name</th>
<th>User ID</th>
<th>User Full Name</th>
<th>Email</th>
<th>Enrollment Date</th>
<th>Status</th>
<th>Attended</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if ($enrollments) {
foreach ($enrollments as $enrollment) {
?>
<tr>
<td><?php echo esc_html($enrollment->activity_name); ?></td>
<td><?php echo esc_html($enrollment->user_id); ?></td>
<td><?php echo esc_html($enrollment->full_name); ?></td>
<td><?php echo esc_html($enrollment->user_email); ?></td>
<td><?php echo esc_html($enrollment->enrollment_date); ?></td>
<td><?php echo esc_html($enrollment->status); ?></td>
<td><?php echo esc_html($enrollment->attended); ?></td>
<td>
<form method="post" action="">
<input type="hidden" name="enrollment_id" value="<?php echo esc_attr($enrollment->enrollment_id); ?>" />
<input type="hidden" name="user_id" value="<?php echo esc_attr($enrollment->user_id); ?>" />
<select name="attended">
<option value="yes"<?php selected($enrollment->attended, 'yes'); ?>>Yes</option>
<option value="no"<?php selected($enrollment->attended, 'no'); ?>>No</option>
</select>
<input type="submit" name="update_attendance" value="Update" class="button button-primary" />
</form>
</td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="8">No approved enrollments found.</td></tr>
<?php
}
?>
</tbody>
</table>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
function initializeQrCodeScanner() {
if (typeof Html5Qrcode !== "undefined") {
const qrReader = new Html5Qrcode("qr-reader");
const startQrReaderBtn = document.getElementById("start-qr-reader");
const userIdInput = document.getElementById("filtered_user_id");
const qrScannerUsedInput = document.getElementById("qr_scanner_used");
let qrScannerRunning = false;
startQrReaderBtn.addEventListener("click", function() {
if (!qrScannerRunning) {
qrReader.start(
{ facingMode: "environment" },
{
fps: 10,
qrbox: 250
},
qrCodeMessage => {
userIdInput.value = qrCodeMessage;
qrScannerUsedInput.value = 1; // Set this to indicate scanner was used
qrReader.stop().then(() => {
qrScannerRunning = false;
startQrReaderBtn.textContent = "Start QR Scanner";
// Auto-submit the form after scanning the QR code
document.getElementById("attendanceForm").submit();
});
},
errorMessage => {
console.warn(`QR Code scanning error: ${errorMessage}`);
}
).then(() => {
qrScannerRunning = true;
startQrReaderBtn.textContent = "Stop QR Scanner";
}).catch(err => {
console.error(`Unable to start QR Code scanning: ${err}`);
});
} else {
qrReader.stop().then(() => {
qrScannerRunning = false;
startQrReaderBtn.textContent = "Start QR Scanner";
}).catch(err => {
console.error(`Unable to stop QR Code scanning: ${err}`);
});
}
});
} else {
console.error("Html5Qrcode library is not loaded properly.");
}
}
function exportToCsv(filename, rows) {
const processRow = function(row) {
let finalVal = '';
for (let j = 0; j < row.length; j++) {
let innerValue = row[j] === null ? '' : row[j].toString();
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
}
let result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0)
result = '"' + result + '"';
if (j > 0)
finalVal += ',';
finalVal += result;
}
return finalVal + '\n';
};
let csvFile = '';
for (let i = 0; i < rows.length; i++) {
csvFile += processRow(rows[i]);
}
const blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
function generateCsvFileName() {
const now = new Date();
const formattedDate = `${("0" + now.getDate()).slice(-2)}_${("0" + (now.getMonth() + 1)).slice(-2)}_${now.getFullYear()}_${("0" + now.getHours()).slice(-2)}_${("0" + now.getMinutes()).slice(-2)}_${("0" + now.getSeconds()).slice(-2)}`;
return `attendance_${formattedDate}.csv`;
}
document.getElementById('export-csv').addEventListener('click', function() {
const table = document.querySelector('.wp-list-table');
const rows = [];
rows.push(["Activity Name", "User ID", "User Full Name", "Email", "Enrollment Date", "Status", "Attended"]);
table.querySelectorAll('tbody tr').forEach(function(row) {
const rowData = [];
row.querySelectorAll('td').forEach(function(cell, index) {
if (index < 7) { // Exclude the last column (Action)
rowData.push(cell.innerText.trim());
}
});
rows.push(rowData);
});
exportToCsv(generateCsvFileName(), rows);
});
initializeQrCodeScanner();
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('frontend_attendance_control', 'frontendAttendanceControl');
// Ensure the phpqrcode and tcpdf library are included
require_once plugin_dir_path(__FILE__) . 'phpqrcode/qrlib.php';
require_once plugin_dir_path(__FILE__) . 'tcpdf/tcpdf.php';
function userbadgeQRCode() {
if (!is_user_logged_in()) {
return '<p>You must be logged in to view your badge.</p>';
}
global $wpdb;
$current_user_id = get_current_user_id();
// Fetch full name from usermeta
$full_name = get_user_meta($current_user_id, 'full_name', true);
// Secret phrase
$secret_phrase = 'mysecretyphrase';
// Generate MD5 hash of the user ID
$hashed_user_id = md5($secret_phrase . $current_user_id);
// Generate QR Code with the hashed user ID
ob_start();
QRcode::png($hashed_user_id, null, QR_ECLEVEL_L, 10);
$imageString = ob_get_contents();
ob_end_clean();
$qrCodeDataUri = 'data:image/png;base64,' . base64_encode($imageString);
// Get activities for the current year
$current_year = date('Y');
$activities = $wpdb->get_results($wpdb->prepare("
SELECT a.*, p.place, s.full_name as speaker, e.name as event_name, e.id as event_id
FROM {$wpdb->prefix}sige_activities a
LEFT JOIN {$wpdb->prefix}sige_place p ON a.place_id = p.id
LEFT JOIN {$wpdb->prefix}sige_speakers s ON a.speaker_id = s.id
LEFT JOIN {$wpdb->prefix}sige_event_names e ON a.event_name_id = e.id
WHERE (a.status = 'Open' OR a.status = 'Closed')
AND YEAR(a.start_date) = %d
AND a.attendance_control = 'yes'
", $current_year));
// Organize activities by event name
$events = [];
foreach ($activities as $activity) {
$enrollment_status_action = $wpdb->get_var($wpdb->prepare("
SELECT status FROM {$wpdb->prefix}sige_enrollments
WHERE activity_id = %d AND user_id = %d
", $activity->id, $current_user_id));
if (!$enrollment_status_action) {
$enrollment_status_action = 'Not Requested';
}
$events[$activity->event_name][] = [
'activity_name' => $activity->name,
'status' => $enrollment_status_action
];
}
// Output the HTML
ob_start();
?>
<div id="badgeContent" style="text-align: center;">
<div style="position: relative; margin: 0 auto; padding: 20px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); background-color: #fff; max-width: 800px;">
<img src="<?php echo plugin_dir_url(__FILE__) . 'image/ita.png'; ?>" alt="ITA Logo" class="ita-logo" style="position: absolute; top: 10px; left: 10px; width: 100px; height: auto;">
<img src="<?php echo plugin_dir_url(__FILE__) . 'image/gladioalado.png'; ?>" alt="Gladio Alado Logo" class="gladio-logo" style="position: absolute; top: 10px; right: 10px; width: 120px; height: auto;">
<h3 style="padding-top: 100px; font-family: 'Times New Roman', Times, serif;">XXVI SYMPOSIUM ON OPERATIONAL APPLICATIONS IN DEFENSE AREAS</h3>
<h3>Event Badge</h3>
<img id="qrCodeImage" src="<?php echo $qrCodeDataUri; ?>" alt="QR Code">
<p align="justify">Dear <strong><?php echo esc_html($full_name); ?></strong>,</p>
<p align="justify">SIGE is an open event promoted by the Technological Institute of Aeronautics with the aim of creating an environment for the exchange of experiences between the academic, industrial and operational sectors of the Armed Forces, on issues of teaching, research and development in Defense areas.</p>
<p align="justify">The organizing team is made up of masters and doctoral students from the Graduate Program in Operational Applications (PPGAO) at ITA.</p>
<h3>Activities for <?php echo $current_year; ?></h3>
<?php if (!empty($events)) { ?>
<?php foreach ($events as $event_name => $activities) { ?>
<div style="margin-bottom: 20px; padding: 15px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background-color: #f9f9f9;">
<h4><strong><?php echo esc_html($event_name); ?></strong></h4>
<ul style="list-style-type: none; padding: 0;">
<?php foreach ($activities as $activity) { ?>
<li style="padding: 10px;"><?php echo esc_html($activity['activity_name']); ?> - Status: <?php echo esc_html($activity['status']); ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
<?php } else { ?>
<p>No activities available for this year.</p>
<?php } ?>
<p style="margin-top: 20px;">Contact the event Organizing Committee for questions via email at sige@ita.br</p>
</div>
<button id="downloadPDF" class="button button-primary" style="margin-top: 20px;">Download PDF</button>
</div>
<script>
document.getElementById('downloadPDF').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
var blob = new Blob([xhr.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'User_Badge_<?php echo $current_user_id; ?>.pdf';
link.click();
} else {
console.error('Error generating PDF:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('Error generating PDF:', xhr.statusText);
};
xhr.send('action=generate_userbadge_pdf');
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('userbadge_qr_code', 'userbadgeQRCode');
// Handle the AJAX request to generate the PDF
add_action('wp_ajax_generate_userbadge_pdf', 'generate_userbadge_pdf');
add_action('wp_ajax_nopriv_generate_userbadge_pdf', 'generate_userbadge_pdf');
function generate_userbadge_pdf() {
if (!is_user_logged_in()) {
wp_die('You must be logged in to perform this action.');
}
global $wpdb;
$current_user_id = get_current_user_id();
// Fetch full name from usermeta
$full_name = get_user_meta($current_user_id, 'full_name', true);
// Secret phrase
$secret_phrase = 'mysecretyphrase';
// Generate MD5 hash of the user ID
$hashed_user_id = md5($secret_phrase . $current_user_id);
// Generate QR Code with the hashed user ID
ob_start();
QRcode::png($hashed_user_id, null, QR_ECLEVEL_L, 10);
$imageString = ob_get_contents();
ob_end_clean();
$imgdata = base64_decode(str_replace('data:image/png;base64,', '', base64_encode($imageString)));
// Get activities for the current year
$current_year = date('Y');
$activities = $wpdb->get_results($wpdb->prepare("
SELECT a.*, p.place, s.full_name as speaker, e.name as event_name, e.id as event_id
FROM {$wpdb->prefix}sige_activities a
LEFT JOIN {$wpdb->prefix}sige_place p ON a.place_id = p.id
LEFT JOIN {$wpdb->prefix}sige_speakers s ON a.speaker_id = s.id
LEFT JOIN {$wpdb->prefix}sige_event_names e ON a.event_name_id = e.id
WHERE (a.status = 'Open' OR a.status = 'Closed')
AND YEAR(a.start_date) = %d
AND a.attendance_control = 'yes'
", $current_year));
// Organize activities by event name
$events = [];
foreach ($activities as $activity) {
$enrollment_status_action = $wpdb->get_var($wpdb->prepare("
SELECT status FROM {$wpdb->prefix}sige_enrollments
WHERE activity_id = %d AND user_id = %d
", $activity->id, $current_user_id));
if (!$enrollment_status_action) {
$enrollment_status_action = 'Not Requested';
}
$events[$activity->event_name][] = [
'activity_name' => $activity->name,
'status' => $enrollment_status_action
];
}
// Create a new PDF document
$pdf = new TCPDF();
$pdf->AddPage();
// Add custom styling
$css = '
<style>
.badge-box {
position: relative;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
background-color: #fff;
max-width: 800px;
text-align: center;
}
.event-box {
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background-color: #f9f9f9;
border: 1px solid #ddd; /* Add border for the event box */
}
.event-box ul {
list-style-type: none;
}
.event-box ul li {
border: none; /* Remove borders between list items */
}
img.ita-logo {
width: 100px;
height: auto;
}
img.gladio-logo {
width: 120px;
height: auto;
}
</style>';
// Add logos (adjusted Y coordinate by 10 pixels)
$pdf->Image(plugin_dir_path(__FILE__) . 'image/ita.png', 15, 15, 27.5); // Adjusted Y coordinate to 20
$pdf->Image(plugin_dir_path(__FILE__) . 'image/gladioalado.png', 145, 15, 40); // Adjusted Y coordinate to 20
// Add QR code image
$pdf->Image('@' . $imgdata, 55, 70, 100, 100, 'PNG'); // Adjusted 100px down
// Add text
$pdf->SetXY(15, 55); // Adjusted 100px down
$pdf->writeHTMLCell(0, 0, '', '', '<h3 style="font-family: Times New Roman, Times, serif;">XXVI SYMPOSIUM ON OPERATIONAL APPLICATIONS IN DEFENSE AREAS</h3>', 0, 1, 0, true, 'C', true);
$pdf->SetXY(15, 65); // Adjusted 100px down
$pdf->writeHTMLCell(0, 0, '', '', '<h3>Event Badge</h3>', 0, 1, 0, true, 'C', true);
// Prepare the HTML content
$html_content = '<div class="badge-box">';
$html_content .= '<p align="justify" style="margin-top: 10px;">Dear <strong>' . esc_html($full_name) . '</strong>,</p>';
$html_content .= '<p align="justify">SIGE is an open event promoted by the Technological Institute of Aeronautics with the aim of creating an environment for the exchange of experiences between the academic, industrial and operational sectors of the Armed Forces, on issues of teaching, research and development in Defense areas.</p>';
$html_content .= '<p align="justify">The organizing team is made up of masters and doctoral students from the Graduate Program in Operational Applications (PPGAO) at ITA.</p>';
$html_content .= '<h3>Activities for ' . $current_year . '</h3>';
if (!empty($events)) {
foreach ($events as $event_name => $activities) {
$html_content .= '<div class="event-box"><h4><strong>' . esc_html($event_name) . '</strong></h4><ul>';
foreach ($activities as $activity) {
$html_content .= '<li>' . esc_html($activity['activity_name']) . ' - Status: ' . esc_html($activity['status']) . '</li>';
}
$html_content .= '</ul></div><p>&nbsp;</p>'; // Add <p> to separate content
}
} else {
$html_content .= '<p>No activities available for this year.</p>';
}
$html_content .= '<p style="margin-top: 20px;">Contact the event Organizing Committee for questions via email at sige@ita.br</p>';
$html_content .= '<p style="margin-top: 10px;">Generated on: ' . date('d-m-Y - H:i:s') . '</p>';
$html_content .= '</div>';
// Add HTML content
$pdf->SetXY(15, 170); // Adjusted 100px down
$pdf->writeHTMLCell(0, 0, '', '', $css . $html_content, 0, 1, 0, true, '', true);
// Output PDF
$pdf->Output('user_badge.pdf', 'D');
wp_die();
}
function verifyUserBasedOnQRCode($hashed_user_id) {
global $wpdb;
// Define the secret phrase used for hashing
$secret_phrase = 'mysecretyphrase';
// Loop through users to find the matching hash
$users = get_users();
foreach ($users as $user) {
if (md5($secret_phrase . $user->ID) === $hashed_user_id) {
return $user->ID;
}
}
// Return false if no match found
return false;
}