<?php

/**
 * Description of client
 *
 * @author NaYeM
 */
require_once(APPPATH . 'third_party/elfinder/autoload.php');

class Client extends Admin_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('client_model');
		$this->load->model('invoice_model');
		$this->load->model('estimates_model');
	}

	public function manage_client($id = NULL)
	{
		$data['title'] = lang('manage_client'); //Page title
		$data['page_title'] = lang('client');
		$data['page_description'] = lang('manage') . ' ' . lang('client');
		$data['header_actions'] = array(
			array(
				'label' => lang('new') . ' ' . lang('client'),
				'icon' => 'plus',
				'href' => base_url('admin/client/create_client/new'),
				'style' => 'primary',
			),
			array(
				'label' => lang('import') . ' ' . lang('client'),
				'icon' => 'upload',
				'href' => base_url('admin/client/import'),
				'style' => 'info',
			),
		);
		$data['header_filters'] = array();
		$data['page'] = lang('client');
		$data['active'] = 1;
		$data['dataTables'] = true;
		$data['datatable_preload'] = $this->capture_datatable_preload(function () {
			$this->clientList();
		});
		$data['subview'] = $this->load->view('admin/client/manage_client', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function create_client($id = NULL)
	{
		if (!empty($id)) {
			if (is_numeric($id)) {
				$data['active'] = 2;
				// get all Client info by client id
				$this->client_model->_table_name = "tbl_client"; //table name
				$this->client_model->_order_by = "client_id";
				$data['client_info'] = $this->client_model->get_by(array('client_id' => $id), TRUE);
				$edited = can_action('4', 'edited');
				if (empty($data['client_info']) || empty($edited)) {
					$type = "error";
					$message = "No Record Found";
					set_message($type, $message);
					redirect('admin/client/manage_client');
				}
			} else if ($id == 'new') {
				$data['active'] = 2;
			}
		} else {
			$data['active'] = 2;
		}
		$data['title'] = lang('manage_client'); //Page title
		$data['page'] = lang('client');

		// get all country
		$data['countries'] = get_all_countries();

		// get all currencies        
		$data['currencies'] = get_all_currencies();

		$data['assign_user'] = $this->client_model->allowed_user('4');

		if (!empty(staff())) {
			$data['showing_created'] = true;
		}
		// get all language
		$data['languages'] = $this->db->where('active', 1)->order_by('name', 'ASC')->get('tbl_languages')->result();


		// of modal page
		if ($this->input->is_ajax_request()) {
			$this->load->view('admin/client/create_client', $data);
		} else {
			$data['subview'] = $this->load->view('admin/client/create_client', $data, TRUE);
			$this->load->view('admin/_layout_main', $data); //page load
		}
	}

	public function clientList($type = null)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_client';
			$this->datatables->join_table = array('tbl_customer_group', 'tbl_account_details');
			$this->datatables->join_where = array('tbl_customer_group.customer_group_id=tbl_client.customer_group_id', 'tbl_account_details.user_id=tbl_client.primary_contact');
			$custom_field = custom_form_table_search(12);
			$main_column = array('tbl_client.name', 'tbl_client.email', 'tbl_account_details.fullname', 'short_note', 'website', 'tbl_customer_group.customer_group');
			$action_array = array('tbl_client.client_id');
			$result = array_merge($main_column, $custom_field, $action_array);
			$this->datatables->column_order = $result;
			$this->datatables->column_search = $result;

			$this->datatables->order = array('client_id' => 'desc');
			// get all invoice
			if (!empty($type)) {
				$where = array('tbl_client.customer_group_id' => $type);
			} else {
				$where = null;
			}

			$fetch_data = $this->datatables->get_datatable_permission($where);


			$data = array();
			$edited = can_action('4', 'edited');
			$deleted = can_action('4', 'deleted');
			foreach ($fetch_data as $_key => $client_details) {
				$action = null;
				$client_transactions = $this->db->select_sum('amount')->where(array('type' => 'Expense', 'paid_by' => $client_details->client_id))->get('tbl_transactions')->result();
				$customer_group = $this->db->where('customer_group_id', $client_details->customer_group_id)->get('tbl_customer_group')->row();

				$client_outstanding = $this->invoice_model->client_outstanding($client_details->client_id);

				$sub_array = array();
				if (!empty($deleted)) {
					$sub_array[] = '<div class="checkbox c-checkbox" ><label class="needsclick"> <input value="' . $client_details->client_id . '" type="checkbox"></label></div>';
				}
				$name = null;
				$name .= '<a class="text-info text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/client/details/' . $client_details->client_id . '">' . (!empty($client_details->name) ? $client_details->name : '-') . '</a>';
				$sub_array[] = $name;

				$contacts = null;
				$contacts .= '<span class="label label-success" data-toggle="tooltip" data-palcement="top" title="' . lang('contacts') . '" >' . $this->client_model->count_rows('tbl_account_details', array('company' => $client_details->client_id)) . '</a>';
				$sub_array[] = $contacts;
				$sub_array[] = $client_details->fullname;

				$sub_array[] = $this->db->where('client_id', $client_details->client_id)->count_all_results('tbl_project');
				if ($client_outstanding > 0) {
					$due_amount = display_money($client_outstanding, client_currency($client_details->client_id));
				} else {
					$due_amount = '0.00';
				}
				$sub_array[] = $due_amount;
				$sub_array[] = display_money($this->client_model->client_paid($client_details->client_id), client_currency($client_details->client_id));
				if ($client_transactions[0]->amount > 0) {
					$paid_amount = display_money($client_transactions[0]->amount, client_currency($client_details->client_id));
				} else {
					$paid_amount = '0.00';
				}
				$sub_array[] = $paid_amount;
				$sub_array[] = (!empty($customer_group->customer_group) ? '<span class="tags">' . $customer_group->customer_group . '</span>' : '-');

				$custom_form_table = custom_form_table(12, $client_details->client_id);
				if (!empty($custom_form_table)) {
					foreach ($custom_form_table as $c_label => $v_fields) {
						$sub_array[] = $v_fields;
					}
				}

				if (!empty($edited)) {
					$action .= btn_edit('admin/client/create_client/' . $client_details->client_id) . ' ';
				}
				if (!empty($deleted)) {
					$action .= btn_delete('admin/client/delete_client/' . $client_details->client_id, '', 'trash-2') . ' ';
				}
				$action .= btn_view('admin/client/details/' . $client_details->client_id) . ' ';

				$sub_array[] = $action;
				$data[] = $sub_array;
			}

			render_table($data, $where);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function change_client_status($id = null)
	{
		$edited = can_action('4', 'edited');
		if (empty($edited)) {
			$type = "error";
			$message = "No Record Found";
			echo json_encode(array("status" => $type, "message" => $message));
			exit();
		}
		$data['active'] = $this->input->post('active', true);
		$this->client_model->_table_name = 'tbl_client';
		$this->client_model->_primary_key = "client_id";
		$this->client_model->save($data, $id);
		// save into activities
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'client',
			'module_field_id' => $id,
			'activity' => 'activity_change_status',
			'icon' => 'fa-ticket',
			'value1' => $data['active'],
		);
		// Update into tbl_project
		$this->client_model->_table_name = "tbl_activities"; //table name
		$this->client_model->_primary_key = "activities_id";
		$this->client_model->save($activities);
		$type = "success";
		$message = lang('update_client_status');
		echo json_encode(array("status" => $type, "message" => $message));
		exit();
	}

	public function searchByGroup($id = NULL)
	{
		$data['active'] = 1;
		$data['title'] = lang('manage_client'); //Page title
		$data['page'] = lang('client');

		// get all country
		$this->client_model->_table_name = "tbl_countries"; //table name
		$this->client_model->_order_by = "id";
		$data['countries'] = $this->client_model->get();

		// get all currencies
		$this->client_model->_table_name = 'tbl_currencies';
		$this->client_model->_order_by = 'name';
		$data['currencies'] = $this->client_model->get();
		// get all language
		$data['languages'] = $this->db->where('active', 1)->order_by('name', 'ASC')->get('tbl_languages')->result();

		$data['all_client_info'] = $this->db->where('customer_group_id', $id)->get('tbl_client')->result();

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

	public function import()
	{
		$data['title'] = lang('import') . ' ' . lang('client');
		// get all country
		$this->client_model->_table_name = "tbl_countries"; //table name
		$this->client_model->_order_by = "id";
		$data['countries'] = $this->client_model->get();

		// get all currencies
		$this->client_model->_table_name = 'tbl_currencies';
		$this->client_model->_order_by = 'name';
		$data['currencies'] = $this->client_model->get();
		// get all language
		$data['languages'] = $this->db->where('active', 1)->order_by('name', 'ASC')->get('tbl_languages')->result();

		$data['assign_user'] = $this->client_model->allowed_user('4');
		if (!empty(staff())) {
			$data['showing_created'] = true;
		}

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

	public function save_imported()
	{
		$created = can_action('4', 'created');
		if (!empty($created)) {
			if (empty($_FILES['upload_file']['tmp_name'])) {
				set_message('error', lang('choose_file') . ' Field is required');
				redirect('admin/client/import');
				return;
			}
			//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');
				return;
			}
			if (empty($files)) {
				set_message('error', lang('no_data_available'));
				redirect('admin/client/import');
				return;
			}
			$permission = $this->input->post('permission', true);
			if (!empty($permission)) {
				if ($permission == 'everyone') {
					$assigned = 'all';
				} else {
					$assigned_to = $this->client_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';
				}
			} else {
				$assigned = 'all';
			}
			$data = $this->client_model->array_from_post(array('customer_group_id', 'vat', 'language', 'currency', 'country'));
			$my_data = array();
			foreach ($files as $key => $value) {
				$value = array_pad((array)$value, 18, '');
				if (trim((string)$value[0]) === '') {
					continue;
				}
				$data['name'] = trim((string)$value[0]);
				$data['email'] = trim((string)$value[1]);
				$data['short_note'] = trim((string)$value[2]);
				$data['phone'] = trim((string)$value[3]);
				$data['mobile'] = trim((string)$value[4]);
				$data['fax'] = trim((string)$value[5]);
				$data['city'] = trim((string)$value[6]);
				$data['zipcode'] = trim((string)$value[7]);
				$data['address'] = trim((string)$value[8]);
				$data['skype_id'] = trim((string)$value[9]);
				$data['twitter'] = trim((string)$value[10]);
				$data['facebook'] = trim((string)$value[11]);
				$data['linkedin'] = trim((string)$value[12]);
				$data['hosting_company'] = trim((string)$value[13]);
				$data['hostname'] = trim((string)$value[14]);
				$data['username'] = trim((string)$value[15]);
				$data['password'] = trim((string)$value[16]);
				$data['port'] = trim((string)$value[17]);
				$data['permission'] = $assigned;
				$my_data[] = $data;
			}
			if (!empty($my_data)) {
				$this->db->insert_batch('tbl_client', $my_data);


				$action = ('activity_import_client');
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'client',
					// 'module_field_id' => '',
					'activity' => $action,
					'icon' => 'fa-user',
					'value1' => 'import_client' . $_FILES["upload_file"]['name']
				);
				$this->client_model->_table_name = 'tbl_activities';
				$this->client_model->_primary_key = "activities_id";
				$this->client_model->save($activities);
				$type = 'success';
				$message = "Client Information Successfully imported ";
			} else {
				$type = 'error';
				$message = lang('no_data_available');
			}
		} else {
			$type = 'error';
			$message = "You is no permission to access it ";
		}
		set_message($type, $message);
		redirect('admin/client/manage_client');
	}


	public function save_client($id = NULL)
	{
		$created = can_action('4', 'created');
		$edited = can_action('4', 'edited');
		if (!empty($created) || !empty($edited) && !empty($id)) {
			$data = $this->client_model->array_from_post(array(
				'name',
				'email',
				'short_note',
				'website',
				'phone',
				'mobile',
				'fax',
				'address',
				'city',
				'zipcode',
				'currency',
				'sms_notification',
				'skype_id',
				'linkedin',
				'facebook',
				'twitter',
				'language',
				'country',
				'vat',
				'hosting_company',
				'hostname',
				'port',
				'username',
				'latitude',
				'longitude',
				'customer_group_id'
			));

			$data['permission'] = permission_post();
			$password = $this->input->post('password', true);
			if (!empty($password)) {
				$data['password'] = encrypt($password);
			}

			if (!empty($_FILES['profile_photo']['name'])) {
				$val = $this->client_model->uploadImage('profile_photo');
				$val == TRUE || redirect('admin/client/manage_client');
				$data['profile_photo'] = $val['path'];
			}

			$this->client_model->_table_name = 'tbl_client';
			$this->client_model->_primary_key = "client_id";
			$return_id = $this->client_model->save($data, $id);
			if (!empty($id)) {
				$id = $id;
				$action = ('activity_update_company');
			} else {
				$id = $return_id;
				$action = ('activity_added_new_company');
			}
			save_custom_field(12, $id);

			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'client',
				'module_field_id' => $id,
				'activity' => $action,
				'icon' => 'fa-user',
				'value1' => $data['name']
			);
			$this->client_model->_table_name = 'tbl_activities';
			$this->client_model->_primary_key = "activities_id";
			$this->client_model->save($activities);
			// messages for user
			$type = "success";
			$message = lang('client_updated');
			set_message($type, $message);
		}
		$save_and_create_contact = $this->input->post('save_and_create_contact', true);
		if (!empty($save_and_create_contact)) {
			redirect('admin/client/details/' . $id . '/contacts');
		} else {
			redirect('admin/client/manage_client');
		}
	}

	public function see_password($type = null)
	{

		$data['title'] = lang('see_password');
		$data['ids'] = null;
		$data['password'] = null;
		if (!empty($type) && !is_numeric($type)) {
			$ex = explode('_', $type);
			if ($ex[0] == 'c') {
				$data['password'] = get_row('tbl_client', array('client_id' => $ex[1]), 'password');
			} elseif ($ex[0] == 'smtp') {
				$data['password'] = config_item('smtp_pass');
			} elseif ($ex[0] == 'emin') {
				$data['password'] = config_item('config_password');
			} elseif ($ex[0] == 'timap') {
				$data['password'] = get_row('tbl_departments', array('departments_id' => $ex[1]), 'password');
				$data['ids'] = $ex[1];
			} elseif ($ex[0] == 'paypalpassword') {
				$data['password'] = config_item('paypal_api_password');
			} else {
				$data['password'] = config_item($type);
			}
		}
		$this->load->view('admin/settings/see_password', $data, FALSE);
		// $this->load->view('admin/_layout_modal', $data);
	}

	public function customer_group()
	{
		$data['title'] = lang('customer_group');
		if ($this->input->is_ajax_request()) {
			$this->load->view('admin/client/customer_group', $data);
			return;
		}
		$data['subview'] = $this->load->view('admin/client/customer_group', $data, TRUE);
		$this->load->view('admin/_layout_main', $data);
	}

	public function update_customer_group($id = null)
	{
		if (!$this->input->is_ajax_request()) {
			redirect('admin/dashboard');
		}
		$this->client_model->_table_name = 'tbl_customer_group';
		$this->client_model->_primary_key = 'customer_group_id';

		$cate_data['customer_group'] = $this->input->post('customer_group', TRUE);
		$cate_data['description'] = $this->input->post('description', TRUE);
		$type = $this->input->post('type', TRUE);
		if (!empty($type)) {
			$cate_data['type'] = $type;
		} else {
			$cate_data['type'] = 'client';
		}
		// update root category
		$where = array('type' => $cate_data['type'], 'customer_group' => $cate_data['customer_group']);
		// duplicate value check in DB
		if (!empty($id)) { // if id exist in db update data
			$customer_group_id = array('customer_group_id !=' => $id);
		} else { // if id is not exist then set id as null
			$customer_group_id = null;
		}
		// check whether this input data already exist or not
		$check_category = $this->client_model->check_update('tbl_customer_group', $where, $customer_group_id);
		if (!empty($check_category)) { // if input data already exist show error alert
			// massage for user
			$type = 'error';
			$msg = "<strong style='color:#000'>" . $cate_data['customer_group'] . '</strong>  ' . lang('already_exist');
		} else { // save and update query
			$id = $this->client_model->save($cate_data, $id);
			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'settings',
				'module_field_id' => $id,
				'activity' => ('customer_group_added'),
				'value1' => $cate_data['customer_group']
			);
			$this->client_model->_table_name = 'tbl_activities';
			$this->client_model->_primary_key = 'activities_id';
			$this->client_model->save($activity);

			// messages for user
			$type = "success";
			$msg = lang('customer_group_added');
		}
		if (!empty($id)) {
			$result = array(
				'id' => $id,
				'group' => $cate_data['customer_group'],
				'status' => $type,
				'message' => $msg,
			);
		} else {
			$result = array(
				'status' => $type,
				'message' => $msg,
			);
		}
		echo json_encode($result);
		exit();
	}


	public function details($id, $action = null)
	{
		$data['id'] = $id;
		$data['perm'] = '4';
		$data['module'] = 'client';
		$data['redirect'] = 'client/details';
		$data['table'] = 'tbl_client';
		if (empty($action)) {
			$data['active'] = 'details';
		} else {
			$data['active'] = $action;
		}
		$data['dataTables'] = true;

		$data['all_tabs'] = client_details_tabs($id, 'segmented');

		$data['connector'] = base_url('admin/client/elfinder_init/' . $id);
		$data['title'] = "View Client Details"; //Page title
		// get all client details
		$data['client_details'] = get_row('tbl_client', array('client_id' => $id));
		$data['client_summary'] = $this->get_client_summary($id);
		$data['client_tab_data'] = $this->get_client_tab_data($id, $data['active']);
		$data['page_title'] = !empty($data['client_details']->name) ? $data['client_details']->name : lang('client');
		$client_email = !empty($data['client_details']->email) ? $data['client_details']->email : lang('no_email');
		$client_phone = !empty($data['client_details']->phone) ? $data['client_details']->phone : lang('no_phone');
		$data['page_description'] = $client_email . ' . ' . $client_phone;
		$data['header_badge'] = array(
			'label' => !empty($data['client_details']->client_no) ? $data['client_details']->client_no : ('#' . $id),
			'tone' => 'primary',
		);
		$data['header_actions'] = array(
			array(
				'label' => lang('edit'),
				'icon' => 'pencil',
				'href' => base_url('admin/client/create_client/' . $data['client_details']->client_id),
			),
		);
		$client_tab_labels = array(
			'details' => lang('details'),
			'contacts' => lang('contacts'),
			'notes' => lang('notes'),
			'invoices' => lang('invoices'),
			'payments' => lang('payments'),
			'estimates' => lang('estimates'),
			'proposals' => lang('proposals'),
			'transactions' => lang('transactions'),
			'projects' => lang('projects'),
			'tickets' => lang('tickets'),
			'contracts' => lang('contracts'),
			'bugs' => lang('bugs'),
			'award_point' => lang('award_point'),
			'filemanager' => lang('file_manager'),
			'map' => lang('map'),
		);
		$client_filter_items = array();
		foreach ($data['all_tabs'] as $tab) {
			if (!is_array($tab) || empty($tab['name']) || empty($tab['url'])) {
				continue;
			}
			$client_filter_items[] = array(
				'label' => isset($client_tab_labels[$tab['name']]) ? $client_tab_labels[$tab['name']] : ucfirst(str_replace('_', ' ', $tab['name'])),
				'icon' => !empty($tab['icon']) ? $tab['icon'] : 'chevron-right',
				'href' => base_url($tab['url']),
				'active' => $data['active'] === $tab['name'],
				'meta' => isset($tab['count']) && $tab['count'] !== '' ? (string) $tab['count'] : null,
			);
		}
		$data['header_filters'] = array(
			array(
				'label' => lang('more_actions'),
				'icon' => 'ellipsis',
				'active' => true,
				'items' => $client_filter_items,
			),
		);
		$data['subview'] = $this->load->view('admin/client/client_details', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	private function get_client_summary($client_id)
	{
		$client_id = (int) $client_id;
		if (empty($client_id)) {
			return array(
				'payments_total' => 0,
				'outstanding_total' => 0,
				'payable_total' => 0,
				'paid_percent' => 0,
				'currency_symbol' => default_currency(),
			);
		}

		$cache_key = 'client_summary_' . $client_id;
		$cached = function_exists('helper_cache_get') ? helper_cache_get($cache_key) : false;
		if ($cached !== false) {
			return $cached;
		}

		$payments_total = (float) $this->invoice_model->get_sum('tbl_payments', 'amount', array('paid_by' => $client_id));
		$outstanding_total = (float) $this->invoice_model->client_outstanding($client_id);
		$payable_total = $payments_total + $outstanding_total;
		$client_currency = $this->invoice_model->client_currency_symbol($client_id);
		if (!empty($client_currency) && !empty($client_currency->symbol)) {
			$currency_symbol = $client_currency->symbol;
		} else {
			$currency = get_row('tbl_currencies', array('code' => config_item('default_currency')));
			$currency_symbol = !empty($currency->symbol) ? $currency->symbol : default_currency();
		}

		if ($payable_total > 0 && $payments_total > 0) {
			$paid_percent = round(($payments_total / $payable_total) * 100, 1);
			if ($paid_percent > 100) {
				$paid_percent = 100;
			}
		} else {
			$paid_percent = 0;
		}

		$result = array(
			'payments_total' => $payments_total,
			'outstanding_total' => $outstanding_total,
			'payable_total' => $payable_total,
			'paid_percent' => $paid_percent,
			'currency_symbol' => $currency_symbol,
		);

		if (function_exists('helper_cache_save')) {
			helper_cache_save($cache_key, $result, 60);
		}

		return $result;
	}

	private function get_client_tab_data($client_id, $active_tab)
	{
		$client_id = (int) $client_id;
		$active_tab = (string) $active_tab;
		if (empty($client_id) || empty($active_tab)) {
			return array();
		}

		$cache_key = 'client_tab_data_' . $client_id . '_' . $active_tab;
		$cached = function_exists('helper_cache_get') ? helper_cache_get($cache_key) : false;
		if ($cached !== false) {
			return $cached;
		}

		$data = array();
		switch ($active_tab) {
			case 'payments':
				$data['payments'] = get_result('tbl_payments', array('paid_by' => $client_id));
				$data['payments_total'] = 0;
				if (!empty($data['payments'])) {
					foreach ($data['payments'] as $payment) {
						$data['payments_total'] += (float) $payment->amount;
					}
				}
				break;

			case 'tickets':
				$data['tickets'] = $this->db
					->select('tbl_tickets.*')
					->from('tbl_tickets')
					->join('tbl_account_details', 'tbl_account_details.user_id = tbl_tickets.reporter', 'left')
					->where('tbl_account_details.company', $client_id)
					->order_by('tbl_tickets.tickets_id', 'DESC')
					->get()
					->result();
				break;

			case 'bugs':
				$data['bugs'] = $this->db
					->select('tbl_bug.*')
					->from('tbl_bug')
					->join('tbl_account_details', 'tbl_account_details.user_id = tbl_bug.reporter', 'left')
					->where('tbl_account_details.company', $client_id)
					->order_by('tbl_bug.bug_id', 'DESC')
					->get()
					->result();
				break;

			case 'invoices':
				$data['invoices'] = $this->db
					->where('client_id', $client_id)
					->order_by('invoices_id', 'DESC')
					->get('tbl_invoices')
					->result();
				$data['invoice_total'] = 0;
				if (!empty($data['invoices'])) {
					foreach ($data['invoices'] as $invoice) {
						$payable = (float) $this->invoice_model->invoice_payable($invoice->invoices_id);
						$invoice->payable_total = $payable;
						$data['invoice_total'] += $payable;
					}
				}
				break;

			case 'transactions':
				$data['transactions'] = $this->db
					->where('paid_by', $client_id)
					->order_by('transactions_id', 'DESC')
					->get('tbl_transactions')
					->result();
				$data['currency'] = client_currency($client_id);
				break;

			case 'projects':
				$data['projects'] = get_result('tbl_project', array('client_id' => $client_id));
				break;

			case 'estimates':
				$data['estimates'] = get_result('tbl_estimates', array('client_id' => $client_id));
				$data['estimate_total'] = 0;
				if (!empty($data['estimates'])) {
					foreach ($data['estimates'] as $estimate) {
						$total = (float) $this->estimates_model->estimate_calculation('total', $estimate->estimates_id);
						$estimate->display_total = $total;
						$data['estimate_total'] += $total;
					}
				}
				break;

			case 'proposals':
				$data['proposals'] = get_result('tbl_proposals', array('module' => 'client', 'module_id' => $client_id));
				break;

			case 'contracts':
				$data['contracts'] = array();
				if ($this->db->table_exists('tbl_contracts')) {
					$data['contracts'] = get_result('tbl_contracts', array('client_id' => $client_id));
				}
				break;
		}

		if (function_exists('helper_cache_save')) {
			helper_cache_save($cache_key, $data, 60);
		}

		return $data;
	}


	public function contactList($id)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_account_details';
			$this->datatables->column_order = array('fullname', 'email', 'phone', 'mobile', 'address', 'city', 'zipcode');
			$this->datatables->column_search = array('fullname', 'email', 'phone', 'mobile', 'address', 'city', 'zipcode');
			$this->datatables->order = array('user_id' => 'desc');
			// get all invoice
			$fetch_data = $this->client_model->get_client_contacts($id);

			$client_details = get_row('tbl_client', array('client_id' => $id));

			$data = array();
			foreach ($fetch_data as $_key => $contact) {
				$action = null;
				$sub_array = array();
				$name = null;
				$name .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/user/user_details/' . $contact->user_id . '">' . $contact->fullname . '</a>';
				$sub_array[] = $name;

				$sub_array[] = $contact->email;
				$sub_array[] = '<a href="tel:' . $contact->phone . '">' . $contact->phone . '</a>';
				$sub_array[] = '<a href="tel:' . $contact->mobile . '">' . $contact->mobile . '</a>';
				$sub_array[] = '<a href="skype:' . $contact->skype . '?call">' . $contact->skype . '</a>';

				if (!empty($contact->online_time)) {
					$login_time = time_ago($contact->online_time);
				} else {
					$login_time = lang('never');
				}
				$sub_array[] = $login_time;

				$action .= '<a href="' . base_url() . 'admin/client/make_primary/' . $contact->user_id . '/' . $id . '" data-toggle="tooltip" class="btn ' . (($client_details->primary_contact == $contact->user_id) ? "btn-success" : "btn-default") . ' btn-xs " title="' . lang('primary_contact') . '"><i data-lucide="link"></i> </a>' . ' ';
				$action .= btn_edit('admin/client/details/' . $client_details->client_id . '/contacts/add_contacts/' . $contact->user_id) . ' ';
				$action .= ajax_anchor(base_url('admin/client/delete_contacts/' . $client_details->client_id . '/' . $contact->user_id), lang('delete'), array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';

				$sub_array[] = $action;
				$data[] = $sub_array;
			}

			render_table($data);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function invoiceList($id)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_invoices';
			$this->datatables->column_order = array('reference_no', 'date_saved', 'due_date');
			$this->datatables->column_search = array('reference_no', 'date_saved', 'due_date');
			$this->datatables->order = array('user_id' => 'desc');
			// get all invoice
			$fetch_data = get_result('tbl_invoices', array('client_id' => $id));

			$data = array();
			foreach ($fetch_data as $_key => $invoice) {
				$action = null;
				$sub_array = array();
				$name = null;
				$name .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/invoice/manage_invoice/invoice_details/' . $invoice->invoices_id . '">' . $invoice->reference_no . '</a>';
				$sub_array[] = $name;

				$sub_array[] = display_date($invoice->date_saved);
				$sub_array[] = display_date($invoice->due_date);

				$sub_array[] = display_money($this->invoice_model->invoice_payable($invoice->invoices_id), client_currency($id));
				$data[] = $sub_array;
			}
			render_table($data);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function notesList($id)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_notes';
			$this->datatables->column_order = array('notes', 'added_by', 'added_date');
			$this->datatables->column_search = array('notes', 'added_by', 'added_date');
			$this->datatables->order = array('notes_id' => 'desc');
			// get all invoice
			$fetch_data = $this->db->where(array('user_id' => $id, 'is_client' => 'Yes'))->get('tbl_notes')->result();

			$data = array();
			foreach ($fetch_data as $_key => $v_notes) {
				$n_user = $this->db->where('user_id', $v_notes->added_by)->get('tbl_users')->row();
				if (empty($n_user)) {
					$n_user->fullname = '-';
					$n_url = '#';
				} else {
					$n_url = base_url() . 'admin/user/user_details/' . $n_user->user_id;
				}

				$action = null;
				$sub_array = array();
				$name = null;
				$name .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/client/details/' . $id . '/notes/' . $v_notes->notes_id . '">' . $v_notes->notes . '</a>';
				$sub_array[] = $name;

				$sub_array[] = '<a href="' . $n_url . '">' . $n_user->username . '</a>';
				$sub_array[] = display_date($v_notes->added_date) . ' ' . display_time($v_notes->added_date);

				$action .= btn_edit('admin/client/details/' . $id . '/notes/' . $v_notes->notes_id) . ' ';
				$action .= ajax_anchor(base_url('admin/client/delete_notes/' . $v_notes->notes_id . '/' . $id), lang('delete'), array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
				$sub_array[] = $action;
				$data[] = $sub_array;
			}

			render_table($data);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function paymentsList($id)
	{
		if ($this->input->is_ajax_request()) {
			$this->load->model('datatables');
			$this->datatables->table = 'tbl_payments';
			$this->datatables->column_order = array('payment_date', 'invoices_id', 'amount');
			$this->datatables->column_search = array('payment_date', 'invoices_id', 'amount');
			$this->datatables->order = array('payments_id' => 'desc');
			// get all invoice
			$fetch_data = $this->db
				->where('paid_by', $id)
				->order_by('created_date', 'desc')
				->get('tbl_payments')
				->result();;

			$data = array();
			foreach ($fetch_data as $_key => $v_paid) {

				$invoice_info = $this->db->where(array('invoices_id' => $v_paid->invoices_id))->get('tbl_invoices')->row();
				if (is_numeric($v_paid->payment_method)) {
					$payment_methods = get_row('tbl_payment_methods', array('payment_methods_id' => $v_paid->payment_method));
				} else {
					$payment_methods->method_name = $v_paid->payment_method;
				}

				if ($v_paid->payment_method == '1') {
					$label = 'success';
				} elseif ($v_paid->payment_method == '2') {
					$label = 'danger';
				} else {
					$label = 'dark';
				}
				$action = null;
				$sub_array = array();
				$name = null;
				$name .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/invoice/manage_invoice/payments_details/' . $v_paid->payments_id . '">' . display_date($v_paid->payment_date) . '</a>';
				$sub_array[] = $name;

				$sub_array[] = display_date($invoice_info->date_saved);
				$invoice = null;
				$invoice .= '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/invoice/manage_invoice/invoice_details/' . $v_paid->invoices_id . '">' . $invoice_info->reference_no . '</a>';
				$sub_array[] = $invoice;

				$sub_array[] = display_money($v_paid->amount, client_currency($id));
				$sub_array[] = '<span class="label label-' . $label . '">' . !empty($payment_methods->method_name) ? $payment_methods->method_name : '-' . '</span>';

				$action .= btn_edit('admin/invoice/all_payments/' . $v_paid->payments_id) . ' ';
				$action .= btn_view('admin/invoice/manage_invoice/payments_details/' . $v_paid->payments_id) . ' ';
				$action .= ajax_anchor(base_url("admin/invoice/delete/delete_payment/$v_paid->payments_id"), lang('delete'), array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
				$action .= '<a data-toggle="tooltip" data-placement="top"
                                                   href="' . base_url() . 'admin/invoice/send_payment/' . $v_paid->payments_id . '/' . $v_paid->amount . '"
                                                   title="' . lang('send_email') . '"
                                                   class="btn btn-xs btn-success">
                                                    <i data-lucide="mail"></i> </a>' . ' ';

				$sub_array[] = $action;
				$data[] = $sub_array;
			}

			render_table($data);
		} else {
			redirect('admin/dashboard');
		}
	}

	public function elfinder_init($client_id)
	{
		$this->load->helper('path');
		$_allowed_files = explode('|', config_item('allowed_files'));
		$config_allowed_files = array();
		if (is_array($_allowed_files)) {
			foreach ($_allowed_files as $v_extension) {
				array_push($config_allowed_files, '.' . $v_extension);
			}
		}
		$allowed_files = array();
		if (is_array($config_allowed_files)) {
			foreach ($config_allowed_files as $extension) {
				$_mime = get_mime_by_extension($extension);
				if ($_mime == 'application/x-zip') {
					array_push($allowed_files, 'application/zip');
				}
				if ($extension == '.exe') {
					array_push($allowed_files, 'application/x-executable');
					array_push($allowed_files, 'application/x-msdownload');
					array_push($allowed_files, 'application/x-ms-dos-executable');
				}
				array_push($allowed_files, $_mime);
			}
		}
		$client_info = $this->db->where('client_id', $client_id)->get('tbl_client')->row();
		if (empty($client_info)) {
			show_error('Client file manager is not available for this record.', 404);
		}

		$c_slug = $this->safe_media_slug($client_info->name, 'client-' . $client_id);
		$path = $this->ensure_filemanager_directory('filemanager/' . $c_slug);
		$root_options = array(
			'dispInlineRegex' => '^(?:image|application/(?:vnd\.)?(?:ms(?:-office|word|-excel|-powerpoint)|openxmlformats-officedocument)|text/plain$)',
			'driver' => 'LocalFileSystem',
			'path' => $path,
			'URL' => site_url('filemanager/' . $c_slug) . '/',
			'uploadMaxSize' => config_item('max_file_size') . 'M',
			'accessControl' => 'access',
			'uploadAllow' => $allowed_files,
			'uploadDeny' => [
				'application/x-httpd-php',
				'application/php',
				'application/x-php',
				'text/php',
				'text/x-php',
				'application/x-httpd-php-source',
				'application/perl',
				'application/x-perl',
				'application/x-python',
				'application/python',
				'application/x-bytecode.python',
				'application/x-python-bytecode',
				'application/x-python-code',
				'wwwserver/shellcgi', // CGI
			],
			'uploadOrder' => array(
				'allow',
				'deny'
			),
			'attributes' => array(
				array(
					'pattern' => '/.tmb/',
					'hidden' => true
				),
				array(
					'pattern' => '/.quarantine/',
					'hidden' => true
				)
			)
		);

		$client_contacts = $this->client_model->get_client_contacts($client_id);
		if (!empty($client_contacts)) {
			foreach ($client_contacts as $contact) {
				if (empty($contact->media_path_slug)) {
					$this->db->where('user_id', $contact->user_id);
					$slug = $this->safe_media_slug($contact->username, 'user-' . $contact->user_id);
					$this->db->update('tbl_users', array(
						'media_path_slug' => $slug
					));
					$contact->media_path_slug = $slug;
				}

				$contact_slug = $this->safe_media_slug($contact->media_path_slug, 'user-' . $contact->user_id);
				$this->ensure_filemanager_directory('filemanager/' . $c_slug . '/' . $contact_slug);
				array_push($root_options['attributes'], array(
					'pattern' => '/.(' . preg_quote($contact_slug, '/') . '+)/', // Prevent deleting/renaming folder
					'read' => true,
					'write' => true,
				));
			}
		}

		array_push($root_options['attributes'], array(
			'pattern' => '/.(' . preg_quote($c_slug, '/') . '+)/', // Prevent deleting/renaming the client root
			'read' => true,
			'write' => true,
			'locked' => true,
		));

		$opts = array(
			'roots' => array(
				$root_options
			)
		);

		$connector = new elFinderConnector(new elFinder($opts));
		$connector->run();
	}

	private function safe_media_slug($value, $fallback)
	{
		$slug = trim((string) slug_it((string) $value));
		if ($slug === '') {
			$slug = trim((string) slug_it((string) $fallback));
		}
		return $slug !== '' ? $slug : 'files';
	}

	private function ensure_filemanager_directory($relative_path)
	{
		$path = set_realpath($relative_path);
		if (!is_dir($path)) {
			mkdir($path, 0755, true);
		}
		if (!file_exists($path . '/index.html')) {
			fclose(fopen($path . '/index.html', 'w'));
		}
		return set_realpath($relative_path);
	}

	public function save_contact($id = NULL)
	{
		$data = $this->client_model->array_from_post(array('fullname', 'company', 'phone', 'mobile', 'skype', 'language', 'locale', 'direction'));
		$data['fullname'] = trim((string) ($data['fullname'] ?? ''));
		$data['company'] = (int) ($data['company'] ?? 0);
		$redirect_url = $this->input->post('r_url', TRUE);
		if (empty($redirect_url)) {
			$redirect_url = !empty($data['company'])
				? 'admin/client/details/' . $data['company'] . '/contacts'
				: 'admin/client/manage_client';
		}
		$message = array('error' => array());
		$user_id = null;
		$return_id = null;

		if (empty($data['company'])) {
			$message['error'][] = lang('client') . ' is required';
		}
		if ($data['fullname'] === '') {
			$message['error'][] = lang('full_name') . ' is required';
		}

		if (!empty($id)) {
			$id = (int) $id;
			$u_data['email'] = $this->input->post('email', TRUE);
			$u_data['username'] = $this->input->post('username', TRUE);
			$u_data['last_ip'] = $this->input->ip_address();
			$u_data['email'] = trim((string) $u_data['email']);
			$u_data['username'] = trim((string) $u_data['username']);
			$password = (string) $this->input->post('password', TRUE);
			$confirm_password = (string) $this->input->post('confirm_password', TRUE);

			if ($u_data['email'] === '') {
				$message['error'][] = lang('email') . ' is required';
			}
			if ($u_data['username'] === '') {
				$message['error'][] = lang('username') . ' is required';
			}
			$check_email = $this->db->where('email', $u_data['email'])->where('user_id !=', $id)->get('tbl_users')->row();
			if (!empty($check_email)) {
				$message['error'][] = lang('this_email_already_exist');
			}
			$check_username = $this->db->where('username', $u_data['username'])->where('user_id !=', $id)->get('tbl_users')->row();
			if (!empty($check_username)) {
				$message['error'][] = lang('this_username_already_exist');
			}
			if ($password !== '' || $confirm_password !== '') {
				if ($password !== $confirm_password) {
					$message['error'][] = lang('password_does_not_macth');
				} else {
					$u_data['password'] = $this->hash($password);
				}
			}

			$acount_info = $this->client_model->check_by(array('user_id' => $id), 'tbl_account_details');
			if (empty($acount_info)) {
				$message['error'][] = lang('no_record_found');
			}

			if (empty($message['error'])) {
				$this->client_model->_table_name = 'tbl_users';
				$this->client_model->_primary_key = 'user_id';
				$user_id = $this->client_model->save($u_data, $id);
				$data['user_id'] = $user_id;

				$this->client_model->_table_name = 'tbl_account_details';
				$this->client_model->_primary_key = 'account_details_id';
				$return_id = $this->client_model->save($data, $acount_info->account_details_id);

				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'client',
					'module_field_id' => $data['company'],
					'activity' => ('activity_update_contact'),
					'icon' => 'fa-user',
					'value1' => $data['fullname']
				);
				$this->client_model->_table_name = 'tbl_activities';
				$this->client_model->_primary_key = "activities_id";
				$this->client_model->save($activities);
				if (!empty($u_data['password']) && $this->input->post('send_email_password', true) == 'on') {
					$this->send_confirmation_email($u_data, $password);
				}
			}
		} else {
			$user_data = $this->client_model->array_from_post(array('email', 'username', 'password'));
			$user_data['email'] = trim((string) ($user_data['email'] ?? ''));
			$user_data['username'] = trim((string) ($user_data['username'] ?? ''));
			$user_data['password'] = (string) ($user_data['password'] ?? '');
			$confirm_password = (string) $this->input->post('confirm_password', TRUE);
			$u_data['last_ip'] = $this->input->ip_address();

			if ($user_data['email'] === '') {
				$message['error'][] = lang('email') . ' is required';
			}
			if ($user_data['username'] === '') {
				$message['error'][] = lang('username') . ' is required';
			}
			if ($user_data['password'] === '') {
				$message['error'][] = lang('password') . ' is required';
			}

			$check_email = !empty($user_data['email']) ? $this->client_model->check_by(array('email' => $user_data['email']), 'tbl_users') : null;
			$check_username = !empty($user_data['username']) ? $this->client_model->check_by(array('username' => $user_data['username']), 'tbl_users') : null;

			if ($user_data['password'] === $confirm_password) {
				$u_data['password'] = $this->hash($user_data['password']);

				if (!empty($check_username)) {
					$message['error'][] = lang('this_username_already_exist');
				} else {
					$u_data['username'] = $user_data['username'];
				}
				if (!empty($check_email)) {
					$message['error'][] = lang('this_email_already_exist');
				} else {
					$u_data['email'] = $user_data['email'];
				}
			} else {
				$message['error'][] = lang('password_does_not_macth');
			}

			if (empty($message['error']) && !empty($u_data['password']) && !empty($u_data['username']) && !empty($u_data['email'])) {
				$u_data['role_id'] = $this->input->post('role_id', true);
				if (empty($u_data['role_id'])) {
					$u_data['role_id'] = 2;
				}
				$u_data['activated'] = '1';

				$this->client_model->_table_name = 'tbl_users';
				$this->client_model->_primary_key = 'user_id';
				$user_id = $this->client_model->save($u_data, $id);

				$data['user_id'] = $user_id;

				$this->client_model->_table_name = 'tbl_account_details';
				$this->client_model->_primary_key = 'account_details_id';
				$return_id = $this->client_model->save($data, $id);
				// check primary contact
				$primary_contact = $this->client_model->check_by(array('client_id' => $data['company']), 'tbl_client');

				if ($primary_contact->primary_contact == 0) {
					$c_data['primary_contact'] = $user_id;
					$this->client_model->_table_name = 'tbl_client';
					$this->client_model->_primary_key = 'client_id';
					$this->client_model->save($c_data, $data['company']);
				}
				if ($this->input->post('send_email_password', true) == 'on') {
					$this->send_confirmation_email($u_data, $user_data['password']); //send thank you email
				}
				//                $send_email_password = $this->input->post('send_email_password', true);
				//                if (!empty($send_email_password)) {
				//
				//                    $email_template = $this->client_model->check_by(array('email_group' => 'registration'), 'tbl_email_templates');
				//                    $SITE_URL = str_replace("{SITE_URL}", base_url(), $email_template->template_body);
				//                    $username = str_replace("{USERNAME}", $u_data['username'], $SITE_URL);
				//                    $user_email = str_replace("{EMAIL}", $u_data['email'], $username);
				//
				//                    $user_password = str_replace("{PASSWORD}", $user_data['password'], $user_email);
				//                    $message = str_replace("{SITE_NAME}", config_item('company_name'), $user_password);
				//
				//                    $params['recipient'] = $u_data['email'];
				//                    $params['subject'] = '[ ' . config_item('company_name') . ' ]' . ' ' . $email_template->subject;
				//                    $params['message'] = $message;
				//                    $params['resourceed_file'] = '';
				//
				//                    $this->client_model->send_email($params);
				//                }
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'client',
					'module_field_id' => $data['company'],
					'activity' => ('activity_added_new_contact'),
					'icon' => 'fa-user',
					'value1' => $data['fullname']
				);
				$this->client_model->_table_name = 'tbl_activities';
				$this->client_model->_primary_key = "activities_id";
				$this->client_model->save($activities);
			}
		}
		if (!empty($user_id) && empty($message['error'])) {
			$this->client_model->_table_name = 'tbl_client_role'; //table name
			$this->client_model->delete_multiple(array('user_id' => $user_id));

			$all_client_menu = $this->db->get('tbl_client_menu')->result();

			foreach ($all_client_menu as $v_client_menu) {
				$client_role_data['menu_id'] = $this->input->post($v_client_menu->label, true);
				if (!empty($client_role_data['menu_id'])) {
					$client_role_data['user_id'] = $user_id;
					$this->client_model->_table_name = 'tbl_client_role';
					$this->client_model->_primary_key = 'client_role_id';
					$this->client_model->save($client_role_data);
				}
			}
		}
		// messages for user
		if (!empty($message['error'])) {
			set_message('error', implode('<br>', $message['error']));
		} else {
			if (empty($return_id)) {
				set_message('error', lang('contact_information_successfully_update') . ' ' . lang('failed'));
			} else {
				$this->clear_client_contact_cache($data['company']);
				set_message('success', lang('contact_information_successfully_update'));
			}
		}
		redirect($redirect_url);
	}

	private function clear_client_contact_cache($client_id)
	{
		$client_id = (int) $client_id;
		if (empty($client_id) || empty($this->cache) || !method_exists($this->cache, 'delete')) {
			return;
		}
		$this->cache->delete('client_tab_data_' . $client_id . '_contacts');
		$this->cache->delete('client_summary_' . $client_id);
	}

	public function update_latitude($id)
	{
		$data = $this->client_model->array_from_post(array('latitude', 'longitude'));
		$this->client_model->_table_name = 'tbl_client';
		$this->client_model->_primary_key = "client_id";
		$this->client_model->save($data, $id);
		redirect('admin/client/details/' . $id . '/map');
	}

	function send_confirmation_email($u_data, $password)
	{
		$email_template = email_templates(array('email_group' => 'registration'));
		$SITE_URL = str_replace("{SITE_URL}", base_url(), $email_template->template_body);
		$username = str_replace("{USERNAME}", $u_data['username'], $SITE_URL);
		$user_email = str_replace("{EMAIL}", $u_data['email'], $username);

		$user_password = str_replace("{PASSWORD}", $password, $user_email);
		$message = str_replace("{SITE_NAME}", config_item('company_name'), $user_password);

		$params['recipient'] = $u_data['email'];
		$params['subject'] = '[ ' . config_item('company_name') . ' ]' . ' ' . $email_template->subject;
		$params['message'] = $message;
		$params['resourceed_file'] = '';

		$this->client_model->send_email($params);
	}

	public function make_primary($user_id, $client_id)
	{
		$user_info = $this->client_model->check_by(array('user_id' => $user_id), 'tbl_account_details');

		$this->db->set('primary_contact', $user_id);
		$this->db->where('client_id', $client_id)->update('tbl_client');
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'client',
			'module_field_id' => $client_id,
			'activity' => ('activity_primary_contact'),
			'icon' => 'fa-user',
			'value1' => $user_info->fullname
		);
		$this->client_model->_table_name = 'tbl_activities';
		$this->client_model->_primary_key = "activities_id";
		$this->client_model->save($activities);

		// messages for user
		$type = "success";
		$message = lang('primary_contact_set');
		set_message($type, $message);
		redirect('admin/client/details/' . $client_id);
	}

	public function bulk_delete()
	{
		$selected_id = $this->input->post('ids', true);
		if (!empty($selected_id)) {
			foreach ($selected_id as $client_id) {
				$result[] = $this->delete_client($client_id, true, 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_contacts($client_id, $id)
	{
		$sbtn = $this->input->post('submit', true);
		if (!empty($sbtn)) {
			// delete into user table by user id
			$this->client_model->_table_name = 'tbl_client';
			$this->client_model->_order_by = 'primary_contact';
			$primary_contact = $this->client_model->get_by(array('primary_contact' => $id), TRUE);
			if (!empty($primary_contact)) {
				// delete into user table by user id
				$this->client_model->_table_name = 'tbl_account_details';
				$this->client_model->_order_by = 'company';
				$client_info = $this->client_model->get_by(array('company' => $client_id), FALSE);
				$result = count(array($client_info));
				if ($result != '1') {
					$data['primary_contact'] = $client_info[1]->account_details_id;
				} else {
					$data['primary_contact'] = 0;
				}
				$this->client_model->_table_name = 'tbl_client';
				$this->client_model->_primary_key = 'primary_contact';
				$this->client_model->save($data, $client_id);
			}
			$user_info = $this->client_model->check_by(array('user_id' => $id), 'tbl_account_details');
			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'client',
				'module_field_id' => $id,
				'activity' => ('activity_deleted_contact'),
				'icon' => 'fa-user',
				'value1' => $user_info->fullname
			);
			$this->client_model->_table_name = 'tbl_account_details';
			$this->client_model->delete_multiple(array('user_id' => $id));

			$this->client_model->_table_name = 'tbl_activities';
			$this->client_model->delete_multiple(array('user' => $id));

			// delete all tbl_quotations by id
			$this->client_model->_table_name = 'tbl_quotations';
			$this->client_model->_order_by = 'user_id';
			$quotations_info = $this->client_model->get_by(array('user_id' => $id), FALSE);

			if (!empty($quotations_info)) {
				foreach ($quotations_info as $v_quotations) {
					$this->client_model->_table_name = 'tbl_quotation_details';
					$this->client_model->delete_multiple(array('quotations_id' => $v_quotations->quotations_id));
				}
			}
			$this->client_model->_table_name = 'tbl_quotations';
			$this->client_model->delete_multiple(array('user_id' => $id));

			$this->client_model->_table_name = 'tbl_quotationforms';
			$this->client_model->delete_multiple(array('quotations_created_by_id' => $id));
			$this->client_model->_table_name = 'tbl_users';
			$this->client_model->delete_multiple(array('user_id' => $id));


			$this->client_model->_table_name = 'tbl_inbox';
			$this->client_model->delete_multiple(array('user_id' => $id));

			$this->client_model->_table_name = 'tbl_sent';
			$this->client_model->delete_multiple(array('user_id' => $id));

			$this->client_model->_table_name = 'tbl_draft';
			$this->client_model->delete_multiple(array('user_id' => $id));

			$this->client_model->_table_name = 'tbl_tickets';
			$this->client_model->delete_multiple(array('reporter' => $id));

			$this->client_model->_table_name = 'tbl_tickets_replies';
			$this->client_model->delete_multiple(array('replierid' => $id));

			// messages for user
			$type = "success";
			$message = lang('delete_contact');
			$this->clear_client_contact_cache($client_id);
			set_message($type, $message);
			redirect('admin/client/details/' . $client_id . '/contacts');
		} else {
			$data['title'] = "Delete Client Contact"; //Page title
			$data['user_info'] = $this->db->where('user_id', $id)->get('tbl_account_details')->row();
			$data['client_id'] = $client_id;
			$data['subview'] = $this->load->view('admin/user/delete_user', $data, TRUE);
			$this->load->view('admin/_layout_main', $data); //page load
		}
	}

	public
	function delete_client($client_id, $yes = null, $bulk = null)
	{
		$deleted = can_action('4', 'deleted');
		$sbtn = $this->input->post('submit', true);
		if (!empty($bulk)) {
			$sbtn = true;
		}
			if (!empty($sbtn) && !empty($yes)) {
				if (!empty($deleted)) {
					$client_transactions = $this->db
						->select('transactions_id, date')
						->where('paid_by', $client_id)
						->get('tbl_transactions')
						->result();
					if (!empty($client_transactions)) {
						foreach ($client_transactions as $v_transaction) {
							if (!finance_accounting_period_is_open($v_transaction->date)) {
								$type = "error";
								$message = lang('accounting_period_closed');
								echo json_encode(array("status" => $type, 'message' => $message));
								exit();
							}
						}
					}

					// delete into user table by user id
					$this->client_model->_table_name = 'tbl_account_details';
				$this->client_model->_order_by = 'company';
				$client_info = $this->client_model->get_by(array('company' => $client_id), FALSE);
				if (!empty($client_info)) {
					foreach ($client_info as $v_client) {
						$cwhere = array('user_id' => $v_client->user_id);
						if ($this->db->table_exists('tbl_private_chat')) {
							$this->client_model->_table_name = 'tbl_private_chat';
							$this->client_model->delete_multiple($cwhere);
						}

						$this->client_model->_table_name = 'tbl_private_chat_users';
						$this->client_model->delete_multiple($cwhere);

						$this->client_model->_table_name = 'tbl_private_chat_messages';
						$this->client_model->delete_multiple($cwhere);

						$this->client_model->_table_name = 'tbl_activities';
						$this->client_model->delete_multiple(array('user' => $v_client->user_id));

						$this->client_model->_table_name = 'tbl_inbox';
						$this->client_model->delete_multiple(array('user_id' => $v_client->user_id));

						$this->client_model->_table_name = 'tbl_sent';
						$this->client_model->delete_multiple(array('user_id' => $v_client->user_id));

						$this->client_model->_table_name = 'tbl_draft';
						$this->client_model->delete_multiple(array('user_id' => $v_client->user_id));


						$account_info = get_row('tbl_account_details', array('user_id' => $v_client->user_id));
						if (!empty($account_info)) {

							$this->client_model->_table_name = 'tbl_client_role';
							$this->client_model->delete_multiple(array('user_id' => $v_client->user_id));
							//delete user roll id
							$this->client_model->_table_name = 'tbl_account_details';
							$this->client_model->delete_multiple(array('user_id' => $v_client->user_id)); //delete user roll id
						}
						$this->client_model->_table_name = 'tbl_users';
						$this->client_model->delete_multiple(array('user_id' => $v_client->user_id));
					}
				}

				// project
				// delete all leads by id
				$this->client_model->_table_name = 'tbl_project';
				$this->client_model->_order_by = 'client_id';
				$project_info = $this->client_model->get_by(array('client_id' => $client_id), FALSE);
				if (!empty($project_info)) {
					foreach ($project_info as $v_project) {
						//delete data into table.
						$this->client_model->_table_name = "tbl_task_comment"; // table name
						$this->client_model->delete_multiple(array('module_field_id' => $v_project->project_id, 'module' => 'projects'));

						$this->client_model->_table_name = "tbl_attachments"; //table name
						$this->client_model->_order_by = "module_field_id";
						$files_info = $this->client_model->get_by(array('module_field_id' => $v_project->project_id, 'module' => 'projects'), FALSE);
						if (!empty($files_info)) {
							foreach ($files_info as $v_files) {
								//save data into table.
								$this->client_model->_table_name = "tbl_attachments_files"; // table name
								$this->client_model->delete_multiple(array('attachments_id' => $v_files->attachments_id, 'module' => 'projects'));
							}
						}
						//save data into table.
						$this->client_model->_table_name = "tbl_attachments"; // table name
						$this->client_model->delete_multiple(array('module_field_id' => $v_project->project_id, 'module' => 'projects'));

						//save data into table.
						$this->client_model->_table_name = "tbl_milestones"; // table name
						$this->client_model->delete_multiple(array('project_id' => $v_project->project_id));

						// tasks
						$taskss_info = $this->db->where('project_id', $v_project->project_id)->get('tbl_task')->result();
						if (!empty($taskss_info)) {
							foreach ($taskss_info as $v_taskss) {

								$this->client_model->_table_name = "tbl_attachments"; //table name
								$this->client_model->_order_by = "module_field_id";
								$files_info = $this->client_model->get_by(array('module_field_id' => $v_taskss->task_id, 'module' => 'tasks'), FALSE);
								foreach ($files_info as $v_files) {
									$this->client_model->_table_name = "tbl_attachments_files"; //table name
									$this->client_model->delete_multiple(array('attachments_id' => $v_files->attachments_id));
								}
								//delete into table.
								$this->client_model->_table_name = "tbl_attachments"; // table name
								$this->client_model->delete_multiple(array('module_field_id' => $v_taskss->task_id, 'module' => 'tasks'));

								//delete data into table.
								$this->client_model->_table_name = "tbl_task_comment"; // table name
								$this->client_model->delete_multiple(array('module_field_id' => $v_taskss->task_id, 'module' => 'tasks'));

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

						// Bugs
						$bugs_info = $this->db->where('project_id', $v_project->project_id)->get('tbl_bug')->result();
						if (!empty($bugs_info)) {
							foreach ($bugs_info as $v_bugs) {


								$this->client_model->_table_name = "tbl_attachments"; //table name
								$this->client_model->_order_by = "module_field_id";
								$files_info = $this->client_model->get_by(array('module_field_id' => $v_bugs->bug_id, 'module' => 'bugs'), FALSE);
								foreach ($files_info as $v_files) {
									$this->client_model->_table_name = "tbl_attachments_files"; //table name
									$this->client_model->delete_multiple(array('attachments_id' => $v_files->attachments_id));
								}
								//delete into table.
								$this->client_model->_table_name = "tbl_attachments"; // table name
								$this->client_model->delete_multiple(array('module_field_id' => $v_bugs->bug_id, 'module' => 'bugs'));

								//delete data into table.
								$this->client_model->_table_name = "tbl_task_comment"; // table name
								$this->client_model->delete_multiple(array('module_field_id' => $v_bugs->bug_id, 'module' => 'bugs'));

								//delete data into table.
								$this->client_model->_table_name = "tbl_task"; // table name
								$this->client_model->delete_multiple(array('module_field_id' => $v_bugs->bug_id, 'module' => 'bugs'));

								$this->client_model->_table_name = "tbl_bug"; // table name
								$this->client_model->_primary_key = "bug_id"; // $id
								$this->client_model->delete($v_bugs->bug_id);
							}
						}

						$this->client_model->_table_name = 'tbl_project';
						$this->client_model->_primary_key = 'project_id';
						$this->client_model->delete($v_project->project_id);
					}
				}

				// delete all invoice by id
				$invoice_info = $this->db->where('client_id', $client_id)->get('tbl_invoices')->result();
				if (!empty($invoice_info)) {
					foreach ($invoice_info as $v_invoice) {
						// delete all payment info by id
						$this->client_model->_table_name = 'tbl_payments';
						$this->client_model->delete_multiple(array('invoices_id' => $v_invoice->invoices_id));
					}
				}
				$this->client_model->_table_name = 'tbl_invoices';
				$this->client_model->delete_multiple(array('client_id' => $client_id));

				// delete all project by id
				$this->client_model->_table_name = 'tbl_estimates';
				$this->client_model->_order_by = 'client_id';
				$estimates_info = $this->client_model->get_by(array('client_id' => $client_id), FALSE);
				if (!empty($estimates_info)) {
					foreach ($estimates_info as $v_estimates) {
						$this->client_model->_table_name = 'tbl_estimate_items';
						$this->client_model->delete_multiple(array('estimates_id' => $v_estimates->estimates_id));
					}
				}
				$this->client_model->_table_name = 'tbl_estimates';
				$this->client_model->delete_multiple(array('client_id' => $client_id));
				// delete all tbl_quotations by id
				$this->client_model->_table_name = 'tbl_quotations';
				$this->client_model->_order_by = 'client_id';
				$quotations_info = $this->client_model->get_by(array('client_id' => $client_id), FALSE);

				if (!empty($quotations_info)) {
					foreach ($quotations_info as $v_quotations) {
						$this->client_model->_table_name = 'tbl_quotation_details';
						$this->client_model->delete_multiple(array('quotations_id' => $v_quotations->quotations_id));
					}
				}
				$this->client_model->_table_name = 'tbl_quotations';
				$this->client_model->delete_multiple(array('client_id' => $client_id));

					if (!empty($client_transactions)) {
						foreach ($client_transactions as $v_transaction) {
							finance_sync_model()->delete_transaction_by_id($v_transaction->transactions_id);
					}
				}
				$this->client_model->_table_name = 'tbl_transactions';
				$this->client_model->delete_multiple(array('paid_by' => $client_id));

				$this->client_model->_table_name = 'tbl_reminders';
				$this->client_model->delete_multiple(array('module' => 'client', 'module_id' => $client_id));

				$user_info = $this->client_model->check_by(array('client_id' => $client_id), 'tbl_client');
				$activities = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'client',
					'module_field_id' => $this->session->userdata('user_id'),
					'activity' => ('activity_deleted_client'),
					'icon' => 'fa-user',
					'value1' => $user_info->name
				);
				$this->client_model->_table_name = 'tbl_activities';
				$this->client_model->_primary_key = "activities_id";
				$this->client_model->save($activities);

				// deletre into tbl_account details by user id
				$this->client_model->_table_name = 'tbl_client';
				$this->client_model->_primary_key = 'client_id';
				$this->client_model->delete($client_id);
				// messages for user
				$type = "success";
				$message = lang('delete_client');
			} else {
				$type = "error";
				$message = client_name($client_id) . ' ' . lang('no_permission');
			}
			if (!empty($bulk)) {
				return (array("status" => $type, 'message' => $message));
			} else {
				set_message($type, $message);
				redirect('admin/client/manage_client');
			}
		} else {
			$data['title'] = "Delete Client "; //Page title
			$data['client_info'] = $this->db->where('client_id', $client_id)->get('tbl_client')->row();
			$data['subview'] = $this->load->view('admin/client/delete_client', $data, TRUE);
			$this->load->view('admin/_layout_main', $data); //page load
		}
	}

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

	public function new_notes($id = NULL)
	{
		$data['title'] = lang('give_award');
		$notes = $this->input->post('notes', true);
		$n_data['user_id'] = $this->input->post('client_id', true);
		if (!empty($notes)) {
			$n_data['notes'] = $notes;
			$n_data['is_client'] = 'Yes';
			$n_data['added_by'] = $this->session->userdata('user_id');
			// deletre into tbl_account details by user id
			$this->client_model->_table_name = 'tbl_notes';
			$this->client_model->_primary_key = 'notes_id';
			$this->client_model->save($n_data, $id);
			$this->clear_client_notes_cache($n_data['user_id']);
		}
		redirect('admin/client/details/' . $n_data['user_id'] . '/notes');
	}

	public function delete_notes($id, $client_id)
	{
		$notes_info = $this->db->where('notes_id', $id)->get('tbl_notes')->row();
		if (empty($notes_info)) {
			$type = "error";
			$message = "No Record Found";
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('status' => $type, 'message' => $message));
				exit;
			}
			set_message($type, $message);
			redirect('admin/client/details/' . $client_id . '/notes');
		}
		$activities = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'client',
			'module_field_id' => $this->session->userdata('user_id'),
			'activity' => ('activity_deleted_notes'),
			'icon' => 'fa-user',
			'value1' => $notes_info->notes
		);
		$this->client_model->_table_name = 'tbl_activities';
		$this->client_model->_primary_key = "activities_id";
		$this->client_model->save($activities);

		$this->client_model->_table_name = 'tbl_notes';
		$this->client_model->_primary_key = 'notes_id';
		$this->client_model->delete($id);
		$this->clear_client_notes_cache($client_id);
		$type = "success";
		$message = lang('delete') . ' ' . lang('notes');
		if ($this->input->is_ajax_request()) {
			echo json_encode(array('status' => $type, 'message' => $message));
			exit;
		}
		set_message($type, $message);
		redirect('admin/client/details/' . $client_id . '/notes');
	}

	private function clear_client_notes_cache($client_id)
	{
		$client_id = (int) $client_id;
		if (empty($client_id) || empty($this->cache) || !method_exists($this->cache, 'delete')) {
			return;
		}
		$this->cache->delete('client_tab_data_' . $client_id . '_notes');
	}

	public function contract($client_id = null)
	{
		$client_id = (int) $client_id;
		if (empty($client_id)) {
			set_message('error', lang('no_record_found'));
			redirect('admin/client/details/' . $client_id . '/contracts');
		}
		$this->ensure_client_contracts_table();

		$data['title'] = lang('new') . ' ' . lang('contract');
		$data['client_details'] = get_row('tbl_client', array('client_id' => $client_id));
		$data['client_id'] = $client_id;
		if ($this->db->table_exists('tbl_contract_type')) {
			$data['contract_types'] = get_result('tbl_contract_type');
		} else {
			$data['contract_types'] = array();
		}

		if ($this->input->is_ajax_request()) {
			$this->load->view('admin/client/details/new_contract', $data);
			return;
		}

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

	public function save_contract($client_id = null)
	{
		$client_id = (int) $client_id;
		if (empty($client_id)) {
			set_message('error', lang('no_record_found'));
			redirect('admin/client/details/' . $client_id . '/contracts');
		}
		$this->ensure_client_contracts_table();

		$fields = $this->db->list_fields('tbl_contracts');
		$posted = array(
			'client_id' => $client_id,
			'subject' => $this->input->post('subject', true),
			'contract_type_id' => $this->input->post('contract_type_id', true),
			'start_date' => $this->input->post('start_date', true),
			'end_date' => $this->input->post('end_date', true),
			'status' => $this->input->post('status', true),
			'contract_value' => $this->input->post('contract_value', true),
			'notes' => $this->input->post('notes', true),
			'description' => $this->input->post('notes', true),
			'created_by' => $this->session->userdata('user_id'),
			'added_by' => $this->session->userdata('user_id'),
			'created_at' => date('Y-m-d H:i:s'),
			'date_added' => date('Y-m-d H:i:s'),
		);

		$data = array();
		foreach ($posted as $field => $value) {
			if (in_array($field, $fields, true)) {
				$data[$field] = $value;
			}
		}

		if (empty($data['subject'])) {
			set_message('error', lang('contract') . ' field is required');
			redirect('admin/client/details/' . $client_id . '/contracts');
		}

		$this->client_model->_table_name = 'tbl_contracts';
		$this->client_model->_primary_key = in_array('contract_id', $fields, true) ? 'contract_id' : $fields[0];
		$this->client_model->save($data);
		if (!empty($this->cache) && method_exists($this->cache, 'delete')) {
			$this->cache->delete('client_tab_data_' . $client_id . '_contracts');
		}
		set_message('success', lang('save') . ' ' . lang('contract'));
		redirect('admin/client/details/' . $client_id . '/contracts');
	}

	private function ensure_client_contracts_table()
	{
		if ($this->db->table_exists('tbl_contracts')) {
			return;
		}

		$this->db->query("CREATE TABLE IF NOT EXISTS `tbl_contracts` (
			`contract_id` int(11) NOT NULL AUTO_INCREMENT,
			`client_id` int(11) NOT NULL,
			`subject` varchar(255) NOT NULL,
			`contract_type_id` int(11) DEFAULT NULL,
			`start_date` date DEFAULT NULL,
			`end_date` date DEFAULT NULL,
			`status` varchar(50) DEFAULT 'active',
			`contract_value` decimal(15,2) DEFAULT '0.00',
			`notes` text NULL,
			`created_by` int(11) DEFAULT NULL,
			`created_at` datetime DEFAULT NULL,
			PRIMARY KEY (`contract_id`),
			KEY `idx_tbl_contracts_client_id` (`client_id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
	}


	public function new_client()
	{
		$data['title'] = lang('new_client');
		$data['languages'] = $this->db->where('active', 1)->order_by('name', 'ASC')->get('tbl_languages')->result();
		// get all currencies
		$this->client_model->_table_name = 'tbl_currencies';
		$this->client_model->_order_by = 'name';
		$data['currencies'] = $this->client_model->get();
		if ($this->input->is_ajax_request()) {
			$this->load->view('admin/client/new_client', $data);
			return;
		}
		$data['subview'] = $this->load->view('admin/client/new_client', $data, TRUE);
		$this->load->view('admin/_layout_main', $data);
	}

	public function update_client()
	{
		$created = can_action('4', 'created');
		if (!empty($created)) {
			$data = $this->client_model->array_from_post(array(
				'name',
				'email',
				'short_note',
				'website',
				'phone',
				'mobile',
				'fax',
				'address',
				'city',
				'zipcode',
				'currency',
				'skype_id',
				'linkedin',
				'facebook',
				'twitter',
				'language',
				'country',
				'vat',
				'hosting_company',
				'hostname',
				'port',
				'username',
				'latitude',
				'longitude',
				'customer_group_id'
			));

			$password = $this->input->post('password', true);
			if (!empty($password)) {
				$data['password'] = encrypt($password);
			}

			if (!empty($_FILES['profile_photo']['name'])) {
				$val = $this->client_model->uploadImage('profile_photo');
				$val == TRUE || redirect('admin/client/manage_client');
				$data['profile_photo'] = $val['path'];
			}

			$this->client_model->_table_name = 'tbl_client';
			$this->client_model->_primary_key = "client_id";
			$id = $this->client_model->save($data);
			$action = ('activity_update_company');
			save_custom_field(12, $id);

			$activities = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'client',
				'module_field_id' => $id,
				'activity' => $action,
				'icon' => 'fa-user',
				'value1' => $data['name']
			);
			$this->client_model->_table_name = 'tbl_activities';
			$this->client_model->_primary_key = "activities_id";
			$this->client_model->save($activities);
			//            messages for user
			$type = "success";
			$message = lang('client_updated');
			set_message($type, $message);
		}
		if (!empty($id)) {
			$result = array(
				'id' => $id,
				'name' => $data['name'],
				'status' => $type,
				'message' => $message,
			);
		} else {
			$result = array(
				'status' => 'error',
				'message' => lang('there_in_no_value'),
			);
		}
		echo json_encode($result);
		exit();
	}
}
