<?php

/**
 * Plugin Name: WP TTAR
 * Plugin URI: https://ommune.com/codecanyon/wpttar/
 * Description: WP TTAR plugin by Ommune.
 * Version: 1.0.10
 * Author: Ommune
 * Author URI: https://ommune.com
 * Text Domain: wpttar
 */
require_once('wp-ttar-config.php');
require_once('wp-ttar-reports.php');
Class WPTTAR extends WPTTARConfig {

    // Define Global Variables and Other Private and Protected Variables For The WP-TTAR Plugin.
    // Constructor For The Default Call Actions
    function __construct() {
        define('WPTTARMPDF', dirname(__FILE__) . '/library/wp-ttar-pdf/');
        define('WPTTARLIB', dirname(__FILE__) . '/library/wp-ttar/');
        add_action('admin_enqueue_scripts', array(&$this, 'WPTTARAssets'));
        add_action('init', array(&$this, 'WPTTARTextDomain'));
        add_action('admin_init', array(&$this, 'WPTTARAssets'));
        add_action('admin_menu', array(&$this, 'WPTTARMenu'));
        add_action('wp_login', array(&$this, 'WPTTARLoginUser'), 10, 2);
        register_activation_hook(__FILE__, array(&$this, 'WPTTARPluginActivation'));
        register_deactivation_hook(__FILE__, array(&$this, 'WPTTARPluginDeactive'));
        $wpttarReporting = new WPTTARReporting($this);
        $this->WPTTARREPORTS = $wpttarReporting;
    }

    /* WP TTAR Assets * */

    public function WPTTARAssets() {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        wp_enqueue_style('wp-custom-css', plugins_url('assets/css/wp-custom.css', __FILE__), '');
        wp_enqueue_script('wpttar-loader-js', plugins_url('assets/js/wp-ttar-loader.js', __FILE__), '');
        wp_localize_script('wpttar-loader-js', 'WPTTARLoaderJS', array('CurrectRole' => $wpttarUserRole));
        wp_enqueue_style('wpttar-font-awesome-css', plugins_url('assets/css/font-awesome.min.css', __FILE__), '');
        wp_register_style('wpttar-bootstrap-min-css', plugins_url('assets/css/bootstrap.min.css', __FILE__), '');
        wp_register_style('wpttar-jquery.simple-dtpicker-css', plugins_url('assets/css/jquery.simple-dtpicker.css', __FILE__), '');
        wp_register_style('wpttar-css', plugins_url('assets/css/wp-ttar.css', __FILE__), array(), '');
        wp_register_script('wpttar-bootstrap-fileinput-js', plugins_url('assets/js/bootstrap-fileinput.js', __FILE__), '');
        wp_register_style('wpttar-datepicker3-css', plugins_url('assets/css/datepicker3.css', __FILE__), '');
        wp_register_script('wpttar-multiple-select-option-js', plugins_url('assets/js/sol.js', __FILE__), '');
        wp_register_script('wpttar-jquery.simple-dtpicker-js', plugins_url('assets/js/jquery.simple-dtpicker.js', __FILE__), '');
        wp_register_script('wpttar-jquery-jqplot-min-js', plugins_url('assets/js/jquery.jqplot.min.js', __FILE__), '');
        wp_register_script('wpttar-jqplot-barRenderer-min-js', plugins_url('assets/js/jqplot.barRenderer.min.js', __FILE__), '');
        wp_register_script('wpttar-jqplot-categoryAxisRenderer-min-js', plugins_url('assets/js/jqplot.categoryAxisRenderer.min.js', __FILE__), '');
        wp_register_script('wpttar-jqplot-pointLabels-min-js', plugins_url('assets/js/jqplot.pointLabels.min.js', __FILE__), '');
        wp_register_script('wpttar-jqplot-highlighter-min-js', plugins_url('assets/js/jqplot.highlighter.min.js', __FILE__), '');
        wp_register_script('wpttar-bootstrap-datepicker-js', plugins_url('assets/js/bootstrap-datepicker.js', __FILE__), '');
        wp_register_script('wpttar-jquery-validate-js', plugins_url('assets/js/jquery.validate.min.js', __FILE__), '');
        wp_register_script('wpttar-bootstrap-min-js', plugins_url('assets/js/bootstrap.min.js', __FILE__), '');
        wp_register_script('wpttar-jquery-dataTables-min-js', plugins_url('assets/js/jquery.dataTables.min.js', __FILE__), '');
        wp_register_script('wpttar-dataTables-bootstrap-js', plugins_url('assets/js/dataTables.bootstrap.js', __FILE__), '');
        wp_register_script('wpttar-custom-js', plugins_url('assets/js/wp-ttar.js', __FILE__), '');
        wp_register_script('wpttar-timer-jquery-js', plugins_url('assets/js/timer.jquery.js', __FILE__), '');
    }

    //** All Js and Css Enqueeues Function**//
    public function WPTTAREnqueues() {
        wp_enqueue_media();
        wp_enqueue_style('wpttar-bootstrap-min-css');
        wp_enqueue_style('wpttar-css');
        wp_enqueue_script('wpttar-bootstrap-fileinput-js');
        wp_enqueue_script('wpttar-multiple-select-option-js');
        wp_enqueue_script('wpttar-jquery.simple-dtpicker-js');
        wp_enqueue_script('wpttar-jquery-jqplot-min-js');
        wp_enqueue_script('wpttar-jqplot-barRenderer-min-js');
        wp_enqueue_script('wpttar-jqplot-categoryAxisRenderer-min-js');
        wp_enqueue_script('wpttar-jqplot-pointLabels-min-js');
        wp_enqueue_script('wpttar-jqplot-highlighter-min-js');
        wp_enqueue_script('wpttar-bootstrap-datepicker-js');
        wp_enqueue_script('wpttar-jquery-validate-js');
        wp_enqueue_script('wpttar-bootstrap-min-js');
        wp_enqueue_script('wpttar-jquery-dataTables-min-js');
        wp_enqueue_script('wpttar-dataTables-bootstrap-js');
        wp_enqueue_script('wpttar-timer-jquery-js');
        wp_enqueue_script('wpttar-custom-js');

        wp_localize_script('wpttar-custom-js', 'WPTTARCustomJS', array('records' => __('Records :', 'wpttar'),
            'sortAscending' => __(': activate to sort column ascending', 'wpttar'), 'sortDescending' => __(': activate to sort column descending', 'wpttar'),
            'emptyTable' => __('No data available', 'wpttar'), 'info' => __('Showing _START_ to _END_ of _TOTAL_ entries', 'wpttar'),
            'infoEmpty' => __('No entries found', 'wpttar'), 'infoFiltered' => __('filtered1 from _MAX_ total entries', 'wpttar'),
            'lengthMenu' => __('Show _MENU_ entries', 'wpttar'), 'search' => __('Search:', 'wpttar'),
            'zeroRecords' => __('No matching records found'), 'DocumentsName' => __('Documents Name'), 'DocumentsUrl' => __('Documents Url'), 'ExportMsg' => __('Export have no data found!'))
        );
        wp_localize_script('wpttar-jquery-dataTables-min-js', 'WPTTARJS', array('sSearch' => __('Search :', 'wpttar'), 'sSortAscending' => __(': activate to sort column ascending', 'wpttar'), 'sSortDescending' => __(': activate to sort column descending', 'wpttar'), 'sFirst' => __('First', 'wpttar'), 'sLast' => __('Last', 'wpttar')
            , 'sNext' => __('Next :', 'wpttar'), 'sPrevious' => __('Previous', 'wpttar'), 'sEmptyTable' => __('No data available in table', 'wpttar'), 'sInfo' => __('Showing ', 'wpttar'), 'of' => __('of', 'wpttar'), 'to' => __('to', 'wpttar'), 'entries' => __('entries', 'wpttar'), 'sInfoEmpty' => __('Showing 0 to 0 of 0 entries', 'wpttar'), 'totalentries' => __('total entries', 'wpttar'), 'filteredfrom' => __('filtered from', 'wpttar'), 'sLoadingRecords' => __('Loading...', 'wpttar')
            , 'sProcessing' => __('Processing...', 'wpttar'), 'sZeroRecords' => __('No matching records found', 'wpttar')));

        wp_localize_script('wpttar-multiple-select-option-js', 'WPTTARSol', array('noItemsAvailable' => __('No entries found', 'wpttar'), 'selectAll' => __('Select all', 'wpttar'), 'selectNone' => __('Select none', 'wpttar'), 'quickDelete' => __('times', 'wpttar'), 'searchplaceholder' => __('Click here to search', 'wpttar')
            , 'loadingData' => __('Still loading data...', 'wpttar'), 'itemsSelected' => __('items selected', 'wpttar'), 'itemsattribute' => __('name attribute is required', 'wpttar')));
    }

    /* WP-TTAR Text Domain * */

    public function WPTTARTextDomain() {
        load_plugin_textdomain('wpttar', false, basename(dirname(__FILE__)) . '/languages');
        // $this->redirect_login_page();
    }

    /* WP-TTAR Menu * */

    public function WPTTARMenu() {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $wpttarGetPagePermissions = $this->WPTTARGetPagePermissions();
        $wpttarViewOnlyPermissionPages = $this->WPTTARViewOnlyPermissionPages();

        if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
            $wpttarPage = add_menu_page('WP TTAR', __('WP TTAR', 'wpttar'), 'wpttar-dashboard', 'wpttar', '', '');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            $wpttarPage = add_submenu_page('wpttar', 'Dashboard', __('Dashboard', 'wpttar'), 'manage_options_projects', 'wpttar-dashboard', array(&$this, 'WPTTARDashboard'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        } else {
            $wpttarPage = add_menu_page('WP TTAR', __('WP TTAR', 'wpttar'), 'wpttar-dashboard', 'wpttar', '', '');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            $wpttarPage = add_submenu_page('wpttar', 'Dashboard', __('Dashboard', 'wpttar'), 'manage_options_projectView', 'wpttar-dashboard', array(&$this, 'WPTTARDashboard'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }

        if (empty($wpttarViewOnlyPermissionPages)) {
            if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
                $wpttarPage = add_submenu_page('wpttar', 'Projects', __('Projects', 'wpttar'), 'manage_options_projects', 'wpttar-projects', array(&$this, 'WPTTARProjects'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            } else {
                $wpttarPage = add_submenu_page('wpttar', 'Projects', __('Projects', 'wpttar'), 'manage_options_projectView', 'wpttar-developer-projects-details', array(&$this, 'WPTTARDeveloperProjectsDetails'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            }


            $wpttarPage = add_submenu_page('wpttar', 'Team Members', __('Team Members', 'wpttar'), 'manage_options_projects', 'wpttar-development-team', array(&$this, 'WPTTARPDevelopmentTeamCallback'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

            if (in_array('manage_options_projectView', $wpttarGetPagePermissions)) {
                if (isset($wpttarUserRole) && !in_array('administrator', $current_user->roles)) {
                    $wpttarPage = add_submenu_page('wpttar', 'Log Status', __('Log Status', 'wpttar'), 'manage_options_projectView', 'wpttar-project-custom-log', array(&$this, 'WPTTARProjectCustomLogs'), 'Project');
                    add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
                }
            }
            if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
                if (isset($wpttarUserRole) && in_array('administrator', $current_user->roles)) {
                    $wpttarPage = add_submenu_page('wpttar', 'Log Request', __('Log Request', 'wpttar'), 'manage_options_projects', 'wpttar-project-custom-log', array(&$this, 'WPTTARProjectCustomLogs'), 'Project');
                    add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
                }
            }

            $wpttarPage = add_submenu_page('wpttar', 'Settings', __('Settings', 'wpttar'), 'manage_options_wpttarsettings', 'wpttar-settings', array(&$this, 'WPTTARPSettingsCallback'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));



            $wpttarPage = add_submenu_page('wpttar', 'FB Support Group', __('Follow Us on Facebook', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-fb-support', array(&$this, 'WPTTARFBSupportCallback'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            $wpttarPage = add_submenu_page('wpttar', 'Support Desk', __('Support', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-support', array(&$this, 'WPTTARSupportCallback'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            $wpttarPage = add_submenu_page('wpttar', 'Documentation', __('Documentation', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-documentation', array(&$this, 'WPTTARDocumentsSupportCallback'));
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        } else {
            $this->wpttarAddMainMenu($wpttarViewOnlyPermissionPages);
        }

        if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
            $wpttarPage = add_submenu_page('wpttar-development-team', '', '', 'manage_options_projects', 'wpttar-developer-projects-details', array(&$this, 'WPTTARDeveloperProjectsDetails'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }

        $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projects', 'wpttar-add-project', array(&$this, 'WPTTARAddProject'), 'Project');
        add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

        if (in_array('manage_options_projectView', $wpttarGetPagePermissions)) {
            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projectView', 'wpttar-project-view', array(&$this, 'WPTTARProjectView'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }

        if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projects', 'wpttar-project-view', array(&$this, 'WPTTARProjectView'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }

        if (in_array('manage_options_projectView', $wpttarGetPagePermissions)) {
            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projectView', 'wpttar-project-logs', array(&$this, 'WPTTARProjectLogs'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projectView', 'wpttar-projects-reports', array(&$this, 'WPTTARProjectsReports'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projectView', 'wpttar-developer-projects-comments', array(&$this, 'WPTTARDeveloperProjectsComments'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }

        if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projects', 'wpttar-project-logs', array(&$this, 'WPTTARProjectLogs'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projects', 'wpttar-projects-reports', array(&$this, 'WPTTARProjectsReports'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));

            $wpttarPage = add_submenu_page('wpttar-projects', '', '', 'manage_options_projects', 'wpttar-developer-projects-comments', array(&$this, 'WPTTARDeveloperProjectsComments'), 'Project');
            add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
        }
    }

    /** WP-TTAR Activation Plugin * */
    public function WPTTARPluginActivation() {
        global $wpdb;
        require_once('wp-ttar-import.php');
        $WpttarImport = new WpttarImport();
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarProjectsTable'") != $this->WpttarProjectsTable) :
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS `$this->WpttarProjectsTable` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `authorID` int(11) NOT NULL,
                    `projectName` varchar(255) NOT NULL,
                    `members` varchar(255) NOT NULL,
                    `clientName` varchar(100) NOT NULL,
                    `description` varchar(255) NOT NULL,
                    `projectStatus` enum('Open','Close','Reopen') NOT NULL,
                    `lastUpdate` date DEFAULT NULL,
                    `dateTime` date DEFAULT NULL,
                    PRIMARY KEY (`id`)
                  )";
            dbDelta($sql);
        endif;

        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarCustomProjectLogTable'") != $this->WpttarCustomProjectLogTable) :
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS `$this->WpttarCustomProjectLogTable` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `wpttarUserID` int(11) NOT NULL,
                    `startTime` datetime NOT NULL,
                    `endTime` datetime NOT NULL,
                    `projectID` int(11) NOT NULL,
                    `wpttarStatus` enum('pending','approved','rejected') NOT NULL,
                    `projectComment` longtext NOT NULL,
                    `wpttarDate` date NOT NULL,
                    PRIMARY KEY (`id`)
                  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;";
            dbDelta($sql);
        endif;
        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarAttachmentsTable'") != $this->WpttarAttachmentsTable) :
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS `$this->WpttarAttachmentsTable` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `authorID` int(11) NOT NULL,
                    `projectID` int(11) NOT NULL,
                    `documentName` text NOT NULL,
                    `attachmentLink` text NOT NULL,
                    `lastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    `dateTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
                    PRIMARY KEY (`id`)
                  )";
            dbDelta($sql);
        endif;

        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarTeamsTable'") != $this->WpttarTeamsTable) :
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS `wpttar_teams` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `authorID` int(11) NOT NULL,
                    `projectID` int(11) NOT NULL,
                    `teamName` varchar(100) NOT NULL,
                    `teamMember` int(11) NOT NULL,
                    `lastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    `dateTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
                    PRIMARY KEY (`id`)
                  )";
            dbDelta($sql);
        endif;

        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarMessagesTable'") != $this->WpttarMessagesTable) :
            $WpttarImport->sqlImport(WPTTARLIB . 'wpttar_messages.sql');
        endif;

        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarSettingsTable'") != $this->WpttarSettingsTable) :
            $WpttarImport->sqlImport(WPTTARLIB . 'wpttar_settings.sql');
        endif;

        if ($wpdb->get_var("SHOW TABLES LIKE '$this->WpttarProjectsLogTable'") != $this->WpttarProjectsLogTable) :
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS `$this->WpttarProjectsLogTable` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `projectID` int(11) NOT NULL,
                    `developerID` int(11) NOT NULL,
                    `startTime` time NOT NULL,
                    `endTime` time NOT NULL,
                    `workedHour` time NOT NULL,
                    `userComment` text NOT NULL,
                    `updateDate` date NOT NULL,
                    PRIMARY KEY (`id`)
                  )";
            dbDelta($sql);
        endif;
        
         $results = $wpdb->query("SHOW COLUMNS FROM `$this->WpttarProjectsTable` LIKE 'members'");
         if ($results == true) {
                $wpdb->query("ALTER TABLE `$this->WpttarProjectsTable` MODIFY COLUMN `members` text");
            }
      
        $this->WPTTARAddCapabilityWithRole();
    }

    /** WPTTAR get user roles
     *   @access only relative the family
     *   @no-argument
     *   @return all user roles
     * */
    public function WPTTARGetUserRoles() {
        global $wp_roles;
        $wpttarUserRole = $wp_roles->roles;
        $wpttarUserRoles = array();
        foreach ($wpttarUserRole as $k => $role) :
            $wpttarUserRoles[$k] = $role['name'];
        endforeach;
        return $wpttarUserRoles;
    }

    /** WP-TTAR Add Capability Plugin * */
    public function WPTTARAddCapabilityWithRole() {

        $getAllRoles = $this->WPTTARGetUserRoles();
        foreach ($getAllRoles as $key => $role) {
            if ($key == 'administrator') {
                $role_admin = get_role($key);
                $role_admin = get_role($key);
                if (isset($role_admin->capabilities['manage_options_projects']) && $role_admin->capabilities['manage_options_projects'] == 1) {
                    
                } else {
                    $role_admin->add_cap('manage_options_projects');
                }

                if (isset($role_admin->capabilities['manage_options_wpttarsettings']) && $role_admin->capabilities['manage_options_wpttarsettings'] == 1) {
                    
                } else {
                    $role_admin->add_cap('manage_options_wpttarsettings');
                }
                if (isset($role_admin->capabilities['manageOptionswpttarFbGroup']) && $role_admin->capabilities['manageOptionswpttarFbGroup'] == 1) {
                    
                } else {
                    $role_admin->add_cap('manageOptionswpttarFbGroup');
                }
                $role_admin->add_cap('read');
            } else {
                $role_subscriber = get_role($key);
                if (isset($role_subscriber->capabilities['manage_options_projectView']) && $role_subscriber->capabilities['manage_options_projectView'] == 1) {
                    $role_subscriber->remove_cap('manage_options_projects');
                    $role_subscriber->add_cap('manage_options_projectView');
                } else if (isset($role_subscriber->capabilities['manage_options_projects']) && $role_subscriber->capabilities['manage_options_projects'] == 1) {
                    $role_subscriber->remove_cap('manage_options_projectView');
                    $role_subscriber->add_cap('manage_options_projects');
                } else {
                    $role_subscriber->remove_cap('manage_options_projects');
                    $role_subscriber->add_cap('manage_options_projectView');
                }

                if (isset($role_subscriber->capabilities['manage_options_projectView']) && $role_subscriber->capabilities['manage_options_projectView'] == 1) {
                    $role_subscriber->remove_cap('manage_options_projects');
                    $role_subscriber->add_cap('manage_options_projectView');
                } else if (isset($role_subscriber->capabilities['manage_options_projects']) && $role_subscriber->capabilities['manage_options_projects'] == 1) {
                    $role_subscriber->remove_cap('manage_options_projectView');
                    $role_subscriber->add_cap('manage_options_projects');
                } else {
                    $role_subscriber->remove_cap('manage_options_projects');
                    $role_subscriber->add_cap('manage_options_projectView');
                }

                $role_subscriber->add_cap('read');
            }
        }
        return;
    }

    /** End WP-TTAR All Roles and Capability Functions * */
    public function WPTTARAddRoles() {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $message = array();
        $wpttarGetDefineCapability = array();
        $wpttarAccess = array();
        $wpttarUserCapability = array();
        $wpttar_rolename = '';
        $wpttar_rolenames = '';
        $wpttar_displayname = '';
        $pagename = $_POST['pageName'];
        $wpttarAll = $_POST['wpttar-all'];


        if (isset($_POST['wpttar_user_permission']) && $_POST['wpttar_user_permission'] != '') {
            $wpttar_rolenames = sanitize_text_field($_POST['wpttar_user_permission']);
        } else if (isset($_POST['wpttar_rolename']) && $_POST['wpttar_rolename'] != '') {
            $wpttar_displaynames = sanitize_text_field($_POST['wpttar_rolename']);
            $rolenames = strtolower($wpttar_displaynames);
            $rolenames = str_replace(' ', '_', $rolenames);
            $wpttar_rolenames = sanitize_text_field($rolenames);
        }


        if ($wpttar_rolenames != '') {
            foreach ($pagename as $pageKey => $pagenames) {
                foreach ($wpttarAll as $wpttarAllKey => $wpttarAllpermission) {
                    if ($pageKey == $wpttarAllKey) {
                        if ($wpttarAllpermission == 'all') {
                            $wpttarAccess[] = $pagenames;
                        }
                    }
                }
            }

            $wpttarGetAccess = $this->WPTTARGetAccess($wpttarAccess);
            $wpttarGetDefines = base64_encode(serialize($wpttarGetAccess));
            $checkPageAccess = $this->WPTTARCheckPageAccess($wpttar_rolenames);
            if (empty($checkPageAccess)) {
                $wpdb->insert($this->WpttarSettingsTable, array('authorID' => 'defineaccess', 'settingKey' => $wpttar_rolenames, 'settingValue' => $wpttarGetDefines));
            } else {
                $whereArray = array('authorID' => 'defineaccess', 'settingKey' => $wpttar_rolenames);
                $datas = array('settingValue' => $wpttarGetDefines);
                $wpdb->update($this->WpttarSettingsTable, $datas, $whereArray);
            }
        }

        if ((isset($_POST['roleAction']) && $_POST['roleAction'] == 'add-role')) {
            if (isset($_POST['wpttar_rolename']) && $_POST['wpttar_rolename'] != '') {
                $wpttar_displayname = sanitize_text_field($_POST['wpttar_rolename']);
            }
            $rolename = strtolower($wpttar_displayname);
            $rolename = str_replace(' ', '_', $rolename);
            $wpttar_rolename = sanitize_text_field($rolename);

            $checkExistRole = get_role($rolenameget);
            if (empty($checkExistRole)) {
                add_role($wpttar_rolename, $wpttar_displayname, array('read' => true));
            }
            $wpttarUserCapabilities = $this->wpttarUserDefineCapability;
            foreach ($wpttarUserCapabilities as $key => $wpttarUserCapabilities) {
                $wpttarUserCapability[] = $key;
            }
            $getRoles = get_role($wpttar_rolename);
            $wpttarCheckPages = $this->wpttarCheckPages;
            foreach ($getRoles->capabilities as $key => $wpttarDefineCapability) {
                if (in_array($key, $wpttarUserCapability)) {
                    $wpttarGetDefineCapability[] = $key;
                }
            }
            $wpttarGetDefineCapabilityData = array_merge_recursive($wpttarGetDefineCapability, $wpttarCheckPages);
            $this->wpttarPageInAddCapability($wpttar_rolename, $pagename, $wpttarAll, $wpttarGetDefineCapabilityData);
            if (empty($checkExistRole)) {
                $message['success'] = __('Role has been successfully added.', 'wpttar');
            } else {
                $message['error'] = __('Something went wrong', 'wpttar');
            }
            echo json_encode($message);
            exit;
        } else if ((isset($_POST['roleAction']) && $_POST['roleAction'] == 'edit-role')) {
            if (isset($_POST['wpttar_user_permission']) && $_POST['wpttar_user_permission'] != '') {
                $wpttar_rolename = sanitize_text_field($_POST['wpttar_user_permission']);
            }
            $wpttarUserCapabilities = $this->wpttarUserDefineCapability;
            foreach ($wpttarUserCapabilities as $key => $wpttarUserCapabilities) {
                $wpttarUserCapability[] = $key;
            }
            $getRoles = get_role($wpttar_rolename);
            $wpttarCheckPages = $this->wpttarCheckPages;
            foreach ($getRoles->capabilities as $key => $wpttarDefineCapability) {
                if (in_array($key, $wpttarUserCapability)) {
                    $wpttarGetDefineCapability[] = $key;
                }
            }
            $wpttarGetDefineCapabilityData = array_merge_recursive($wpttarGetDefineCapability, $wpttarCheckPages);
            $this->wpttarPageInAddCapability($wpttar_rolename, $pagename, $wpttarAll, $wpttarGetDefineCapabilityData);


            if (isset($_POST['roleAction']) && $_POST['roleAction'] == 'edit-role') {
                $message['success'] = __('Role has been successfully updated.', 'wpttar');
            } else {
                $message['error'] = __('Something went wrong', 'wpttar');
            }
        }
        echo json_encode($message);
        exit;
    }

    public function WPTTARGetAccess($wpttarAccess) {
        $getPages = array();
        foreach ($wpttarAccess as $wpttarAccessPage) {
            if ($wpttarAccessPage == 'manage_options_projectView') {
                $getPages[] = 'manage_options_projects';
            } else {
                $getPages[] = $wpttarAccessPage;
            }
        }
        return $getPages;
    }

    public function wpttarPageInAddCapability($wpttar_rolename, $pagename, $wpttarAll, $wpttarGetDefineCapabilityData) {
        $getRoles = get_role($wpttar_rolename);
        foreach ($pagename as $pageKey => $pagenames) {
            foreach ($wpttarAll as $wpttarAllKey => $wpttarAllpermission) {
                if ($pageKey == $wpttarAllKey) {
                    if (in_array($pagenames, $wpttarGetDefineCapabilityData)) {
                        if (isset($pagenames) && $pagenames == 'manage_options_projectView') {
                            if (isset($getRoles->capabilities['manage_options_projectView']) && $getRoles->capabilities['manage_options_projectView'] == 1) {
                                if ($wpttarAllpermission == 'all') {
                                    $getRoles->remove_cap('manage_options_projectView');
                                    $getRoles->add_cap('manage_options_projects');
                                }
                            }
                        } else if (isset($pagenames) && $pagenames == 'manage_options_wpttarsettings') {
                            if (isset($getRoles->capabilities['manage_options_wpttarsettings']) && $getRoles->capabilities['manage_options_wpttarsettings'] == 1) {
                                if ($wpttarAllpermission == 'view') {
                                    $getRoles->remove_cap('manage_options_wpttarsettings');
                                }
                            } else {
                                if ($wpttarAllpermission == 'view') {
                                    $getRoles->remove_cap('manage_options_wpttarsettings');
                                } else if ($wpttarAllpermission == 'all') {
                                    $getRoles->add_cap('manage_options_wpttarsettings');
                                }
                            }
                        } else if (isset($pagenames) && $pagenames == 'manageOptionswpttarFbGroup') {
                            if (isset($getRoles->capabilities['manageOptionswpttarFbGroup']) && $getRoles->capabilities['manageOptionswpttarFbGroup'] == 1) {
                                if ($wpttarAllpermission == 'view') {
                                    $getRoles->remove_cap('manageOptionswpttarFbGroup');
                                }
                            } else {
                                if ($wpttarAllpermission == 'view') {
                                    $getRoles->remove_cap('manageOptionswpttarFbGroup');
                                } else if ($wpttarAllpermission == 'all') {
                                    $getRoles->add_cap('manageOptionswpttarFbGroup');
                                }
                            }
                        }
                    } else {
                        if (isset($pagenames) && $pagenames == 'manage_options_projects') {
                            if ($wpttarAllpermission == 'view') {
                                $getRoles->remove_cap('manage_options_projects');
                                $getRoles->add_cap('manage_options_projectView');
                            } else if ($wpttarAllpermission == 'all') {
                                $getRoles->remove_cap('manage_options_projectView');
                                $getRoles->add_cap('manage_options_projects');
                            }
                        } else if (isset($pagenames) && $pagenames == 'manage_options_wpttarsettings') {
                            if ($wpttarAllpermission == 'all') {
                                $getRoles->add_cap('manage_options_wpttarsettings');
                            }
                        } else if (isset($pagenames) && $pagenames == 'manageOptionswpttarFbGroup') {
                            if ($wpttarAllpermission == 'all') {
                                $getRoles->add_cap('manageOptionswpttarFbGroup');
                            }
                        }
                    }
                }
            }
        }
        return;
    }

    public function wpttarAddMainMenu($wpttarManupages) {

        foreach ($wpttarManupages as $pageKey => $pagenames) {
            if ($pagenames == 'manage_options_projects') {
                $wpttarPage = add_submenu_page('wpttar', 'Projects', __('Projects', 'wpttar'), 'manage_options_projects', 'wpttar-projects', array(&$this, 'WPTTARProjects'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
                $wpttarPage = add_submenu_page('wpttar', 'Team Members', __('Team Members', 'wpttar'), 'manage_options_projects', 'wpttar-development-team', array(&$this, 'WPTTARPDevelopmentTeamCallback'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            } else if ($pagenames == 'manage_options_wpttarsettings') {
                $wpttarPage = add_submenu_page('wpttar', 'Settings', __('Settings', 'wpttar'), 'manage_options_wpttarsettings', 'wpttar-settings', array(&$this, 'WPTTARPSettingsCallback'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            } else if ($pagenames == 'manageOptionswpttarFbGroup') {
                $wpttarPage = add_submenu_page('wpttar', 'FB Support Group', __('Follow Us on Facebook', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-fb-support', array(&$this, 'WPTTARFBSupportCallback'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
                $wpttarPage = add_submenu_page('wpttar', 'Support Desk', __('Support', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-support', array(&$this, 'WPTTARSupportCallback'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
                $wpttarPage = add_submenu_page('wpttar', 'Documentation', __('Documentation', 'wpttar'), 'manageOptionswpttarFbGroup', 'wpttar-documentation', array(&$this, 'WPTTARDocumentsSupportCallback'));
                add_action("admin_print_styles-{$wpttarPage}", array(&$this, 'WPTTAREnqueues'));
            }
        }
        return;
    }

    public function wpttarRoleWiseCapabilityGet() {
        $message = array();
        $rolenameget = '';
        if (isset($_POST['rolenameget']) && $_POST['rolenameget'] != '') {
            $rolenameget = sanitize_text_field($_POST['rolenameget']);
        }
        $getRoles = get_role($rolenameget);
        $wpttarCheckPages = $this->wpttarCheckPages;
        foreach ($getRoles->capabilities as $key => $wpttarDefineCapability) {
            $wpttarGetDefineCapability[] = $key;
        }
        $wpttarGetDefineCapabilityData = array_merge_recursive($wpttarGetDefineCapability, $wpttarCheckPages);
        $wpttarUserCapabilities = $this->wpttarUserCapabilities;
        foreach ($wpttarUserCapabilities as $key => $wpttarUserCapabilities) {
            $wpttarUserCapability[] = $wpttarUserCapabilities;
        }
        $wpttarUserDefineCapabilities = $this->wpttarUserDefineCapability;
        $i = 1;
        $html .='<thead><tr><th>' . __('Role Name', 'wpttar') . '</th>
                                    <th>' . __('Permissions', 'wpttar') . '</th>
                                </tr>
                            </thead>';

        foreach ($wpttarUserDefineCapabilities as $key => $getRole) {
            if (in_array($key, $wpttarGetDefineCapabilityData)) {
                if (in_array($key, $wpttarUserCapability)) {
                    $html .= '<tr>td>' . $i . '</td>' .
                            '<td>' . $getRole . '</td>' .
                            '<td><div class="radio-list" data-error-container="#form_2_membership_error">' .
                            '<input type="hidden" name="pageName[' . $i . ']" value=' . $key . '>' .
                            '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="all" type="radio">&nbsp;' . __('All', 'wpttar') . ' &nbsp;&nbsp;&nbsp;&nbsp;' .
                            '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="view" checked type="radio">&nbsp;' . __('Only', 'wpttar') . ' View' .
                            '</div></td></tr>';
                } else {
                    if (in_array($key, $wpttarGetDefineCapability)) {
                        $html .= '<tr>td>' . $i . '</td>' .
                                '<td>' . $getRole . '</td>' .
                                '<td><div class="radio-list" data-error-container="#form_2_membership_error">' .
                                '<input type="hidden" name="pageName[' . $i . ']" value=' . $key . '>' .
                                '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="all" checked type="radio">&nbsp;' . __('All', 'wpttar') . ' &nbsp;&nbsp;&nbsp;&nbsp;' .
                                '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="view" type="radio">&nbsp;' . __('Only', 'wpttar') . ' View' .
                                '</div></td></tr>';
                    } else {
                        $html .= '<tr>td>' . $i . '</td>' .
                                '<td>' . $getRole . '</td>' .
                                '<input type="hidden" name="pageName[' . $i . ']" value=' . $key . '>' .
                                '<td><div class="radio-list" data-error-container="#form_2_membership_error">' .
                                '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="all" type="radio">&nbsp;' . __('All', 'wpttar') . ' &nbsp;&nbsp;&nbsp;&nbsp;' .
                                '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="view" checked type="radio">&nbsp;' . __('Only', 'wpttar') . ' View' .
                                '</div></td></tr>';
                    }
                }
            }
            $i++;
        }
        $html .='<input type="hidden" name="roleAction" value="edit-role">';

        if (isset($html)) {
            $message['success'] = $html;
        } else {
            $message['error'] = __('Something went wrong', 'wpttar');
        }
        echo json_encode($message);
        exit;
    }

    public function WPTTARGetRoles() {
        $message = array();
        $wpttarUserAllRoles = $this->WPTTARGetUserRoles();
        $getOption .='<option value="">--' . __('Select', 'wpttar') . '--</option>';
        $array = array('administrator');
        foreach ($wpttarUserAllRoles as $key => $wpttarUserRoles) {
            if (!in_array($key, $array)) {
                $getOption .='<option value=' . esc_attr($key) . '>' . esc_html($wpttarUserRoles) . '</option>';
            }
        }
        $message['success'] = $getOption;
        echo json_encode($message);
        exit;
    }

    /** WPTTAR Team Member Role Assign Function * */
    public function WPTTARTeamMemberRoleAssign() {
        global $current_user, $wpdb;
        $result = array();
        $wpttarFormDetailsData = array();
        $wpdb->query("DELETE FROM `$this->WpttarSettingsTable` WHERE `settingKey`= 'wpttarTeamMemberInfo'");
        if (isset($_POST['wpttar-team-member-name']) && !empty($_POST['wpttar-team-member-name'])) {
            $wpttarFormDetailsData = $this->WPTTARSetSerialize($_POST['wpttar-team-member-name']);
        } 
        $wpttarDatas = $wpttarFormDetailsData;
        $wpttarData = array('settingKey' => 'wpttarTeamMemberInfo', 'settingValue' => sanitize_text_field($wpttarDatas));
        $wpdb->insert($this->WpttarSettingsTable, $wpttarData);
        $result['success'] = __('Team member roles has been successfully added.', 'wpttar');
        echo json_encode($result);
        exit;
    }

    public function WPTTARGetDefaultRolePages() {
        $message = array();
        $wpttarUserDefineCapabilities = $this->wpttarDefineCapability;
        $i = 1;
        $html .='<thead><tr><th>' . __('Role Name', 'wpttar') . '</th>
                            <th>' . __('Permissions', 'wpttar') . '</th>
                         </tr></thead>';

        foreach ($wpttarUserDefineCapabilities as $key => $getRole) {
            $html .= '<tr>td>' . $i . '</td>' .
                    '<td>' . $getRole . '</td>' .
                    '<td><div class="radio-list" data-error-container="#form_2_membership_error">' .
                    '<input type="hidden" name="pageName[' . $i . ']" value=' . $key . '>' .
                    '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="all" type="radio">&nbsp;' . __('All', 'wpttar') . ' &nbsp;&nbsp;&nbsp;&nbsp;' .
                    '<input style="margin: 9px 4px 10px;" name="wpttar-all[' . $i . ']" id="wpttar-according-' . $i . '" value="view" checked type="radio">&nbsp;' . __('Only View', 'wpttar') . '' .
                    '</div></td></tr>';
            $i++;
        }
        $html .='<input type="hidden" name="roleAction" value="add-role">';
        if (isset($html)) {
            $message['success'] = $html;
        } else {
            $message['error'] = __('Something went wrong', 'wpttar');
        }
        echo json_encode($message);
        exit;
    }

    public function WPTTARGetPagePermissions() {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $allRoles = array();
        $getRoles = get_role($wpttarUserRole);
        foreach ($getRoles->capabilities as $key => $getRole) {
            $allRoles[] = $key;
        }
        return $allRoles;
    }
   
     public function WPTTARGetCurrentUserCall() {
        global $current_user;
        $wpttarRoleChecked = array();
        $wpttarUserRole = implode(',', $current_user->roles);
        
        if (in_array('administrator', $current_user->roles)) {
            $getRoles = 'administrator';
        } else {
            $role_check = count($current_user->roles);
            if ($role_check > 1) {
                $wpttarUserRole_1 = explode(',', $wpttarUserRole);
                foreach ($wpttarUserRole_1 as $wpttarUserRoled) {
                    $wpttarRoleCheck = $this->WPTTARUserRollCheck($wpttarUserRoled);
                    if (!empty($wpttarRoleCheck)) {
                        $wpttarRoleChecked[] = $wpttarRoleCheck;
                    }
                }
                if (!empty($wpttarRoleChecked)) {
                    $getRoles = $wpttarRoleChecked[0];
                } else {
                    $getRoles = $wpttarUserRole_1[0];
                }
            } else {
                $getRoles = $wpttarUserRole;
            }
        }
        return $getRoles;
    }
    
     public function WPTTARUserRollCheck($wpttarUserRole) {
        global $current_user, $wpdb;
        $settingsDatas = array();
        $settingsDatas = $wpdb->get_row("select * from $this->WpttarSettingsTable where `settingKey`='$wpttarUserRole' and `authorID` = 'defineaccess'");
        if (!empty($settingsDatas)) {
            return $settingsDatas->settingKey;
        } else {
            return $settingsDatas;
        }
    }
    
    public function WPTTARChangeRolePermission($action) {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $settingsDatas = array();
        $settingsDatas = $wpdb->get_row("select * from $this->WpttarSettingsTable where `settingKey`='" . esc_sql($wpttarUserRole) . "' and `authorID` = '" . esc_sql($current_user->ID) . "'");

        if ($action == 'getData') {
            if (!empty($settingsDatas)) {
                $result = $settingsDatas;
            } else {
                $result = $settingsDatas;
            }
        } else if (!empty($settingsDatas)) {
            $result = 'yes';
        } else {
            $result = 'no';
        }
        return $result;
    }

    public function WPTTARChangeRoleGet() {
        global $current_user, $wpdb;
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $result = array();
        $settingsDatas = $wpdb->get_row("select * from $this->WpttarSettingsTable where `settingKey`='" . esc_sql($wpttarUserRole) . "' and `authorID` = 'defineaccess'");
        if (!empty($settingsDatas)) {
            $result = $settingsDatas;
        }
        return $result;
    }

    public function WPTTARGetUserWiseData($userID, $userRole) {
        global $wpdb;
        $settingsDatas = array();
        $settingsData = $wpdb->get_row("select * from $this->WpttarSettingsTable where `settingKey` = '" . esc_sql($userRole) . "' and `authorID` = '" . esc_sql($userID) . "'");
        if (!empty($settingsData)) {
            $settingsDatas = $settingsData;
        }
        return $settingsDatas;
    }

    public function WPTTARCheckPageAccess($wpttarUserRole) {
        global $current_user, $wpdb;
        $settingsDatas = array();
        $settingsData = $wpdb->get_row("select * from $this->WpttarSettingsTable where `authorID` = 'defineaccess' and `settingKey`='" . esc_sql($wpttarUserRole) . "'");
        if (!empty($settingsData)) {
            $settingsDatas = $settingsData;
        }
        return $settingsDatas;
    }

    public function WPTTARViewOnlyPermissionPages() {
        global $current_user, $wpdb;
        $pages = array();
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        $checkPage = $this->WPTTARGetUserWiseData($current_user->ID, $wpttarUserRole);
        if (empty($checkPage)) {
            $checkPageAccess = $this->WPTTARCheckPageAccess($wpttarUserRole);
            if (!empty($checkPageAccess)) {
                $pages = unserialize(base64_decode($checkPageAccess->settingValue));
            }
        }
        return $pages;
    }

    public function WPTTARChangeRoleWiseDisplay() {
        global $current_user, $wpdb;
        $wpttarGetDefine = array();
        $message = array();
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        if (isset($_POST['wpttar-actions']) && $_POST['wpttar-actions'] == 'adddatabaserole') {
            $changeRole = $this->WPTTARChangeRolePermission('status');
            if ($changeRole == 'yes') {
                $getData = $this->WPTTARChangeRolePermission('getData');
                $defaultPages = $this->wpttarUserCapabilities;
                $wpttarUserRoles = get_role($wpttarUserRole);
                foreach ($defaultPages as $defaultPage) {
                    $wpttarUserRoles->remove_cap($defaultPage);
                }
                $getRoles = get_role($getData->settingKey);
                $pagesArray = unserialize(base64_decode($getData->settingValue));
           
                foreach ($pagesArray as $pagesWiseMenu) {
                    if($pagesWiseMenu == 'manage_options_projects' || $pagesWiseMenu == 'manage_options_projectView'){
                      $seriesWiseMenu[] =$pagesWiseMenu;
                    }else if($pagesWiseMenu == 'manage_options_projects' || $pagesWiseMenu == 'manage_options_projectView'){
                        $seriesWiseMenu[] =$pagesWiseMenu; 
                    }
                }
                  
                foreach ($pagesArray as $pages) {
                    $getRoles->remove_cap($pages);
                    $getRoles->add_cap($pages);
                }
                $wpdb->query("DELETE FROM `$this->WpttarSettingsTable` WHERE `settingKey`= '" . esc_sql($wpttarUserRole) . "' and `authorID` = '" . esc_sql($current_user->ID) . "'");
            }
        } else if (isset($_POST['wpttar-actions']) && $_POST['wpttar-actions'] == 'adddefaultrole') {
            $changeRole = $this->WPTTARChangeRolePermission('status');
            if ($changeRole == 'no') {
                $getRoles = get_role($wpttarUserRole);
                foreach ($getRoles->capabilities as $key => $wpttarDefineCapability) {
                    $wpttarGetDefineCapability[] = $key;
                }
                $wpttarGetDefine = base64_encode(serialize($wpttarGetDefineCapability));
                $wpdb->insert($this->WpttarSettingsTable, array('authorID' => $current_user->ID, 'settingKey' => $wpttarUserRole, 'settingValue' => $wpttarGetDefine));


                $wpttarUserDefineCapability = $this->wpttarUserDefineCapability;
                foreach ($wpttarUserDefineCapability as $key => $wpttarUserDefineCap) {
                    $capability[] = $key;
                }

                $wpttarUserRoles = get_role($wpttarUserRole);
                foreach ($wpttarUserRoles->capabilities as $key => $defaultPage) {
                    if (in_array($key, $capability)) {
                        $wpttarUserRoles->remove_cap($key);
                    }
                }
                $defaultPages = $this->wpttarUserCapabilities;
                $getUserRoles = get_role($wpttarUserRole);
                foreach ($defaultPages as $pages) {
                    $getUserRoles->remove_cap($pages);
                    $getUserRoles->add_cap($pages);
                }
            }
        }
        $message['success'] = true;
        echo json_encode($message);
        exit;
    }

    public function WPTTARDefaultRoleToLogin($addDefaultRole, $wpttarUserRoles, $userID) {
        global $current_user, $wpdb;
        $wpttarGetDefine = array();
        $message = array();
        $wpttarGetDefineCapability = array();
        $wpttarUserRole = $wpttarUserRoles;
        if (isset($addDefaultRole) && $addDefaultRole == 'adddefaultrole') {
            $changeRole = $this->WPTTARChangeRolePermission('status');
            $getRoles = get_role($wpttarUserRole);
            foreach ($getRoles->capabilities as $key => $wpttarDefineCapability) {
                $wpttarGetDefineCapability[] = $key;
            }

            $wpttarGetDefine = base64_encode(serialize($wpttarGetDefineCapability));
            $id = $wpdb->insert($this->WpttarSettingsTable, array('authorID' => $userID, 'settingKey' => $wpttarUserRole, 'settingValue' => $wpttarGetDefine));

            $wpttarUserDefineCapability = $this->wpttarUserDefineCapability;
            foreach ($wpttarUserDefineCapability as $key => $wpttarUserDefineCap) {
                $capability[] = $key;
            }

            $wpttarUserRoles = get_role($wpttarUserRole);
            foreach ($wpttarUserRoles->capabilities as $key => $defaultPage) {
                if (in_array($key, $capability)) {
                    $wpttarUserRoles->remove_cap($key);
                }
            }
            $defaultPages = $this->wpttarUserCapabilities;
            $getUserRoles = get_role($wpttarUserRole);
            foreach ($defaultPages as $pages) {
                $getUserRoles->remove_cap($pages);
                $getUserRoles->add_cap($pages);
            }
        }
        return;
    }

    /** End WP-TTAR All Roles and Capability Functions * */

    /** WP-TTAR Deactive Plugin * */
    public function WPTTARPluginDeactive() {
        
    }

    /** WP-TTAR Dashboard* */
    public function WPTTARDashboard() {
        include_once('wp-ttar-dashboard.php');
    }

    /** WP-TTAR  Project Wise list * */
    public function WPTTARProjects() {
        include_once('wp-ttar-project-list.php');
    }

    /** WP-TTAR Developers Project Wise Assign list * */
    public function WPTTARPDevelopmentTeamCallback() {
        include_once('wp-ttar-development-team-list.php');
    }

    /** WP-TTAR Settings * */
    public function WPTTARPSettingsCallback() {
        include_once('wp-ttar-settings.php');
    }

    /** WP-TTAR Searching * */
    public function WPTTARAddProject() {
        include_once('wp-ttar-project.php');
    }

    /** WP-TTAR Project View * */
    public function WPTTARProjectView() {
        include_once('wp-ttar-project-view.php');
    }

    /** WP-TTAR Project View * */
    public function WPTTARDeveloperProjectsDetails() {
        include_once('wp-ttar-developer-projects-details.php');
    }

    /** WP-TTAR Developer Project Comments View * */
    public function WPTTARDeveloperProjectsComments() {
        include_once('wp-ttar-developers-comments-list.php');
    }

    /** WP-TTAR Developer User Project Log * */
    public function WPTTARProjectLogs() {
        include_once('wp-ttar-project-logs.php');
    }

    /** WP-TTAR Project Custom Logs * */
    public function WPTTARProjectCustomLogs() {
        include_once('wp-ttar-project-custom-log.php');
    }

    /** WP-TTAR FB Support * */
    public function WPTTARFBSupportCallback() {
        ?>
        <script> window.location = "https://www.facebook.com/indigothemes/";</script>
        <?php

    }

    /** WP-TTAR Support* */
    public function WPTTARSupportCallback() {
        ?>
        <script> window.location = "https://indigothemes.com/support/";</script>
        <?php

    }

    /** WP-TTAR Documents Support* */
    public function WPTTARDocumentsSupportCallback() {
        ?>
        <script> window.location = "https://indigothemes.com/documentation/wpttar/";</script>
        <?php

    }

    /** WP-TTAR Get All Ajax Data * */

    /** WP-TTAR Get USer Timer Ajax * */
    public function WPTTARUserTimer() {
        ob_clean();
        include("wp-ttar-user-timer.php");
        exit();
    }

    /** WP-TTAR Get All Employee Active User
     *   @no-argument
     *   @return if administrator all Employee Users & if employee only one datas return.
     * */
    public function WPTTARGetEmployees() {
        global $current_user;
        $wpttarEmployeeUsers = array();
        $wpttarUserRole = $this->WPTTARGetCurrentUserCall();
        if ($wpttarUserRole == 'administrator') {
            $employeeRole = array('role__in' => array('subscriber', 'editor'));
            $wpttarEmployeeUsers = get_users($employeeRole);
        } else {
            $wpttarEmployeeUsers[] = get_userdata($current_user->ID);
        }
        return $wpttarEmployeeUsers;
    }

    /**
     *   WP-TTAR get User Information
     *   Perameter ID is user id
     *   Return User Information
     * */
    public function WPTTARGetUserDatas($ID, $key) {
        $wpttarUserInfo = get_user_meta($ID, $key, true);
        $wpttarUserDatas = array();
        if ($wpttarUserInfo != '') :
            $wpttarUserDatas = unserialize(base64_decode($wpttarUserInfo));
        endif;
        return $wpttarUserDatas;
    }

    /**
     *   WP-TTAR get Message
     *   Perameter ID is Message ID
     *   Return Meaage Description
     * */
    public function WPTTARGetMessage($ID) {
        global $wpdb;
        $ID = esc_sql($ID);
        $wpttarMessage = '';
        $messages = $this->WPTTARGetTableDataByID($ID, $this->WpttarMessagesTable, 'id');
        if (isset($messages->messagesDesc)) : $wpttarMessage = $messages->messagesDesc;
        else : $wpttarMessage = '';
        endif;
        return $wpttarMessage;
    }

    /**
     *   WP-TTAR Serialize Data for array value
     *   Perameter array 
     *   Return array in serialize
     * */
    public function WPTTARSetSerialize($Array) {
        global $wpdb;
        $wpttarFormDetailsData = '';
        $wpttarFormDetails = array();
        $wpttarFormDetailsData = base64_encode(serialize($Array));
        if (isset($wpttarFormDetailsData)) : $wpttarFormDetailsData = $wpttarFormDetailsData;
        else : $wpttarFormDetailsData = '';
        endif;
        return $wpttarFormDetailsData;
    }

    /** WP-TTAR Sanitize array value
     *   @ Array value
     *   @return return Sanitize value.
     * */
    public function WPTTARSanitize($input) {
        $new_input = array();
        foreach ($input as $key => $val) {
            $new_input[$key] = sanitize_text_field($val);
        }
        return $new_input;
    }

    /**
     *   WP-TTAR Unserialize Data for array value
     *   Perameter array 
     *   Return array in Unserialize
     * */
    public function WPTTARSetUnSerialize($Array) {
        global $wpdb;
        $wpttarFormDetailsData = '';
        $wpttarFormDetails = array();
        $wpttarFormDetailsData = unserialize(base64_decode($Array));
        if (isset($wpttarFormDetailsData)) : $wpttarFormDetailsData = $wpttarFormDetailsData;
        else : $wpttarFormDetailsData = '';
        endif;
        return $wpttarFormDetailsData;
    }

    /**
     *   WP-TTAR get table data
     *   @argument Id , Table Name , Filed name
     *   @returns table datas
     * */
    public function WPTTARGetTableDataByID($id, $tableName, $fieldName) {
        global $wpdb;
        $where = '';
        $condition = '';
        $id = esc_sql($id);
        if (!empty($fieldName)) {
            $condition = 'get_row';
            $where = "where `$fieldName` = '$id'";
        } else {
            $condition = 'get_results';
        }
        $wpttarTableResults = array();
        $wpttarTableDatas = $wpdb->$condition("SELECT * FROM  $tableName  $where");
        if (!empty($wpttarTableDatas)) {
            $wpttarTableResults = $wpttarTableDatas;
        }
        return $wpttarTableResults;
    }

    /**
     *   WP-TTAR get row result by variables
     *   @argument $tableName is store table name, $firstField database column field, $secondField database column field,
     *    first variable name, second variable name data fetch by metch conditions,
     *    $fetchCondition is a condition for fetch results or row in data base.
     *    if $fetchCondition == 'getRow'   it will fetch 1 row into data base.
     *    if $fetchCondition == 'getResults'  it will fetch multiple results into data base.
     *   @returns table datas
     * */
    public function WPTTARGetResultsByMultipleFields($tableName, $firstField, $secondField, $firstVariable, $secondVariable, $fetchCondition) {
        global $wpdb;
        $where = '';
        $condition = '';
        $firstVariable = esc_sql($firstVariable);
        $secondVariable = esc_sql($secondVariable);

        if (!empty($fetchCondition) && $fetchCondition == 'getRow') {
            $condition = 'get_row';
            $where = "where `$firstField` = '$firstVariable' AND `$secondField` = '$secondVariable'";
        } else {
            $condition = 'get_results';
            $where = "where `$firstField` = '$firstVariable' AND `$secondField` = '$secondVariable'";
        }
        $wpttarTableResults = array();
        $wpttarTableDatas = $wpdb->$condition("SELECT * FROM  $tableName  $where");
        if (!empty($wpttarTableDatas)) {
            $wpttarTableResults = $wpttarTableDatas;
        }
        return $wpttarTableResults;
    }

    /**
     *   WP-TTAR get Settings
     *   @argument key 
     *   -featch settings from settingsTable using setting key
     *   @returns settings datas
     * */
    public function WPTTARGetSettings($key) {
        global $wpdb;
        $wpttarSettingsResults = array();
        $key = esc_sql($key); // esc
        $wpttarSettings = $wpdb->get_row("SELECT `settingValue` FROM  $this->WpttarSettingsTable  where `settingKey` = '$key'");
        if (!empty($wpttarSettings)) {
            $wpttarSettingsResults = unserialize(base64_decode($wpttarSettings->settingValue));
        }
        return $wpttarSettingsResults;
    }

    /**
     *   WP-TTAR get row result by variables
     *   @argument $tableName is store table name, $fieldName database column field and $fieldVariable is variable name ,
     *    $orderByFieldName is that result fetch by order,
     *    $fetchCondition is a condition for fetch results or row into data base.
     *    $orderByFieldValue is a order by ASC or DESC data fetch.
     *    if $fetchCondition == 'getRow'  it will fetch 1 row into data base.
     *    if $fetchCondition == 'getResults'  it will fetch multiple results into data base.
     *   @returns table datas
     * */
    public function WPTTARGetResultsByOrderByFieldName($tableName, $fieldName, $fieldVariable, $orderByFieldName, $orderByFieldValue, $fetchCondition) {
        global $wpdb;
        $where = '';
        $condition = '';
        $fieldVariable = esc_sql($fieldVariable);
        if (!empty($orderByFieldValue) && ($orderByFieldValue == 'ASC' || $orderByFieldValue == 'asc')) {
            if (!empty($fetchCondition) && $fetchCondition == 'getRow') {
                $condition = 'get_row';
            } else if (!empty($fetchCondition) && $fetchCondition == 'getResults') {
                $condition = 'get_results';
            }
            $where = "where `$fieldName` = '$fieldVariable' ORDER BY $orderByFieldName $orderByFieldValue";
        } else if (!empty($orderByFieldValue) && ($orderByFieldValue == 'DESC' || $orderByFieldValue == 'desc')) {
            if (!empty($fetchCondition) && $fetchCondition == 'getRow') {
                $condition = 'get_row';
            } else {
                $condition = 'get_results';
            }
            $where = "where `$fieldName` = '$fieldVariable' ORDER BY $orderByFieldName $orderByFieldValue";
        }
        $wpttarTableResults = array();
        $wpttarTableDatas = $wpdb->$condition("SELECT * FROM  $tableName  $where");
        if (!empty($wpttarTableDatas)) {
            $wpttarTableResults = $wpttarTableDatas;
        }
        return $wpttarTableResults;
    }

    /**
     *   WP-TTAR get Multiple result by id
     *   @argument Id , Table Name , Filed name
     *   @returns table datas
     * */
    public function WPTTARGetResultsByID($id, $tableName, $fieldName) {
        global $wpdb;
        $id = esc_sql($id);
        $wpttarTableResults = array();
        
        $wpttarTableDatas = $wpdb->get_results("SELECT * FROM  $tableName  WHERE $fieldName = '$id'");
        if (!empty($wpttarTableDatas)) {
            $wpttarTableResults = $wpttarTableDatas;
        }
        return $wpttarTableResults;
    }

    /**
     *   WP-TTAR Graph report  
     *   @argument Developer array , Project Id , graph type
     *   @returns table datas
     * */
    public function WPTTARProjectGraphReports() {
        global $wpdb, $current_user;
        $result = array();
        $projectWiseMemberArray = array();
        $projectReportGraphTypes = array();
        $wpttarGetPagePermissions = $this->WPTTARGetPagePermissions();
        if (isset($_POST['productID']) && $_POST['productID'] != '') {
            $projectID = $_POST['productID'];
        } else {
            $projectID = '';
        }
        if (isset($_POST['startDate']) && $_POST['startDate'] != '') {
            $startDate = date('Y-m-d', strtotime('01-' . $_POST['startDate']));
        } else {
            $startDate = '';
        }
        if (isset($_POST['endDate']) && $_POST['endDate'] != '') {
            $endDate = date('Y-m-d', strtotime('31-' . $_POST['endDate']));
        } else {
            $endDate = '';
        }
        if (isset($_POST['graphType']) && $_POST['graphType'] != '') {
            $graphType = $_POST['graphType'];
        } else {
            $graphType = '';
        }
        $year = date('Y');
        $month = date('m');

        $developersname = '';
        $wpttarProjectResults = $this->WPTTARGetTableDataByID($projectID, $this->WpttarProjectsTable, 'id');
        if (!empty($wpttarProjectResults)) {
            $developersname = $this->WPTTARSetUnSerialize($wpttarProjectResults->members);
        }

        if (isset($graphType) && $graphType == 'MonthWise') {
            if ($startDate != '' && $endDate != '') {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "'  GROUP BY month(updateDate)");
                foreach ($wpttarGarphKey as $wpttarGarphKeys) {
                    $projectReportGraphTypes[] = date('M Y', strtotime($wpttarGarphKeys->updateDate));
                }
            } else {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND year(`updateDate`)='" . esc_sql($year) . "'  GROUP BY month(updateDate)");
                foreach ($wpttarGarphKey as $wpttarGarphKeys) {
                    $projectReportGraphTypes[] = date('M Y', strtotime($wpttarGarphKeys->updateDate));
                }
            }
        } else if (isset($graphType) && $graphType == 'DayWise') {

            if ($startDate != '' && $endDate != '') {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "' GROUP BY updateDate");
                foreach ($wpttarGarphKey as $K => $wpttarGarphKeys) {
                    if ($K <= 14) {
                        $projectReportGraphTypes[] = date('d M Y', strtotime($wpttarGarphKeys->updateDate));
                    }
                }
            } else {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND year(`updateDate`)='" . esc_sql($year) . "' GROUP BY updateDate");
                foreach ($wpttarGarphKey as $K => $wpttarGarphKeys) {
                    if ($K <= 14) {
                        $projectReportGraphTypes[] = date('d M Y', strtotime($wpttarGarphKeys->updateDate));
                    }
                }
            }
        } else if (isset($graphType) && $graphType == 'YearWise') {
            if ($startDate != '' && $endDate != '') {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "' AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "'  GROUP BY year(updateDate)");
                foreach ($wpttarGarphKey as $wpttarGarphKeys) {
                    $projectReportGraphTypes[] = date('Y', strtotime($wpttarGarphKeys->updateDate));
                }
            } else {
                $wpttarGarphKey = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  GROUP BY year(updateDate)");
                foreach ($wpttarGarphKey as $wpttarGarphKeys) {
                    $projectReportGraphTypes[] = date('Y', strtotime($wpttarGarphKeys->updateDate));
                }
            }
        }
        foreach ($developersname as $devKey => $projectDevelopersnames) {
            $wpttarNotEmptyUser = $this->WPTTARGetResultsByMultipleFields($this->WpttarProjectsLogTable, 'projectID', 'developerID', $projectID, $projectDevelopersnames, 'getRow');
           
            if (!empty($wpttarNotEmptyUser)) {
                if (in_array('manage_options_projects', $wpttarGetPagePermissions)) {
                    $WpttarEmployeeFirstName = get_user_meta($projectDevelopersnames, 'first_name', true);
                } else {
                    $WpttarEmployeeFirstName = get_user_meta($projectDevelopersnames, 'first_name', true);
                }
                $projectWiseMemberArray[] = array('label' => '' . $WpttarEmployeeFirstName . '');

                if (isset($graphType) && $graphType == 'MonthWise') {
                    if ($startDate != '' && $endDate != '') {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "'  GROUP BY month(updateDate)");
                    } else {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND year(`updateDate`)='" . esc_sql($year) . "'  GROUP BY month(updateDate)");
                    }
                    $developersHours = array();
                    foreach ($wpttarProjectAllUsers as $dates) {
                        $graphLoadMonth = date('m', strtotime($dates->updateDate));
                        $graphLoadYear = date('Y', strtotime($dates->updateDate));

                        $totalHours = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "' AND `developerID` = '" . esc_sql($projectDevelopersnames) . "' AND year(`updateDate`)='" . esc_sql($graphLoadYear) . "' AND month(`updateDate`) ='" . esc_sql($graphLoadMonth) . "'");

                        $totalHourss = $this->WPTTARGetProjectGraphTime($totalHours, 'graphOnTime');
                        if ($totalHourss['hour'] != '' && $totalHourss['minutes'] != '') {
                            $totalHourss = $totalHourss['hour'] . '.' . $totalHourss['minutes'];
                        } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] != '') {
                            $totalHourss = '0.' . $totalHourss['minutes'];
                        } else if ($totalHourss['hour'] != '' && $totalHourss['minutes'] == '') {
                            $totalHourss = $totalHourss['hour'] . '.0';
                        } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] == '') {
                            $totalHourss = '0';
                        } else {
                            $totalHourss = '0.' . $totalHourss['minutes'];
                        }
                        $developersHours[] = $totalHourss;
                    }
                    array_push($result, $developersHours);
                } else if (isset($graphType) && $graphType == 'DayWise') {
                    if ($startDate != '' && $endDate != '') {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "' AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "' GROUP BY updateDate");
                    } else {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "'  AND year(`updateDate`)='" . esc_sql($year) . "' GROUP BY updateDate");
                    }
                    $developersHours = array();
                    foreach ($wpttarProjectAllUsers as $dates) {
                        $totalHours = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '$projectID' AND `developerID` = '" . esc_sql($projectDevelopersnames) . "' AND  `updateDate` ='" . esc_sql($dates->updateDate) . "'");
                        if (!empty($totalHours)) {
                            $totalHourss = $this->WPTTARGetProjectGraphTime($totalHours, 'graphOnTime');

                            if ($totalHourss['hour'] != '' && $totalHourss['minutes'] != '') {
                                $totalHourss = $totalHourss['hour'] . '.' . $totalHourss['minutes'];
                            } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] != '') {
                                $totalHourss = '0.' . $totalHourss['minutes'];
                            } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] == '') {
                                $totalHourss = '0';
                            } else if ($totalHourss['hour'] != '' && $totalHourss['minutes'] == '') {
                                $totalHourss = $totalHourss['hour'] . '.0';
                            }
                        } else {
                            $totalHourss = '0';
                        }
                        $developersHours[] = $totalHourss;
                    }
                    $developersHourss = array_reverse($developersHours);
                    foreach ($developersHourss as $H => $developersHoursss) {
                        if ($H <= 14) {
                            $developersHourss[] = $developersHoursss;
                        }
                    }
                    $totalHours = array_reverse($developersHourss);
                    array_push($result, $developersHours);
                } else if (isset($graphType) && $graphType == 'YearWise') {

                    if ($startDate != '' && $endDate != '') {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "' AND `updateDate` BETWEEN '" . esc_sql($startDate) . "' AND '" . esc_sql($endDate) . "' GROUP BY year(updateDate)");
                    } else {
                        $wpttarProjectAllUsers = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '$projectID'  GROUP BY year(updateDate)");
                    }
                    $developersHours = array();
                    foreach ($wpttarProjectAllUsers as $dates) {
                        $graphLoadYear = date('Y', strtotime($dates->updateDate));
                        $totalHours = $wpdb->get_results("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE   `projectID` = '" . esc_sql($projectID) . "' AND `developerID` = '" . esc_sql($projectDevelopersnames) . "' AND year(`updateDate`)='" . esc_sql($graphLoadYear) . "'");
                        $totalHourss = $this->WPTTARGetProjectGraphTime($totalHours, 'graphOnTime');

                        if ($totalHourss['hour'] != '' && $totalHourss['minutes'] != '') {
                            $totalHourss = $totalHourss['hour'] . '.' . $totalHourss['minutes'];
                        } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] != '') {
                            $totalHourss = '0.' . $totalHourss['minutes'];
                        } else if ($totalHourss['hour'] != '' && $totalHourss['minutes'] == '') {
                            $totalHourss = $totalHourss['hour'] . '.0';
                        } else if ($totalHourss['hour'] == '' && $totalHourss['minutes'] == '') {
                            $totalHourss = '0';
                        } else {
                            $totalHourss = '0.' . $totalHourss['minutes'];
                        }

                        $developersHours[] = $totalHourss;
                    }
                    array_push($result, $developersHours);
                }
            }
        }
        $results = array_filter($result);
        if (!empty($results)) {
            $projectWiseMember = $projectWiseMemberArray;
            $projectWiseMemberHours = json_encode($result);
            $projectWiseMemberHour = str_replace('"', "", $projectWiseMemberHours);
            $projectWiseMemberHour = str_replace(' ', "", $projectWiseMemberHour);
            $projectReportGraphType = $projectReportGraphTypes;
            $details = array('member' => $projectWiseMember, 'hour' => json_decode($projectWiseMemberHour), 'graphType' => $projectReportGraphType);
        } else {
            $err = __('No data found!', 'wpttar');
            $details = array('error' => $err);
        }
        echo json_encode($details);
        exit;
    }

    public function WPTTARDeleteRow() {
        global $wpdb;
        $datas = array();
        $fieldName = $_POST['filedName'];
        $filedID = $_POST['id'];
        if (isset($_POST['delete-action']) && $_POST['delete-action'] == 'project-delete') {
            $getProjectRow = $wpdb->get_row("SELECT * FROM `$this->WpttarProjectsTable` WHERE `" . esc_sql($fieldName) . "` = '" . esc_sql($filedID) . "'");
            if (isset($getProjectRow->id) && $getProjectRow->id != '') {
                $wpdb->query("DELETE FROM `$this->WpttarProjectsLogTable` WHERE `projectID` ='" . esc_sql($filedID) . "'");
                $wpttarDocuments = $this->WPTTARGetTableDataByID($filedID, $this->WpttarAttachmentsTable, 'projectID');
                if (!empty($wpttarDocuments->documentName)) {
                    $attechmentArray = $this->WPTTARSetUnSerialize($wpttarDocuments->documentName);
                    foreach ($attechmentArray['documentlink'] as $postID) {
                        wp_delete_attachment($postID);
                    }
                }
                $wpdb->query("DELETE FROM `$this->WpttarAttachmentsTable` WHERE `projectID` ='" . esc_sql($filedID) . "'");
                $wpdb->query("DELETE FROM `$this->WpttarTeamsTable` WHERE `projectID` ='" . esc_sql($filedID) . "'");
                $resposeDatas = $wpdb->query("DELETE FROM `$this->WpttarProjectsTable` WHERE `id` ='" . esc_sql($filedID) . "'");
            }
            if (!empty($resposeDatas)) {
                $datas['success'] = true;
                $datas['message'] = true;
            } else {
                $datas['error'] = true;
                $result['message'] = __('Something went wrong.', 'wpttar');
            }
        } if (isset($_POST['delete-action']) && $_POST['delete-action'] == 'logrequest-delete') {
            $resposeDatas = $wpdb->query("DELETE FROM `$this->WpttarCustomProjectLogTable` WHERE `id` ='" . esc_sql($filedID) . "'");
            if (!empty($resposeDatas)) {
                $datas['success'] = true;
                $datas['message'] = true;
            } else {
                $datas['error'] = true;
                $result['message'] = __('Something went wrong.', 'wpttar');
            }
        } else {
            $datas['error'] = true;
            $result['message'] = __('Something went wrong.', 'wpttar');
        }
        echo json_encode($datas);
        exit;
    }

    public function WPTTAREditComment() {
        global $wpdb;

        $id = $_POST['id'];
        $comment = $_POST['comment'];
        $whereArray = array('id' => $id);
        $resposeDatas = $wpdb->update($this->WpttarProjectsLogTable, array('userComment' => sanitize_text_field($comment)), $whereArray);
        if (!empty($resposeDatas)) {
            $datas['success'] = true;
            $datas['message'] = __('Comment have been successfully updated.', 'wpttar');
        } else {
            $datas['error'] = true;
            $result['message'] = __('Something went wrong.', 'wpttar');
        }

        echo json_encode($datas);
        exit;
    }

    public function WPTTARAddLogInfo() {
        global $wpdb;
        $startTime = date('Y-m-d H:i:s', strtotime($_POST['start-time']));
        $id = '';
        $status = '';
        $wpttarRole = '';

        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }

        $endTime = date('Y-m-d H:i:s', strtotime($_POST['end-time']));
        $projectId = $_POST['project-id'];
        $projectcomment = $_POST['projectcomment'];
        $action = $_POST['wpttar-action'];
        $developerId = $_POST['developer-id'];
        if (isset($_POST['log-id']) && $_POST['log-id'] != '') {
            $id = $_POST['log-id'];
        }
        if (isset($_POST['wpttar-status']) && $_POST['wpttar-status'] != '') {
            $status = $_POST['wpttar-status'];
        }

        if (isset($_POST['wpttar-role']) && $_POST['wpttar-role'] != '') {
            $wpttarRole = $_POST['wpttar-role'];
        }

        $wpttarDate = date('Y-m-d');

        if ($action == 'add-log') {
            if ($wpttarRole != 'administrator') {
                $checkDay = $this->WPTTARCheckDateBetween(date('Y-m-d', strtotime($_POST['start-time'])), date('Y-m-d', strtotime($_POST['end-time'])));
                if ($checkDay == 0 || $checkDay == 1) {
                    $resposeDatas = $wpdb->insert($this->WpttarCustomProjectLogTable, array('wpttarUserID' => sanitize_text_field($developerId), 'startTime' => sanitize_text_field($startTime), 'endTime' => sanitize_text_field($endTime), 'projectID' => sanitize_text_field($projectId), 'wpttarStatus' => sanitize_text_field('pending'), 'wpttarDate' => sanitize_text_field($wpttarDate), 'projectComment' => sanitize_text_field($projectcomment)));
                } else {
                    $datas['error'] = __(' Please select appropriate date.', 'wpttar');
                    echo json_encode($datas);
                    exit;
                }
            } else {
                $checkDay = $this->WPTTARCheckDateBetween(date('Y-m-d', strtotime($_POST['start-time'])), date('Y-m-d', strtotime($_POST['end-time'])));
                if ($checkDay == 0) {
                    $getTotalHour = $this->WPTTARBetweenTime($startTime, $endTime);
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field(date('H:i:s', strtotime($startTime))) . "', '" . sanitize_text_field(date('H:i:s', strtotime($endTime))) . "', '" . sanitize_text_field($getTotalHour) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($endTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");
                } else if ($checkDay == 1) {
                    $getTotalHour_1st = $this->WPTTARBetweenTime(date('H:i:s', strtotime($startTime)), '23:59:59');
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field(date('H:i:s', strtotime($startTime))) . "', '" . sanitize_text_field('23:59:59') . "', '" . sanitize_text_field($getTotalHour_1st) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($startTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");

                    $getTotalHour_2nd = $this->WPTTARBetweenTime('00:00:01', date('H:i:s', strtotime($endTime)));
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field('00:00:01') . "', '" . sanitize_text_field(date('H:i:s', strtotime($endTime))) . "', '" . sanitize_text_field($getTotalHour_2nd) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($endTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");
                } else {
                    $datas['error'] = __(' Please select appropriate date.', 'wpttar');
                    echo json_encode($datas);
                    exit;
                }
            }
            if (!empty($resposeDatas)) {
                $datas['success'] = __('Project Log has been successfully added.', 'wpttar');
            } else {
                $datas['success'] = __('Project Log has been successfully added.', 'wpttar');
            }
        } else if ($action == 'edit-log') {
            $checkDay = $this->WPTTARCheckDateBetween(date('Y-m-d', strtotime($_POST['start-time'])), date('Y-m-d', strtotime($_POST['end-time'])));
            if ($checkDay == 0 || $checkDay == 1) {
                $whereArray = array('id' => $id);
                $resposeDatas = $wpdb->update($this->WpttarCustomProjectLogTable, array('startTime' => sanitize_text_field($startTime), 'endTime' => sanitize_text_field($endTime), 'wpttarDate' => sanitize_text_field($wpttarDate), 'projectID' => sanitize_text_field($projectId), 'projectComment' => sanitize_text_field($projectcomment)), $whereArray);
                if (!empty($resposeDatas)) {
                    $datas['success'] = __('Project Log has been successfully updated.', 'wpttar');
                } else {
                    $datas['success'] = __('Project Log has been successfully updated.', 'wpttar');
                }
            } else {
                $datas['error'] = __(' Please select appropriate date.', 'wpttar');
                echo json_encode($datas);
                exit;
            }
        } else if ($action == 'edit-change-status') {

            $whereArray = array('id' => $id);
            $resposeDatas = $wpdb->update($this->WpttarCustomProjectLogTable, array('startTime' => sanitize_text_field($startTime), 'endTime' => sanitize_text_field($endTime), 'wpttarDate' => sanitize_text_field($wpttarDate), 'wpttarStatus' => sanitize_text_field($status), 'projectID' => sanitize_text_field($projectId), 'projectComment' => sanitize_text_field($projectcomment)), $whereArray);
            if ($status == 'approved') {
                $checkDay = $this->WPTTARCheckDateBetween(date('Y-m-d', strtotime($_POST['start-time'])), date('Y-m-d', strtotime($_POST['end-time'])));
                if ($checkDay == 0) {
                    $getTotalHour = $this->WPTTARBetweenTime($startTime, $endTime);
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field(date('H:i:s', strtotime($startTime))) . "', '" . sanitize_text_field(date('H:i:s', strtotime($endTime))) . "', '" . sanitize_text_field($getTotalHour) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($endTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");
                } else if ($checkDay == 1) {
                    $getTotalHour_1st = $this->WPTTARBetweenTime(date('H:i:s', strtotime($startTime)), '23:59:59');
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field(date('H:i:s', strtotime($startTime))) . "', '" . sanitize_text_field('23:59:59') . "', '" . sanitize_text_field($getTotalHour_1st) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($startTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");

                    $getTotalHour_2nd = $this->WPTTARBetweenTime('00:00:01', date('H:i:s', strtotime($endTime)));
                    $id = $wpdb->query("INSERT INTO `$this->WpttarProjectsLogTable` (`projectID`, `developerID`, `startTime`, `endTime`, `workedHour`, `updateDate`, `userComment`) VALUES ('" . sanitize_text_field($projectId) . "','" . sanitize_text_field($developerId) . "', '" . sanitize_text_field('00:00:01') . "', '" . sanitize_text_field(date('H:i:s', strtotime($endTime))) . "', '" . sanitize_text_field($getTotalHour_2nd) . "', '" . sanitize_text_field(date('Y-m-d', strtotime($endTime))) . "'
,'" . sanitize_text_field($projectcomment) . "')");
                }
            }
            if (!empty($resposeDatas)) {
                $datas['success'] = __('Project Log has been successfully updated.', 'wpttar');
            } else {
                $datas['success'] = __('Project Log has been successfully updated.', 'wpttar');
            }
        }

        echo json_encode($datas);
        exit;
    }

    public function WPTTARCheckDateBetween($startDate, $endDate) {
        $now = strtotime($endDate);
        $your_date = strtotime($startDate);
        $datediff = $now - $your_date;
        return floor($datediff / (60 * 60 * 24));
    }

    /**
     *   WP-TTAR get Project Graph in show hour and minute 
     *   @argument Userwise wokedhour array ,action
     *   @returns minute and hour data
     * */
    public function WPTTARGetProjectGraphTime($wpttarProjectHours, $action) {

        if (!empty($wpttarProjectHours) && !empty($action))
            if ($action == 'graphOnTime') {
                foreach ($wpttarProjectHours as $wpttarProjectHour) {
                    $hourMinutes[] = $wpttarProjectHour->workedHour;
                }
                $sum = new DateTime("00:00");
                $i = 0;
                foreach ($hourMinutes as $hourMinute) {
                    $elements = explode(':', $hourMinute);
                    $hours = (string) ((int) $elements[0]);
                    $minutes = (string) ((int) $elements[1]);
                    $i += $hours * 60 + $minutes;
                }
                if ($h = floor($i / 60)) {
                    $i %= 60;
                }

               
                $WorkTimes = sprintf('%2d:%2d', $h, $i);
                $WorkTime = explode(':', $WorkTimes);

                if (isset($WorkTime[0]) && $WorkTime[0] != '00') {
                    if (!empty($WorkTime[0])) {
                        $workTimeHours = $WorkTime[0];
                    }
                } else {
                    $workTimeHours = '';
                }

                
                 if ($WorkTime[1] <= 9) {
                    $g = '0' . $WorkTime[1];
                } else {
                    $g = $WorkTime[1];
                }

                
                if (isset($g) && $g != '00') {
                    if (!empty($g)) {
                        $workTimeMinutes = $g;
                    }
                } else {
                    $workTimeMinutes = '';
                }

                $dataOFWorked = array('hour' => $workTimeHours, 'minutes' => $workTimeMinutes);

                return $dataOFWorked;
                exit();
            }
    }

    /**
     *   WP-TTAR get Project Graph in show hour and minute 
     *   @argument Userwise wokedhour array ,action
     *   @returns minute and hour data
     * */
    public function WPTTARGetProjectTime($wpttarProjectHours, $action) {
        global $wpdb;
        $workTimeMinutes = '';
        $workTimeHours = '';


        if (!empty($wpttarProjectHours) && !empty($action)) {
            if ($action != 'graghHours') {
                foreach ($wpttarProjectHours as $wpttarProjectHour) {
                    $hourMinutes[] = $wpttarProjectHour->workedHour;
                }
                $sum = new DateTime("00:00");
                $i = 0;
                foreach ($hourMinutes as $hourMinute) {
                    $elements = explode(':', $hourMinute);
                    $hours = (string) ((int) $elements[0]);
                    $minutes = (string) ((int) $elements[1]);
                    $i += $hours * 60 + $minutes;
                }
                if ($h = floor($i / 60)) {
                    $i %= 60;
                }
                $WorkTimes = sprintf('%2d:%2d', $h, $i);
                $WorkTime = explode(':', $WorkTimes);
                if ($action == 'totalHours') {

                    if (isset($WorkTime[0]) && $WorkTime[0] != '00') {
                        if (!empty($WorkTime[0])) {
                            $workTimeHours = $WorkTime[0] . ' Hours';
                        }
                    } else {
                        $workTimeHours = '';
                    }
                    if (isset($WorkTime[1]) && $WorkTime[1] != '00') {
                        if (!empty($WorkTime[1])) {
                            $workTimeMinutes = $WorkTime[1] . ' Minutes';
                        }
                    } else {
                        $workTimeMinutes = '';
                    }

                    $dataOFWorked = array('hour' => $workTimeHours, 'minutes' => $workTimeMinutes);
                    return $dataOFWorked;
                    exit();
                } else {
                    return $WorkTime[0];
                    exit();
                }
            } else {

                $i = 0;
                $elements = explode(':', $wpttarProjectHours->workedHour);
                $hours = (string) ((int) $elements[0]);
                $minutes = (string) ((int) $elements[1]);
                $i += $hours * 60 + $minutes;
                if ($h = floor($i / 60)) {
                    $i %= 60;
                }
                $WorkTimes = sprintf('%2d:%02d', $h, $i);
                $WorkTime = explode(':', $WorkTimes);
                return $WorkTime[0];
                exit();
            }
        }
        return false;
    }

    /** Genrate All Excel and pdf File function. * */
    public function WPTTARProjectsReports() {
        global $wpdb;
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        
        if (isset($_POST)) {
            $wpttarCheck = $this->WPTTARGetTableDataByID('', $this->WpttarProjectsTable, '');
            if (!empty($wpttarCheck)) {
               
                if (isset($_POST['from-date']) && isset($_POST['to-date'])) {
                    
                    if (isset($_POST['wpttar-report-type']) && ($_POST['wpttar-report-type'] == 'Wpttar-excel-reports' || $_POST['wpttar-report-type'] == 'Wpttar-developer-excel-reports')) {
                        $this->WPTTARREPORTS->WPTTARGetProjectReportExcel($_POST['from-date'], $_POST['to-date'], $_POST['wpttar-report-type'], $_POST['wpttar-developer-id']);
                        ob_clean();
                    } elseif (isset($_POST['wpttar-report-type']) && ($_POST['wpttar-report-type'] == 'Wpttar-pdf-reports' || $_POST['wpttar-report-type'] == 'Wpttar-developer-pdf-reports')) {
                        require_once (WPTTARMPDF . 'wpttarpdf.php');
                        ob_clean();
                        $pdfData = $this->WPTTARREPORTS->WPTTARGetProjectReportPdf($_POST['from-date'], $_POST['to-date'], $_POST['wpttar-report-type'], $_POST['wpttar-developer-id']);
                       
                        $htmlSections = $pdfData; //ob_get_contents();
                        ob_clean();
                        $wphrmpdf = new WPTTAR_mPDF();
                        $wphrmpdf->WriteHTML($htmlSections);
                        $filename = date('YmdHis'). '.pdf';
                        echo $wphrmpdf->Output($filename, 'D');
                       
                    }
                }
            } else {
                if ($_POST['wpttar-project-report-action'] == 'finacial-report') {
                    wp_redirect(admin_url('admin.php?page=wp-ttar-financials'), 301);
                } else {
                    wp_redirect(admin_url('admin.php?page=wp-ttar-dashboard'), 301);
                }
            }
        }
    }

    /**     *   WP-TTAR File Upload * */
    function wpttarHandleUpload($file_handler, $post_id, $set_thu = false) {
        if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK)
            __return_false();
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');
        $attach_id = media_handle_upload($file_handler, $post_id);
        if (is_wp_error($attach_id)) {
            return $attach_id = '';
        } else {
            if ($set_thu)
                set_post_thumbnail($post_id, $attach_id);
            return $attach_id;
        }
    }

    /** WPTTAR Project Add And Update Function * */
    public function WPTTARProjectForm() {
        global $current_user, $wpdb;
        $result = array();
        $movefileProjectDocuments = array();
        $wpttarDocumentsData = '';
        $attechmentArray = array();
        $documentName = '';
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        $Wpttar['documentName'] = $_POST['documentsname'];
        $Wpttar['documenturl'] = $_POST['documenturl'];

        if (isset($_POST['wpttar-assign-developers-name']) && !empty($_POST['wpttar-assign-developers-name'])) {
            $wpttarFormDetailsData = $this->WPTTARSetSerialize($_POST['wpttar-assign-developers-name']);
        }
        if (isset($_POST['wpttar-project-status']) && $_POST['wpttar-project-status'] == 'Close') {
            $wpttarLastUpdate = date('Y-m-d H:i:s');
        } else {
            $wpttarLastUpdate = '';
        }

        $files = $_FILES["wpttar-project-document"];
        foreach ($files['name'] as $key => $value) {
            if ($files['name'][$key]) {
                $file = array(
                    'name' => $files['name'][$key],
                    'type' => $files['type'][$key],
                    'tmp_name' => $files['tmp_name'][$key],
                    'error' => $files['error'][$key],
                    'size' => $files['size'][$key]
                );
                $_FILES = array("wpttar-project-document" => $file);
                foreach ($_FILES as $file => $array) {
                    $movefileProjectDocuments[] = $this->wpttarHandleUpload($file, $pid);
                }
            }
        }

        if (isset($_POST['wpttar-project-id']) && !empty($_POST['wpttar-project-id'])) {
            $updateData = array('clientName' => sanitize_text_field($_POST['wpttar-client-name']),
                'projectName' => sanitize_text_field($_POST['wpttar-project-name']),
                'members' => sanitize_text_field($wpttarFormDetailsData),
                'projectStatus' => sanitize_text_field($_POST['wpttar-project-status']),
                'description' => sanitize_post($_POST['wpttar-project-dev-server-details']),
                'lastUpdate' => sanitize_text_field($wpttarLastUpdate),
            );
            $whereArray = array('id' => $_POST['wpttar-project-id']);
            $id = $wpdb->update($this->WpttarProjectsTable, $updateData, $whereArray);

            $wpttarGetProjectMembers = $this->WPTTARGetTableDataByID($_POST['wpttar-project-id'], $this->WpttarTeamsTable, 'projectID');
            if (!empty($wpttarGetProjectMembers)) {
                $wpdb->query("DELETE FROM `$this->WpttarTeamsTable` WHERE `projectID` = '" . $_POST['wpttar-project-id'] . "'");
                foreach ($_POST['wpttar-assign-developers-name'] as $inserProjectMember) {
                    $updateProjectMembers = array('projectID' => sanitize_text_field($_POST['wpttar-project-id']),
                        'teamName' => sanitize_text_field(''),
                        'teamMember' => sanitize_text_field($inserProjectMember),
                        'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                        'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
                    );
                    $id = $wpdb->insert($this->WpttarTeamsTable, $updateProjectMembers);
                }
            } else {
                foreach ($_POST['wpttar-assign-developers-name'] as $inserProjectMember) {
                    $updateProjectMembers = array('projectID' => sanitize_text_field($_POST['wpttar-project-id']),
                        'teamName' => sanitize_text_field(''),
                        'teamMember' => sanitize_text_field($inserProjectMember),
                        'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                        'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
                    );
                    $id = $wpdb->insert($this->WpttarTeamsTable, $updateProjectMembers);
                }
            }

            $wpttarGetDocuments = $this->WPTTARGetTableDataByID($_POST['wpttar-project-id'], $this->WpttarAttachmentsTable, 'projectID');
            if (!empty($wpttarGetDocuments)) {
                if (!empty($wpttarGetDocuments->documentName)) {
                    $attechmentDocument = $this->WPTTARSetUnSerialize($wpttarGetDocuments->documentName);
                    $attechmentArray = $attechmentDocument['documentlink'];

                    $docummentArrayMerge = array_merge($attechmentArray, $movefileProjectDocuments);
                    $Wpttar['documentName'] = $_POST['documentsname'];
                    $Wpttar['documenturl'] = $_POST['documenturl'];
                    $Wpttar['documentlink'] = $docummentArrayMerge;
                    $documentName = $this->WPTTARSetSerialize($Wpttar);
                    $DocumentsData = array(
                        'documentName' => sanitize_text_field($documentName),
                        'attachmentLink' => '',
                        'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                    );
                    $whereID = array('projectID' => $_POST['wpttar-project-id']);
                    $wpdb->update($this->WpttarAttachmentsTable, $DocumentsData, $whereID);
                    $result['success'] = $_POST['wpttar-project-id'];
                } else {
                    $attechmentArray = '';
                    $Wpttar['documentlink'] = $movefileProjectDocuments;
                    $documentName = $this->WPTTARSetSerialize($Wpttar);

                    $wpttarDocumentsData = $this->WPTTARSetSerialize($movefileProjectDocuments);
                    $DocumentsData = array(
                        'documentName' => sanitize_text_field($documentName),
                        'attachmentLink' => sanitize_text_field($wpttarDocumentsData),
                        'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                    );
                    $whereID = array('projectID' => $_POST['wpttar-project-id']);
                    $wpdb->update($this->WpttarAttachmentsTable, $DocumentsData, $whereID);
                    $result['success'] = $_POST['wpttar-project-id'];
                }
            } else {
                if (isset($movefileProjectDocuments) && !empty($movefileProjectDocuments)) {
                    $wpttarDocumentsData = $this->WPTTARSetSerialize($movefileProjectDocuments);
                }
                $Wpttar['documentlink'] = $movefileProjectDocuments;

                $documentName = $this->WPTTARSetSerialize($Wpttar);
                $DocumentsDataArray = array('projectID' => sanitize_text_field($_POST['wpttar-project-id']),
                    'documentName' => sanitize_text_field($documentName),
                    'attachmentLink' => sanitize_text_field($wpttarDocumentsData),
                    'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                    'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
                );
                $wpdb->insert($this->WpttarAttachmentsTable, $DocumentsDataArray);
                $result['success'] = $_POST['wpttar-project-id'];
            }
        } else {
            $AddData = array('clientName' => sanitize_text_field($_POST['wpttar-client-name']),
                'projectName' => sanitize_text_field($_POST['wpttar-project-name']),
                'members' => sanitize_text_field($wpttarFormDetailsData),
                'description' => sanitize_post($_POST['wpttar-project-dev-server-details']),
                'projectStatus' => sanitize_text_field('Open'),
                'lastUpdate' => sanitize_text_field($wpttarLastUpdate),
                'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
            );
            $wpdb->insert($this->WpttarProjectsTable, $AddData);
            $lastInsertID = $wpdb->insert_id;

            foreach ($_POST['wpttar-assign-developers-name'] as $inserProjectMember) {
                $updateProjectMembers = array('projectID' => sanitize_text_field($lastInsertID),
                    'teamName' => sanitize_text_field(''),
                    'teamMember' => sanitize_text_field($inserProjectMember),
                    'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                    'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
                );
                $id = $wpdb->insert($this->WpttarTeamsTable, $updateProjectMembers);
            }

            if (isset($movefileProjectDocuments) && !empty($movefileProjectDocuments)) {
                $wpttarDocumentsData = $this->WPTTARSetSerialize($movefileProjectDocuments);
            }

            $Wpttar['documentlink'] = $movefileProjectDocuments;
            $documentName = $this->WPTTARSetSerialize($Wpttar);
            $DocumentsData = array('projectID' => sanitize_text_field($lastInsertID),
                'documentName' => sanitize_text_field($documentName),
                'attachmentLink' => sanitize_text_field($wpttarDocumentsData),
                'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
                'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
            );
            $wpdb->insert($this->WpttarAttachmentsTable, $DocumentsData);
            $result['success'] = true;
        }

        echo json_encode($result);
        exit;
    }

    /*     * *   WP-TTAR Delete Project Documents Uploaded * */

    function WPTTARDeleteProjectDocuments() {
        global $current_user, $wpdb;
        $documentArrayData = array();
        $attechmentSetSerialize = '';
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        if (isset($_POST['wpttrPostid']) && $_POST['wpttrPostid'] != '' && isset($_POST['attechmentvalue']) && $_POST['attechmentvalue'] != '')
            $wpttarDocuments = $this->WPTTARGetTableDataByID($_POST['wpttrPostid'], $this->WpttarAttachmentsTable, 'projectID');
        $attechmentArray = $this->WPTTARSetUnSerialize($wpttarDocuments->documentName);
        wp_delete_attachment($_POST['attechmentvalue']);
        foreach ($attechmentArray['documentlink'] as $documentlinkKey => $documentlink) {
            foreach ($attechmentArray['documenturl'] as $documenturlKey => $documenturl) {
                foreach ($attechmentArray['documentName'] as $documentNameKey => $documentName) {
                    if ($documentlinkKey == $documenturlKey && $documentNameKey == $documenturlKey && $documentlinkKey == $documentNameKey) {
                        if ($documentlink == $_POST['attechmentvalue']) {
                            
                        } else {
                            $wpttar['documentlink'][] = $documentlink;
                            $wpttar['documenturl'][] = $documenturl;
                            $wpttar['documentName'][] = $documentName;
                        }
                    }
                }
            }
        }

        if (!empty($wpttar)) {
            $attechmentSetSerialize = $this->WPTTARSetSerialize($wpttar);
        }
        $DocumentsData = array(
            'documentName' => sanitize_text_field($attechmentSetSerialize),
            'lastUpdate' => sanitize_text_field(date('Y-m-d H:i:s')),
        );
        $whereID = array('projectID' => $_POST['wpttrPostid']);
        $wpdb->update($this->WpttarAttachmentsTable, $DocumentsData, $whereID);
        $result['success'] = true;
        echo json_encode($result);
        exit;
    }

    /**   WP-TTAR User Start Time Function * */
    function WPTTARUserStartTimeLog() {
        global $current_user, $wpdb;
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        $todayDate = esc_sql(date('Y-m-d'));
        $startTime = $_POST['startTime'];
        $developerId = esc_sql($_POST['developerId']);
        $projectId = esc_sql($_POST['projectId']);
        $addData = array('projectID' => sanitize_text_field($_POST['projectId']),
            'developerID' => sanitize_text_field($_POST['developerId']),
            'startTime' => sanitize_text_field(date('H:i:s')),
            'endTime' => sanitize_text_field(''),
            'workedHour' => sanitize_text_field(''),
            'updateDate' => sanitize_text_field($todayDate),
        );
        $id = $wpdb->insert($this->WpttarProjectsLogTable, $addData);
        $wpttarCheckProjectLogDate = WPTTARGetTableDataByID($_POST['projectId'], $this->WpttarProjectsTable, 'projectID');
        if (empty($wpttarCheckProjectLogDate)) {
            $updateProjectData = array(
                'dateTime' => sanitize_text_field(date('Y-m-d H:i:s')),
            );
            $whereProjectArray = array('id' => $_POST['projectId']);
            $id = $wpdb->update($this->WpttarProjectsTable, $updateProjectData, $whereProjectArray);
        }

        if (!empty($id)) {
            $result['success'] = true;
        } else {
            $result['error'] = __('Something went wrong.', 'wpttar');
        }

        echo json_encode($result);
        exit;
    }

    /** Messages details functions. * */
    public function WPTTARMessagesInfo() {
        global $wpdb;
        $result = array();
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        $wpttarMessagesTitle = esc_sql($_POST['wpttar-messages-title']); // esc
        $wpttarMessagesDesc = esc_sql($_POST['wpttar-messages-desc']); // esc
        $wpttarMessagesId = esc_sql($_POST['wpttar-messages-id']); // esc
        $wpttarMessagesInfo = $wpdb->get_row("SELECT * FROM $this->WpttarMessagesTable WHERE `id` = '$wpttarMessagesId'");
        if (!empty($wpttarMessagesInfo)) {
            $wpttarMessagesTitle = sanitize_text_field($wpttarMessagesTitle); // sanitize_text_field
            $wpttarMessagesDesc = sanitize_text_field($wpttarMessagesDesc); // sanitize_text_field
            $id = $wpdb->query("UPDATE $this->WpttarMessagesTable SET `messagesTitle` = '$wpttarMessagesTitle', `messagesDesc` ='$wpttarMessagesDesc' WHERE `id`= '$wpttarMessagesId'");
            $result['success'] = true;
        } else {
            $result['error'] = __('Something went wrong.', 'wpttar');
        }
        echo json_encode($result);
        exit;
    }

    /** Setting Function for Time Zone . * */
    public function WPTTARTimeZoneSettingsInfo() {
        global $wpdb;

        $message = array();
        $wpttarTimeZone = '';
        $wpttarTimeFormat = '';
        if (isset($_POST['wpttar-time-zone']) && $_POST['wpttar-time-zone'] != '') {
            $wpttarTimeZone = $_POST['wpttar-time-zone'];
        }

        if (isset($_POST['wpttar-time-format']) && $_POST['wpttar-time-format'] != '') {
            $wpttarTimeFormat = $_POST['wpttar-time-format'];
        }

        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (!empty($wpttarTimeZoneSettings)) {
            $wpttarFormDetails['wpttar-time-zone'] = sanitize_text_field($wpttarTimeZone);
            $wpttarFormDetails['wpttar-time-format'] = sanitize_text_field($wpttarTimeFormat);
            $wpttarFormDetailsData = base64_encode(serialize($wpttarFormDetails));
            $id = $wpdb->query("UPDATE $this->WpttarSettingsTable SET `settingValue`= '$wpttarFormDetailsData' WHERE `settingKey`='wpttarTimeZoneSettingsInfo'");
            $message['success'] = true;
        } else {
            $wpttarFormDetails['wpttar-time-zone'] = sanitize_text_field($wpttarTimeZone);
            $wpttarFormDetails['wpttar-time-format'] = sanitize_text_field($wpttarTimeFormat);
            $wpttarFormDetailsData = base64_encode(serialize($wpttarFormDetails));
            $id = $wpdb->query("INSERT INTO $this->WpttarSettingsTable (`settingKey`, `settingValue`) 
                                               VALUES('wpttarTimeZoneSettingsInfo', '$wpttarFormDetailsData')");
            if ($id) {
                $message['success'] = true;
            } else {
                $message['error'] = __('Something went wrong.', 'wpttar');
            }
        }
        echo json_encode($message);
        exit;
    }

    /** User Login * */
    public function WPTTARLoginUser($user_login, $user = null) {
        global $current_user;
        if (!$user) {
            $user = get_user_by('login', $user_login);
        }
        if (!$user) {
            return;
        }
        $wpttarUserRoles = implode(',', $user->roles);
        if (in_array('administrator', $user->roles)) {
            $wpttarUserRole = 'administrator';
        } else {
            $role_check = count($user->roles);
            if ($role_check > 1) {
                $wpttarUserRole_1 = explode(',', $wpttarUserRoles);
                $wpttarUserRole = $wpttarUserRole_1[0];
            } else {
                $wpttarUserRole = $wpttarUserRoles;
            }
        }

        if (isset($wpttarUserRole) && $wpttarUserRole != 'administrator') {
            $details = $this->WPTTARGetUserWiseData($user->ID, $wpttarUserRole);
            if (empty($details)) {
                $this->WPTTARDefaultRoleToLogin('adddefaultrole', $wpttarUserRole, $user->ID);
            }
        }
        
        
    }

    /**   WP-TTAR User Start Time Function * */
    public function WPTTARUserEndTimeLog() {
        global $current_user, $wpdb;
        $wpttarTimeZoneSettings = $this->WPTTARGetSettings('wpttarTimeZoneSettingsInfo');
        if (isset($wpttarTimeZoneSettings['wpttar-time-zone']) && $wpttarTimeZoneSettings['wpttar-time-zone'] != '') {
            date_default_timezone_set($wpttarTimeZoneSettings['wpttar-time-zone']);
        }
        $todayDate = esc_sql(date('Y-m-d'));
        $developerId = esc_sql($_POST['developerId']);
        $projectId = esc_sql($_POST['projectId']);
        $wpttarTableDatas = $wpdb->get_row("SELECT * FROM  $this->WpttarProjectsLogTable  WHERE  `updateDate` = '$todayDate' AND `projectID` = '$projectId' AND `developerID` = '$developerId' AND `endtime` = '00:00:00'");

        if (isset($wpttarTableDatas) && !empty($wpttarTableDatas)) {
            $tStart = $wpttarTableDatas->startTime;
            $tEnd = $_POST['endtime'];
            $updateData = array(
                'endTime' => sanitize_text_field(date('H:i:s')),
                'workedHour' => sanitize_text_field($tEnd),
                'userComment' => sanitize_text_field($_POST['timercomment']),
                'updateDate' => sanitize_text_field($todayDate),
            );
            $whereArray = array('updateDate' => $todayDate, 'projectID' => $projectId, 'developerID' => $developerId, 'endtime' => '00:00:00');
            $id = $wpdb->update($this->WpttarProjectsLogTable, $updateData, $whereArray);
            if (!empty($id)) {
                $result['success'] = true;
            } else {
                $result['error'] = __('Something went wrong.', 'wpttar');
            }
        }
        echo json_encode($result);
        exit;
    }

    /**   WP-TTAR User Start Time Function * */
    public function WPTTARBetweenTime($startTime = '', $endTime = '') {
        global $current_user, $wpdb;
        $data = '00:00:00';
        $to_time = strtotime($startTime);
        $from_time = strtotime($endTime);
        $datas = round(abs($to_time - $from_time) / 60, 2);
        $data = date('H:i', mktime(0, $datas));
        return $data . ':00';
    }

}

/** Create Object For WPTTAR function. * */
$WPTTAR = new WPTTAR();
/** Ajax Calling function. * */
add_action('wp_ajax_WPTTARProjectForm', array(&$WPTTAR, 'WPTTARProjectForm'));
add_action('wp_ajax_nopriv_WPTTARProjectForm', array(&$WPTTAR, 'WPTTARProjectForm'));
add_action('wp_ajax_WPTTARDeleteProjectDocuments', array(&$WPTTAR, 'WPTTARDeleteProjectDocuments'));
add_action('wp_ajax_nopriv_WPTTARDeleteProjectDocuments', array(&$WPTTAR, 'WPTTARDeleteProjectDocuments'));
add_action('wp_ajax_WPTTARUserTimer', array(&$WPTTAR, 'WPTTARUserTimer'));
add_action('wp_ajax_nopriv_WPTTARUserTimer', array(&$WPTTAR, 'WPTTARUserTimer'));
add_action('wp_ajax_WPTTARUserStartTimeLog', array(&$WPTTAR, 'WPTTARUserStartTimeLog'));
add_action('wp_ajax_nopriv_WPTTARUserStartTimeLog', array(&$WPTTAR, 'WPTTARUserStartTimeLog'));
add_action('wp_ajax_WPTTARUserEndTimeLog', array(&$WPTTAR, 'WPTTARUserEndTimeLog'));
add_action('wp_ajax_nopriv_WPTTARUserEndTimeLog', array(&$WPTTAR, 'WPTTARUserEndTimeLog'));
add_action('wp_ajax_WPTTARTimeZoneSettingsInfo', array(&$WPTTAR, 'WPTTARTimeZoneSettingsInfo'));
add_action('wp_ajax_nopriv_WPTTARTimeZoneSettingsInfo', array(&$WPTTAR, 'WPTTARTimeZoneSettingsInfo'));
add_action('wp_ajax_WPTTARMessagesInfo', array(&$WPTTAR, 'WPTTARMessagesInfo'));
add_action('wp_ajax_nopriv_WPTTARMessagesInfo', array(&$WPTTAR, 'WPTTARMessagesInfo'));
add_action('wp_ajax_WPTTARProjectGraphReports', array(&$WPTTAR, 'WPTTARProjectGraphReports'));
add_action('wp_ajax_nopriv_WPTTARProjectGraphReports', array(&$WPTTAR, 'WPTTARProjectGraphReports'));
add_action('wp_ajax_WPTTARDeleteRow', array(&$WPTTAR, 'WPTTARDeleteRow'));
add_action('wp_ajax_nopriv_WPTTARDeleteRow', array(&$WPTTAR, 'WPTTARDeleteRow'));
add_action('wp_ajax_WPTTAREditComment', array(&$WPTTAR, 'WPTTAREditComment'));
add_action('wp_ajax_nopriv_WPTTAREditComment', array(&$WPTTAR, 'WPTTAREditComment'));

add_action('wp_ajax_WPTTARAddRoles', array(&$WPTTAR, 'WPTTARAddRoles'));
add_action('wp_ajax_WPTTARAddRoles', array(&$WPTTAR, 'WPTTARAddRoles'));
add_action('wp_ajax_wpttarRoleWiseCapabilityGet', array(&$WPTTAR, 'wpttarRoleWiseCapabilityGet'));
add_action('wp_ajax_wpttarRoleWiseCapabilityGet', array(&$WPTTAR, 'wpttarRoleWiseCapabilityGet'));
add_action('wp_ajax_wpttarGetDefaultRolePages', array(&$WPTTAR, 'WPTTARGetDefaultRolePages'));
add_action('wp_ajax_wpttarGetDefaultRolePages', array(&$WPTTAR, 'WPTTARGetDefaultRolePages'));
add_action('wp_ajax_WPTTARChangeRoleWiseDisplay', array(&$WPTTAR, 'WPTTARChangeRoleWiseDisplay'));
add_action('wp_ajax_WPTTARChangeRoleWiseDisplay', array(&$WPTTAR, 'WPTTARChangeRoleWiseDisplay'));
add_action('wp_ajax_WPTTARGetRoles', array(&$WPTTAR, 'WPTTARGetRoles'));
add_action('wp_ajax_WPTTARGetRoles', array(&$WPTTAR, 'WPTTARGetRoles'));
add_action('wp_ajax_WPTTARTeamMemberRoleAssign', array(&$WPTTAR, 'WPTTARTeamMemberRoleAssign'));
add_action('wp_ajax_WPTTARTeamMemberRoleAssign', array(&$WPTTAR, 'WPTTARTeamMemberRoleAssign'));
add_action('wp_ajax_WPTTARAddLogInfo', array(&$WPTTAR, 'WPTTARAddLogInfo'));
add_action('wp_ajax_WPTTARAddLogInfo', array(&$WPTTAR, 'WPTTARAddLogInfo'));

if (!function_exists('WPTTARAddActionLink')) {
    add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'WPTTARAddActionLink', 10, 2);

    function WPTTARAddActionLink($actions, $plugin_file) {
        $action_links = array();
        $action_links = array(
            'forum' => array(
                'label' => __('Support', 'wpttar'),
                'url' => 'https://indigothemes.com/support',
            ),
            'docs' => array(
                'label' => __('Documentation', 'wpttar'),
                'url' => 'https://indigothemes.com/documentation/wpttar/',
            ),
            'settings' => array(
                'label' => __('Settings', 'wpttar'),
                'url' => admin_url('admin.php?page=wpttar-settings', __FILE__),
            ),
        );

        unset($actions['edit']);
        return WPTTARActionLinks($actions, $plugin_file, $action_links, 'before');
    }

}

if (!function_exists('WPTTARActionLinks')) {

    function WPTTARActionLinks($actions, $plugin_file, $action_links = array(), $position = 'after') {
        static $plugin;
        if (!isset($plugin)) {
            $plugin = plugin_basename(__FILE__);
        }
        if ($plugin === $plugin_file && !empty($action_links)) {
            foreach ($action_links as $key => $value) {
                $link = array($key => '<a href="' . $value['url'] . '">' . $value['label'] . '</a>');
                if ('after' === $position) {
                    $actions = array_merge($actions, $link);
                } else {
                    $actions = array_merge($link, $actions);
                }
            }//foreach
        }// if
        return $actions;
    }

}