<?php
/**
 * Plugin Name: Voidek Employee Portal 
 * Description: A full-featured frontend employee management plugin with projects, tasks, EOD reports, and role-based dashboards.
 * Version: 1.0.8
 * Author: Voidek Webolutions 
 * Requires at least: 5.0
 * Tested up to: 6.9
 * Requires PHP: 7.4
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * Template to display a View of create Eods.
 *
 * @package voidek-employee-portal
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}


// Define plugin constants.
define( 'VOIDEMPO_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'VOIDEMPO_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );

/**
 * Register custom rewrite rules.
 */
function voidempo_ep_rewrite_rules() {

	add_rewrite_rule( '^user-dashboard/([^/]+)/?$', 'index.php?pagename=user-dashboard&custom_page=$matches[1]', 'top' );
}
add_action( 'init', 'voidempo_ep_rewrite_rules' );


/**
 * Register 'page' as a query variable.
 *
 * Adds custom query variables to WordPress's list of public query vars,
 * allowing them to be safely used in URLs and retrieved via get_query_var().
 *
 * @param array $vars Existing array of query variables.
 * @return array Modified array of query variables including 'page'.
 */
function voidempo_ep_query_vars( $vars ) {

	$vars[] = 'custom_page'; // Add the new query var.
	$vars[] = 'project_id';
	return $vars;
}
add_filter( 'query_vars', 'voidempo_ep_query_vars' );

/**
 * Flushes custom rewrite rules for the plugin.
 *
 * This function is typically called on plugin activation or permalink structure changes
 * to ensure that custom rewrite rules are correctly registered with WordPress.
 *
 * @return void
 */
function voidempo_flush_custom_rewrite_rules() {
	voidempo_ep_rewrite_rules();
	flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'voidempo_flush_custom_rewrite_rules' );

/**
 * Flush rewrite rules on plugin deactivation.
 */
function voidempo_deactivate_custom_rewrite_rules() {
	flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'voidempo_deactivate_custom_rewrite_rules' );

/**
 * Include the main class file after WordPress has loaded.
 */
function voidempo_employee_portal_init() {
	include_once VOIDEMPO_PLUGIN_PATH . 'classes/class-voidempo-main-call.php';
	$VOIDEMPO_class_includes = new VOIDEMPO_Main_Call();

	include VOIDEMPO_PLUGIN_PATH . '/classes/class-voidempo-other.php';
}
add_action( 'plugins_loaded', 'voidempo_employee_portal_init' );

/**
 * Creates the user dashboard page programmatically if it doesn't exist.
 *
 * This function checks if the user dashboard page is already created,
 * and if not, inserts a new page into the database with a predefined slug and content.
 * Useful for plugin activation to ensure frontend dashboard is available.
 *
 * @return void
 */
function voidempo_create_user_dashboard_page() {

	$page_exists = get_page_by_path( 'user-dashboard' );

	if ( ! $page_exists ) {
		// Create the page.
		$page_id = wp_insert_post(
			array(
				'post_title'   => 'User Dashboard',
				'post_name'    => 'user-dashboard',
				'post_content' => '',
				'post_status'  => 'publish',
				'post_type'    => 'page',
				'post_author'  => 1,
			)
		);

		if ( $page_id ) {
			update_option( 'voidempo_user_dashboard_page_id', $page_id );
		}
	}
}

/**
 * Deletes the 'User Dashboard' page when the plugin is deactivated.
 *
 * This function removes the custom dashboard page created during plugin activation
 * to clean up unused content.
 *
 * @return void
 */
function voidempo_delete_user_dashboard_page() {
	$page_id = get_option( 'voidempo_user_dashboard_page_id' );

	if ( $page_id ) {
		wp_delete_post( $page_id, true );
		delete_option( 'voidempo_user_dashboard_page_id' );
	}
}

// Hook into plugin activation & deactivation.
register_activation_hook( __FILE__, 'voidempo_create_user_dashboard_page' );
register_deactivation_hook( __FILE__, 'voidempo_delete_user_dashboard_page' );


/**
 * Registers the custom post type for Projects.
 *
 * This function defines the 'project' post type used to manage projects within the plugin.
 * Should be hooked to 'init'.
 *
 * @return void
 */
function voidempo_register_project_cpt() {
	$labels = array(
		'name'               => __( 'Projects', 'voidek-employee-portal' ),
		'singular_name'      => __( 'Project', 'voidek-employee-portal' ),
		'menu_name'          => __( 'Projects', 'voidek-employee-portal' ),
		'add_new'            => __( 'Add New', 'voidek-employee-portal' ),
		'add_new_item'       => __( 'Add New Project', 'voidek-employee-portal' ),
		'edit_item'          => __( 'Edit Project', 'voidek-employee-portal' ),
		'new_item'           => __( 'New Project', 'voidek-employee-portal' ),
		'view_item'          => __( 'View Project', 'voidek-employee-portal' ),
		'search_items'       => __( 'Search Projects', 'voidek-employee-portal' ),
		'not_found'          => __( 'No projects found', 'voidek-employee-portal' ),
		'not_found_in_trash' => __( 'No projects found in Trash', 'voidek-employee-portal' ),
	);

	$args = array(
		'labels'          => $labels,
		'public'          => true,
		'show_ui'         => true,
		'show_in_menu'    => true,
		'capability_type' => 'post',
		'has_archive'     => true,
		'supports'        => array( 'title', 'editor', 'thumbnail', 'author', 'custom-fields' ),
		'rewrite'         => array( 'slug' => 'projects' ),
	);

	register_post_type( 'voidempo_projects', $args );
}

add_action( 'init', 'voidempo_register_project_cpt' );


register_activation_hook( __FILE__, 'voidempo_plugin_activate' );
/**
 * Handles tasks to run when the plugin is activated.
 *
 * This function can register custom roles, options, or perform setup operations.
 *
 * @return void
 */
function voidempo_plugin_activate() {
	global $wpdb;

	// Table: leave_applications.
	$create_table_leave_applications = $wpdb->prefix. 'leave_applications';
	$users_table                     = $wpdb->prefix . 'users';
	$charset_collate                 = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $create_table_leave_applications (
        id int(11) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) UNSIGNED NOT NULL,
        month varchar(20) DEFAULT NULL,
        leave_type varchar(20) DEFAULT NULL,
        from_date date DEFAULT NULL,
        to_date date DEFAULT NULL,
        reason text DEFAULT NULL,
        status varchar(255) DEFAULT NULL,
        PRIMARY KEY  (id),
        FOREIGN KEY (user_id) REFERENCES $users_table(ID) ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB $charset_collate;";

	// Load upgrade functions.
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	dbDelta( $sql );

	$table_name_project = $wpdb->prefix . 'voidempo_projects';

	$charset_collate = $wpdb->get_charset_collate();

	$create_table_project = "CREATE TABLE $table_name_project (
        id INT AUTO_INCREMENT PRIMARY KEY,
        project_title TEXT,
        project_desc TEXT,
        related_post_id INT,
        member_id TEXT,
        manager_id TEXT,
        status TEXT,
        start_date DATE,
        end_date DATE,
        date_created DATETIME DEFAULT CURRENT_TIMESTAMP
    ) $charset_collate;";

	dbDelta( $create_table_project );

		$table_name_task   = $wpdb->prefix . 'voidempo_task';
		$create_table_task = "CREATE TABLE $table_name_task (
        id INT NOT NULL AUTO_INCREMENT,
        project_id INT,
        user_id TEXT,
        manager_id INT,
        task_title TEXT,
        task_description TEXT,
        status TEXT,
        members_status TEXT,
        estimated_hours TEXT,
        date_created DATETIME DEFAULT CURRENT_TIMESTAMP,
        complete_date DATETIME DEFAULT NULL,
        is_delete INT(11) DEFAULT 0,
        PRIMARY KEY (id)
        )";
		dbDelta( $create_table_task );

		$table_name_eod   = $wpdb->prefix . 'voidempo_eod';
		$create_table_eod = "CREATE TABLE  $table_name_eod (
        id INT NOT NULL AUTO_INCREMENT,
        project_id INT,
        task_id INT,
        user_id TEXT,
        hours TEXT,
        notes TEXT,
        status TEXT,
        date_created DATE,
        is_delete INT DEFAULT 0,
        entry_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_date DATETIME DEFAULT NULL,
        PRIMARY KEY (id)
        ) ";
		dbDelta( $create_table_eod );

		$table_name_increment = $wpdb->prefix . 'voidempo_increments';
		$sql                  = "CREATE TABLE  $table_name_increment(
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            user_id mediumint(9) NOT NULL,
            date_of_increment date NOT NULL,
            CTC_amount varchar(255) NOT NULL,
            status varchar(255) NOT NULL,
            PRIMARY KEY (id)
        ) ";
		dbDelta( $sql );

		// project log Table.
		$table_name_project_log = $wpdb->prefix . 'voidempo_projects_log';
		$charset_collate        = $wpdb->get_charset_collate();

		$create_table_project_log = "CREATE TABLE $table_name_project_log (
            id INT NOT NULL AUTO_INCREMENT,
            user_id INT NOT NULL,
            description TEXT NOT NULL,
            object_id INT NOT NULL,
            date_created DATETIME DEFAULT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";

		dbDelta( $create_table_project_log );

		// task log Table.
		$table_task_log  = $wpdb->prefix . 'voidempo_task_log';
		$charset_collate = $wpdb->get_charset_collate();

		$create_table_task_log = "CREATE TABLE $table_task_log (
            id INT NOT NULL AUTO_INCREMENT,
            user_id INT NOT NULL,
            description TEXT NOT NULL,
            object_id INT NOT NULL,
            date_created DATETIME DEFAULT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";

		dbDelta( $create_table_task_log );

		// eod log Table.
		$table_eod_log   = $wpdb->prefix . 'voidempo_eod_log';
		$charset_collate = $wpdb->get_charset_collate();

		$create_table_eod_log = "CREATE TABLE $table_eod_log (
            id INT NOT NULL AUTO_INCREMENT,
            user_id INT NOT NULL,
            description TEXT NOT NULL,
            object_id INT NOT NULL,
            date_created DATETIME DEFAULT NULL,
            PRIMARY KEY (id)
        ) $charset_collate;";

		dbDelta( $create_table_eod_log );

		// Holidays Table.
		$table_holidays  = $wpdb->prefix . 'voidempo_holidays';
		$charset_collate = $wpdb->get_charset_collate();

		$create_table_holidays = "CREATE TABLE $table_holidays (
            id INT NOT NULL AUTO_INCREMENT,
            event_title TEXT NOT NULL,
            eventstartdata DATE,
            eventenddata DATE,
            date_created DATE,
            PRIMARY KEY (id)
        ) $charset_collate;";

		dbDelta( $create_table_holidays );
}
/**
 * Adds a custom 'manager' role to WordPress with specific capabilities.
 *
 * This function can be hooked into plugin activation to ensure the role is available.
 *
 * @return void
 */
function VOIDEMPO_add_manager_role() {

    // Create role if not exists
    if ( ! get_role( 'manager' ) ) {

        add_role(
            'manager',
            'Manager',
            array(
                'read'                    => true,
                'voidempo_manager_access' => true, 
                'delete_users'            => true, 
            )
        );

    } else {

        // If role exists, ensure capability is added
        $manager = get_role( 'manager' );

         if ( $manager ) {

            if ( ! $manager->has_cap( 'voidempo_manager_access' ) ) {
                $manager->add_cap( 'voidempo_manager_access' );
            }

            if ( ! $manager->has_cap( 'delete_users' ) ) {
                $manager->add_cap( 'delete_users' ); 
            }
        }
    }
}
register_activation_hook( __FILE__, 'VOIDEMPO_add_manager_role' );



function voidempo_add_employee_cap() {
    $subscriber = get_role( 'subscriber' );
    if ( $subscriber && ! $subscriber->has_cap( 'voidempo_employee_access' ) ) {
        $subscriber->add_cap( 'voidempo_employee_access' );
    }
}
register_activation_hook( __FILE__, 'voidempo_add_employee_cap' );


function voidempo_remove_caps_on_deactivation() {

    // Remove manager capabilities
    $manager = get_role( 'manager' );
    if ( $manager ) {
        $manager->remove_cap( 'voidempo_manager_access' );
        $manager->remove_cap( 'delete_users' );
      
    }

    // Remove employee (subscriber) capabilities
    $subscriber = get_role( 'subscriber' );
    if ( $subscriber ) {
        $subscriber->remove_cap( 'voidempo_employee_access' );
    }
}
register_deactivation_hook( __FILE__, 'voidempo_remove_caps_on_deactivation' );