<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Common extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('common_model');
		$this->load->model('admin_model');
	}

	private function normalize_leave_request_date($date)
	{
		$date = trim(rawurldecode((string) $date));
		if ($date === '' || strtolower($date) === 'null') {
			return '';
		}

		$formats = array('Y-m-d', 'd/m/Y', 'd-m-Y', 'm/d/Y', 'm-d-Y');
		foreach ($formats as $format) {
			$parsed = DateTime::createFromFormat($format, $date);
			$errors = DateTime::getLastErrors();
			if ($parsed && empty($errors['warning_count']) && empty($errors['error_count'])) {
				return $parsed->format('Y-m-d');
			}
		}

		$timestamp = safe_strtotime($date);
		return !empty($timestamp) ? date('Y-m-d', $timestamp) : '';
	}

	public function fetch_address_info_gmaps()
	{
		include_once(APPPATH . 'third_party/JD_Geocoder_Request.php');
		$data = $this->input->post();
		$address = '';
		$address .= $data['address'];
		if (!empty($data['city'])) {
			$address .= ', ' . $data['city'];
		}
		if (!empty($data['country'])) {
			$address .= ', ' . $data['country'];
		}
		$georequest = new JD_Geocoder_Request();
		$georequest->forwardSearch($address);
		echo json_encode($georequest);
		exit();
	}

	public function get_project_by_client_id($client_id)
	{
		$HTML = null;
		$client_project_info = $this->db->where(array('client_id' => $client_id))->get('tbl_project')->result();
		if (!empty($client_project_info)) {
			$HTML .= "<option value='" . 0 . "'>" . lang('none') . "</option>";
			foreach ($client_project_info as $v_client_project) {
				$HTML .= "<option value='" . $v_client_project->project_id . "'>" . $v_client_project->project_name . "</option>";
			}
		}
		echo $HTML;
		exit();
	}

	public function get_milestone_by_project_id($project_id)
	{
		$milestone_info = $this->db->where(array('project_id' => $project_id))->get('tbl_milestones')->result();
		$HTML = null;
		if (!empty($milestone_info)) {
			$HTML .= "<option value='" . 0 . "'>" . lang('none') . "</option>";
			foreach ($milestone_info as $v_milestone) {
				$HTML .= "<option value='" . $v_milestone->milestones_id . "'>" . $v_milestone->milestone_name . "</option>";
			}
		}
		echo $HTML;
		exit();
	}

	public function project_lookup()
	{
		$this->run_lookup('project');
	}

	public function projects_lookup()
	{
		$this->run_lookup('project');
	}

	public function activity_page()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}

		$module = trim((string) $this->input->get('module', true));
		$id = (int) $this->input->get('id', true);
		$offset = (int) $this->input->get('offset', true);
		$limit = (int) $this->input->get('limit', true);
		if ($limit <= 0) {
			$limit = (int) config_item('activity_pagination_limit');
		}
		if ($limit <= 0) {
			$limit = 20;
		}
		if ($limit > 100) {
			$limit = 100;
		}
		if ($offset < 0) {
			$offset = 0;
		}

		if ($module === '' || $id <= 0) {
			header('Content-Type: application/json');
			echo json_encode(array('html' => '', 'next_offset' => $offset, 'has_more' => false));
			exit();
		}

		$style = config_item('activity_style');
		if (empty($style)) {
			$style = 'timeline';
		}
		$style_map = array('1' => 'timeline', '2' => 'feed', '3' => 'cards', '4' => 'stacked', '5' => 'compact');
		if (is_numeric($style)) {
			$style = isset($style_map[$style]) ? $style_map[$style] : 'timeline';
		}
		if (!in_array($style, array('timeline', 'feed', 'cards', 'stacked', 'compact'), true)) {
			$style = 'timeline';
		}

		$activities = $this->common_model->get_activities_info($module, $id, $limit, $offset);
		$total = $this->common_model->count_activities_info($module, $id);
		$html = $this->load->view('admin/common/activites', array(
			'module' => $module,
			'id' => $id,
			'activity_style' => $style,
			'activities_info' => $activities,
			'activity_items_only' => true,
		), true);
		$next_offset = $offset + count($activities);

		header('Content-Type: application/json');
		echo json_encode(array(
			'html' => $html,
			'next_offset' => $next_offset,
			'has_more' => $next_offset < $total,
		));
		exit();
	}

	public function client_lookup()
	{
		$this->run_lookup('client');
	}

	public function clients_lookup()
	{
		$this->run_lookup('client');
	}

	public function task_lookup()
	{
		$this->run_lookup('task');
	}

	public function tasks_lookup()
	{
		$this->run_lookup('task');
	}
	public function invoice_lookup()
	{
		$this->run_lookup('invoice');
	}
	public function estimate_lookup()
	{
		$this->run_lookup('estimate');
	}
	public function estimates_lookup()
	{
		$this->run_lookup('estimate');
	}
	public function account_lookup()
	{
		$this->run_lookup('account');
	}

	public function chart_of_account_lookup()
	{
		$this->run_lookup('chart_of_account');
	}

	public function account_sub_type_lookup()
	{
		$this->run_lookup('account_sub_type');
	}

	public function chart_of_accounts_lookup()
	{
		$this->run_lookup('chart_of_account');
	}

	public function supplier_lookup()
	{
		$this->run_lookup('supplier');
	}

	public function suppliers_lookup()
	{
		$this->run_lookup('supplier');
	}

	public function tax_rate_lookup()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}

		$query = trim((string) $this->input->get('q', true));
		$limit = (int) $this->input->get('limit', true);
		if ($limit <= 0) {
			$limit = 20;
		}
		if ($limit > 50) {
			$limit = 50;
		}

		$this->db->select('tax_rates_id, tax_rate_name, tax_rate_percent');
		$this->db->from('tbl_tax_rates');
		if ($query !== '') {
			$this->db->group_start();
			$this->db->like('tax_rate_name', $query);
			$this->db->or_like('tax_rate_percent', $query);
			$this->db->group_end();
			$this->db->order_by('tax_rate_name', 'ASC');
		} else {
			$this->db->order_by('tax_rates_id', 'DESC');
		}
		$rows = $this->db->limit($limit)->get()->result();

		$results = array();
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$results[] = array(
					'id' => (string) $row->tax_rates_id,
					'text' => $row->tax_rate_name . ' (' . $row->tax_rate_percent . '%)',
				);
			}
		}

		echo json_encode(array('results' => $results));
		exit();
	}

	public function tax_rates_lookup()
	{
		$this->tax_rate_lookup();
	}

	public function client_menu_lookup()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}

		$query = trim((string) $this->input->get('q', true));
		$limit = (int) $this->input->get('limit', true);
		if ($limit <= 0) {
			$limit = 20;
		}
		if ($limit > 50) {
			$limit = 50;
		}

		$this->db->select('menu_id, label');
		$this->db->from('tbl_client_menu');
		$this->db->where('parent', 0);
		$this->db->where('label !=', 'dashboard');
		if ($query !== '') {
			$this->db->like('label', $query);
			$this->db->order_by('label', 'ASC');
		} else {
			$this->db->order_by('sort', 'ASC');
		}
		$rows = $this->db->limit($limit)->get()->result();

		$results = array();
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$results[] = array(
					'id' => (string) $row->menu_id,
					'text' => lang($row->label),
				);
			}
		}

		echo json_encode(array('results' => $results));
		exit();
	}

	public function client_menus_lookup()
	{
		$this->client_menu_lookup();
	}

	public function form_lookup()
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}

		$query = trim((string) $this->input->get('q', true));
		$limit = (int) $this->input->get('limit', true);
		if ($limit <= 0) {
			$limit = 20;
		}
		if ($limit > 50) {
			$limit = 50;
		}

		$this->db->select('form_id, form_name');
		$this->db->from('tbl_form');
		if ($query !== '') {
			$this->db->like('form_name', $query);
			$this->db->order_by('form_name', 'ASC');
		} else {
			$this->db->order_by('form_id', 'DESC');
		}
		$rows = $this->db->limit($limit)->get()->result();

		$results = array();
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$results[] = array(
					'id' => (string) $row->form_id,
					'text' => lang($row->form_name),
				);
			}
		}

		echo json_encode(array('results' => $results));
		exit();
	}

	public function forms_lookup()
	{
		$this->form_lookup();
	}

	// award_rule
	public function award_rule_lookup()
	{
		$this->run_lookup('award_rule');
	}
	public function income_category_lookup()
	{
		$this->run_lookup('income_category');
	}

	public function expense_category_lookup()
	{
		$this->run_lookup('expense_category');
	}

	public function payment_method_lookup()
	{
		$this->run_lookup('payment_method');
	}
	public function manufacturer_lookup()
	{
		$this->run_lookup('manufacturer');
	}
	public function manufacturers_lookup()
	{
		$this->run_lookup('manufacturer');
	}
	public function item_group_lookup()
	{
		$this->run_lookup('item_group');
	}
	public function item_groups_lookup()
	{
		$this->run_lookup('item_group');
	}
	public function warehouse_lookup()
	{
		$this->run_lookup('warehouse');
	}
	public function warehouses_lookup()
	{
		$this->run_lookup('warehouse');
	}

	public function milestone_lookup()
	{
		$this->run_lookup('milestone');
	}

	public function milestones_lookup()
	{
		$this->run_lookup('milestone');
	}

	public function department_lookup()
	{
		$this->run_lookup('department');
	}

	public function departments_lookup()
	{
		$this->run_lookup('department');
	}

	public function goal_type_lookup()
	{
		$this->run_lookup('goal_type');
	}

	public function goal_types_lookup()
	{
		$this->run_lookup('goal_type');
	}

	public function goal_lookup()
	{
		$this->run_lookup('goal_tracking');
	}

	public function goals_lookup()
	{
		$this->run_lookup('goal_tracking');
	}

	public function expense_lookup()
	{
		$this->run_lookup('expense');
	}

	public function expenses_lookup()
	{
		$this->run_lookup('expense');
	}

	public function category_lookup()
	{
		$options = array();
		// get type from request
		$category_type = $this->input->get('category_type', true);;
		if (empty($category_type)) {
			$category_type = $this->input->get('type', true);
		}
		if (!empty($category_type)) {
			$options['category_type'] = $category_type;
		}
		$this->run_lookup('category', $options);
	}

	public function warning_type_lookup()
	{
		$this->run_lookup('category', array('category_type' => 'warning'));
	}

	public function warning_types_lookup()
	{
		$this->warning_type_lookup();
	}

	public function termination_type_lookup()
	{
		$this->run_lookup('category', array('category_type' => 'termination'));
	}

	public function termination_types_lookup()
	{
		$this->termination_type_lookup();
	}

	public function project_categories_lookup()
	{
		$this->run_lookup('project_category');
	}

	public function bug_lookup()
	{
		$this->run_lookup('bug');
	}

	public function bugs_lookup()
	{
		$this->run_lookup('bug');
	}

	public function opportunity_lookup()
	{
		$this->run_lookup('opportunity');
	}

	public function opportunities_lookup()
	{
		$this->run_lookup('opportunity');
	}

	public function lead_lookup()
	{
		$this->run_lookup('lead');
	}

	public function leads_lookup()
	{
		$this->run_lookup('lead');
	}

	// staff_lookup
	public function staff_lookup()
	{
		$this->run_lookup('staff');
	}
	//lead_status_lookup
	public function lead_status_lookup()
	{
		$this->run_lookup('lead_status');
	}

	// lead_source_lookup
	public function lead_source_lookup()
	{
		$this->run_lookup('lead_source');
	}

	public function complaint_type_lookup()
	{
		$this->run_lookup('complaint_type');
	}

	public function complaint_types_lookup()
	{
		$this->run_lookup('complaint_type');
	}

	public function user_lookup()
	{
		$this->run_lookup('user');
	}

	public function users_lookup()
	{
		$this->run_lookup('user');
	}

	// warning_by_lookup
	public function warning_by_lookup()
	{
		$this->run_lookup('staff');
	}
	//state_reason_lookup
	public function state_reason_lookup()
	{
		$this->run_lookup('state_reason');
	}

	private function run_lookup($type, $options = array())
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}

		$lookup_map = array(
			'project' => array(
				'table' => 'tbl_project',
				'id' => 'project_id',
				'text' => 'project_name',
				'order' => 'project_id',
				'filters' => array('client_id' => 'client_id'),
			),
			'client' => array(
				'table' => 'tbl_client',
				'id' => 'client_id',
				'text' => 'name',
				'order' => 'client_id',
			),
			'task' => array(
				'table' => 'tbl_task',
				'id' => 'task_id',
				'text' => 'task_name',
				'order' => 'task_id',
				'filters' => array('project_id' => 'project_id', 'milestones_id' => 'milestones_id'),
			),
			'milestone' => array(
				'table' => 'tbl_milestones',
				'id' => 'milestones_id',
				'text' => 'milestone_name',
				'order' => 'milestones_id',
				'filters' => array('project_id' => 'project_id'),
			),
			'department' => array(
				'table' => 'tbl_departments',
				'id' => 'departments_id',
				'text' => 'deptname',
				'order' => 'departments_id',
			),
			'goal_type' => array(
				'table' => 'tbl_goal_type',
				'id' => 'goal_type_id',
				'text' => 'type_name',
				'order' => 'goal_type_id',
			),
			'goal_tracking' => array(
				'table' => 'tbl_goal_tracking',
				'id' => 'goal_tracking_id',
				'text' => 'subject',
				'order' => 'goal_tracking_id',
			),
			'category' => array(
				'table' => 'tbl_customer_group',
				'id' => 'customer_group_id',
				'text' => 'customer_group',
				'order' => 'customer_group_id',
				'where' => array('type' => $options['category_type'] ?? 'project'),
			),
			'bug' => array(
				'table' => 'tbl_bug',
				'id' => 'bug_id',
				'text' => 'bug_title',
				'order' => 'bug_id',
				'filters' => array('project_id' => 'project_id'),
			),
			'opportunity' => array(
				'table' => 'tbl_opportunities',
				'id' => 'opportunities_id',
				'text' => 'opportunity_name',
				'order' => 'opportunities_id',
				'filters' => array('client_id' => 'client_id', 'project_id' => 'project_id'),
			),
			'lead' => array(
				'table' => 'tbl_leads',
				'id' => 'leads_id',
				'text' => 'lead_name',
				'order' => 'leads_id',
			),
			'staff' => array(
				'table' => 'tbl_users',
				'id' => 'tbl_users.user_id',
				'text' => 'fullname',
				'order' => 'tbl_users.user_id',
				'where' => array('role_id !=' => 2), // exclude clients
				'joins' => array(
					array(
						'table' => 'tbl_account_details',
						'condition' => 'tbl_account_details.user_id = tbl_users.user_id',
						'type' => 'left',
					),
				),
			),
			'user' => array(
				'table' => 'tbl_users',
				'id' => 'tbl_users.user_id',
				'text' => 'fullname',
				'order' => 'tbl_users.user_id',
				'joins' => array(
					array(
						'table' => 'tbl_account_details',
						'condition' => 'tbl_account_details.user_id = tbl_users.user_id',
						'type' => 'left',
					),
				),
			),
			'invoice' => array(
				'table' => 'tbl_invoices',
				'id' => 'invoices_id',
				'text' => 'reference_no',
				'order' => 'invoices_id',
			),
			'estimate' => array(
				'table' => 'tbl_estimates',
				'id' => 'estimates_id',
				'text' => 'reference_no',
				'order' => 'estimates_id',
			),
			'account' => array(
				'table' => 'tbl_accounts',
				'id' => 'account_id',
				'text' => 'account_name',
				'order' => 'account_id',
			),
			'expense' => array(
				'table' => 'tbl_transactions',
				'id' => 'transactions_id',
				'text' => 'name',
				'order' => 'transactions_id',
			),
			'chart_of_account' => array(
				'table' => 'tbl_chart_of_accounts',
				'id' => 'chart_of_account_id',
				'text' => 'name',
				'order' => 'chart_of_account_id',
				'where' => array('status' => 1),
			),
			'supplier' => array(
				'table' => 'tbl_suppliers',
				'id' => 'supplier_id',
				'text' => 'name',
				'order' => 'supplier_id',
			),
			'income_category' => array(
				'table' => 'tbl_income_category',
				'id' => 'income_category_id',
				'text' => 'income_category',
				'order' => 'income_category_id',
			),
			'expense_category' => array(
				'table' => 'tbl_expense_category',
				'id' => 'expense_category_id',
				'text' => 'expense_category',
				'order' => 'expense_category_id',
			),
			'payment_method' => array(
				'table' => 'tbl_payment_methods',
				'id' => 'payment_methods_id',
				'text' => 'method_name',
				'order' => 'payment_methods_id',
			),
			'manufacturer' => array(
				'table' => 'tbl_manufacturer',
				'id' => 'manufacturer_id',
				'text' => 'manufacturer',
				'order' => 'manufacturer_id',
			),
			'item_group' => array(
				'table' => 'tbl_customer_group',
				'id' => 'customer_group_id',
				'text' => 'customer_group',
				'order' => 'customer_group_id',
				'where' => array('type' => 'items'),
			),
			'warehouse' => array(
				'table' => 'tbl_warehouse',
				'id' => 'warehouse_id',
				'text' => 'warehouse_name',
				'order' => 'warehouse_id',
				'where' => array('status' => 'published'),
			),
			'lead_status' => array(
				'table' => 'tbl_lead_status',
				'id' => 'lead_status_id',
				'text' => 'lead_status',
				'order' => 'lead_status_id',
			),
			'lead_source' => array(
				'table' => 'tbl_lead_source',
				'id' => 'lead_source_id',
				'text' => 'lead_source',
				'order' => 'lead_source_id',
			),
			'complaint_type' => array(
				'table' => 'tbl_complaints_types',
				'id' => 'id',
				'text' => 'name',
				'order' => 'id',
			),
			'state_reason' => array(
				'table' => 'tbl_opportunities_state_reason',
				'id' => 'opportunities_state_reason_id',
				'text' => 'opportunities_state_reason',
				'order' => 'opportunities_state_reason_id',
			),
			'award_rule' => array(
				'table' => 'tbl_award_rule',
				'id' => 'award_rule_id',
				'text' => 'rule_name',
				'order' => 'award_rule_id',
			),
			'account_sub_type' => array(
				'table' => 'tbl_account_sub_type',
				'id' => 'account_sub_type_id',
				'text' => 'account_sub_type',
				'order' => 'account_sub_type_id',
			),
			'project_category' => array(
				'table' => 'tbl_project_category',
				'id' => 'project_category_id',
				'text' => 'category_name',
				'order' => 'project_category_id',
			),
		);

		if (empty($lookup_map[$type])) {
			echo json_encode(array('results' => array()));
			exit();
		}

		$config = $lookup_map[$type];
		$query = trim((string) $this->input->get('q', true));
		$limit = (int) $this->input->get('limit', true);
		if ($limit <= 0) {
			$limit = 20;
		}
		if ($limit > 50) {
			$limit = 50;
		}

		$id_field = $config['id'];
		$text_field = $config['text'];
		$this->db->select($id_field . ' AS id, ' . $text_field . ' AS text', false);
		$this->db->from($config['table']);

		if (!empty($config['where']) && is_array($config['where'])) {
			$this->db->where($config['where']);
		}
		if (!empty($config['joins']) && is_array($config['joins'])) {
			foreach ($config['joins'] as $join) {
				$this->db->join($join['table'], $join['condition'], $join['type'] ?? 'inner');
			}
		}

		if (!empty($config['filters']) && is_array($config['filters'])) {
			foreach ($config['filters'] as $param => $column) {
				$value = $this->input->get($param, true);
				if ($value !== null && $value !== '') {
					$this->db->where($column, $value);
				}
			}
		}

		if ($query !== '') {
			$this->db->group_start();
			$this->db->like($text_field, $query);
			if (ctype_digit($query)) {
				$this->db->or_where($id_field, (int) $query);
			}
			$this->db->group_end();
		}

		$this->admin_model->staff_query($config['table']);
		if ($query !== '') {
			$this->db->order_by($text_field, 'asc');
		} else {
			$this->db->order_by($config['order'], 'desc');
		}
		$this->db->limit($limit);
		$rows = $this->db->get()->result();

		$results = array();
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$results[] = array(
					'id' => $row->id,
					'text' => $row->text,
				);
			}
		}

		echo json_encode(array('results' => $results));
		exit();
	}

	public function get_related_moduleName_by_value($val, $proposal = null)
	{
		$this->load->helper('admin');
		if ($val == 'project') {
			$HTML = null;
			$HTML .= form_project_lookup_group($val . '_id', lang('project'), '', '', true, array('class' => 'project_module', 'data-lookup-onchange' => ''));
			$HTML .= form_lookup_group('milestones_id', lang('milestones'), '', '', false, array(), 'md:col-span-2', array('type' => 'milestone', 'depends' => 'project_id', 'min_length' => 0));
			echo $HTML;
			exit();
		} elseif ($val == 'opportunities') {
			$HTML = null;
			$all_opp_info = $this->admin_model->get_permission('tbl_opportunities');
			if ($all_opp_info) {
				$options = array();
				foreach ($all_opp_info as $v_opp) {
					$options[$v_opp->opportunities_id] = $v_opp->opportunity_name;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group($val . '_id', lang('select') . ' ' . lang('opportunities'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box opportunities_module')) . '</div>';
			}
			echo $HTML;
			exit();
		} elseif ($val == 'leads') {
			$all_leads_info = $this->admin_model->get_permission('tbl_leads');
			$HTML = null;
			if ($all_leads_info) {
				$options = array();
				foreach ($all_leads_info as $v_leads) {
					$options[$v_leads->leads_id] = $v_leads->lead_name;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group($val . '_id', lang('select') . ' ' . lang('leads'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box leads_module')) . '</div>';
				if (!empty($proposal)) {
					$all_currency = $this->db->get('tbl_currencies')->result();
					$currency_options = array();
					$all_currency = $this->db->get('tbl_currencies')->result();
					foreach ($all_currency as $v_currency) {
						$currency_options[$v_currency->code] = $v_currency->name;
					}
					$HTML .= '<div class="md:col-span-2">' . form_select_group('currency', lang('currency'), $currency_options, config_item('default_currency'), true, array('data-live-search' => 'true')) . '</div>';
				}
			}
			echo $HTML;
			exit();
		} elseif ($val == 'client') {
			$HTML = '<div class="md:col-span-2">'
				. form_lookup_group($val . '_id', lang('client'), '', '', true, array(), 'md:col-span-2', array('type' => 'client'))
				. '</div>';
			echo $HTML;
			exit();
		} elseif ($val == 'supplier') {
			$HTML = '<div class="md:col-span-2">'
				. form_lookup_group($val . '_id', lang('supplier'), '', '', false, array(), 'md:col-span-2', array('type' => 'supplier'))
				. '</div>';
			echo $HTML;
			exit();
		} elseif ($val == 'bug') {
			$all_bugs_info = $this->admin_model->get_permission('tbl_bug');
			$HTML = null;
			if ($all_bugs_info) {
				$options = array();
				foreach ($all_bugs_info as $v_bugs) {
					$options[$v_bugs->bug_id] = $v_bugs->bug_title;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group('bug_id', lang('select') . ' ' . lang('bugs'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box bugs_module')) . '</div>';
			}
			echo $HTML;
			exit();
		} elseif ($val == 'goal') {
			$all_goal_info = $this->admin_model->get_permission('tbl_goal_tracking');
			$HTML = null;
			if ($all_goal_info) {
				$options = array();
				foreach ($all_goal_info as $v_goal) {
					$options[$v_goal->goal_tracking_id] = $v_goal->subject;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group('goal_tracking_id', lang('select') . ' ' . lang('goal_tracking'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box goal_tracking')) . '</div>';
			}
			echo $HTML;
			exit();
		} elseif ($val == 'sub_task') {
			$all_task_info = $this->admin_model->get_permission('tbl_task');
			$HTML = null;
			if ($all_task_info) {
				$options = array();
				foreach ($all_task_info as $v_task) {
					$options[$v_task->task_id] = $v_task->task_name;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group('sub_task_id', lang('select') . ' ' . lang('tasks'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box sub_tasks')) . '</div>';
			}
			echo $HTML;
			exit();
		} elseif ($val == 'expenses') {
			$all_expenses = $this->admin_model->get_permission('tbl_transactions');
			$HTML = null;
			if ($all_expenses) {
				$options = array();
				foreach ($all_expenses as $expenses) {
					$label = $expenses->name . (!empty($expenses->reference) ? '#' . $expenses->reference : '');
					$options[$expenses->transactions_id] = $label;
				}
				$HTML .= '<div class="md:col-span-2">' . form_select_group('transactions_id', lang('select') . ' ' . lang('expenses'), $options, '', true, array('data-live-search' => 'true', 'class' => 'select_box expenses')) . '</div>';
			}
			echo $HTML;
			exit();
		}
	}

	public function check_current_password()
	{
		$old_password = $this->input->post('name', true);
		if (!empty($old_password)) {
			if (!empty($old_password)) {
				$password = $this->hash($old_password);
			}
			$check_dupliaction_id = $this->admin_model->check_by(array('user_id' => my_id(), 'password' => $password), 'tbl_users');
			if (empty($check_dupliaction_id)) {
				$result['error'] = lang("password_does_not_match");
			} else {
				$result['success'] = 1;
				$encrypt_password = $this->input->post('encrypt_password', true);
				if (!empty($encrypt_password)) {
					$result['password'] = decrypt($encrypt_password);
				}
			}
			echo json_encode($result);
			exit();
		}
	}

	public function check_existing_user_name($user_id = null)
	{
		$username = $this->input->post('name', true);
		if (!empty($username)) {
			$check_user_name = $this->admin_model->check_user_name($username, $user_id);
			if (!empty($check_user_name)) {
				$result['error'] = lang("name_already_exist");
			} else {
				$result['success'] = 1;
			}
			echo json_encode($result);
			exit();
		}
	}


	public function check_duplicate_emp_id($user_id = null)
	{
		$employment_id = $this->input->post('name', true);
		if (!empty($employment_id)) {
			$where = array('employment_id' => $employment_id);
			if (!empty($user_id)) {
				$where['user_id !='] = $user_id;
			}
			$check_dupliaction_id = $this->admin_model->check_by($where, 'tbl_account_details');
			if (!empty($check_dupliaction_id)) {
				$result['error'] = lang("employee_id_exist");
			} else {
				$result['success'] = 1;
			}
			echo json_encode($result);
			exit();
		}
	}

	public function check_email_addrees($user_id = null)
	{
		$email_address = $this->input->post('name', true);
		if (!empty($email_address)) {
			$where = array('email' => $email_address);
			if (!empty($user_id)) {
				$where['user_id !='] = $user_id;
			}
			$check_email_address = $this->admin_model->check_by($where, 'tbl_users');
			if (!empty($check_email_address)) {
				$result['error'] = lang("this_email_already_exist");
			} else {
				$result['success'] = 1;
			}
			echo json_encode($result);
			exit();
		}
	}


	public function get_item_name_by_id($stock_sub_category_id)
	{
		$HTML = NULL;
		$this->admin_model->_table_name = 'tbl_stock';
		$this->admin_model->_order_by = 'stock_sub_category_id';
		$stock_info = $this->admin_model->get_by(array('stock_sub_category_id' => $stock_sub_category_id, 'total_stock >=' => '1'), FALSE);
		if (!empty($stock_info)) {
			foreach ($stock_info as $v_stock_info) {
				$HTML .= "<option value='" . $v_stock_info->stock_id . "'>" . $v_stock_info->item_name . "</option>";
			}
		}
		echo $HTML;
		exit();
	}


	public function check_available_leave($user_id, $start_date = NULL, $end_date = NULL, $leave_category_id = NULL, $leave_application_id = null)
	{

		$office_hours = config_item('office_hours');
		$result = null;
		$start_date = $this->normalize_leave_request_date($start_date);
		$end_date = $this->normalize_leave_request_date($end_date);
		if (!empty($leave_category_id) && !empty($start_date)) {
			$total_leave = $this->admin_model->check_by(array('leave_category_id' => $leave_category_id), 'tbl_leave_category');
			$leave_total = $total_leave->leave_quota;

			$all_leave = $this->db->where(array('leave_application_id !=' => $leave_application_id, 'user_id' => $user_id))->get('tbl_leave_application')->result();
			//            $leave_info = $this->db->where(array('leave_application_id' => $leave_application_id))->get('tbl_leave_application')->row();
			if (!empty($all_leave)) {
				foreach ($all_leave as $v_all_leave) {
					if (empty($v_all_leave->leave_end_date)) {
						$v_all_leave->leave_end_date = $v_all_leave->leave_start_date;
					}
					$get_dates = $this->admin_model->GetDays($v_all_leave->leave_start_date, $v_all_leave->leave_end_date);
					//                    $get_datesaa[] = $this->admin_model->GetDays($v_all_leave->leave_start_date, $v_all_leave->leave_end_date);
					$result_start = in_array($start_date, $get_dates);
					if (!empty($end_date)) {
						$result_end = in_array($end_date, $get_dates);
						if (!empty($result_end)) {
							$result = lang('leave_date_conflict') . ' Date is:' . $end_date;
						}
					}
					if (!empty($result_start)) {
						$result = lang('leave_date_conflict') . ' Date is:' . $start_date;
					}
				}
			}

			$token_leave = $this->db->where(array('user_id' => $user_id, 'leave_category_id' => $leave_category_id, 'YEAR(`leave_start_date`)' => date('Y'), 'application_status' => '2'))->get('tbl_leave_application')->result();

			$total_taken = 0;
			$total_hourly = 0;
			if (!empty($token_leave)) {
				$res = calculate_taken_leave($token_leave);
				$total_taken = $res['total_taken'];
				$total_hourly = $res['total_hourly'];
			}
			if (empty($total_taken)) {
				$total_taken = 0;
			}
			if (empty($total_hourly)) {
				$total_hourly = 0;
			}
			$total_taken = $total_hourly + $total_taken;

			$input_ge_days = 0;
			$input_m_days = 0;
			if (!empty($end_date) && $end_date != 'null') {
				$input_month = cal_days_in_month(CAL_GREGORIAN, date('m', safe_strtotime($start_date)), date('Y', safe_strtotime($end_date)));

				$input_datetime1 = new DateTime($start_date);
				$input_datetime2 = new DateTime($end_date);
				$input_difference = $input_datetime1->diff($input_datetime2);
				if ($input_difference->m != 0) {
					$input_m_days += $input_month;
				} else {
					$input_m_days = 0;
				}
				$input_ge_days += $input_difference->d + 1;
				$input_total_taken = $input_m_days + $input_ge_days;
			} else {
				$input_total_taken = 1;
			}
			$taken_with_input = $total_taken + $input_total_taken;
			$left_leave = $leave_total - $total_taken;
			$left_leave_hours = $left_leave * $office_hours;
			$left_leave_days = (int)($left_leave_hours / $office_hours);

			$left_leave_hours = $left_leave_hours % $office_hours;
			$left_leave_string = $left_leave_days . ' days ' . $left_leave_hours . ' hours ';

			if ($leave_total < $taken_with_input) {
				if ($user_id == $this->session->userdata('user_id')) {
					$t = 'You ';
				} else {
					$profile = $this->db->where('user_id', $user_id)->get('tbl_account_details')->row();
					$t = $profile->fullname;
				}
				$total_taken = leave_days_hours($total_taken, true);
				$result = "$t already took  $total_taken $total_leave->leave_category You can apply maximum for $left_leave_string more";
			}
		} else {
			$result = lang('all_required_fill');
		}
		echo $result;
		exit();
	}

	public function get_leave_details($user_id)
	{
		if ($user_id == $this->session->userdata('user_id')) {
			$title = lang('my_leave');
		} else {
			$profile = $this->db->where('user_id', $user_id)->get('tbl_account_details')->row();
			$title = $profile->fullname;
		}
		$panel = null;
		$panel .= '<div class="panel panel-custom"><div class="panel-heading"><div class="panel-title"><strong>' . $title . ' ' . lang('details') . '</strong></div></div><table class="table"><tbody>';
		$total_taken = 0;
		$total_quota = 0;
		$leave_report = leave_report($user_id);
		if (!empty($leave_report['leave_category'])) {
			foreach ($leave_report['leave_category'] as $lkey => $v_l_report) {
				$total_quota += $leave_report['leave_quota'][$lkey];
				$total_taken += $leave_report['leave_taken'][$lkey];

				$panel .= '<tr><td><strong>' . $leave_report['leave_category'][$lkey] . '</strong>:</td><td>';
				$panel .= $leave_report['leave_taken'][$lkey] . '/' . $leave_report['leave_quota'][$lkey];
				$panel .= '</td></tr>';
			}
		}
		$panel .= '<tr><td class="l_report"><strong>' . lang('total') . '</strong>:</td><td class="l_report">' . $total_taken . '/' . $total_quota . '</td></tr></tbody></table></div>';
		echo $panel;
		exit();
	}

	public function get_employee_by_designations_id($designation_id)
	{
		$HTML = NULL;
		$this->admin_model->_table_name = 'tbl_account_details';
		$this->admin_model->_order_by = 'designations_id';
		$employee_info = $this->admin_model->get_by(array('designations_id' => $designation_id), FALSE);
		if (!empty($employee_info)) {
			foreach ($employee_info as $v_employee_info) {
				$HTML .= "<option value='" . $v_employee_info->user_id . "'>" . $v_employee_info->fullname . "</option>";
			}
		}
		echo $HTML;
		exit();
	}

	public function check_advance_amount($amount, $user_id = null)
	{
		$result = $this->common_model->get_advance_amount($user_id);
		if (!empty($result)) {
			if ($result < $amount) {
				echo lang('exced_basic_salary');
				exit();
			} else {
				echo null;
				exit();
			}
		} else {
			echo lang('you_can_not_apply');
			exit();
		}
	}

	public function get_taxes_dropdown()
	{
		$name = $this->input->post('name', true);
		$taxname = $this->input->post('taxname', true);
		echo $this->admin_model->get_taxes_dropdown($name, $taxname);
		exit();
	}

	/* Get item by id / ajax */
	public function get_item_by_id($id)
	{
		if ($this->input->is_ajax_request()) {
			$item = $this->admin_model->get_item_by_id($id);
			echo json_encode($item);
			exit();
		}
	}

	public function update_ei_items_order($type)
	{
		$data = $this->input->post();
		foreach ($data['items_id'] as $order) {
			if ($type == 'estimate') {
				$this->db->where('estimate_items_id', $order[0]);
				$this->db->update('tbl_estimate_items', array(
					'order' => $order[1]
				));
			} else if ($type == 'credit_note') {
				$this->db->where('credit_note_items_id', $order[0]);
				$this->db->update('tbl_credit_note_items', array(
					'order' => $order[1]
				));
			} else if ($type == 'proposal') {
				$this->db->where('proposals_items_id', $order[0]);
				$this->db->update('tbl_proposals_items', array(
					'order' => $order[1]
				));
			} else if ($type == 'todo') {
				$this->db->where('todo_id', $order[0]);
				$this->db->update('tbl_todo', array(
					'order' => $order[1]
				));
			} else {
				$this->db->where('items_id', $order[0]);
				$this->db->update('tbl_items', array(
					'order' => $order[1]
				));
			}
		}
	}

	/* Set notifications to read */
	public function mark_as_read()
	{
		if ($this->input->is_ajax_request()) {
			$userId = (int) $this->session->userdata('user_id');
			$this->db->where('to_user_id', $userId);
			$this->db->update('tbl_notifications', array(
				'read' => 1
			));
			$this->cache->save('unread_notif_count_' . $userId, 0, 60);
			echo json_encode(array(
				'success' => true,
				'unread_count' => 0
			));
			return false;
		}
	}

	public function read_inline($id)
	{
		$this->db->where('to_user_id', $this->session->userdata('user_id'));
		$this->db->where('notifications_id', $id);
		$this->db->update('tbl_notifications', array(
			'read_inline' => 1
		));
		if ($this->input->is_ajax_request()) {
			echo json_encode(array(
				'success' => true
			));
		}
	}

	public function mark_desktop_notification_as_read($id)
	{
		$userId = (int) $this->session->userdata('user_id');
		$this->db->where('to_user_id', $userId);
		$this->db->where('notifications_id', $id);
		$this->db->update('tbl_notifications', array(
			'read' => 1,
			'read_inline' => 1
		));
		$unread = (int) $this->db
			->where(array('to_user_id' => $userId, 'read' => 0))
			->count_all_results('tbl_notifications');
		$this->cache->save('unread_notif_count_' . $userId, $unread, 60);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array(
				'success' => true,
				'unread_count' => $unread
			));
		}
	}

	public function mark_all_as_read()
	{
		$userId = (int) $this->session->userdata('user_id');
		$this->db->where('to_user_id', $userId);
		$this->db->update('tbl_notifications', array(
			'read' => 1,
			'read_inline' => 1
		));
		$this->cache->save('unread_notif_count_' . $userId, 0, 60);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array(
				'success' => true,
				'unread_count' => 0
			));
		}
	}

	public function header_notifications()
	{
		if (!$this->input->is_ajax_request()) {
			show_404();
		}

		$userId = (int) $this->session->userdata('user_id');
		$isClientPanel = (int) ($this->session->userdata('user_type') ?? 0) === 2;
		$data['notifications'] = $this->common_model->get_user_notifications(false);
		$data['unread_count'] = (int) $this->db
			->where(array('to_user_id' => $userId, 'read' => 0))
			->count_all_results('tbl_notifications');
		$data['is_client_panel'] = $isClientPanel;
		$data['notifications_page_url'] = $isClientPanel
			? base_url('client/user/user_details/' . $userId . '?tab=notifications')
			: base_url('admin/user/user_details/' . $userId . '?tab=notifications');
		$html = $this->load->view('admin/components/header_notifications_panel', $data, true);
		$this->cache->save('unread_notif_count_' . $userId, $data['unread_count'], 60);

		echo json_encode(array(
			'success' => true,
			'html' => $html,
			'unread_count' => $data['unread_count'],
		));
	}

	public function get_notification()
	{
		$notificationsIds = array();

		if (config_item('desktop_notifications') == "1") {
			$notifications = $this->common_model->get_user_notifications(false);

			$notificationsPluck = array_filter($notifications, function ($n) {
				return $n->read == 0;
			});
			$notificationsIds = array_pluck($notificationsPluck, 'notifications_id');
		}
		echo json_encode(array(
			'html' => $this->load->view('admin/components/notifications', array(), true),
			'notificationsIds' => $notificationsIds
		));
		exit();
	}

	/* upload a post file */

	function upload_file()
	{
		$result = upload_file_to_temp();
		if (is_array($result)) {
			echo json_encode($result);
			exit();
		}
	}

	public function delete_temp_file()
	{
		$file_name = $this->input->post('file_name', true);
		if (empty($file_name)) {
			echo json_encode(array('success' => false, 'message' => lang('invalid_file_type')));
			exit();
		}
		$file_name = basename($file_name);
		$path = getcwd() . '/uploads/temp/' . $file_name;
		if (is_file($path)) {
			@unlink($path);
		}
		echo json_encode(array('success' => true));
		exit();
	}

	/* check valid file for project */

	function validate_project_file()
	{
		return validate_post_file($this->input->post("file_name", true));
	}

	function set_media_view($type, $module)
	{
		$k_session[$module . '_media_view'] = $type;
		$this->session->set_userdata($k_session);
		return true;
	}

	public function hash($string)
	{
		return hash('sha512', $string . config_item('encryption_key'));
	}

	public function set_language($lang)
	{
		$this->session->set_userdata('lang', $lang);
		if (empty($_SERVER['HTTP_REFERER'])) {
			redirect('admin/dashboard');
		} else {
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public function download_all_attachment($type, $id)
	{

		$attachment_info = get_result('tbl_attachments', array('module' => $type, 'module_field_id' => $id));
		$FileName = $type . '_attachment';
		$this->load->library('zip');
		if (!empty($attachment_info) && !empty($FileName)) {
			foreach ($attachment_info as $v_attach) {
				$uploaded_files_info = $this->db->where('attachments_id', $v_attach->attachments_id)->get('tbl_attachments_files')->result();
				$filename = slug_it($FileName);
				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);
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/dashboard');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public function get_search_result()
	{
		$value = $this->input->post('value', true);
		$searchType = $this->input->post('searchType', true);
		if (!empty($value)) {
			$result = $this->getSearchResult($searchType, $value);
			echo json_encode($result);
			exit();
		} else {
			set_message('error', lang('nothing_to_display'));
			redirect('admin/dashboard');
		}
	}

	function getSearchResult($searchType, $value)
	{
		$where2 = '';
		if (!empty($searchType)) {
			if ($searchType == 'projects') {
				$tblName = 'tbl_project';
				$where = 'project_name';
				$where2 = 'project_no';
				$id = 'project_id';
			} else if ($searchType == 'tasks') {
				$tblName = 'tbl_task';
				$where = 'task_name';
				$id = 'task_id';
			} else if ($searchType == 'employee') {
				$tblName = 'tbl_account_details';
				$where = 'fullname';
				$where2 = 'employment_id';
				$id = 'user_id';
			} else if ($searchType == 'client') {
				$tblName = 'tbl_client';
				$where = 'name';
				$where2 = 'email';
				$id = 'client_id';
			} else if ($searchType == 'bugs') {
				$tblName = 'tbl_bug';
				$where = 'bug_title';
				$where2 = 'issue_no';
				$id = 'bug_id';
			} else if ($searchType == 'opportunities') {
				$tblName = 'tbl_opportunities';
				$where = 'opportunity_name';
				$where2 = 'stages';
				$id = 'opportunities_id';
			} elseif ($searchType == 'leads') {
				$tblName = 'tbl_leads';
				$where = 'lead_name';
				$id = 'leads_id';
			} elseif ($searchType == 'purchase') {
				$tblName = 'tbl_purchases';
				$where = 'reference_no';
				$id = 'purchase_id';
			} elseif ($searchType == 'invoice') {
				$tblName = 'tbl_invoices';
				$where = 'reference_no';
				$id = 'invoices_id';
			} elseif ($searchType == 'credit_note') {
				$tblName = 'tbl_credit_note';
				$where = 'reference_no';
				$id = 'credit_note_id';
			} elseif ($searchType == 'estimates') {
				$tblName = 'tbl_estimates';
				$where = 'reference_no';
				$id = 'estimates_id';
			} elseif ($searchType == 'tickets') {
				$tblName = 'tbl_tickets';
				$where = 'subject';
				$where2 = 'ticket_code';
				$id = 'tickets_id';
			}
		}
		if (!empty($tblName)) {
			$select = $tblName . '.*,' . $tblName . '.' . $where . ' as title,' . $tblName . '.' . $id . ' as id';
			$this->db->select($select);
			$this->db->from($tblName);
			$this->db->like($where, $value);
			if (!empty($where2)) {
				$this->db->or_like($where2, $value);
			}
			$query_result = $this->db->get();
			$result = $query_result->result();
		}
		$result_array = array();
		if (!empty($result)) {
			foreach ($result as $value) {
				$title = $value->title;
				if (!empty($where2) && !empty($value->$where2)) {
					$title = $value->title . '(' . $value->$where2 . ')';
				}
				$result_array[] = array("value" => $value->id, "label" => $title);
			}
		}
		return $result_array;
	}

	public function items_suggestions($limit = null)
	{
		if (empty($limit)) {
			$limit = 12;
			$class = 'select_pos_item';
		} else {
			$class = 'select_item';
		}
		$term = $this->input->post('term', true);
		$warehouse_id = $this->input->post('warehouse_id', true);
		if (!empty($warehouse_id)) {
			$rows = $this->admin_model->getItemsInfo($term, $warehouse_id, $limit);
		}

		$html = null;
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$imgaeURL = base_url('assets/img/product.png');
				if (!empty($row->upload_file)) {
					$uploaded_file = json_decode($row->upload_file);
					$rand_keys = array_rand($uploaded_file, 1);
					if ($uploaded_file[$rand_keys]->is_image == 1) {
						$imgaeURL = base_url($uploaded_file[$rand_keys]->path);
					} else {
						$imgaeURL = base_url('assets/img/filepreview.jpg');
					}
				}
				$html .= '<div class="col-xs-2 p0 m0" style="max-height:108px;overflow: hidden"> <a  class="' . $class . ' btn p0" data-item-id="' . $row->saved_items_id . '">
                                            <img class="round" src="' . $imgaeURL . '" style="height: 70px;width: 70%"> <div class="text-xs-center text"> <small style="white-space: pre-wrap;">' . $row->item_name . ' ' . $row->code . '</small></div></a></div>';
			}
			echo $html;
		}
		exit();
	}

	public function itemAddedManualy()
	{
		$data = (object)$this->input->post();
		$saved_items_id = 0;
		$data->saved_items_id = $saved_items_id;
		$data->code = '';
		$data->new_item_id = $saved_items_id;
		$tax_info = $this->input->post('tax_rates_id', true);
		if (!empty($tax_info)) {
			foreach ($tax_info as $tax_id) {
				$tax = $this->db->where('tax_rates_id', $tax_id)->get('tbl_tax_rates')->row();
				if (!empty($tax->tax_rate_name)) {
					$tax_name[] = $tax->tax_rate_name . '|' . $tax->tax_rate_percent;
				}
			}
			$tax = (object)[
				'taxname' => (!empty($tax_name) ? ($tax_name) : null),
			];
		}
		unset($data->tax_rates_id);
		if (empty($tax)) {
			$tax = (object)[
				'taxname' => '',
			];
		}
		$result = (object)array_merge((array)$data, (array)$tax);
		$pr = array('saved_items_id' => $saved_items_id, 'label' => $data->item_name, 'row' => $result);
		echo json_encode($pr);
		die();
	}

	function suggestions($id = NULL)
	{
		$for_purcahse = $this->input->get('for', true);
		$cost = 'unit_cost';
		if ($for_purcahse == 'purchase_item') {
			$cost = 'cost_price';
		}
		if (!empty($id)) {
			// $row = $this->itemInfo($id);
			$row = $this->admin_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
			$row->qty = 1;
			$row->rate = $row->$cost;
			$row->unit = $row->unit_type;
			$row->new_itmes_id = $row->saved_items_id;
			$tax_info = json_decode($row->tax_rates_id);
			if (!empty($tax_info)) {
				foreach ($tax_info as $tax_id) {
					$tax = $this->db->where('tax_rates_id', $tax_id)->get('tbl_tax_rates')->row();
					if (!empty($tax->tax_rate_name)) {
						$tax_name[] = $tax->tax_rate_name . '|' . $tax->tax_rate_percent;
					}
				}
				$tax = (object)[
					'taxname' => (!empty($tax_name) ? ($tax_name) : null),
				];
			}
			if (empty($tax)) {
				$tax = (object)[
					'taxname' => '',
				];
			}
			$result = (object)array_merge((array)$row, (array)$tax);
			$pr = array('saved_items_id' => str_replace(".", "", microtime(true)), 'saved_items_id' => $row->saved_items_id, 'label' => $row->item_name . " (" . $row->code . ")", 'row' => $result);
			echo json_encode($pr);
			die();
		}
		$term = $this->input->get('term', TRUE);

		$warehouse_id = $this->input->get('warehouse_id', TRUE);
		$limit = (int) $this->input->get('limit', TRUE);
		if (!empty($warehouse_id)) {
			$rows = $this->admin_model->getItemsInfo($term, $warehouse_id, $limit > 0 ? $limit : 10);
		}
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$row->qty = 1;
				$row->rate = $row->$cost;
				$row->unit = $row->unit_type;
				$row->new_itmes_id = $row->saved_items_id;
				$tax_info = json_decode($row->tax_rates_id);
				if (!empty($tax_info)) {
					foreach ($tax_info as $tax_id) {
						$tax = $this->db->where('tax_rates_id', $tax_id)->get('tbl_tax_rates')->row();
						if (!empty($tax->tax_rate_name)) {
							$tax_name[] = $tax->tax_rate_name . '|' . $tax->tax_rate_percent;
						}
					}
					$tax = (object)[
						'taxname' => (!empty($tax_name) ? ($tax_name) : null),
					];
				}
				if (empty($tax)) {
					$tax = (object)[
						'taxname' => '',
					];
				}
				$result = (object)array_merge((array)$row, (array)$tax);
				$pr[] = array('saved_items_id' => $row->saved_items_id, 'label' => $row->item_name . " (" . $row->code . ")", 'row' => $result);
			}
			echo json_encode($pr);
			die();
		} else {
			echo json_encode(array(array('saved_items_id' => 0, 'label' => lang('no_match_found'), 'value' => $term)));
			die();
		}
	}

	public function getItemByWarehouse($warehouseId = NULL)
	{
		$where = null;
		$class = 'select_pos_item';
		if (!empty($warehouseId)) {
			$rows = $this->admin_model->getItemsInfo('', $warehouseId);
		}
		$html = null;
		if (!empty($rows)) {
			foreach ($rows as $row) {
				$imgaeURL = base_url('assets/img/product.png');
				if (!empty($row->upload_file)) {
					$uploaded_file = json_decode($row->upload_file);
					$rand_keys = array_rand($uploaded_file, 1);
					if ($uploaded_file[$rand_keys]->is_image == 1) {
						$imgaeURL = base_url($uploaded_file[$rand_keys]->path);
					} else {
						$imgaeURL = base_url('assets/img/filepreview.jpg');
					}
				}
				$html .= '<div class="col-xs-2 p0 m0" style="max-height:108px;overflow: hidden"> <a class="' . $class . ' btn p0" data-item-id="' . $row->saved_items_id . '">
                                            <img class="round" src="' . $imgaeURL . '" style="height: 70px;width: 70%"> <div class="text-xs-center text"> <small style="white-space: pre-wrap;">' . $row->item_name . ' ' . $row->code . '</small></div></a></div>';
			}
		}
		echo json_encode($html);
		exit();
	}


	function save_comments()
	{
		if (ob_get_length()) {
			ob_clean();
		}
		$data['module'] = $this->input->post('module', TRUE);
		$data['module_field_id'] = $this->input->post('module_field_id', TRUE);
		$data['comment'] = $this->input->post('comment', TRUE);

		$files = $this->input->post("files", true);
		$target_path = getcwd() . "/uploads/";
		$up_data = array();
		//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);
					$file_comment = $this->input->post('comment_' . $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,
							"comment" => $file_comment,
						);
						$success = true;
					} else {
						$success = false;
					}
				}
			}
		}
		//process the files which has been submitted manually
		if (!empty($_FILES)) {
			$file_sets = array();
			if (!empty($_FILES['manualFiles'])) {
				$file_sets[] = $_FILES['manualFiles'];
			}
			if (!empty($_FILES['comment_files'])) {
				$file_sets[] = $_FILES['comment_files'];
			}
			if (!empty($_FILES['files'])) {
				$file_sets[] = $_FILES['files'];
			}

			foreach ($file_sets as $files) {
				if (empty($files['name'])) {
					continue;
				}
				$is_multi = is_array($files['name']);
				$names = $is_multi ? $files['name'] : array($files['name']);
				$tmp_names = $is_multi ? $files['tmp_name'] : array($files['tmp_name']);
				$sizes = $is_multi ? $files['size'] : array($files['size']);

				foreach ($tmp_names as $key => $file) {
					if (empty($names[$key])) {
						continue;
					}
					$temp_file = $file;
					$file_name = $names[$key];
					$file_size = $sizes[$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->common_model->_table_name = "tbl_task_comment"; // table name
		$this->common_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->common_model->save($data);
		if ($this->session->userdata('user_type') == 2) {
			$url = 'client/';
		} else {
			$url = 'admin/';
		}
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => $data['module'],
			'module_field_id' => $data['module_field_id'],
			'activity' => 'activity_new_' . $data['module'] . '_comment',
			'icon' => 'fa-rocket',
			'link' => $url . $data['module'] . '/details/' . $data['module_field_id'] . '/2',
			'value1' => $data['comment'],
		);

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

			if (!empty($comment_id)) {
				$response_data = "";
				$view_data['comment_type'] = $data['module'];
				$view_data['comment_details'] = $this->common_model->get_comment_details($comment_id);
				$response_data = $this->load->view("admin/common/comments_list", $view_data, true);
				if (!$this->input->is_ajax_request()) {
					set_message('success', lang($data['module'] . '_comment_save'));
					redirect(!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'admin/dashboard');
				}
				header('Content-Type: application/json');
				echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang($data['module'] . '_comment_save')));
				exit();
			} else {
				if (!$this->input->is_ajax_request()) {
					set_message('error', lang('error_occurred'));
					redirect(!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'admin/dashboard');
				}
				header('Content-Type: application/json');
				echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
				exit();
			}
		}

	public function save_comments_reply($comment_id)
	{
		$data['module'] = $this->input->post('module', true);
		$data['module_field_id'] = $this->input->post('module_field_id', true);
		$data['comment'] = $this->input->post('reply_comments', true);
		$data['user_id'] = $this->session->userdata('user_id');
		$data['comments_reply_id'] = $comment_id;
		//save data into table.
		$this->common_model->_table_name = "tbl_task_comment"; // table name
		$this->common_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->common_model->save($data);
		if (!empty($comment_id)) {
			$comments_info = $this->common_model->get_comment_details($comment_id)[0];
			if ($this->session->userdata('user_type') == 2) {
				$url = 'client/';
			} else {
				$url = 'admin/';
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => $data['module'],
				'module_field_id' => $data['module_field_id'],
				'activity' => 'activity_new_' . $data['module'] . '_comment_reply',
				'icon' => 'fa-rocket',
				'link' => $url . $data['module'] . '/details/' . $data['module_field_id'] . '/2',
				'value1' => $comments_info->comment,
				'value2' => $data['comment'],
			);
			// Update into tbl_project
			$this->common_model->_table_name = "tbl_activities"; //table name
			$this->common_model->_primary_key = "activities_id";
			$this->common_model->save($activities);


			$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_new_comment',
							'link' => $url . $data['module'] . '/details/' . $data['module_field_id'] . '/2',
							'value' => lang('lead') . ' ' . $data['comment'],
						));
					}
				}
				show_notification($notifiedUsers);
			}
			$response_data = "";
			$view_data['comment_reply_details'] = $this->common_model->get_comment_details($comment_id);
			$view_data['comment_type'] = $data['module'];
			$response_data = $this->load->view("admin/common/comments_reply", $view_data, true);
			if (!$this->input->is_ajax_request()) {
				set_message('success', lang($data['module'] . '_comment_save'));
				redirect(!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'admin/dashboard');
			}
			echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang($data['module'] . '_comment_save')));
			exit();
		} else {
			if (!$this->input->is_ajax_request()) {
				set_message('error', lang('error_occurred'));
				redirect(!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'admin/dashboard');
			}
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	public
	function delete_comments($task_comment_id = null)
	{
		$comments_info = $this->common_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);
			}
		}
		if ($this->session->userdata('user_type') == 2) {
			$url = 'client/';
		} else {
			$url = 'admin/';
		}
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => $comments_info->module,
			'module_field_id' => $comments_info->module_field_id,
			'activity' => 'activity_comment_deleted',
			'icon' => 'fa-rocket',
			'link' => $url . $comments_info->module . '/details/' . $comments_info->module_field_id . '/2',
			'value1' => $comments_info->comment,
		);
		// Update into tbl_project
		$this->common_model->_table_name = "tbl_activities"; //table name
		$this->common_model->_primary_key = "activities_id";
		$this->common_model->save($activities);

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

		echo json_encode(array("status" => 'success', 'message' => lang('task_comment_deleted')));
		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
				if (!empty($down_data)) {
					force_download($uploaded_files_id, $down_data);
				} else {
					$type = "error";
					$message = lang('operation_failed');
					set_message($type, $message);
					if (empty($_SERVER['HTTP_REFERER'])) {
						redirect('admin/dashboard');
					} else {
						redirect($_SERVER['HTTP_REFERER']);
					}
				}
			} else {
				$type = "error";
				$message = 'Operation Fieled !';
				set_message($type, $message);
				if (empty($_SERVER['HTTP_REFERER'])) {
					redirect('admin/dashboard');
				} else {
					redirect($_SERVER['HTTP_REFERER']);
				}
			}
		} else {
			$uploaded_files_info = $this->common_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 {
				$type = "error";
				$message = lang('operation_failed');
				set_message($type, $message);
				if (empty($_SERVER['HTTP_REFERER'])) {
					redirect('admin/dashboard');
				} else {
					redirect($_SERVER['HTTP_REFERER']);
				}
			}
		}
	}

	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);
			if (empty($_SERVER['HTTP_REFERER'])) {
				redirect('admin/dashboard');
			} else {
				redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}

	public function new_call($module, $id, $call_id = null)
	{
		$data['title'] = lang('new') . ' ' . lang('call');
		$data['module'] = $module;
		$data['module_id'] = $id;
		$data['call_id'] = $call_id;
		$this->load->view('admin/common/new_call', $data);
	}

	public function new_meeting($module, $id, $meeting_id = null)
	{
		$data['title'] = lang('new') . ' ' . lang('mettings');
		$data['module'] = $module;
		$data['module_id'] = $id;
		$data['meeting_id'] = $meeting_id;
		$this->load->view('admin/common/new_meeting', $data);
	}

	public function new_reminder($module, $id, $reminder_id = null)
	{
		$data['title'] = lang('new') . ' ' . lang('reminder');
		$data['module'] = $module;
		$data['module_id'] = $id;
		$data['reminder_id'] = $reminder_id;
		$this->load->view('admin/common/new_reminder', $data);
	}

	public
	function new_attachment($module, $id)
	{
		$data['title'] = lang('new_attachment');
		$data['dropzone'] = true;
		$data['module'] = $module;
		$data['module_field_id'] = $id;
		$this->load->view('admin/common/new_attachment', $data);
	}

	public
	function attachment_details($type, $id, $files_id = null)
	{
		$data['title'] = lang('attachment') . ' ' . lang('details');
		$data['type'] = $type;
		$data['dropzone'] = true;
		$data['module'] = 'attachment-module';
		$data['attachment_info'] = $this->common_model->get_attach_file($id, $type, $files_id);
		$data['modal_subview'] = $this->load->view('admin/common/attachment_details', $data, FALSE);
	}

	public function save_attachment($attachments_id = null)
	{
		$data = $this->common_model->array_from_post(array('title', 'description', 'module', 'module_field_id'));
		$data['user_id'] = $this->session->userdata('user_id');

		// save and update into tbl_files
		$this->common_model->_table_name = "tbl_attachments"; //table name
		$this->common_model->_primary_key = "attachments_id";
		if (!empty($attachments_id)) {
			$id = $attachments_id;
			$this->common_model->save($data, $id);
			$msg = lang('file_updated');
		} else {
			$id = $this->common_model->save($data);
			$msg = lang('file_added');
		}
		$success = true;
		$type = "success";
		$message = $msg;
		$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->common_model->_table_name = "tbl_attachments_files"; // table name
						$this->common_model->_primary_key = "uploaded_files_id"; // $id
						$uploaded_files_id = $this->common_model->save($up_data);

						// saved into comments
						$comment = $this->input->post('comment_' . $file, true);
						if (!empty($comment)) {
							$u_cdata = array(
								"comment" => $comment,
								"module" => $data['module'],
								"module_field_id" => $data['module_field_id'],
								"user_id" => $this->session->userdata('user_id'),
								"uploaded_files_id" => $uploaded_files_id,
							);
							$this->common_model->_table_name = "tbl_task_comment"; // table name
							$this->common_model->_primary_key = "task_comment_id"; // $id
							$this->common_model->save($u_cdata);
						}
						$success = true;
					} else {
						$success = false;
					}
				}
			}
		}
		//process the files which has been submitted manually
		if (!empty($_FILES) && !empty($_FILES['manualFiles']) && !empty($_FILES['manualFiles']['name'])) {
			$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->common_model->_table_name = "tbl_attachments_files"; // table name
						$this->common_model->_primary_key = "uploaded_files_id"; // $id
						$uploaded_files_id = $this->common_model->save($up_data);

						// saved into comments
						if (!empty($comment[$key])) {
							$u_cdata = array(
								"comment" => $comment[$key],
								"module" => $data['module'],
								"module_field_id" => $data['module_field_id'],
								"user_id" => $this->session->userdata('user_id'),
								"uploaded_files_id" => $uploaded_files_id,
							);
							$this->common_model->_table_name = "tbl_task_comment"; // table name
							$this->common_model->_primary_key = "task_comment_id"; // $id
							$this->common_model->save($u_cdata);
						}
					}
				}
			}
		}
		$moduleUrl = '/details/';
		if ($data['module'] == 'projects') {
			$moduleUrl = '/project_details/';
		}
		if ($data['module'] == 'leads') {
			$moduleUrl = '/leads_details/';
		}
		$url = 'admin/' . $data['module'] . $moduleUrl . $data['module_field_id'] . '/attachments';
		if ($success) {
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => $data['module'],
				'module_field_id' => $data['module_field_id'],
				'activity' => 'activity_new_' . $data['module'] . '_attachment',
				'icon' => 'fa-rocket',
				'link' => $url,
				'value1' => $data['title'],
			);
			// Update into tbl_project
			$this->common_model->_table_name = "tbl_activities"; //table name
			$this->common_model->_primary_key = "activities_id";
			$this->common_model->save($activities);

			$configEmail = $data['module'] . '_email';
			$tasks_email = config_item($configEmail);
			if (!empty($tasks_email) && $tasks_email == 1) {
				// send notification message
				$model = $data['module'] . '_model';
				// $this->$model->notify_attachment_email($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_uploaded_attachment',
							'link' => $url,
							'value' => lang($data['module']) . ' ' . $data['title'],
						));
					}
				}
				show_notification($notifiedUsers);
			}
			// messages for user
			$type = "success";
			$message = $msg;
		} elseif (!$success) {
			$type = "error";
			$message = lang('operation_failed');
		}
		// set_message($type, $message);
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
		// redirect($url);
	}

	public function delete_attach_files($attachments_id = null)
	{
		if (empty($attachments_id)) {
			echo json_encode(array("status" => 'error', 'message' => 'Ops there is an issue for delete.please contact administrator'));
		} else {
			$file_info = $this->common_model->check_by(array('attachments_id' => $attachments_id), 'tbl_attachments');
			if (empty($file_info)) {
				echo json_encode(array("status" => 'error', 'message' => lang('there_in_no_value')));
				exit();
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => $file_info->module,
				'module_field_id' => $file_info->module_field_id,
				'activity' => 'activity_opportunity_attachfile_deleted',
				'icon' => 'fa-filter',
				'link' => 'admin/' . $file_info->module . '/details/' . $file_info->module_field_id . '/5',
				'value1' => $file_info->title,
			);
			// Update into tbl_project
			$this->common_model->_table_name = "tbl_activities"; //table name
			$this->common_model->_primary_key = "activities_id";
			$this->common_model->save($activities);

			//save data into table.
			$this->common_model->_table_name = "tbl_attachments"; // table name
			$this->common_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->common_model->_table_name = "tbl_attachments_files"; // table name
			$this->common_model->delete_multiple(array('attachments_id' => $attachments_id));
			echo json_encode(array("status" => 'success', 'message' => lang('attachfile_successfully_deleted')));
		}
		exit();
	}

	public function delete_task_files($attachments_id = null)
	{
		$this->delete_attach_files($attachments_id);
	}

	public
	function save_attachment_comments()
	{
		if (ob_get_length()) {
			ob_clean();
		}
		$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['module'] = $this->input->post('module', true);
		$data['module_field_id'] = $this->input->post('module_field_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->common_model->_table_name = "tbl_task_comment"; // table name
		$this->common_model->_primary_key = "task_comment_id"; // $id
		$comment_id = $this->common_model->save($data);
		if (!empty($comment_id)) {
			if ($this->session->userdata('user_type') == 2) {
				$url = 'client/';
			} else {
				$url = 'admin/';
			}
			// save into activities
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => $data['module'],
				'module_field_id' => $data['module_field_id'],
				'activity' => 'activity_new_' . $data['module'] . '_comment',
				'icon' => 'fa-rocket',
				'link' => $url . $data['module'] . '/details/' . $data['module_field_id'] . '/2',
				'value1' => $data['comment'],
			);
			// Update into tbl_project
			$this->common_model->_table_name = "tbl_activities"; //table name
			$this->common_model->_primary_key = "activities_id";
			$this->common_model->save($activities);

			$response_data = "";
			$view_data['comment_type'] = $data['module'];
			$view_data['comment_details'] = $this->common_model->get_comment_details($comment_id);
			$response_data = $this->load->view("admin/common/comments_list", $view_data, true);
			header('Content-Type: application/json');
			echo json_encode(array("status" => 'success', "data" => $response_data, 'message' => lang('task_comment_save')));
			exit();
		} else {
			header('Content-Type: application/json');
			echo json_encode(array("status" => 'error', 'message' => lang('error_occurred')));
			exit();
		}
	}

	public
	function save_all_notes($id)
	{

		$data = $this->common_model->array_from_post(array('notes'));
		$contacted_indicator = $this->input->post('contacted_indicator', true);
		$module = $this->input->post('module', true);
		$redirect = $this->input->post('redirect', true);
		if (!empty($contacted_indicator) && $contacted_indicator == 'touch_with_leads') {
			$data['last_contact'] = $this->input->post('last_contact', true);

			if ($module === 'leads') {
				$ldata['last_contact'] = $data['last_contact'];
				$this->common_model->_table_name = 'tbl_leads';
				$this->common_model->_primary_key = 'leads_id';
				$this->common_model->save($ldata, $id);
			}
		}
		$data['module_field_id'] = $id;
		$data['user_id'] = my_id();
		$data['module'] = $module;
		//save data into table.
		$this->common_model->_table_name = 'tbl_leads_notes';
		$this->common_model->_primary_key = 'notes_id';
		$sid = $this->common_model->save($data);

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

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

	public
	function delete_notes($notes_id, $leads_id, $redirect = null)
	{
		$notes_info = get_row('tbl_leads_notes', array('notes_id' => $notes_id));
		$module = !empty($notes_info->module) ? $notes_info->module : 'leads';
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => $module,
			'module_field_id' => $leads_id,
			'activity' => 'activity_delete_notes',
			'icon' => 'fa-folder-open-o',
			'link' => 'admin/' . $redirect . '/' . $leads_id . '/notes',
			'value1' => $notes_info->notes,
		);
		// Update into tbl_project
		$this->common_model->_table_name = "tbl_activities"; //table name
		$this->common_model->_primary_key = "activities_id";
		$this->common_model->save($activities);

		$this->common_model->_table_name = 'tbl_leads_notes';
		$this->common_model->_primary_key = 'notes_id';
		$this->common_model->delete($notes_id);

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