<?php

/**
 * Description of Tasks
 *
 * @author Nayeem
 */
class Tasks extends Admin_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('tasks_model');
	}

	public function all_task()
	{
		$this->load->driver('cache', ['adapter' => 'file']);
		$data['title'] = lang('all_task');
		$data['page_title'] = lang('tasks');
		$data['page_description'] = 'Delivery queue, due dates, and assigned work.';		
		$data['all_customer_group'] = $this->tasks_model->select_data('tbl_customer_group', 'customer_group_id', 'customer_group', array('type' => 'tasks'));
		$data['dataTables'] = true;
		$data['task_kpis'] = $this->tasks_model->get_task_kpis();
		$kanban = $this->session->userdata('task_kanban');
		$uri_segment = $this->uri->segment(4);
		if (!empty($kanban)) {
			$tasks_view = 'kanban';
		} elseif ($uri_segment == 'kanban') {
			$tasks_view = 'kanban';
		} else {
			$tasks_view = 'list';
		}
		$toggle_target = $tasks_view == 'kanban' ? 'list' : 'kanban';
		$data['header_actions'] = array(
			array(
				'label' => lang('switch_to_' . $toggle_target),
				'icon' => 'repeat',
				'href' => base_url('admin/tasks/all_task/' . $toggle_target),
				'style' => 'warning',
			),
		);
		if (!empty(can_action('54', 'created')) || !empty(can_action('54', 'edited'))) {
			$data['header_actions'][] = array(
				'label' => lang('assign_task'),
				'icon' => 'plus',
				'href' => base_url('admin/tasks/create'),
				'style' => 'primary',
			);
			$data['header_actions'][] = array(
				'label' => lang('import'),
				'icon' => 'upload',
				'href' => base_url('admin/tasks/import'),
				'style' => 'info',
			);
		}
		if ($tasks_view == 'list') {
			$preload_cache_key = 'tasks_list_preload_' . $this->session->userdata('user_id');
			$data['datatable_preload'] = $this->cache->get($preload_cache_key);
			if ($data['datatable_preload'] === false) {
				$data['datatable_preload'] = $this->build_tasks_list_response();
				$this->cache->save($preload_cache_key, $data['datatable_preload'], 30);
			}
			$data['header_filters'] = array(
				array(
					'label' => 'Filters',
					'icon' => 'sliders-horizontal',
					'selected_label' => lang('all'),
					'attrs' => array('id' => 'tasks-header-filter'),
					'items' => array(
						array('label' => lang('all'), 'active' => true, 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => '', 'data-task-search' => 'status', 'data-task-filter-label' => lang('all'), 'data-task-tab' => 'all')),
						array('label' => lang('not_started'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'not_started', 'data-task-search' => 'status', 'data-task-filter-label' => lang('not_started'), 'data-task-tab' => 'not_started')),
						array('label' => lang('in_progress'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'in_progress', 'data-task-search' => 'status', 'data-task-filter-label' => lang('in_progress'), 'data-task-tab' => 'in_progress')),
						array('label' => lang('completed'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'completed', 'data-task-search' => 'status', 'data-task-filter-label' => lang('completed'), 'data-task-tab' => 'completed')),
						array('label' => lang('deferred'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'deferred', 'data-task-search' => 'status', 'data-task-filter-label' => lang('deferred'), 'data-task-tab' => 'deferred')),
						array('label' => lang('waiting_for_someone'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'waiting_for_someone', 'data-task-search' => 'status', 'data-task-filter-label' => lang('waiting_for_someone'), 'data-task-tab' => 'waiting_for_someone')),
						array('label' => lang('billable'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'billable', 'data-task-search' => 'status', 'data-task-filter-label' => lang('billable'), 'data-task-tab' => 'billable')),
						array('label' => lang('non_billable'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'non_billable', 'data-task-search' => 'status', 'data-task-filter-label' => lang('non_billable'), 'data-task-tab' => 'non_billable')),
						array('label' => lang('assigned_to_me'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => 'assigned_to_me', 'data-task-search' => 'status', 'data-task-filter-label' => lang('assigned_to_me'), 'data-task-tab' => 'assigned_to_me')),
						array(
							'label' => lang('project'),
							'icon' => 'folder',
							'divider_before' => true,
							'items' => array(
								array('label' => lang('all') . ' ' . lang('project'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => '', 'data-task-search' => 'by_project', 'data-task-filter-label' => lang('all') . ' ' . lang('project'), 'data-task-tab' => 'all')),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/project_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'action_attrs' => array('data-task-header-filter-action' => '1', 'data-task-search' => 'by_project', 'data-task-tab' => 'all'),
								'filter_attr' => 'data-task-filter',
								'label_attr' => 'data-task-filter-label',
								'label_prefix' => lang('project') . ': ',
								'placeholder' => lang('search') . ' ' . lang('project'),
								'cache_key' => 'tasks_project_lookup',
							),
						),
						array(
							'label' => lang('staff'),
							'icon' => 'users',
							'items' => array(
								array('label' => lang('all') . ' ' . lang('staff'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => '', 'data-task-search' => 'by_staff', 'data-task-filter-label' => lang('all') . ' ' . lang('staff'), 'data-task-tab' => 'all')),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/staff_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'action_attrs' => array('data-task-header-filter-action' => '1', 'data-task-search' => 'by_staff', 'data-task-tab' => 'all'),
								'filter_attr' => 'data-task-filter',
								'label_attr' => 'data-task-filter-label',
								'label_prefix' => lang('staff') . ': ',
								'placeholder' => lang('search') . ' ' . lang('staff'),
								'cache_key' => 'tasks_staff_lookup',
							),
						),
						array(
							'label' => lang('categories'),
							'icon' => 'layers',
							'items' => array(
								array('label' => lang('all') . ' ' . lang('categories'), 'attrs' => array('data-task-header-filter-action' => '1', 'data-task-filter' => '', 'data-task-search' => 'by_category', 'data-task-filter-label' => lang('all') . ' ' . lang('categories'), 'data-task-tab' => 'all')),
							),
							'lookup' => array(
								'endpoint' => base_url('admin/common/category_lookup'),
								'limit' => 12,
								'min_length' => 0,
								'extra' => array('type' => 'tasks'),
								'action_attrs' => array('data-task-header-filter-action' => '1', 'data-task-search' => 'by_category', 'data-task-tab' => 'all'),
								'filter_attr' => 'data-task-filter',
								'label_attr' => 'data-task-filter-label',
								'label_prefix' => lang('categories') . ': ',
								'placeholder' => lang('search') . ' ' . lang('categories'),
								'cache_key' => 'tasks_category_lookup',
							),
						),
					),
				),
			);
			$data['header_filter_extras_html'] = '';
		}

		$data['active'] = 1;

		$data['subview'] = $this->load->view('admin/tasks/tasks', $data, TRUE);
		$this->load->view('admin/_layout_main', $data);
	}

	public function create($id = NULL, $opt_id = NULL)
	{
		$data['title'] = lang('all_task');
		$data['assign_user'] = $this->tasks_model->allowed_user('54');
		$data['all_customer_group'] = $this->tasks_model->select_data('tbl_customer_group', 'customer_group_id', 'customer_group', array('type' => 'tasks'));
		$filterBy = null;
		if ($id) { // retrive data from db by id
			if ($id == 'kanban') {
				$data['active'] = 1;
				$k_session['task_kanban'] = $id;
				$this->session->set_userdata($k_session);
			} elseif ($id == 'list') {
				$data['active'] = 1;
				$this->session->unset_userdata('task_kanban');
			} else {
				if ($id == 'not_started' || $id == 'in_progress' || $id == 'completed' || $id == 'deferred' || $id == 'waiting_for_someone') {
					$data['active'] = 1;
					$filterBy = $id;
					$data['completed'] = true;
				} else {
					$data['active'] = 2;
					$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $id));
					$edited = can_action('54', 'edited');
					if ($id == 'project') {
						$data['project_id'] = $opt_id;
						$project_info = get_row('tbl_project', array('project_id' => $opt_id));
						if ($project_info->permission == 'all') {
							$data['assign_user'] = $this->tasks_model->allowed_user('57');
						} else {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($project_info->permission);
						}
					} elseif ($id == 'opportunities') {
						$data['opportunities_id'] = $opt_id;
						$option_info = get_row('tbl_opportunities', array('opportunities_id' => $opt_id));
						if ($option_info->permission == 'all') {
							$data['assign_user'] = $this->tasks_model->allowed_user('56');
						} else {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'leads') {
						$data['leads_id'] = $opt_id;
						$option_info = get_row('tbl_leads', array('leads_id' => $opt_id));
						if ($option_info->permission == 'all') {
							$data['assign_user'] = $this->tasks_model->allowed_user('55');
						} else {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'bugs') {
						$data['bug_id'] = $opt_id;
						$option_info = get_row('tbl_bug', array('bug_id' => $opt_id));
						if ($option_info->permission == 'all') {
							$data['assign_user'] = $this->tasks_model->allowed_user('58');
						} else {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'goal') {
						$data['goal_tracking_id'] = $opt_id;
						$option_info = get_row('tbl_goal_tracking', array('goal_tracking_id' => $opt_id));
						if ($option_info->permission == 'all') {
							$data['assign_user'] = $this->tasks_model->allowed_user('69');
						} else {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'sub_tasks') {
						$data['sub_task_id'] = $opt_id;
						$option_info = get_row('tbl_task', array('task_id' => $opt_id));
						if ($option_info->permission != 'all') {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'expense') {
						$data['transactions_id'] = $opt_id;
						$option_info = $this->db->where('transactions_id', $opt_id)->get('tbl_transactions')->row();
						if ($option_info->permission != 'all') {
							$data['assign_user'] = $this->tasks_model->permitted_allowed_user($option_info->permission);
						}
					} elseif ($id == 'deals') {
						$data['deals_id'] = $opt_id;
						$deal_info = get_row('tbl_deals', array('id' => $opt_id));
						if (!empty($deal_info)) {
							$data['title'] = lang('deals') . ' ' . lang('tasks');
							$data['back_url'] = base_url('admin/deals/details/' . $opt_id . '/tasks');
							$data['back_label'] = lang('deals') . ' ' . lang('tasks');
							$data['task_context'] = array(
								'module' => 'deals',
								'id' => $opt_id,
								'title' => !empty($deal_info->title) ? $deal_info->title : (lang('deals') . ' #' . $opt_id),
								'url' => base_url('admin/deals/details/' . $opt_id . '/tasks'),
							);
						}
						if (!empty($deal_info->user_id)) {
							$deal_users = json_decode($deal_info->user_id, true);
							if (!empty($deal_users) && is_array($deal_users)) {
								$permission = array();
								foreach ($deal_users as $deal_user_id) {
									$permission[$deal_user_id] = array('view', 'edit', 'delete');
								}
								$data['assign_user'] = $this->tasks_model->permitted_allowed_user($permission);
							}
						}
					} else {
						if (!empty($can_edit) && !empty($edited)) {
							//get all task information
							$data['task_info'] = $this->db->where('task_id', $id)->get('tbl_task')->row();
						}
					}
				}
				$this->session->unset_userdata('task_kanban');
			}
		} else {
			$data['active'] = 2;
		}
		$data['subview'] = $this->load->view('admin/tasks/create', $data, TRUE);
		$this->load->view('admin/_layout_main', $data);
	}

	public function tasks_state_report()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}
		$data = array();
		$pathonor_jonno['tasks_state_report_div'] = $this->load->view("admin/tasks/tasks_state_report", $data, true);
		echo json_encode($pathonor_jonno);
		exit;
	}

	public function tasksList($filterBy = null, $search_by = null)
	{
		if ($this->input->is_ajax_request()) {
			echo json_encode($this->build_tasks_list_response($filterBy, $search_by));
			exit();
		} else {
			redirect('admin/dashboard');
		}
	}

	private function build_tasks_list_response($filterBy = null, $search_by = null)
	{
		$this->load->model('datatables');
		$this->load->driver('cache', ['adapter' => 'file']);
		$original_post = $_POST;
		if (!isset($_POST['length'])) {
			$_POST['length'] = config_item('tables_pagination_limit') ?: 10;
		}
		if (!isset($_POST['start'])) {
			$_POST['start'] = 0;
		}
		if (!isset($_POST['draw'])) {
			$_POST['draw'] = 1;
		}
		if (!isset($_POST['search'])) {
			$_POST['search'] = array('value' => '', 'regex' => 'false');
		}

		$custom_field = $this->cache->get('tasks_custom_fields_3');
		if ($custom_field === false) {
			$custom_field = custom_form_table_search(3);
			$this->cache->save('tasks_custom_fields_3', $custom_field, 300);
		}
		$this->datatables->table = 'tbl_task';
		$this->datatables->join_table = array('tbl_customer_group');
		$this->datatables->join_where = array('tbl_task.category_id=tbl_customer_group.customer_group_id');
		$main_column = array('task_id', 'task_name', 'tbl_customer_group.customer_group', 'tbl_task.tags', 'due_date', 'task_status', 'billable');
		$action_array = array('task_id');
		$result = array_merge($main_column, $custom_field, $action_array);
		$this->datatables->column_order = $result;
		$this->datatables->column_search = $result;
		$this->datatables->order = array('task_id' => 'desc');

		$where = array();
		if (empty($filterBy) && !empty(admin())) {
			$where = array('task_status !=' => 'completed');
		}
		if (!empty($search_by)) {
			if ($search_by == 'by_project') {
				$where = array('project_id' => $filterBy);
			}
			if ($search_by == 'by_opportunity') {
				$where = array('opportunities_id' => $filterBy);
			}
			if ($search_by == 'by_goal') {
				$where = array('goal_tracking_id' => $filterBy);
			}
			if ($search_by == 'by_leads') {
				$where = array('leads_id' => $filterBy);
			}
			if ($search_by == 'by_bug') {
				$where = array('bug_id' => $filterBy);
			}
			if ($search_by == 'by_staff') {
				if ($filterBy == 'everyone') {
					$where = array('permission' => 'all');
				} else {
					$where = $filterBy;
				}
			}
			if ($search_by == 'by_category') {
				$where = array('tbl_task.category_id' => $filterBy);
			}
		} else {
			if ($filterBy == 'billable') {
				$where = array('billable' => 'Yes');
			} else if ($filterBy == 'non_billable') {
				$where = array('billable' => 'No');
			} else if ($filterBy == 'assigned_to_me') {
				$where = 'assigned_to_me';
			} elseif (!empty($filterBy)) {
				$where = array('task_status' => $filterBy);
			}
		}
		$fetch_data = $this->datatables->get_datatable_permission($where);

		$data = array();
		$created = can_action('54', 'created');
		$edited = can_action('54', 'edited');
		$deleted = can_action('54', 'deleted');

		$permission_user_ids = array();
		foreach ($fetch_data as $task_row) {
			if (!empty($task_row->permission) && $task_row->permission !== 'all') {
				$perm = json_decode($task_row->permission, true);
				if (!empty($perm) && is_array($perm)) {
					$permission_user_ids = array_merge($permission_user_ids, array_keys($perm));
				}
			}
		}
		$permission_user_ids = array_unique(array_filter($permission_user_ids));
		$permission_users = array();
		if (!empty($permission_user_ids)) {
			$rows = $this->db
				->select('tbl_users.user_id, tbl_users.role_id, tbl_account_details.fullname, tbl_account_details.avatar')
				->from('tbl_users')
				->join('tbl_account_details', 'tbl_account_details.user_id = tbl_users.user_id', 'left')
				->where_in('tbl_users.user_id', $permission_user_ids)
				->get()
				->result();
			foreach ($rows as $row) {
				$permission_users[$row->user_id] = $row;
			}
		}
		foreach ($fetch_data as $_key => $v_task) {
			if (!empty($v_task)) {
				$checkbox = null;
				$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $v_task->task_id));
				$can_delete = $this->tasks_model->can_action('tbl_task', 'delete', array('task_id' => $v_task->task_id));
				$c_progress = ($v_task->task_progress == 100 || $v_task->task_status == 'completed') ? 100 : 0;
				$sub_array = array();
				if (!empty($created) || !empty($edited) || !empty($deleted)) {
					$checkbox .= '<label class="inline-flex h-4 w-4 items-center justify-center"><input type="checkbox" value="' . $v_task->task_id . '" data-id="' . $v_task->task_id . '" class="js-task-row-check h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20"></label>';
					$sub_array[] = $checkbox;
				}

				$is_overdue = safe_strtotime(date('Y-m-d')) > safe_strtotime($v_task->due_date) && $c_progress < 100;
				$tags_html = get_tags($v_task->tags, true);
				$task_name = '<div class="flex items-center gap-1.5">';
				$task_name .= '<a class="text-[13px] font-semibold text-slate-800 hover:text-slate-900 dark:text-slate-100 dark:hover:text-white" href="' . base_url() . 'admin/tasks/details/' . $v_task->task_id . '">' . html_escape($v_task->task_name) . '</a>';
				if (!empty($tags_html)) {
					$task_name .= '<span class="inline-flex items-center gap-1">' . $tags_html . '</span>';
				}
				$task_name .= '</div>';
				$sub_array[] = $task_name;

				$disabled = null;
				if ($v_task->task_status == 'completed') {
					$disabled = 'disabled';
				}
				$status_icon = '<i data-lucide="circle-dot" class="h-3.5 w-3.5 text-blue-500"></i>';
				if ($v_task->task_status == 'completed') {
					$status_icon = '<i data-lucide="check-circle" class="h-3.5 w-3.5 text-emerald-500"></i>';
				} elseif ($v_task->task_status == 'not_started') {
					$status_icon = '<i data-lucide="circle" class="h-3.5 w-3.5 text-slate-400"></i>';
				} elseif ($v_task->task_status == 'waiting_for_someone') {
					$status_icon = '<i data-lucide="clock-3" class="h-3.5 w-3.5 text-amber-500"></i>';
				}
				$sub_array[] = '<div class="flex items-center gap-1.5 text-[12px] font-medium text-slate-700 dark:text-slate-200" data-status="' . html_escape($v_task->task_status) . '">' . $status_icon . '<span>' . lang($v_task->task_status) . '</span></div>';

				$due = '<div class="text-[12px] font-medium text-slate-700 dark:text-slate-200">' . display_date($v_task->due_date) . '</div>';
				if ($is_overdue) {
					$due = '<span class="inline-flex items-center gap-1 rounded-md bg-rose-50 px-2 py-0.5 text-[12px] font-semibold text-rose-600 dark:bg-rose-900/30 dark:text-rose-300"><i data-lucide="alert-circle" class="h-3.5 w-3.5"></i>' . display_date($v_task->due_date) . '</span>';
				}
				$sub_array[] = $due;

				$project_name = '-';
				if (!empty($v_task->project_id)) {
					$project_name = get_any_field('tbl_project', array('project_id' => $v_task->project_id), 'project_name');
				}
				$project_meta = '<div class="text-[12px]"><span class="font-semibold text-slate-700 dark:text-slate-200">' . html_escape($project_name) . '</span>';
				$project_meta .= '<span class="mx-2 text-slate-300">.</span>';
				$project_meta .= '<span class="text-slate-500 dark:text-slate-400">' . (!empty($v_task->customer_group) ? html_escape($v_task->customer_group) : '-') . '</span></div>';
				$sub_array[] = $project_meta;
				$assignee_name = lang('everyone');
				if ($v_task->permission != 'all') {
					$get_permission = json_decode($v_task->permission, true);
					if (!empty($get_permission)) {
						$first_user_id = (int) array_key_first($get_permission);
						$first_user = isset($permission_users[$first_user_id]) ? $permission_users[$first_user_id] : null;
						if (!empty($first_user) && !empty($first_user->fullname)) {
							$assignee_name = $first_user->fullname;
						}
					}
				}
				$sub_array[] = '<div class="inline-flex items-center gap-1.5 text-[12px] font-medium text-slate-700 dark:text-slate-200"><i data-lucide="user-circle-2" class="h-4 w-4 text-slate-400"></i><span>' . html_escape($assignee_name) . '</span></div>';

				$action = '<div class="erp-table-actions">';
				$action .= '<a href="' . base_url() . 'admin/tasks/details/' . $v_task->task_id . '" class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-sky-500 text-white hover:bg-sky-600" title="' . lang('view') . '"><i data-lucide="list" class="h-3.5 w-3.5"></i></a>';
				if (!empty($can_edit) && !empty($edited)) {
					$action .= '<a href="' . base_url() . 'admin/tasks/create/' . $v_task->task_id . '" class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-violet-500 text-white hover:bg-violet-600" title="' . lang('edit') . '"><i data-lucide="square-pen" class="h-3.5 w-3.5"></i></a>';
				}
				if (!empty($can_delete) && !empty($deleted)) {
					$action .= ajax_anchor(base_url("admin/tasks/delete_task/$v_task->task_id"), '', array("class" => "mt-1", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key));
				}
				if (!empty($can_edit) && !empty($edited)) {
					if (timer_status('tasks', $v_task->task_id, 'on')) {
						$timer_url = base_url('admin/tasks/tasks_timer/off/' . $v_task->task_id);
						$action .= '<a class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-amber-500 text-white hover:bg-amber-600" data-toggle="tooltip" title="' . lang('stop_timer') . '" href="' . $timer_url . '" data-act="ajax-request" data-action-url="' . $timer_url . '" data-reload-page="1"><i data-lucide="timer-reset" class="h-3.5 w-3.5"></i></a>';
					} else {
						$timer_url = base_url('admin/tasks/tasks_timer/on/' . $v_task->task_id);
						$action .= '<a class="inline-flex h-7 w-7 items-center justify-center rounded-md bg-emerald-500 text-white hover:bg-emerald-600 ' . $disabled . '" data-toggle="tooltip" title="' . lang('start_timer') . '" href="' . $timer_url . '" data-act="ajax-request" data-action-url="' . $timer_url . '" data-reload-page="1"><i data-lucide="play" class="h-3.5 w-3.5"></i></a>';
					}
				}
				$action .= '</div>';
				$sub_array[] = $action;
				$data[] = $sub_array;
			}
		}

		$output = build_table_output($data, $where);
		$_POST = $original_post;
		return $output;
	}

	public function new_category()
	{
		$data['title'] = lang('new') . ' ' . lang('categories');
		$data['type'] = 'tasks';
		$data['subview'] = $this->load->view('admin/projects/new_category', $data, FALSE);
	}

	public
	function import()
	{
		$data['title'] = lang('import') . ' ' . lang('tasks');
		$data['assign_user'] = $this->tasks_model->allowed_user('54');
		$data['subview'] = $this->load->view('admin/tasks/import_tasks', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public
	function save_imported()
	{
		//load the excel library
		$this->load->library('excel');
		$files = $this->excel->import($_FILES['upload_file']['tmp_name']);
		if (!empty($files['message'])) {
			set_message('error', $files['message']);
			redirect('admin/client/import');
		}
		$data = $this->tasks_model->array_from_post(array('task_status'));
		$permission = $this->input->post('permission', true);
		if (!empty($permission)) {
			if ($permission == 'everyone') {
				$assigned = 'all';
			} else {
				$assigned_to = $this->tasks_model->array_from_post(array('assigned_to'));
				if (!empty($assigned_to['assigned_to'])) {
					foreach ($assigned_to['assigned_to'] as $assign_user) {
						$assigned[$assign_user] = $this->input->post('action_' . $assign_user, true);
					}
				}
			}
			if (!empty($assigned)) {
				if ($assigned != 'all') {
					$assigned = json_encode($assigned);
				}
			} else {
				$assigned = 'all';
			}
		}
		$all_data = array();
		foreach ($files as $key => $value) {
			$data['task_name'] = trim($value[0]);
			$data['task_start_date'] = date('Y-m-d', safe_strtotime($value[1]));
			$data['due_date'] = date('Y-m-d', safe_strtotime($value[2]));
			$data['task_hour'] = trim($value[3]);
			$data['task_progress'] = trim($value[4]);
			$data['task_description'] = trim($value[5]);
			$data['created_by'] = $this->session->userdata('user_id');
			$data['permission'] = $assigned;
			$all_data[] = $data;
		}
		if (!empty($all_data)) {
			$this->db->insert_batch('tbl_task', $all_data);
		}

		//save data into table.

		$msg = lang('save_task');
		$activity = 'activity_new_task';

		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			// 'module_field_id' => $id,
			'activity' => $activity,
			'icon' => 'fa-tasks',
			// 'link' => 'admin/tasks/details/' . $id,
			'value1' => lang('import') . ' ' . lang('tasks'),
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		$type = "success";
		$message = $msg;

		set_message($type, $message);
		redirect('admin/tasks/all_task');
	}

	public
	function save_task($id = NULL)
	{
		$created = can_action('54', 'created');
		$edited = can_action('54', 'edited');
		if (!empty($created) || !empty($edited) && !empty($id)) {
			$data = $this->tasks_model->array_from_post(array(
				'task_name',
				'category_id',
				'task_description',
				'task_start_date',
				'due_date',
				'task_progress',
				'calculate_progress',
				'client_visible',
				'task_status',
				'hourly_rate',
				'tags',
				'billable'
			));
			$data['tags'] = normalize_and_sync_tags($data['tags']);

			$estimate_hours = $this->input->post('task_hour', true);
			$check_flot = explode('.', $estimate_hours);
			if (!empty($check_flot[0])) {
				if (!empty($check_flot[1])) {
					$data['task_hour'] = $check_flot[0] . ':' . $check_flot[1];
				} else {
					$data['task_hour'] = $check_flot[0] . ':00';
				}
			} else {
				$data['task_hour'] = '0:00';
			}


			if ($data['task_status'] == 'completed') {
				$data['task_progress'] = 100;
			}
			if ($data['task_progress'] == 100) {
				$data['task_status'] = 'completed';
			}
			if (empty($id)) {
				$data['created_by'] = $this->session->userdata('user_id');
			}
			if (empty($data['billable'])) {
				$data['billable'] = 'No';
			}
			if (empty($data['client_visible'])) {
				$data['client_visible'] = 'No';
			}
			if (empty($data['hourly_rate'])) {
				$data['hourly_rate'] = '0';
			}
			$result = 0;
			$related_to = $this->input->post('related_to', true);

			if ($related_to != '0') {
				$project_id = $this->input->post('project_id', TRUE);
				if (!empty($project_id)) {
					$data['project_id'] = $project_id;
					$data['milestones_id'] = $this->input->post('milestones_id', TRUE);
				} else {
					$data['project_id'] = NULL;
					$data['milestones_id'] = NULL;
					$result += 1;
				}
				$opportunities_id = $this->input->post('opportunities_id', TRUE);
				if (!empty($opportunities_id)) {
					$data['opportunities_id'] = $opportunities_id;
				} else {
					$data['opportunities_id'] = NULL;
					$result += 1;
				}
				$leads_id = $this->input->post('leads_id', TRUE);
				if (!empty($leads_id)) {
					$data['leads_id'] = $leads_id;
				} else {
					$data['leads_id'] = NULL;
					$result += 1;
				}
				$bug_id = $this->input->post('bug_id', TRUE);
				if (!empty($bug_id)) {
					$data['bug_id'] = $bug_id;
				} else {
					$data['bug_id'] = NULL;
					$result += 1;
				}
				$goal_tracking_id = $this->input->post('goal_tracking_id', TRUE);
				if (!empty($goal_tracking_id)) {
					$data['goal_tracking_id'] = $goal_tracking_id;
				} else {
					$data['goal_tracking_id'] = NULL;
					$result += 1;
				}
				$sub_task_id = $this->input->post('sub_task_id', TRUE);
				if (!empty($sub_task_id)) {
					$data['sub_task_id'] = $sub_task_id;
				} else {
					$data['sub_task_id'] = NULL;
					$result += 1;
				}
				$transactions_id = $this->input->post('transactions_id', TRUE);
				if (!empty($transactions_id)) {
					$data['transactions_id'] = $transactions_id;
				} else {
					$data['transactions_id'] = NULL;
					$result += 1;
				}

				if ($result == 7) {
					if (!empty($id)) {
						$task_info = $this->db->where('task_id', $id)->get('tbl_task')->row();
						$data['project_id'] = $task_info->project_id;
						$data['milestones_id'] = $task_info->milestones_id;
						$data['opportunities_id'] = $task_info->opportunities_id;
						$data['leads_id'] = $task_info->leads_id;
						$data['bug_id'] = $task_info->bug_id;
						$data['goal_tracking_id'] = $task_info->goal_tracking_id;
						$data['sub_task_id'] = $task_info->sub_task_id;
						$data['transactions_id'] = $task_info->transactions_id;
					} else {
						$data['project_id'] = $this->input->post('un_project_id', TRUE);
						$data['milestones_id'] = $this->input->post('un_milestones_id', TRUE);;
						$data['opportunities_id'] = $this->input->post('un_opportunities_id', TRUE);
						$data['leads_id'] = $this->input->post('un_leads_id', TRUE);
						$data['bug_id'] = $this->input->post('un_bug_id', TRUE);
						$data['goal_tracking_id'] = $this->input->post('un_goal_tracking_id', TRUE);
						$data['sub_task_id'] = $this->input->post('un_sub_task_id', TRUE);
						$data['transactions_id'] = $this->input->post('un_transactions_id', TRUE);
					}
				}
			} else {
				$data['project_id'] = NULL;
				$data['milestones_id'] = NULL;
				$data['goal_tracking_id'] = NULL;
				$data['bug_id'] = NULL;
				$data['leads_id'] = NULL;
				$data['opportunities_id'] = NULL;
				$data['sub_task_id'] = NULL;
				$data['transactions_id'] = NULL;
			}
			$module = $this->input->post('module', true);
			$module_field_id = $this->input->post('module_field_id', true);
			if ($module === 'deals' && !empty($module_field_id)) {
				$data['module'] = 'deals';
				$data['module_field_id'] = $module_field_id;
			}
			$data['permission'] = permission_post();
			// echo '<pre>';
			// print_r($data);
			// echo '</pre>';
			// exit();

			//save data into table.
			$this->tasks_model->_table_name = "tbl_task"; // table name
			$this->tasks_model->_primary_key = "task_id"; // $id
			$id = $this->tasks_model->save($data, $id);

			$this->tasks_model->set_task_progress($id);

			// $u_data['index_no'] = $id;
			// $id = $this->tasks_model->save($u_data, $id);
			$u_data['index_no'] = $id;
			$id = $this->tasks_model->save($u_data, $id);
			save_custom_field(3, $id);

			if ($data['permission'] == 'all') {
				$assigned_to['assigned_to'] = $this->tasks_model->allowed_user_id('54');
			}

			if (!empty($id)) {

				$msg = lang('update_task');
				$activity = 'activity_update_task';
				$id = $id;
				$tasks_email = config_item('tasks_email');
				if (!empty($tasks_email) && $tasks_email == 1) {
					if (!empty($assigned_to['assigned_to'])) {
						// send update
						$this->notify_assigned_tasks($assigned_to['assigned_to'], $id, TRUE);
					}
				}
			} else {
				$msg = lang('save_tasks');
				$activity = 'activity_new_task';
				$tasks_email = config_item('tasks_email');
				if (!empty($tasks_email) && $tasks_email == 1) {
					if (!empty($assigned_to['assigned_to'])) {
						$this->notify_assigned_tasks($assigned_to['assigned_to'], $id);
					}
				}
			}

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $id,
				'activity' => $activity,
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $id,
				'value1' => $data['task_name'],
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			if (!empty($data['project_id'])) {
				$this->tasks_model->set_progress($data['project_id']);
			}

			$type = "success";
			$message = $msg;
			set_message($type, $message);
			if (!empty($data['module']) && $data['module'] === 'deals' && !empty($data['module_field_id'])) {
				redirect('admin/deals/details/' . $data['module_field_id'] . '/tasks');
			} elseif (!empty($data['project_id']) && is_numeric($data['project_id'])) {
				redirect('admin/projects/project_details/' . $data['project_id'] . '/' . 'tasks');
			} else {
				redirect('admin/tasks/details/' . $id);
			}
		} else {
			redirect('admin/tasks/all_task');
		}
	}

	function notify_assigned_tasks($users, $task_id, $update = NULL)
	{
		if (!empty($update)) {
			$email_template = email_templates(array('email_group' => 'tasks_updated'));
			$description = 'not_task_update';
		} else {
			$email_template = email_templates(array('email_group' => 'task_assigned'));
			$description = 'assign_to_you_the_tasks';;
		}
		$tasks_info = $this->tasks_model->check_by(array('task_id' => $task_id), 'tbl_task');
		$message = $email_template->template_body;

		$subject = $email_template->subject;

		$task_name = str_replace("{TASK_NAME}", $tasks_info->task_name, $message);

		$assigned_by = str_replace("{ASSIGNED_BY}", ucfirst($this->session->userdata('name')), $task_name);
		$Link = str_replace("{TASK_URL}", base_url() . 'admin/tasks/details/' . $tasks_info->task_id, $assigned_by);
		$message = str_replace("{SITE_NAME}", config_item('company_name'), $Link);

		$data['message'] = $message;
		$message = $this->load->view('email_template', $data, TRUE);

		$params['subject'] = $subject;
		$params['message'] = $message;
		$params['resourceed_file'] = '';

		foreach ($users as $v_user) {
			$login_info = $this->tasks_model->check_by(array('user_id' => $v_user), 'tbl_users');
			$params['recipient'] = $login_info->email;
			$this->tasks_model->send_email($params);
			if ($v_user != $this->session->userdata('user_id')) {
				add_notification(array(
					'to_user_id' => $v_user,
					'from_user_id' => true,
					'description' => $description,
					'link' => 'admin/tasks/details/' . $task_id,
					'value' => lang('task') . ' ' . $tasks_info->task_name,
				));
			}
		}
		show_notification($users);
	}

	private function render_task_assigned_members($permission)
	{
		$assigned_html = '';
		if ($permission != 'all') {
			$get_permission = json_decode($permission);
			if (!empty($get_permission)) {
				foreach ($get_permission as $permission_id => $v_permission) {
					$user_info = get_staff_details($permission_id);
					if (!empty($user_info)) {
						$ring = ($user_info->role_id == 1) ? 'ring-rose-500' : 'ring-emerald-500';
						$assigned_html .= '<span class="relative inline-flex items-center" data-tooltip="' . html_escape(fullname($permission_id)) . '">'
							. '<img src="' . base_url() . staffImage($permission_id) . '" class="h-7 w-7 rounded-full ring-2 ring-white dark:ring-slate-900 ' . $ring . '" alt="' . html_escape(fullname($permission_id)) . '">'
							. '</span>';
					}
				}
			}
		} else {
			$assigned_html = '<span class="inline-flex items-center gap-1 rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-muted-foreground">' . lang('everyone') . '</span>';
		}

		return $assigned_html;
	}

	private function render_task_assigned_count($permission)
	{
		if ($permission === 'all') {
			return lang('everyone');
		}

		$permission_snapshot = json_decode($permission, true);
		$count = !empty($permission_snapshot) && is_array($permission_snapshot) ? count($permission_snapshot) : 0;

		return $count > 0 ? $count . ' ' . lang('members') : lang('everyone');
	}

	public
	function update_users($id)
	{
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $id));
		if (!empty($can_edit)) {

			$data['assign_user'] = $this->tasks_model->allowed_user('54');
			$data['task_info'] = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
			$data['modal_subview'] = $this->load->view('admin/tasks/_modal_users', $data, FALSE);
		} else {
			set_message('error', lang('there_in_no_value'));
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/tasks/all_task');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public
	function update_member($id)
	{
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $id));
		if (!empty($can_edit)) {
			$tasks_info = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');

			$data['permission'] = permission_post();
			//save data into table.
			$this->tasks_model->_table_name = "tbl_task"; // table name
			$this->tasks_model->_primary_key = "task_id"; // $id
			$this->tasks_model->save($data, $id);

			$msg = lang('update_task');
			$activity = 'activity_update_task';
			$tasks_email = config_item('tasks_email');
			if (!empty($tasks_email) && $tasks_email == 1) {
				if (!empty($assigned_to['assigned_to'])) {
					$this->notify_assigned_tasks($assigned_to['assigned_to'], $id);
				}
			}

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $id,
				'activity' => $activity,
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $id,
				'value1' => $tasks_info->task_name,
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			$type = "success";
			$message = $msg;
			set_message($type, $message);
		} else {
			set_message('error', lang('there_in_no_value'));
		}
		if ($this->input->is_ajax_request()) {
			$status = ($type === 'success') ? 'success' : 'error';
			$patch = array();
			if ($status === 'success') {
				$patch[] = array(
					'selector' => '[data-task-assigned-members="' . (int) $id . '"]',
					'html' => $this->render_task_assigned_members($data['permission']),
				);
				$patch[] = array(
					'selector' => '[data-task-assigned-count="' . (int) $id . '"]',
					'html' => html_escape($this->render_task_assigned_count($data['permission'])),
				);
			}
			echo json_encode(array(
				'status' => $status,
				'message' => $message,
				'patch' => $patch,
			));
			exit();
		}
		if (empty($_SERVER['HTTP_REFERER'])) {
			redirect('admin/tasks/all_task');
		} else {
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public
	function change_status($tasks_id, $status)
	{
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $tasks_id));
		if (!empty($can_edit)) {
			$tasks_info = $this->tasks_model->check_by(array('task_id' => $tasks_id), 'tbl_task');

			$notifiedUsers = array();
			if (!empty($tasks_info->permission) && $tasks_info->permission != 'all') {
				$permissionUsers = json_decode($tasks_info->permission);
				foreach ($permissionUsers as $user => $v_permission) {
					array_push($notifiedUsers, $user);
				}
			} else {
				$notifiedUsers = $this->tasks_model->allowed_user_id('54');
			}
			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_changed_status',
							'link' => 'admin/tasks/details/' . $tasks_id,
							'value' => lang('status') . ' : ' . $tasks_info->task_status . ' to ' . $status,
						));
					}
				}
				show_notification($notifiedUsers);
			}

			if (!empty($tasks_info->project_id)) {
				$this->tasks_model->set_progress($tasks_info->project_id);
			}

			if ($status == 'not_started') {
				$data['task_progress'] = 0;
			}
			if ($status == 'completed') {
				$data['task_progress'] = 100;
				$data['task_status'] = $status;
				$this->tasks_timer('off', $tasks_id, true);
			} else {
				$data['task_status'] = $status;
			}
			$this->tasks_model->_table_name = "tbl_task"; // table name
			$this->tasks_model->_primary_key = "task_id"; // $id
			$id = $this->tasks_model->save($data, $tasks_id);
			$activity = 'activity_update_task';
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $id,
				'activity' => $activity,
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $id,
				'value1' => $tasks_info->task_name,
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);
			// messages for user
			$type = "success";
			$message = lang('change_status');
			set_message($type, $message);
		} else {
			set_message('error', lang('there_in_no_value'));
		}
		if (empty($_SERVER['HTTP_REFERER'])) {
			redirect('admin/tasks/all_task');
		} else {
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public
	function completed_tasks($id = NULL)
	{
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $id));
		if (!empty($can_edit)) {
			$tasks_info = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
			if ($tasks_info->task_progress == 100) {
				$data['task_progress'] = 0;
				$data['task_status'] = 'not_started';
			} else {
				$data['task_progress'] = $this->input->post('task_progress');
				$data['task_status'] = $this->input->post('task_status');
			}
			//save data into table.
			$this->tasks_model->_table_name = "tbl_task"; // table name
			$this->tasks_model->_primary_key = "task_id"; // $id
			$id = $this->tasks_model->save($data, $id);

			$tasks_info = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
			if (!empty($tasks_info->project_id)) {
				$this->tasks_model->set_progress($tasks_info->project_id);
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $id,
				'activity' => 'activity_update_task',
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $id,
				'value1' => $data['task_progress'],
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);
			$type = "success";
			$message = lang('update_task');
			echo json_encode(array("status" => $type, "message" => $message));
			exit();
		} else {
			$type = "error";
			$message = lang('there_in_no_value');
			echo json_encode(array("status" => $type, "message" => $message));
			exit();
		}
	}

	public
	function save_tasks_notes($tasks_id)
	{
		$data = $this->tasks_model->array_from_post(array('notes'));

		$data['module_field_id'] = $tasks_id;
		$data['user_id'] = my_id();
		$data['module'] = 'tasks';
		//save data into table.
		$this->tasks_model->_table_name = 'tbl_leads_notes';
		$this->tasks_model->_primary_key = 'notes_id';
		$id = $this->tasks_model->save($data);

		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			'module_field_id' => $id,
			'activity' => 'activity_update_notes',
			'icon' => 'fa-folder-open-o',
			'link' => 'admin/tasks/details/' . $tasks_id . '/notes',
			'value1' => $data['notes'],
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		$type = "success";
		$message = lang('update_notes');
		set_message($type, $message);
		redirect('admin/tasks/details/' . $tasks_id . '/' . 'notes');
	}

	// public function save_tasks_notes($id)
	// {

	// 	$data = $this->tasks_model->array_from_post(array('tasks_notes'));

	// 	//save data into table.
	// 	$this->tasks_model->_table_name = "tbl_task"; // table name
	// 	$this->tasks_model->_primary_key = "task_id"; // $id
	// 	$id = $this->tasks_model->save($data, $id);
	// 	// save into activities
	// 	$activities = array(
	// 		'user' => $this->session->userdata('user_id'),
	// 		'module' => 'tasks',
	// 		'module_field_id' => $id,
	// 		'activity' => 'activity_update_task',
	// 		'icon' => 'fa-tasks',
	// 		'link' => 'admin/tasks/details/' . $id . '/notes',
	// 		'value1' => $data['tasks_notes'],
	// 	);
	// 	// Update into tbl_project
	// 	$this->tasks_model->_table_name = "tbl_activities"; //table name
	// 	$this->tasks_model->_primary_key = "activities_id";
	// 	$this->tasks_model->save($activities);

	// 	$type = "success";
	// 	$message = lang('update_task');
	// 	set_message($type, $message);
	// 	redirect('admin/tasks/details/' . $id . '/notes');
	// }

	public
	function save_comments()
	{

		$data['task_id'] = $this->input->post('task_id', TRUE);
		$data['comment'] = $this->input->post('comment', TRUE);

		$files = $this->input->post("files", true);
		$target_path = getcwd() . "/uploads/";
		//process the fiiles which has been uploaded by dropzone
		if (!empty($files) && is_array($files)) {
			foreach ($files as $key => $file) {
				if (!empty($file)) {
					$file_name = $this->input->post('file_name_' . $file, true);
					$new_file_name = move_temp_file($file_name, $target_path);
					$file_ext = explode(".", $new_file_name);
					$is_image = check_image_extension($new_file_name);
					$size = $this->input->post('file_size_' . $file, true) / 1000;
					if ($new_file_name) {
						$up_data[] = array(
							"fileName" => $new_file_name,
							"path" => "uploads/" . $new_file_name,
							"fullPath" => getcwd() . "/uploads/" . $new_file_name,
							"ext" => '.' . end($file_ext),
							"size" => round($size, 2),
							"is_image" => $is_image,
						);
						$success = true;
					} else {
						$success = false;
					}
				}
			}
		}
		//process the files which has been submitted manually
		if ($_FILES) {
			$files = $_FILES['manualFiles'];
			if ($files && count(array($files)) > 0) {
				foreach ($files["tmp_name"] as $key => $file) {
					$temp_file = $file;
					$file_name = $files["name"][$key];
					$file_size = $files["size"][$key];
					$new_file_name = move_temp_file($file_name, $target_path, "", $temp_file);
					if ($new_file_name) {
						$file_ext = explode(".", $new_file_name);
						$is_image = check_image_extension($new_file_name);
						$up_data[] = array(
							"fileName" => $new_file_name,
							"path" => "uploads/" . $new_file_name,
							"fullPath" => getcwd() . "/uploads/" . $new_file_name,
							"ext" => '.' . end($file_ext),
							"size" => round($file_size, 2),
							"is_image" => $is_image,
						);
					}
				}
			}
		}
		if (!empty($up_data)) {
			$data['comments_attachment'] = json_encode($up_data);
		}
		$data['user_id'] = $this->session->userdata('user_id');

		//save data into table.
		$this->tasks_model->_table_name = "tbl_task_comment"; // table name
		$this->tasks_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->tasks_model->save($data);
		if (!empty($comment_id)) {

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $data['task_id'],
				'activity' => 'activity_new_task_comment',
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $data['task_id'] . '/comments',
				'value1' => $data['comment'],
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			$tasks_info = $this->tasks_model->check_by(array('task_id' => $data['task_id']), 'tbl_task');

			$notifiedUsers = array();
			if (!empty($tasks_info->permission) && $tasks_info->permission != 'all') {
				$permissionUsers = json_decode($tasks_info->permission);
				foreach ($permissionUsers as $user => $v_permission) {
					array_push($notifiedUsers, $user);
				}
			} else {
				$notifiedUsers = $this->tasks_model->allowed_user_id('54');
			}
			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_new_comment',
							'link' => 'admin/tasks/details/' . $data['task_id'] . '/comments',
							'value' => lang('task') . ' ' . $tasks_info->task_name,
						));
					}
				}
				show_notification($notifiedUsers);
			}
			// send notification
			$tasks_email = config_item('tasks_email');
			if (!empty($tasks_email) && $tasks_email == 1) {
				$this->notify_comments_tasks($comment_id);
			}
			$response_data = "";
			$view_data['comment_details'] = $this->db->where(array('task_comment_id' => $comment_id))->order_by('comment_datetime', 'DESC')->get('tbl_task_comment')->result();
			$response_data = $this->load->view("admin/tasks/comments_list", $view_data, true);
			echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('task_comment_save')));
			exit();
		} else {
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	public
	function save_comments_reply($task_comment_id)
	{
		$data['task_id'] = $this->input->post('task_id', TRUE);
		$data['comment'] = $this->input->post('reply_comments', TRUE);
		$data['user_id'] = $this->session->userdata('user_id');
		$data['comments_reply_id'] = $task_comment_id;
		//save data into table.
		$this->tasks_model->_table_name = "tbl_task_comment"; // table name
		$this->tasks_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->tasks_model->save($data);
		if (!empty($comment_id)) {

			$comments_info = $this->tasks_model->check_by(array('task_comment_id' => $task_comment_id), 'tbl_task_comment');
			$user = $this->tasks_model->check_by(array('user_id' => $comments_info->user_id), 'tbl_users');
			if ($user->role_id == 2) {
				$url = 'client/';
			} else {
				$url = 'admin/';
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $data['task_id'],
				'activity' => 'activity_new_comment_reply',
				'icon' => 'fa-tasks',
				'link' => $url . 'tasks/details/' . $data['task_id'] . '/comments',
				'value1' => $this->db->where('task_comment_id', $task_comment_id)->get('tbl_task_comment')->row()->comment,
				'value2' => $data['comment'],
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			$tasks_info = $this->tasks_model->check_by(array('task_id' => $data['task_id']), 'tbl_task');
			$notifiedUsers = array($comments_info->user_id);
			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_comment_reply',
							'link' => $url . 'tasks/details/' . $data['task_id'] . '/comments',
							'value' => lang('task') . ' ' . $tasks_info->task_name,
						));
					}
				}
				show_notification($notifiedUsers);
			}

			// send notification
			$tasks_email = config_item('tasks_email');
			if (!empty($tasks_email) && $tasks_email == 1) {
				$this->notify_comments_tasks($comment_id);
			}
			$response_data = "";
			$view_data['comment_reply_details'] = $this->db->where(array('task_comment_id' => $comment_id))->order_by('comment_datetime', 'ASC')->get('tbl_task_comment')->result();
			$response_data = $this->load->view("admin/tasks/comments_reply", $view_data, true);
			echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('task_comment_save')));
			exit();
		} else {
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	function notify_comments_tasks($comment_id)
	{
		$email_template = email_templates(array('email_group' => 'tasks_comments'));
		$tasks_comment_info = $this->tasks_model->check_by(array('task_comment_id' => $comment_id), 'tbl_task_comment');
		$user = $this->tasks_model->check_by(array('user_id' => $tasks_comment_info->user_id), 'tbl_users');
		if ($user->role_id == 2) {
			$url = 'client/';
		} else {
			$url = 'admin/';
		}
		$tasks_info = $this->tasks_model->check_by(array('task_id' => $tasks_comment_info->task_id), 'tbl_task');
		$message = $email_template->template_body;

		$subject = $email_template->subject;

		$task_name = str_replace("{TASK_NAME}", $tasks_info->task_name, $message);
		$assigned_by = str_replace("{POSTED_BY}", ucfirst($this->session->userdata('name')), $task_name);
		$Link = str_replace("{COMMENT_URL}", base_url() . $url . 'tasks/details/' . $tasks_info->task_id . '/' . $data['active'] = 2, $assigned_by);
		$comments = str_replace("{COMMENT_MESSAGE}", $tasks_comment_info->comment, $Link);
		$message = str_replace("{SITE_NAME}", config_item('company_name'), $comments);

		$data['message'] = $message;
		$message = $this->load->view('email_template', $data, TRUE);

		$params['subject'] = $subject;
		$params['message'] = $message;
		$params['resourceed_file'] = '';

		if (!empty($tasks_info->permission) && $tasks_info->permission != 'all') {
			$user = json_decode($tasks_info->permission);
			foreach ($user as $key => $v_user) {
				$allowed_user[] = $key;
			}
		} else {
			$allowed_user = $this->tasks_model->allowed_user_id('54');
		}
		if (!empty($allowed_user)) {
			foreach ($allowed_user as $v_user) {
				$login_info = $this->tasks_model->check_by(array('user_id' => $v_user), 'tbl_users');
				$params['recipient'] = $login_info->email;
				$this->tasks_model->send_email($params);
			}
		}
	}

	public
	function delete_task_comments($task_comment_id)
	{
		$comments_info = $this->tasks_model->check_by(array('task_comment_id' => $task_comment_id), 'tbl_task_comment');

		if (!empty($comments_info->comments_attachment)) {
			$attachment = json_decode($comments_info->comments_attachment);
			foreach ($attachment as $v_file) {
				remove_files($v_file->fileName);
			}
		}
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			'module_field_id' => $comments_info->task_id,
			'activity' => 'activity_comment_deleted',
			'icon' => 'fa-folder-open-o',
			'link' => 'admin/tasks/details/' . $comments_info->task_id . '/comments',
			'value1' => $comments_info->comment,
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		//save data into table.
		$this->tasks_model->_table_name = "tbl_task_comment"; // table name
		$this->tasks_model->_primary_key = "task_comment_id"; // $id
		$this->tasks_model->delete($task_comment_id);

		//save data into table.
		$this->tasks_model->_table_name = "tbl_task_comment"; // table name
		$this->tasks_model->delete_multiple(array('comments_reply_id' => $task_comment_id));

		echo json_encode(array("status" => 'success', 'message' => lang('task_comment_deleted')));
		exit();
	}

	public
	function new_attachment($id)
	{
		$data['dropzone'] = true;
		$data['task_details'] = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
		$data['modal_subview'] = $this->load->view('admin/tasks/new_attachment', $data, FALSE);
	}

	public
	function attachment_details($type, $id)
	{
		$data['type'] = $type;
		$data['dropzone'] = true;
		$data['attachment_info'] = $this->tasks_model->check_by(array('attachments_id' => $id), 'tbl_attachments');
		$data['modal_subview'] = $this->load->view('admin/tasks/attachment_details', $data, FALSE);
	}

	public
	function save_attachment($attachments_id = NULL)
	{
		$data = $this->tasks_model->array_from_post(array('title', 'description', 'task_id'));

		$data['user_id'] = $this->session->userdata('user_id');

		// save and update into tbl_files
		$this->tasks_model->_table_name = "tbl_attachments"; //table name
		$this->tasks_model->_primary_key = "attachments_id";
		if (!empty($attachments_id)) {
			$id = $attachments_id;
			$this->tasks_model->save($data, $id);
			$msg = lang('project_file_updated');
		} else {
			$id = $this->tasks_model->save($data);
			$msg = lang('project_file_added');
		}
		$files = $this->input->post("files", true);

		$target_path = getcwd() . "/uploads/";
		//process the fiiles which has been uploaded by dropzone
		if (!empty($files) && is_array($files)) {
			foreach ($files as $key => $file) {
				if (!empty($file)) {
					$file_name = $this->input->post('file_name_' . $file, true);
					$new_file_name = move_temp_file($file_name, $target_path);
					$file_ext = explode(".", $new_file_name);
					$is_image = check_image_extension($new_file_name);

					if ($new_file_name) {
						$up_data = array(
							"files" => "uploads/" . $new_file_name,
							"uploaded_path" => getcwd() . "/uploads/" . $new_file_name,
							"file_name" => $new_file_name,
							"size" => $this->input->post('file_size_' . $file, true),
							"ext" => end($file_ext),
							"is_image" => $is_image,
							"image_width" => 0,
							"image_height" => 0,
							"attachments_id" => $id
						);
						$this->tasks_model->_table_name = "tbl_attachments_files"; // table name
						$this->tasks_model->_primary_key = "uploaded_files_id"; // $id
						$uploaded_files_id = $this->tasks_model->save($up_data);

						// saved into comments
						$comment = $this->input->post('comment_' . $file, true);
						$u_cdata = array(
							"comment" => $comment,
							"task_id" => $data['task_id'],
							"user_id" => $this->session->userdata('user_id'),
							"uploaded_files_id" => $uploaded_files_id,
						);
						$this->tasks_model->_table_name = "tbl_task_comment"; // table name
						$this->tasks_model->_primary_key = "task_comment_id"; // $id
						$this->tasks_model->save($u_cdata);

						$success = true;
					} else {
						$success = false;
					}
				}
			}
		}
		//process the files which has been submitted manually
		if ($_FILES) {
			$files = $_FILES['manualFiles'];
			if ($files && count(array($files)) > 0) {
				$comment = $this->input->post('comment', true);
				foreach ($files["tmp_name"] as $key => $file) {
					$temp_file = $file;
					$file_name = $files["name"][$key];
					$file_size = $files["size"][$key];
					$new_file_name = move_temp_file($file_name, $target_path, "", $temp_file);
					if ($new_file_name) {
						$file_ext = explode(".", $new_file_name);
						$is_image = check_image_extension($new_file_name);
						$up_data = array(
							"files" => "uploads/" . $new_file_name,
							"uploaded_path" => getcwd() . "/uploads/" . $new_file_name,
							"file_name" => $new_file_name,
							"size" => $file_size,
							"ext" => end($file_ext),
							"is_image" => $is_image,
							"image_width" => 0,
							"image_height" => 0,
							"attachments_id" => $id
						);
						$this->tasks_model->_table_name = "tbl_attachments_files"; // table name
						$this->tasks_model->_primary_key = "uploaded_files_id"; // $id
						$uploaded_files_id = $this->tasks_model->save($up_data);

						// saved into comments
						if (!empty($comment[$key])) {
							$u_cdata = array(
								"comment" => $comment[$key],
								"user_id" => $this->session->userdata('user_id'),
								"uploaded_files_id" => $uploaded_files_id,
							);
							$this->tasks_model->_table_name = "tbl_task_comment"; // table name
							$this->tasks_model->_primary_key = "task_comment_id"; // $id
							$this->tasks_model->save($u_cdata);
						}
					}
				}
			}
		}

		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			'module_field_id' => $data['task_id'],
			'activity' => 'activity_new_project_attachment',
			'icon' => 'fa-folder-open-o',
			'link' => 'admin/tasks/details/' . $data['task_id'] . '/attachments',
			'value1' => $data['title'],
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		$tasks_email = config_item('tasks_email');
		if (!empty($tasks_email) && $tasks_email == 1) {
			// send notification message
			$this->notify_attchemnt_tasks($id);
		}

		// messages for user
		$type = "success";
		$message = $msg;
		set_message($type, $message);
		redirect('admin/tasks/details/' . $data['task_id'] . '/' . '3');
	}

	public
	function save_attachment_comments()
	{
		$attachments_id = $this->input->post('attachments_id');
		if (!empty($attachments_id)) {
			$data['attachments_id'] = $attachments_id;
		} else {
			$data['uploaded_files_id'] = $this->input->post('uploaded_files_id');
		}
		$data['task_id'] = $this->input->post('task_id', true);
		$data['comment'] = $this->input->post('description', true);

		$files = $this->input->post("files", true);
		$target_path = getcwd() . "/uploads/";
		//process the fiiles which has been uploaded by dropzone
		if (!empty($files) && is_array($files)) {
			foreach ($files as $key => $file) {
				if (!empty($file)) {
					$file_name = $this->input->post('file_name_' . $file, true);
					$new_file_name = move_temp_file($file_name, $target_path);
					$file_ext = explode(".", $new_file_name);
					$is_image = check_image_extension($new_file_name);
					$size = $this->input->post('file_size_' . $file, true) / 1000;
					if ($new_file_name) {
						$up_data[] = array(
							"fileName" => $new_file_name,
							"path" => "uploads/" . $new_file_name,
							"fullPath" => getcwd() . "/uploads/" . $new_file_name,
							"ext" => '.' . end($file_ext),
							"size" => round($size, 2),
							"is_image" => $is_image,
						);
						$success = true;
					} else {
						$success = false;
					}
				}
			}
		}
		//process the files which has been submitted manually
		if ($_FILES) {
			$files = $_FILES['manualFiles'];
			if ($files && count(array($files)) > 0) {
				$comment = $this->input->post('comment', true);
				foreach ($files["tmp_name"] as $key => $file) {
					$temp_file = $file;
					$file_name = $files["name"][$key];
					$file_size = $files["size"][$key];
					$new_file_name = move_temp_file($file_name, $target_path, "", $temp_file);
					if ($new_file_name) {
						$file_ext = explode(".", $new_file_name);
						$is_image = check_image_extension($new_file_name);
						$up_data[] = array(
							"fileName" => $new_file_name,
							"path" => "uploads/" . $new_file_name,
							"fullPath" => getcwd() . "/uploads/" . $new_file_name,
							"ext" => '.' . end($file_ext),
							"size" => round($file_size, 2),
							"is_image" => $is_image,
						);
					}
				}
			}
		}
		if (!empty($up_data)) {
			$data['comments_attachment'] = json_encode($up_data);
		}
		$data['user_id'] = $this->session->userdata('user_id');

		//save data into table.
		$this->tasks_model->_table_name = "tbl_task_comment"; // table name
		$this->tasks_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->tasks_model->save($data);
		if (!empty($comment_id)) {

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $data['task_id'],
				'activity' => 'activity_new_task_comment',
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $data['task_id'] . '/comments',
				'value1' => $data['comment'],
			);
			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			$tasks_info = $this->tasks_model->check_by(array('task_id' => $data['task_id']), 'tbl_task');

			$notifiedUsers = array();
			if (!empty($tasks_info->permission) && $tasks_info->permission != 'all') {
				$permissionUsers = json_decode($tasks_info->permission);
				foreach ($permissionUsers as $user => $v_permission) {
					array_push($notifiedUsers, $user);
				}
			} else {
				$notifiedUsers = $this->tasks_model->allowed_user_id('54');
			}
			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_new_comment',
							'link' => 'admin/tasks/details/' . $data['task_id'] . '/comments',
							'value' => lang('task') . ' ' . $tasks_info->task_name,
						));
					}
				}
				show_notification($notifiedUsers);
			}
			$response_data = "";
			$view_data['comment_details'] = $this->db->where(array('task_comment_id' => $comment_id))->order_by('comment_datetime', 'DESC')->get('tbl_task_comment')->result();
			$response_data = $this->load->view("admin/tasks/comments_list", $view_data, true);
			echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('task_comment_save')));
			exit();
		} else {
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	public
	function download_files($uploaded_files_id, $comments = null)
	{
		$this->load->helper('download');
		if (!empty($comments)) {
			if ($uploaded_files_id) {
				$down_data = file_get_contents('uploads/' . $uploaded_files_id); // Read the file's contents
				force_download($uploaded_files_id, $down_data);
			} else {
				echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
				exit();
			}
		} else {
			$uploaded_files_info = $this->tasks_model->check_by(array('uploaded_files_id' => $uploaded_files_id), 'tbl_attachments_files');
			if ($uploaded_files_info->uploaded_path) {
				$data = file_get_contents($uploaded_files_info->uploaded_path); // Read the file's contents
				force_download($uploaded_files_info->file_name, $data);
			} else {
				echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
				exit();
			}
		}
	}

	public
	function download_all_files($attachment_id)
	{
		$uploaded_files_info = $this->db->where('attachments_id', $attachment_id)->get('tbl_attachments_files')->result();
		$attachment_info = $this->db->where('attachments_id', $attachment_id)->get('tbl_attachments')->row();
		$this->load->library('zip');
		if (!empty($uploaded_files_info)) {
			$filename = slug_it($attachment_info->title);
			foreach ($uploaded_files_info as $v_files) {
				$down_data = ($v_files->files); // Read the file's contents
				$this->zip->read_file($down_data);
			}
			$this->zip->download($filename . '.zip');
		} else {
			$type = "error";
			$message = lang('operation_failed');
			set_message($type, $message);
			redirect('admin/tasks/details/' . $attachment_info->task_id . '/attachments');
		}
	}

	public
	function delete_task_files($attachments_id)
	{
		$file_info = $this->tasks_model->check_by(array('attachments_id' => $attachments_id), 'tbl_attachments');
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			'module_field_id' => $file_info->task_id,
			'activity' => 'activity_task_attachfile_deleted',
			'icon' => 'fa-tasks',
			'link' => 'admin/tasks/details/' . $file_info->task_id . '/attachments',
			'value1' => $file_info->title,
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		//save data into table.
		$this->tasks_model->_table_name = "tbl_attachments"; // table name
		$this->tasks_model->delete_multiple(array('attachments_id' => $attachments_id));

		$uploadFileinfo = $this->db->where('attachments_id', $attachments_id)->get('tbl_attachments_files')->result();
		if (!empty($uploadFileinfo)) {
			foreach ($uploadFileinfo as $Fileinfo) {
				remove_files($Fileinfo->file_name);
			}
		}
		//save data into table.
		$this->tasks_model->_table_name = "tbl_attachments_files"; // table name
		$this->tasks_model->delete_multiple(array('attachments_id' => $attachments_id));

		echo json_encode(array("status" => 'success', 'message' => lang('task_attachfile_deleted')));
		exit();
	}


	public
	function details($id, $active = NULL, $edit = NULL)
	{
		$data['title'] = lang('task_details');

		$data['dropzone'] = true;
		$data['dataTables'] = true;
		//get all task information
		$data['task_details'] = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
		if (empty($active)) {
			$data['active'] = 'details';
		} else {
			$data['active'] = $active;
		}
		$data['all_tabs'] = tasks_details_tabs($id);
		$data['module'] = 'tasks';
		$data['id'] = $id;
		$data['perm'] = '54';
		$data['redirect'] = 'tasks/details';
		$data['table'] = 'tbl_task';
		$data['page_title'] = !empty($data['task_details']->task_name) ? $data['task_details']->task_name : lang('task_details');
		$task_code = !empty($data['task_details']->task_code) ? $data['task_details']->task_code : ('#' . $id);
		$task_category = '-';
		if (!empty($data['task_details']->category_id)) {
			$category_info = $this->db->where('customer_group_id', $data['task_details']->category_id)->get('tbl_customer_group')->row();
			if (!empty($category_info->customer_group)) {
				$task_category = $category_info->customer_group;
			}
		}
		$task_related = lang('standalone_task');
		if (!empty($data['task_details']->project_id)) {
			$project_info = $this->db->select('project_name')->where('project_id', $data['task_details']->project_id)->get('tbl_project')->row();
			if (!empty($project_info->project_name)) {
				$task_related = $project_info->project_name;
			}
		} elseif (!empty($data['task_details']->opportunities_id)) {
			$opportunity_info = $this->db->select('opportunity_name')->where('opportunities_id', $data['task_details']->opportunities_id)->get('tbl_opportunities')->row();
			if (!empty($opportunity_info->opportunity_name)) {
				$task_related = $opportunity_info->opportunity_name;
			}
		} elseif (!empty($data['task_details']->leads_id)) {
			$lead_info = $this->db->select('lead_name')->where('leads_id', $data['task_details']->leads_id)->get('tbl_leads')->row();
			if (!empty($lead_info->lead_name)) {
				$task_related = $lead_info->lead_name;
			}
		} elseif (!empty($data['task_details']->bug_id)) {
			$bug_info = $this->db->select('bug_title')->where('bug_id', $data['task_details']->bug_id)->get('tbl_bug')->row();
			if (!empty($bug_info->bug_title)) {
				$task_related = $bug_info->bug_title;
			}
		}
		$task_due = !empty($data['task_details']->due_date) ? display_date($data['task_details']->due_date) : '-';
		$data['page_description'] = $task_related . ' . ' . $task_category . ' . ' . lang('due_date') . ': ' . $task_due;
		$status_tone = in_array($data['task_details']->task_status, array('completed'), true) ? 'success' : (in_array($data['task_details']->task_status, array('in_progress', 'waiting_for_someone'), true) ? 'primary' : (in_array($data['task_details']->task_status, array('deferred'), true) ? 'warning' : 'neutral'));
		$data['header_badge'] = array(
			'label' => $task_code,
			'tone' => $status_tone,
		);
		$can_edit = $this->tasks_model->can_action('tbl_task', 'edit', array('task_id' => $data['task_details']->task_id));
		$edited = can_action('54', 'edited');
		$deleted = can_action('54', 'deleted');
		$data['header_actions'] = array();
		$data['header_actions_html'] = '<div class="flex flex-wrap items-center justify-end gap-2">';
		$task_timer_active = (bool) timer_status('tasks', $data['task_details']->task_id, 'on');
		if ($task_timer_active) {
			$timer_url = base_url('admin/tasks/tasks_timer/off/' . $data['task_details']->task_id);
			$data['header_actions_html'] .= '<a href="' . $timer_url . '" data-act="ajax-request" data-action-url="' . $timer_url . '" data-reload-page="1" class="inline-flex items-center gap-2 rounded-xl border border-rose-200 bg-rose-50 px-4 py-2.5 text-sm font-semibold text-rose-700 shadow-sm transition-colors hover:bg-rose-100 dark:border-rose-800 dark:bg-rose-900/20 dark:text-rose-300 dark:hover:bg-rose-900/30"><i data-lucide="timer-reset" class="h-4 w-4"></i><span>' . html_escape(lang('stop_timer')) . '</span></a>';
		} else {
			$timer_url = base_url('admin/tasks/tasks_timer/on/' . $data['task_details']->task_id);
			$data['header_actions_html'] .= '<a href="' . $timer_url . '" data-act="ajax-request" data-action-url="' . $timer_url . '" data-reload-page="1" class="inline-flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-2.5 text-sm font-semibold text-emerald-700 shadow-sm transition-colors hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-900/20 dark:text-emerald-300 dark:hover:bg-emerald-900/30"><i data-lucide="play" class="h-4 w-4"></i><span>' . html_escape(lang('start_timer')) . '</span></a>';
		}
		if (!empty($can_edit) && !empty($edited)) {
			$data['header_actions_html'] .= '<a data-modal-url="' . base_url('admin/tasks/new_timesheet/' . $data['task_details']->task_id) . '" data-modal-title="' . html_escape(lang('timesheet')) . '" data-modal-size="md" href="' . base_url('admin/tasks/new_timesheet/' . $data['task_details']->task_id) . '" class="inline-flex items-center gap-2 rounded-xl border border-border bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"><i data-lucide="clock-3" class="h-4 w-4"></i><span>' . html_escape(lang('timesheet')) . '</span></a>';
			$data['header_actions_html'] .= '<a href="' . base_url('admin/tasks/create/' . $data['task_details']->task_id) . '" class="inline-flex items-center gap-2 rounded-xl border border-border bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"><i data-lucide="pencil" class="h-4 w-4"></i><span>' . html_escape(lang('edit')) . '</span></a>';
		}
		if (!empty($can_edit) && !empty($deleted)) {
			$data['header_actions_html'] .= '<div class="relative" data-dropdown><button type="button" data-dropdown-toggle="task-header-actions" class="inline-flex h-11 items-center gap-2 rounded-xl border border-border bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800" title="' . html_escape(lang('more_actions')) . '" aria-label="' . html_escape(lang('more_actions')) . '"><i data-lucide="more-horizontal" class="h-4 w-4"></i><span>' . html_escape(lang('more_actions')) . '</span></button><div id="task-header-actions" data-dropdown-menu class="hidden absolute right-0 mt-2 w-56 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-6rem)] overflow-y-auto rounded-xl border border-border bg-card p-2 shadow-lg z-30">';
			$data['header_actions_html'] .= '<a data-modal-url="' . base_url('admin/tasks/new_timesheet/' . $data['task_details']->task_id) . '" data-modal-title="' . html_escape(lang('timesheet')) . '" data-modal-size="md" href="' . base_url('admin/tasks/new_timesheet/' . $data['task_details']->task_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="clock-3" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('timesheet')) . '</span></a>';
			$data['header_actions_html'] .= '<a href="' . base_url('admin/tasks/create/' . $data['task_details']->task_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-foreground transition-colors hover:bg-muted"><i data-lucide="pencil" class="h-3.5 w-3.5 text-slate-500"></i><span>' . html_escape(lang('edit')) . '</span></a>';
			$data['header_actions_html'] .= '<div class="my-2 border-t border-border"></div>';
			$data['header_actions_html'] .= '<a href="' . base_url('admin/tasks/delete_task/' . $data['task_details']->task_id) . '" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-rose-600 transition-colors hover:bg-rose-50" onclick="return confirm(\'' . lang('delete_alert') . '\');"><i data-lucide="trash-2" class="h-3.5 w-3.5"></i><span>' . html_escape(lang('delete')) . '</span></a>';
			$data['header_actions_html'] .= '</div></div>';
		}
		$data['header_actions_html'] .= '</div>';
		$data['header_filters'] = array(
			array(
				'label' => lang('more_actions'),
				'icon' => 'ellipsis',
				'active' => true,
				'items' => array(
					array(
						'label' => lang('details'),
						'icon' => 'info',
						'href' => base_url('admin/tasks/details/' . $data['task_details']->task_id),
						'active' => $data['active'] === 'details',
					),
					array(
						'label' => lang('sub_tasks'),
						'icon' => 'list-checks',
						'href' => base_url('admin/tasks/details/' . $data['task_details']->task_id . '/sub_tasks'),
						'active' => $data['active'] === 'sub_tasks',
					),
					array(
						'label' => lang('notes'),
						'icon' => 'notebook-tabs',
						'href' => base_url('admin/tasks/details/' . $data['task_details']->task_id . '/notes'),
						'active' => $data['active'] === 'notes',
					),
					array(
						'label' => lang('timesheets'),
						'icon' => 'clock-3',
						'href' => base_url('admin/tasks/details/' . $data['task_details']->task_id . '/timesheets'),
						'active' => $data['active'] === 'timesheets',
					),
				),
			),
		);

		$data['subview'] = $this->load->view('admin/common/tab_view', $data, TRUE);
		$this->load->view('admin/_layout_main', $data);
	}

	public function new_timesheet($taskId = null, $id = null)
	{
		$data['title'] = lang('timesheet'); //Page title
		if (!empty($id)) {
			$edited = can_action('54', 'edited');
			if (!empty($edited)) {
				$data['task_timer_info'] = $this->db->where('tasks_timer_id', $id)->get('tbl_tasks_timer')->row();
			}
			if (empty($data['task_timer_info'])) {
				$type = "error";
				$message = lang("no_record_found");
				set_message($type, $message);
				redirect('admin/tasks/details/' . $taskId);
			}
		}
		$data['taskId'] = $taskId;

		$this->load->view('admin/tasks/details/create_timesheet', $data, FALSE);
	}

	public
	function update_tasks_timer($id = NULL, $action = NULL)
	{
		if (!empty($action)) {
			$t_data['task_id'] = $this->db->where(array('tasks_timer_id' => $id))->get('tbl_tasks_timer')->row()->task_id;
			$activity = 'activity_delete_tasks_timesheet';
			$msg = lang('delete_timesheet');
		} else {
			$activity = ('activity_update_task_timesheet');
			$msg = lang('timer_update');
		}
		if ($action != 'delete_task_timmer') {

			$t_data = $this->tasks_model->array_from_post(array('task_id', 'start_datetime', 'end_datetime', 'start_date', 'start_time', 'end_date', 'end_time'));
			$start_datetime = !empty($t_data['start_datetime'])
				? $t_data['start_datetime']
				: ((!empty($t_data['start_date']) ? $t_data['start_date'] : date('Y-m-d')) . ' ' . (!empty($t_data['start_time']) ? $t_data['start_time'] : date('H:i')));
			$end_datetime = !empty($t_data['end_datetime'])
				? $t_data['end_datetime']
				: ((!empty($t_data['end_date']) ? $t_data['end_date'] : date('Y-m-d')) . ' ' . (!empty($t_data['end_time']) ? $t_data['end_time'] : date('H:i')));

			$data['start_time'] = safe_strtotime($start_datetime);
			$data['end_time'] = safe_strtotime($end_datetime);
			$data['reason'] = $this->input->post('reason', TRUE);
			$data['edited_by'] = $this->session->userdata('user_id');

			$data['task_id'] = $t_data['task_id'];
			$data['user_id'] = $this->session->userdata('user_id');

			$this->tasks_model->_table_name = "tbl_tasks_timer"; //table name
			$this->tasks_model->_primary_key = "tasks_timer_id";
			if (!empty($id)) {
				$id = $this->tasks_model->save($data, $id);
			} else {
				$id = $this->tasks_model->save($data);
			}
		} else {
			$this->tasks_model->set_task_progress($t_data['task_id']);

			$task_info = $this->tasks_model->check_by(array('task_id' => $t_data['task_id']), 'tbl_task');
			$notifiedUsers = array();
			if (!empty($task_info->permission) && $task_info->permission != 'all') {
				$permissionUsers = json_decode($task_info->permission);
				foreach ($permissionUsers as $user => $v_permission) {
					array_push($notifiedUsers, $user);
				}
			} else {
				$notifiedUsers = $this->tasks_model->allowed_user_id('54');
			}
			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_update_timer',
							'link' => 'admin/tasks/details/' . $task_info->task_id . '/timesheets',
							'value' => lang('task') . ' ' . $task_info->task_name,
						));
					}
				}
			}
			show_notification($notifiedUsers);
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $id,
				'activity' => $activity,
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $task_info->task_id . '/timesheets',
				'value1' => $task_info->task_name,
			);
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			$this->tasks_model->_table_name = "tbl_tasks_timer"; //table name
			$this->tasks_model->_primary_key = "tasks_timer_id";
			$this->tasks_model->delete($id);
		}
		if ($action == 'delete_task_timmer') {
			echo json_encode(array("status" => 'success', 'message' => $msg, 'reload_page' => true));
			exit();
		} else {
			$type = "success";
			$message = $msg;
			set_message($type, $message);
			echo json_encode(array("status" => 'success', 'message' => $msg, 'reload_page' => true));
			exit();
			// redirect('admin/tasks/details/' . $t_data['task_id'] . '/timesheets');
		}
	}

	public function bulk_delete()
	{
		$selected_id = $this->input->post('ids', true);
		if (!empty($selected_id)) {
			foreach ($selected_id as $id) {
				$result[] = $this->delete_task($id, true);
			}
			echo json_encode($result);
			exit();
		} else {
			$type = "error";
			$message = lang('you_need_select_to_delete');
			echo json_encode(array("status" => $type, 'message' => $message));
			exit();
		}
	}

	public
	function delete_task($id, $bulk = null)
	{
		$can_delete = $this->tasks_model->can_action('tbl_task', 'delete', array('task_id' => $id));
		if (!empty($can_delete)) {
			$task_info = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
			$sub_task_info = $this->tasks_model->check_by(array('sub_task_id' => $id), 'tbl_task');
			if (empty($sub_task_info) || !empty($bulk)) {
				// save into activities
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'tasks',
					'module_field_id' => $task_info->task_id,
					'activity' => 'activity_task_deleted',
					'icon' => 'fa-tasks',
					'value1' => $task_info->task_name,
				);
				// Update into tbl_project
				$this->tasks_model->_table_name = "tbl_activities"; //table name
				$this->tasks_model->_primary_key = "activities_id";
				$this->tasks_model->save($activities);
				if (!empty($bulk)) {
					$all_sub_task = get_result('tbl_task', array('sub_task_id' => $id));
					if (!empty($all_sub_task)) {
						foreach ($all_sub_task as $v_sub_task) {
							// save into activities
							$sub_activities = array(
								'user' => $this->session->userdata('user_id'),
								'module' => 'tasks',
								'module_field_id' => $v_sub_task->task_id,
								'activity' => 'activity_task_deleted',
								'icon' => 'fa-tasks',
								'value1' => $v_sub_task->task_name,
							);
							// Update into tbl_project
							$this->tasks_model->_table_name = "tbl_activities"; //table name
							$this->tasks_model->_primary_key = "activities_id";
							$this->tasks_model->save($sub_activities);

							$this->tasks_model->_table_name = "tbl_attachments"; //table name
							$this->tasks_model->_order_by = "task_id";
							$files_info = $this->tasks_model->get_by(array('task_id' => $v_sub_task->task_id), FALSE);

							foreach ($files_info as $v_files) {
								$uploadFileinfo = $this->db->where('attachments_id', $v_files->attachments_id)->get('tbl_attachments_files')->result();
								if (!empty($uploadFileinfo)) {
									foreach ($uploadFileinfo as $Fileinfo) {
										remove_files($Fileinfo->file_name);
									}
								}
								$this->tasks_model->_table_name = "tbl_attachments_files"; //table name
								$this->tasks_model->delete_multiple(array('attachments_id' => $v_files->attachments_id));
							}
							//delete into table.
							$this->tasks_model->_table_name = "tbl_attachments"; // table name
							$this->tasks_model->delete_multiple(array('task_id' => $v_sub_task->task_id));

							// deleted comments with file
							$all_comments_info = $this->db->where(array('module_field_id' => $v_sub_task->task_id, 'module' => 'tasks'))->get('tbl_task_comment')->result();
							if (!empty($all_comments_info)) {
								foreach ($all_comments_info as $comments_info) {
									if (!empty($comments_info->comments_attachment)) {
										$attachment = json_decode($comments_info->comments_attachment);
										foreach ($attachment as $v_file) {
											remove_files($v_file->fileName);
										}
									}
								}
							}
							//delete data into table.
							$this->tasks_model->_table_name = "tbl_task_comment"; // table name
							$this->tasks_model->delete_multiple(array('module_field_id' => $v_sub_task->module_field_id));

							$pin_info = $this->tasks_model->check_by(array('module_name' => 'tasks', 'module_id' => $v_sub_task->task_id), 'tbl_pinaction');
							if (!empty($pin_info)) {
								$this->tasks_model->_table_name = 'tbl_pinaction';
								$this->tasks_model->delete_multiple(array('module_name' => 'tasks', 'module_id' => $v_sub_task->task_id));
							}
							//delete into table.
							$this->tasks_model->_table_name = "tbl_tasks_timer"; // table name
							$this->tasks_model->delete_multiple(array('task_id' => $v_sub_task->task_id));

							$this->tasks_model->_table_name = "tbl_task"; // table name
							$this->tasks_model->_primary_key = "task_id"; // $id
							$this->tasks_model->delete($v_sub_task->task_id);
						}
					}
				}

				$this->tasks_model->_table_name = "tbl_attachments"; //table name
				$this->tasks_model->_order_by = "module_field_id";
				$files_info = $this->tasks_model->get_by(array('module' => 'tasks', 'module_field_id' => $id));
				foreach ($files_info as $v_files) {
					$uploadFileinfo = $this->db->where('attachments_id', $v_files->attachments_id)->get('tbl_attachments_files')->result();
					if (!empty($uploadFileinfo)) {
						foreach ($uploadFileinfo as $Fileinfo) {
							remove_files($Fileinfo->file_name);
						}
					}
					$this->tasks_model->_table_name = "tbl_attachments_files"; //table name
					$this->tasks_model->delete_multiple(array('attachments_id' => $v_files->attachments_id));
				}
				//delete into table.
				$this->tasks_model->_table_name = "tbl_attachments"; // table name
				$this->tasks_model->delete_multiple(array('module' => 'tasks', 'module_field_id' => $id));

				// deleted comments with file
				$all_comments_info = get_result('tbl_task_comment', array('module' => 'tasks', 'module_field_id' => $id));
				if (!empty($all_comments_info)) {
					foreach ($all_comments_info as $comments_info) {
						if (!empty($comments_info->comments_attachment)) {
							$attachment = json_decode($comments_info->comments_attachment);
							foreach ($attachment as $v_file) {
								remove_files($v_file->fileName);
							}
						}
					}
				}
				//delete data into table.
				$this->tasks_model->_table_name = "tbl_task_comment"; // table name
				$this->tasks_model->delete_multiple(array('module' => 'tasks', 'module_field_id' => $id));

				$pin_info = $this->tasks_model->check_by(array('module_name' => 'tasks', 'module_id' => $id), 'tbl_pinaction');
				if (!empty($pin_info)) {
					$this->tasks_model->_table_name = 'tbl_pinaction';
					$this->tasks_model->delete_multiple(array('module_name' => 'tasks', 'module_id' => $id));
				}
				//delete into table.
				$this->tasks_model->_table_name = "tbl_tasks_timer"; // table name
				$this->tasks_model->delete_multiple(array('task_id' => $id));

				$this->tasks_model->_table_name = "tbl_task"; // table name
				$this->tasks_model->_primary_key = "task_id"; // $id
				$this->tasks_model->delete($id);

				$type = 'success';
				$message = lang('task_deleted');
			} else {
				$type = 'error';
				$message = lang('you_cant_delete', $task_info->task_name);
			}
		} else {
			$type = 'error';
			$message = lang('there_in_no_value');
		}
		if (!empty($bulk)) {
			return (array("status" => $type, 'message' => $message));
		}
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	public
	function tasks_timer($status, $task_id, $inline = NULL)
	{
		$task_start = $this->tasks_model->check_by(array('task_id' => $task_id), 'tbl_task');
		$notifiedUsers = array();
		if (!empty($task_start->permission) && $task_start->permission != 'all') {
			$permissionUsers = json_decode($task_start->permission);
			foreach ($permissionUsers as $user => $v_permission) {
				array_push($notifiedUsers, $user);
			}
		} else {
			$notifiedUsers = $this->tasks_model->allowed_user_id('54');
		}

		if ($status == 'off') {
			// check this user start time or this user is admin
			// if true then off time
			// else do not off time
			$check_user = $this->timer_started_by($task_id);
			if ($check_user == TRUE) {
				$tasks_timer_id = timer_status('tasks', $task_id, 'on', true);
				$active_timer = null;
				if (!empty($tasks_timer_id)) {
					$active_timer = $this->db->where('tasks_timer_id', $tasks_timer_id)->get('tbl_tasks_timer')->row();
				} elseif ((int) $this->session->userdata('user_type') === 1) {
					$active_timer = $this->db
						->where(array('task_id' => $task_id, 'timer_status' => 'on'))
						->order_by('tasks_timer_id', 'DESC')
						->get('tbl_tasks_timer')
						->row();
					if (!empty($active_timer)) {
						$tasks_timer_id = $active_timer->tasks_timer_id;
					}
				}
				if (empty($tasks_timer_id)) {
					if ($this->input->is_ajax_request()) {
						echo json_encode(array(
							'status' => 'error',
							'message' => lang('no_data_found'),
						));
						exit;
					}
					set_message('error', lang('no_data_found'));
					if (empty($_SERVER['HTTP_REFERER'])) {
						redirect('admin/tasks/all_task');
					} else {
						redirect($_SERVER['HTTP_REFERER']);
					}
				}
				$task_logged_time = $this->tasks_model->task_spent_time_by_id($task_id);
				$time_logged = (time() - $task_start->start_time) + $task_logged_time; //time already logged
				$data = array(
					'timer_status' => $status,
					'logged_time' => $time_logged,
					'start_time' => 0
				);
				// Update into tbl_task
				$this->tasks_model->_table_name = "tbl_task"; //table name
				$this->tasks_model->_primary_key = "task_id";
				$this->tasks_model->save($data, $task_id);

				// save into tbl_task_timer
				$t_data = array(
					'task_id' => $task_id,
					'user_id' => !empty($active_timer->user_id) ? $active_timer->user_id : $this->session->userdata('user_id'),
					'timer_status' => $status,
					'end_time' => time()
				);
				// insert into tbl_task_timer
				$this->tasks_model->_table_name = "tbl_tasks_timer"; //table name
				$this->tasks_model->_primary_key = "tasks_timer_id";
				$this->tasks_model->save($t_data, $tasks_timer_id);

				// save into activities
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'tasks',
					'module_field_id' => $task_id,
					'activity' => ('activity_tasks_timer_off'),
					'icon' => 'fa-tasks',
					'link' => 'admin/tasks/details/' . $task_id . '/timesheets',
					'value1' => $task_start->task_name,
				);
				// Update into tbl_project
				$this->tasks_model->_table_name = "tbl_activities"; //table name
				$this->tasks_model->_primary_key = "activities_id";
				$this->tasks_model->save($activities);
				if (!empty($notifiedUsers)) {
					foreach ($notifiedUsers as $users) {
						if ($users != $this->session->userdata('user_id')) {
							add_notification(array(
								'to_user_id' => $users,
								'from_user_id' => true,
								'description' => 'not_timer_stop',
								'link' => 'admin/tasks/details/' . $task_start->task_id . '/timesheets',
								'value' => lang('task') . ' ' . $task_start->task_name,
							));
						}
					}
					show_notification($notifiedUsers);
				}
				$this->tasks_model->set_task_progress($task_id);
			}
		} else {
			$data = array(
				'timer_status' => $status,
				'timer_started_by' => $this->session->userdata('user_id'),
				'start_time' => time()
			);

			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'tasks',
				'module_field_id' => $task_id,
				'activity' => 'activity_tasks_timer_on',
				'icon' => 'fa-tasks',
				'link' => 'admin/tasks/details/' . $task_id . '/timesheets',
				'value1' => $task_start->task_name,
			);

			// Update into tbl_project
			$this->tasks_model->_table_name = "tbl_activities"; //table name
			$this->tasks_model->_primary_key = "activities_id";
			$this->tasks_model->save($activities);

			// Update into tbl_task
			$this->tasks_model->_table_name = "tbl_task"; //table name
			$this->tasks_model->_primary_key = "task_id";
			$this->tasks_model->save($data, $task_id);

			// save into tbl_task_timer
			$t_data = array(
				'task_id' => $task_id,
				'timer_status' => $status,
				'user_id' => $this->session->userdata('user_id'),
				'start_time' => time()
			);

			// insert into tbl_task_timer
			$this->tasks_model->_table_name = "tbl_tasks_timer"; //table name
			$this->tasks_model->_primary_key = "tasks_timer_id";
			$this->tasks_model->save($t_data);

			if (!empty($notifiedUsers)) {
				foreach ($notifiedUsers as $users) {
					if ($users != $this->session->userdata('user_id')) {
						add_notification(array(
							'to_user_id' => $users,
							'from_user_id' => true,
							'description' => 'not_timer_start',
							'link' => 'admin/tasks/details/' . $task_start->task_id . '/timesheets',
							'value' => lang('task') . ' ' . $task_start->task_name,
						));
					}
				}
				show_notification($notifiedUsers);
			}
		}
		if (!empty($inline)) {
			return true;
		} elseif ($this->input->is_ajax_request()) {
			$message = $this->task_timer_message($status);
			echo json_encode(array(
				'status' => 'success',
				'message' => $message,
				'reload_page' => true,
			));
			exit;
		} else {
			// messages for user
			$type = "success";
			$message = $this->task_timer_message($status);
			set_message($type, $message);
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/tasks/all_task');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	private function task_timer_message($status)
	{
		$key = 'task_timer_' . $status;
		$message = lang($key);
		if (!empty($message) && $message !== $key) {
			return $message;
		}

		return $status === 'off' ? 'Timer stopped successfully.' : 'Timer started successfully.';
	}

	public
	function timer_started_by($task_id)
	{
		$user_id = $this->session->userdata('user_id');
		//        $user_info = $this->tasks_model->check_by(array('user_id' => $user_id), 'tbl_users');
		$timer_started_info = $this->tasks_model->check_by(array('task_id' => $task_id), 'tbl_task');
		if ($timer_started_info->timer_started_by == $user_id) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public
	function claer_activities($module, $id)
	{
		//save data into table.
		$where = array('module' => $module, 'module_field_id' => $id);
		$this->tasks_model->_table_name = "tbl_activities"; // table name
		$this->tasks_model->delete_multiple($where);
		if (empty($_SERVER['HTTP_REFERER'])) {
			redirect('admin/dashboard');
		} else {
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public
	function export_report($id)
	{
		$data['title'] = lang('export_report');
		$this->tasks_model->_table_name = "tbl_attachments"; //table name
		$this->tasks_model->_order_by = "module_field_id";
		$data['files_info'] = $this->tasks_model->get_by(array('module' => 'tasks', 'module_field_id' => $id), FALSE);

		foreach ($data['files_info'] as $key => $v_files) {
			$this->tasks_model->_table_name = "tbl_attachments_files"; //table name
			$this->tasks_model->_order_by = "attachments_id";
			$data['project_files_info'][$key] = $this->tasks_model->get_by(array('attachments_id' => $v_files->attachments_id), FALSE);
		}
		$data['task_details'] = $this->tasks_model->check_by(array('task_id' => $id), 'tbl_task');
		$viewfile = $this->load->view('admin/tasks/export_report', $data, TRUE);
		$this->load->helper('dompdf');
		pdf_create($viewfile, slug_it($data['task_details']->task_name . '-' . lang('details')), 1, 1);
		//        $this->load->view('admin/_layout_main', $data);
	}

	public
	function change_tasks_status($task_status = NULL)
	{
		$task_id = $this->input->post('task_id', true);
		foreach ($task_id as $key => $id) {
			$data['task_status'] = $task_status;
			if ($data['task_status'] == 1) {
				$data['task_status'] = 'not_started';
			} elseif ($data['task_status'] == 2) {
				$data['task_status'] = 'in_progress';
			} elseif ($data['task_status'] == 3) {
				$data['task_status'] = 'completed';
			} elseif ($data['task_status'] == 4) {
				$data['task_status'] = 'deferred';
			} else {
				$data['task_status'] = 'waiting_for_someone';
			}
			$data['index_no'] = $key + 1;
			//save data into table.
			$this->tasks_model->_table_name = "tbl_task"; // table name
			$this->tasks_model->_primary_key = "task_id"; // $id
			$id = $this->tasks_model->save($data, $id);
		}
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'tasks',
			'module_field_id' => $id,
			'activity' => 'activity_update_task',
			'icon' => 'fa-tasks',
			'link' => 'admin/tasks/details/' . $id,
			'value1' => $data['task_status'],
		);
		// Update into tbl_project
		$this->tasks_model->_table_name = "tbl_activities"; //table name
		$this->tasks_model->_primary_key = "activities_id";
		$this->tasks_model->save($activities);

		$task_start = $this->tasks_model->check_by(array('task_id' => $task_id), 'tbl_task');
		$notifiedUsers = array();
		if (!empty($task_start->permission) && $task_start->permission != 'all') {
			$permissionUsers = json_decode($task_start->permission);
			foreach ($permissionUsers as $user => $v_permission) {
				array_push($notifiedUsers, $user);
			}
		} else {
			$notifiedUsers = $this->tasks_model->allowed_user_id('54');
		}
		if (!empty($notifiedUsers)) {
			foreach ($notifiedUsers as $users) {
				if ($users != $this->session->userdata('user_id')) {
					add_notification(array(
						'to_user_id' => $users,
						'from_user_id' => true,
						'description' => 'not_changed_status',
						'link' => 'admin/tasks/details/' . $task_start->task_id,
						'value' => lang('task') . ' ' . $task_start->task_name,
					));
				}
			}
			show_notification($notifiedUsers);
		}

		$type = "success";
		$message = lang('update_task');
		echo json_encode(array("status" => $type, "message" => $message));
		exit();
	}

	public function load_status_tasks($status_id = null)
	{
		$status_map = array(
			'1' => 'not_started',
			'2' => 'in_progress',
			'3' => 'completed',
			'4' => 'deferred',
			'5' => 'waiting_for_someone',
		);

		$status_id = (string) $status_id;
		if (!isset($status_map[$status_id])) {
			echo json_encode(array('items' => array(), 'total' => 0));
			exit();
		}

		$limit = (int) $this->input->post('limit', true);
		$offset = (int) $this->input->post('offset', true);
		if ($limit <= 0 || $limit > 50) {
			$limit = 6;
		}
		if ($offset < 0) {
			$offset = 0;
		}

		$status_key = $status_map[$status_id];
		$tasks_query = $this->db
			->select('tbl_task.task_id, tbl_task.task_name, tbl_task.task_status, tbl_task.task_progress, tbl_task.task_start_date, tbl_task.due_date')
			->select('COALESCE(task_comments.comment_count, 0) AS comment_count', false)
			->select('COALESCE(task_attachments.attachment_count, 0) AS attachment_count', false)
			->from('tbl_task')
			->join('(SELECT module_field_id, COUNT(*) AS comment_count FROM tbl_task_comment WHERE module="tasks" GROUP BY module_field_id) AS task_comments', 'task_comments.module_field_id = tbl_task.task_id', 'left')
			->join('(SELECT module_field_id, COUNT(*) AS attachment_count FROM tbl_attachments WHERE module="tasks" GROUP BY module_field_id) AS task_attachments', 'task_attachments.module_field_id = tbl_task.task_id', 'left')
			->where('tbl_task.task_status', $status_key)
			->order_by('tbl_task.index_no', 'asc')
			->order_by('tbl_task.task_id', 'desc')
			->limit($limit, $offset);

		if (!empty($this->tasks_model)) {
			$this->tasks_model->staff_query('tbl_task');
		}

		$tasks = $tasks_query->get()->result();
		$items = array();
		if (!empty($tasks)) {
			foreach ($tasks as $task) {
				$progress = (int) $task->task_progress;
				if ($task->task_status === 'completed') {
					$progress = 100;
				}
				if ($progress > 100) {
					$progress = 100;
				}

				$subtitle_parts = array();
				if (!empty($task->task_start_date)) {
					$subtitle_parts[] = display_date($task->task_start_date);
				}
				if (!empty($task->due_date)) {
					$subtitle_parts[] = display_date($task->due_date);
				}

				$items[] = array(
					'id' => (int) $task->task_id,
					'title' => $task->task_name,
					'subtitle' => !empty($subtitle_parts) ? implode(' â€¢ ', $subtitle_parts) : '',
					'progress' => $progress,
					'status' => $status_id,
					'status_label' => lang($status_key),
					'link' => base_url('admin/tasks/details/' . $task->task_id),
					'comments' => (int) $task->comment_count,
					'attachments' => (int) $task->attachment_count,
				);
			}
		}

		$count_query = $this->db
			->select('COUNT(*) AS total', false)
			->from('tbl_task')
			->where('tbl_task.task_status', $status_key);

		if (!empty($this->tasks_model)) {
			$this->tasks_model->staff_query('tbl_task');
		}

		$total_row = $count_query->get()->row();
		$total = !empty($total_row) ? (int) $total_row->total : 0;

		echo json_encode(array('items' => $items, 'total' => $total));
		exit();
	}

	public
	function add_checklist_item()
	{
		//        if ($this->input->is_ajax_request()) {
		//            if ($this->input->post()) {
		$task_id = $this->input->post('task_id', true);
		$data['description'] = $this->input->post('description', true);
		$data['module'] = 'tasks';
		$data['module_id'] = $task_id;
		$data['create_datetime'] = date('Y-m-d H:i:s');
		$data['added_from'] = my_id();
		$data['list_order'] = 0;

		// Update into tbl_checklists
		$this->tasks_model->_table_name = "tbl_checklists"; //table name
		$this->tasks_model->_primary_key = "checklist_id";
		$id = $this->tasks_model->save($data);
		if ($id) {
			$result = true;
		} else {
			$result = false;
		}
		echo json_encode([
			'success' => $result,
		]);
		exit();
		//            }
		//        }
	}

	public
	function init_checklist_items()
	{
		if ($this->input->is_ajax_request()) {
			if ($this->input->post()) {
				$post_data = $this->input->post();
				$data['task_id'] = $post_data['task_id'];
				$data['checklists'] = get_order_by('tbl_checklists', array('module' => 'tasks', 'module_id' => $post_data['task_id']), true);
				$this->load->view('admin/tasks/checklist_items_template', $data);
			}
		}
	}

	public
	function update_checklist_order()
	{
		if ($this->input->is_ajax_request()) {
			if ($this->input->post()) {
				$data = $this->input->post();
				foreach ($data['order'] as $order) {
					update('tbl_checklists', array('checklist_id' => $order[0]), array('list_order' => $order[1]));
				}
			}
		}
	}

	public
	function delete_checklist_item($id)
	{
		$checklists = get_row('tbl_checklists', array('checklist_id' => $id));
		$deleted = can_action('54', 'deleted');
		if (!empty($checklists)) {
			$can_delete = $this->tasks_model->can_action('tbl_task', 'delete', array('task_id' => $checklists->module_id));
			if ((!empty($can_delete) && !empty($deleted)) || $checklists->added_from == my_id()) {
				if ($this->input->is_ajax_request()) {
					$this->db->where('checklist_id', $id);
					$this->db->delete('tbl_checklists');
					$result = false;
					if ($this->db->affected_rows() > 0) {
						$result = true;
					}
					echo json_encode([
						'success' => $result,
					]);
					exit();
				}
			}
		}
	}

	public
	function update_checklist_item()
	{
		if ($this->input->is_ajax_request()) {
			if ($this->input->post()) {
				$desc = $this->input->post('description', true);
				$desc = trim($desc);

				$this->updated_checklist_item($this->input->post('listid', true), $desc);
				echo json_encode(['can_be_template' => (total_rows('tbl_checklists', ['description' => $desc]) == 0)]);
				exit();
			}
		}
	}

	public
	function updated_checklist_item($id, $description)
	{
		$description = strip_html_tags($description, true);
		if ($description === '') {
			$this->db->where('checklist_id', $id);
			$this->db->delete('tbl_checklists');
		} else {
			$this->db->where('checklist_id', $id);
			$this->db->update('tbl_checklists', [
				'description' => nl2br($description),
			]);
		}
	}
}
