<?php

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

class Items extends Admin_Controller
{

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

	public function items_list($id = NULL, $opt = null)
	{
		$data['title'] = lang('all_items');
		$data['page_title'] = lang('items');
		$data['page_description'] = lang('items') . ' ' . lang('list');
		$data['datatable'] = true;
		if (!empty($id)) {
			if (is_numeric($id)) {
				$data['active'] = 2;
				$data['items_info'] = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
			} else {
				if ($id == 'manufacturer') {
					$data['active'] = 4;
					$data['manufacturer_info'] = $this->items_model->check_by(array('manufacturer_id' => $opt), 'tbl_manufacturer');
				} else {
					$data['active'] = 3;
					$data['group_info'] = $this->items_model->check_by(array('customer_group_id' => $opt), 'tbl_customer_group');
				}
			}
		} else {
			$data['active'] = 1;
		}
		$data['warehouseList'] = $this->items_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published'));
		$data['all_customer_group'] = $this->items_model->select_data('tbl_customer_group', 'customer_group_id', 'customer_group', array('type' => 'items'));
		$data['all_manufacturer'] = $this->items_model->select_data('tbl_manufacturer', 'manufacturer_id', 'manufacturer');
		if (!empty(can_action('39', 'created')) || !empty(can_action('39', 'edited'))) {
			$data['header_actions'] = array(
				array(
					'label' => lang('new_items'),
					'icon' => 'plus',
					'href' => base_url('admin/items/new_items'),
					'style' => 'primary',
				),
				array(
					'label' => lang('import') . ' ' . lang('items'),
					'icon' => 'upload',
					'href' => base_url('admin/items/import'),
					'style' => 'info',
				),
			);
		}
		$data['header_filters'] = array(
			array(
				'label' => 'Filters',
				'icon' => 'sliders-horizontal',
				'selected_label' => lang('all'),
				'attrs' => array('id' => 'items-header-filter'),
				'items' => array(
					array(
						'label' => lang('group'),
						'icon' => 'tag',
						'items' => array(
							array('label' => lang('all') . ' ' . lang('group'), 'attrs' => array('data-item-filter-action' => '1', 'data-item-filter' => '', 'data-item-search' => 'by_group', 'data-item-filter-label' => lang('all') . ' ' . lang('group'))),
						),
						'lookup' => array(
							'endpoint' => base_url('admin/common/item_group_lookup'),
							'limit' => 12,
							'min_length' => 0,
							'action_attrs' => array('data-item-filter-action' => '1', 'data-item-search' => 'by_group'),
							'filter_attr' => 'data-item-filter',
							'label_attr' => 'data-item-filter-label',
							'label_prefix' => lang('group') . ': ',
							'placeholder' => lang('search') . ' ' . lang('group'),
							'cache_key' => 'items_group_lookup',
						),
					),
					array(
						'label' => lang('manufacturer'),
						'icon' => 'factory',
						'items' => array(
							array('label' => lang('all') . ' ' . lang('manufacturer'), 'attrs' => array('data-item-filter-action' => '1', 'data-item-filter' => '', 'data-item-search' => 'by_manufacturer', 'data-item-filter-label' => lang('all') . ' ' . lang('manufacturer'))),
						),
						'lookup' => array(
							'endpoint' => base_url('admin/common/manufacturer_lookup'),
							'limit' => 12,
							'min_length' => 0,
							'action_attrs' => array('data-item-filter-action' => '1', 'data-item-search' => 'by_manufacturer'),
							'filter_attr' => 'data-item-filter',
							'label_attr' => 'data-item-filter-label',
							'label_prefix' => lang('manufacturer') . ': ',
							'placeholder' => lang('search') . ' ' . lang('manufacturer'),
							'cache_key' => 'items_manufacturer_lookup',
						),
					),
					array(
						'label' => lang('warehouse'),
						'icon' => 'warehouse',
						'items' => array(
							array('label' => lang('all') . ' ' . lang('warehouse'), 'attrs' => array('data-item-filter-action' => '1', 'data-item-filter' => '', 'data-item-search' => 'by_warehouse', 'data-item-filter-label' => lang('all') . ' ' . lang('warehouse'))),
						),
						'lookup' => array(
							'endpoint' => base_url('admin/common/warehouse_lookup'),
							'limit' => 12,
							'min_length' => 0,
							'action_attrs' => array('data-item-filter-action' => '1', 'data-item-search' => 'by_warehouse'),
							'filter_attr' => 'data-item-filter',
							'label_attr' => 'data-item-filter-label',
							'label_prefix' => lang('warehouse') . ': ',
							'placeholder' => lang('search') . ' ' . lang('warehouse'),
							'cache_key' => 'items_warehouse_lookup',
						),
					),
				),
			),
		);
		$data['header_filter_extras_html'] = '';
		$data['datatable_preload'] = $this->build_items_list_response();
		$data['dropzone'] = 1;
		$data['subview'] = $this->load->view('admin/items/items_list', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function new_items($id = NULL, $opt = null)
	{
		$data['title'] = lang('all_items');
		$data['items_info'] = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
		if (!empty($id)) {
			if (is_numeric($id)) {
				$data['items_info'] = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
				$data['warehouse_product_info'] = $this->db->where('product_id', $id)->get('tbl_warehouses_products')->row();
			}
		}

		$data['warehouseList'] = $this->items_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published'));
		$data['all_customer_group'] = $this->items_model->select_data('tbl_customer_group', 'customer_group_id', 'customer_group', array('type' => 'items'), null, null);
		$data['all_manufacturer'] = $this->items_model->select_data('tbl_manufacturer', 'manufacturer_id', 'manufacturer');
		$data['selected_group_label'] = '';
		if (!empty($data['items_info']->customer_group_id)) {
			$data['selected_group_label'] = $data['all_customer_group'][$data['items_info']->customer_group_id] ?? '';
		}
		$data['selected_manufacturer_label'] = '';
		if (!empty($data['items_info']->manufacturer_id)) {
			$data['selected_manufacturer_label'] = $data['all_manufacturer'][$data['items_info']->manufacturer_id] ?? '';
		}
		$data['dropzone'] = 1;
		$data['subview'] = $this->load->view('admin/items/createitems', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function newitems_group($id = NULL, $opt = null)
	{
		$data['title'] = lang('all_items');
		if (!empty($id)) {
			if ($id == 'group') {
				$data['active'] = 3;
				$data['group_info'] = $this->items_model->check_by(array('customer_group_id' => $opt), 'tbl_customer_group');
			}
		}

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

	public function itemsList($group_id = null, $type = null)
	{
		if ($this->input->is_ajax_request()) {
			echo json_encode($this->build_items_list_response($group_id, $type));
			exit();
		} else {
			redirect('admin/dashboard');
		}
	}

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

		$this->datatables->table = 'tbl_saved_items';
		$this->datatables->join_table = array('tbl_customer_group', 'tbl_manufacturer');
		$this->datatables->join_where = array('tbl_customer_group.customer_group_id=tbl_saved_items.customer_group_id', 'tbl_manufacturer.manufacturer_id=tbl_saved_items.manufacturer_id');

		$custom_field = custom_form_table_search(18);
		$action_array = array('saved_items_id');
		$main_column = array('item_name', 'code', 'hsn_code', 'quantity', 'unit_cost', 'unit_type', 'tbl_customer_group.customer_group', 'tbl_manufacturer.manufacturer');
		$result = array_merge($main_column, $custom_field, $action_array);
		$this->datatables->column_order = $result;
		$this->datatables->column_search = $result;
		$this->datatables->order = array('tbl_saved_items.order' => 'asc');

		if (!empty($type) && $type == 'by_group') {
			$where = array('tbl_saved_items.customer_group_id' => $group_id);
		} else if (!empty($type) && $type == 'by_manufacturer') {
			$where = array('tbl_saved_items.manufacturer_id' => $group_id);
		} else if (!empty($type) && $type == 'by_warehouse') {
			$where = array('tbl_saved_items.warehouse_id' => $group_id);
		} else {
			$where = null;
		}

		$fetch_data = make_datatables($where);
		$data = array();
		$edited = can_action('39', 'edited');
		$deleted = can_action('39', 'deleted');
		foreach ($fetch_data as $_key => $v_items) {
			$action = null;
			$item_name = !empty($v_items->item_name) ? $v_items->item_name : $v_items->item_name;
			$item_name_escaped = html_escape($item_name);
			$code_text = !empty($v_items->code) ? html_escape($v_items->code) : '-';
			$plu_text = !empty($v_items->plu) ? html_escape($v_items->plu) : '-';
			$manufacturer_text = !empty($v_items->manufacturer) ? html_escape($v_items->manufacturer) : '-';
			$group_text = !empty($v_items->customer_group) ? html_escape($v_items->customer_group) : '-';

			$sub_array = array();
			if (!empty($deleted)) {
				$sub_array[] = '<div class="checkbox c-checkbox" ><label class="needsclick"> <input class="item_checkbox js-item-row-check" id="item_' . $v_items->saved_items_id . '" value="' . $v_items->saved_items_id . '" type="checkbox"></label></div>';
			}
			$sub_array[] = '<div class="item-row-card">'
				. '<a data-toggle="modal" data-target="#myModal_extra_lg" href="' . base_url('admin/items/items_details/' . $v_items->saved_items_id) . '" class="item-row-title">' . $item_name_escaped . '</a>'
				. '<div class="item-row-meta">'
				. '<span class="item-row-chip"><span class="item-row-chip-label">' . lang('kitchen_name') . '</span><span class="item-row-chip-value">' . $code_text . '</span></span>'
				. '<span class="item-row-chip"><span class="item-row-chip-label">' . lang('plu') . '</span><span class="item-row-chip-value">' . $plu_text . '</span></span>'
				. '<span class="item-row-chip"><span class="item-row-chip-label">' . lang('manufacturer') . '</span><span class="item-row-chip-value">' . $manufacturer_text . '</span></span>'
				. '</div>'
				. '</div>';

			$invoice_view = config_item('invoice_view');
			if (!empty($invoice_view) && $invoice_view == '2') {
				$sub_array[] = $v_items->hsn_code;
			}
			if (!empty(admin())) {
				$sub_array[] = display_money($v_items->cost_price, default_currency());
			}
			$sub_array[] = display_money($v_items->unit_cost, default_currency());
			$sub_array[] = $v_items->unit_type;
				if (!empty($v_items->tax_rates_id) && !is_numeric($v_items->tax_rates_id)) {
					$tax_rates = json_decode((string) $v_items->tax_rates_id);
				} else {
					$tax_rates = null;
				}
			$rates = null;
			if (!empty($tax_rates)) {
				if (is_array($tax_rates)) {
					foreach ($tax_rates as $key => $tax_id) {
						$taxes_info = $this->db->where('tax_rates_id', $tax_id)->get('tbl_tax_rates')->row();
						if (!empty($taxes_info)) {
							$rates .= $key + 1 . '. ' . $taxes_info->tax_rate_name . '&nbsp;&nbsp; (' . $taxes_info->tax_rate_percent . '% ) <br>';
						}
					}
				} else {
					$tax_row = $this->db->where('tax_rates_id', $tax_rates)->get('tbl_tax_rates')->row();
					$rates = !empty($tax_row) ? $tax_row->tax_rate_name : null;
				}
			}
			$sub_array[] = !empty($rates) ? '<div class="item-tax-list">' . $rates . '</div>' : '<span class="text-muted">-</span>';

			$sub_array[] = '<span class="item-group-badge">' . $group_text . '</span>';
			if ($v_items->status == 'active') {
				$sub_array[] = '<div class="item-status-wrap"><span class="item-status-badge is-active">' . lang('active') . '</span><a href="' . base_url() . 'admin/items/change_item_status/inactive/' . $v_items->saved_items_id . '" class="item-status-toggle is-active" title="' . lang('inactive') . '"><span class="sr-only">' . lang('inactive') . '</span></a></div>';
			} else {
				$sub_array[] = '<div class="item-status-wrap"><span class="item-status-badge is-inactive">' . lang('inactive') . '</span><a href="' . base_url() . 'admin/items/change_item_status/active/' . $v_items->saved_items_id . '" class="item-status-toggle" title="' . lang('active') . '"><span class="sr-only">' . lang('active') . '</span></a></div>';
			}
			$custom_form_table = custom_form_table(18, $v_items->saved_items_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/items/new_items/' . $v_items->saved_items_id) . ' ';
			}
			if (!empty($deleted)) {
				$action .= ajax_anchor(base_url("admin/items/delete_items/$v_items->saved_items_id"), '', array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
			}
			if (!empty($edited)) {
				$action .= '<a class="btn btn-inverse btn-xs" data-toggle="tooltip" data-placement="top" title="' . lang('print_barcode') . '"  target="_blank" href="' . base_url('admin/items/single_barcode/' . $v_items->saved_items_id) . '"><i data-lucide="scan-barcode" ></i></a>' . ' ';
				$confirm_copy = sprintf(lang('confirm_copy_item'), $v_items->item_name);
				$action .= '<a class="btn btn-inverse btn-xs" data-toggle="tooltip" data-placement="top" title="' . lang('copy_item') . '" href="' . base_url('admin/items/copy_items/' . $v_items->saved_items_id) . '" data-act="ajax-request" data-confirm-action="copy" data-confirm-title="' . html_escape(lang('copy_item')) . '" data-confirm-message="' . html_escape($confirm_copy) . '" data-confirm-accept-label="' . html_escape(lang('copy_item')) . '"><i data-lucide="copy" ></i></a>' . ' ';
			}
			$sub_array[] = '<div class="item-actions-cell">' . $action . '</div>';
			$data[] = $sub_array;
		}

		$output = build_table_output($data);
		$_POST = $original_post;
		return $output;
	}
	// change_status
	public function change_item_status($status, $id)
	{
		$this->items_model->_table_name = 'tbl_saved_items';
		$this->items_model->_primary_key = 'saved_items_id';
		$data['status'] = $status;
		$this->items_model->save($data, $id);

		// activity log
		$activity = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'items',
			'module_field_id' => $id,
			'activity' => 'activity_change_status',
			'icon' => 'fa-circle-o',
			'value1' => $status
		);
		$this->items_model->_table_name = 'tbl_activities';
		$this->items_model->_primary_key = 'activities_id';
		$this->items_model->save($activity);

		// messages for user
		$type = "success";
		if ($status == 'active') {
			$message = lang('item_active');
		} else {
			$message = lang('item_inactive');
		}
		set_message($type, $message);
		redirect('admin/items/items_list');
	}

	// sort_items
	public function sort_items()
	{
		$ids = $this->input->post('order', true);
		if (empty($ids)) {
			$type = 'error';
			$message = lang('no_items_selected');
			echo json_encode(array("status" => $type, 'message' => $message));
			exit();
		}
		// $ids = get_order_by('tbl_saved_items', array(), 'saved_items_id', true);
		if (!empty($ids)) {
			foreach ($ids as $key => $val) {
				$this->db->where('saved_items_id', $val);
				$this->db->update('tbl_saved_items', array('order' => $key));
			}
		}
		$type = 'success';
		$message = lang('items_sort');
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	// sort_group
	public function sort_group()
	{
		$ids = $this->input->post('order', true);

		if (!empty($ids)) {
			foreach ($ids as $key => $val) {
				$this->db->where('customer_group_id', $val);
				$this->db->update('tbl_customer_group', array('order' => $key));
			}
		}
		$type = 'success';
		$message = lang('customer_group_sort');
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	public function copy_items($id)
	{
		// clone the item and get the new id
		$info = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
		if (empty($info)) {
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('status' => 'error', 'message' => lang('item') . ' ' . lang('not_found')));
				exit();
			}
			set_message('error', lang('item') . ' ' . lang('not_found'));
			redirect('admin/items/items_list');
		}

		$copy_lock = $this->session->userdata('last_item_copy');
		if (
			is_array($copy_lock)
			&& (int) ($copy_lock['source_id'] ?? 0) === (int) $id
			&& (time() - (int) ($copy_lock['created_at'] ?? 0)) <= 8
			&& !empty($copy_lock['new_id'])
			&& get_row('tbl_saved_items', array('saved_items_id' => $copy_lock['new_id']))
		) {
			$redirect_url = base_url('admin/items/new_items/' . $copy_lock['new_id']);
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('status' => 'success', 'message' => lang('item_copied'), 'redirect_url' => $redirect_url));
				exit();
			}
			redirect($redirect_url);
		}

		$source_warehouse_product = get_row('tbl_warehouses_products', array('product_id' => $id));
		$item_name = $this->unique_copy_value('tbl_saved_items', 'item_name', $info->item_name, ' ' . lang('copy'));
		$code = $this->unique_copy_value('tbl_saved_items', 'code', $info->code, '-COPY', 100);
		$warehouse_id = !empty($source_warehouse_product->warehouse_id) ? $source_warehouse_product->warehouse_id : null;
		if (empty($warehouse_id)) {
			$warehouse_id = $this->session->userdata('warehouse_id');
		}
		if (empty($warehouse_id)) {
			$warehouse_id = get_any_field('tbl_warehouse', array('status' => 'published'), 'warehouse_id');
		}
		if (empty($warehouse_id)) {
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('status' => 'error', 'message' => lang('please_select') . ' ' . lang('warehouse')));
				exit();
			}
			set_message('error', lang('please_select') . ' ' . lang('warehouse'));
			redirect('admin/items/items_list');
		}

		$data = array(
			'item_name' => $item_name,
			'manufacturer_id' => $info->manufacturer_id,
			'code' => $code,
			'barcode_symbology' => $info->barcode_symbology,
			'item_desc' => $info->item_desc,
			'hsn_code' => $info->hsn_code,
			'cost_price' => $info->cost_price,
			'unit_cost' => $info->unit_cost,
			'unit_type' => $info->unit_type,
			'customer_group_id' => $info->customer_group_id,
			'quantity' => $info->quantity,
			'tax_rates_id' => $info->tax_rates_id,
			'upload_file' => $info->upload_file,
			'item_tax_total' => $info->item_tax_total,
			'total_cost' => $info->total_cost,
		);

		$this->items_model->_table_name = 'tbl_saved_items';
		$this->items_model->_primary_key = 'saved_items_id';
		$new_id = $this->items_model->save($data);

		// info object to array
		$info = (array)$info;
		save_custom_field(18, $new_id, $info);

		$check = get_row('tbl_warehouses_products', array('product_id' => $new_id));
		$data = array(
			'warehouse_id' => $warehouse_id,
			'quantity' => isset($source_warehouse_product->quantity) ? $source_warehouse_product->quantity : $info['quantity'],
			'product_id' => $new_id,
		);
		$this->items_model->_table_name = 'tbl_warehouses_products';
		$this->items_model->_primary_key = 'id';
		if (!empty($check)) {
			$data['product_id'] = $new_id;
			$data_id = $check->id;
			$this->items_model->save($data, $data_id);
		} else {
			$this->items_model->save($data);
		}

		$this->session->set_userdata('last_item_copy', array(
			'source_id' => (int) $id,
			'new_id' => (int) $new_id,
			'created_at' => time(),
		));

		// redirect to the edit page
		$redirect_url = base_url('admin/items/new_items/' . $new_id);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array('status' => 'success', 'message' => lang('item_copied'), 'redirect_url' => $redirect_url));
			exit();
		}
		redirect($redirect_url);
	}

	private function unique_copy_value($table, $field, $value, $suffix, $max_length = null)
	{
		$base = trim((string) $value);
		if ($base === '') {
			$base = lang('item');
		}
		$counter = 2;
		$make_candidate = function ($number = null) use ($base, $suffix, $max_length) {
			$tail = $suffix . ($number === null ? '' : ' ' . $number);
			$allowed_base_length = $max_length === null ? null : max(1, $max_length - strlen($tail));
			$copy_base = $allowed_base_length === null ? $base : substr($base, 0, $allowed_base_length);
			return $copy_base . $tail;
		};
		$candidate = $make_candidate();
		while ($this->items_model->check_by(array($field => $candidate), $table)) {
			$candidate = $make_candidate($counter);
			$counter++;
		}
		return $candidate;
	}



	public function saved_items($id = NULL)
	{
		$data = $this->items_model->array_from_post(array('item_name', 'manufacturer_id', 'code', 'barcode_symbology', 'item_desc', 'hsn_code', 'cost_price', 'unit_cost', 'unit_type', 'customer_group_id', 'quantity'));
		$tax_rates = $this->input->post('tax_rates_id', true);

		// if id is empty then set status as active
		if (empty($id)) {
			$data['status'] = 'active';
		} elseif (empty($data['status'])) {
			$existing_item = get_row('tbl_saved_items', array('saved_items_id' => $id));
			$data['status'] = !empty($existing_item->status) ? $existing_item->status : 'active';
		}

		$total_tax = 0;
		if (!empty($tax_rates)) {
			foreach ($tax_rates as $tax_id) {
				$tax_info = $this->db->where('tax_rates_id', $tax_id)->get('tbl_tax_rates')->row();
				$total_tax += $tax_info->tax_rate_percent;
			}
		}
		if (!empty($tax_rates)) {
			$data['tax_rates_id'] = json_encode($tax_rates);
		} else {
			$data['tax_rates_id'] = '-';
		}
		$warehouse_id = $this->input->post("warehouse_id", true);

		// if customer_group_id is empty then show error
		if (empty($data['customer_group_id'])) {
			$type = 'error';
			$msg = lang('please_select') . ' ' . lang('customer_group');
			set_message($type, $msg);
			redirect('admin/items/new_items');
		}

		// update root category
		$where = array('item_name' => $data['item_name']);
		// duplicate value check in DB
		if (!empty($id)) { // if id exist in db update data
			$saved_items_id = array('saved_items_id !=' => $id);
		} else { // if id is not exist then set id as null
			$saved_items_id = null;
		}
		save_custom_field(18, $id);
		// check whether this input data already exist or not
		$check_items = $this->items_model->check_update('tbl_saved_items', $where, $saved_items_id);
		if (!empty($check_items)) { // if input data already exist show error alert
			// massage for user
			$type = 'error';
			$msg = "<strong style='color:#000'>" . $data['item_name'] . '</strong>  ' . lang('already_exist');
		} else { // save and update query

			$upload_file = array();

			$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 (!empty($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,
							);
							array_push($upload_file, $up_data);
						}
					}
				}
			}
			$fileName = $this->input->post('fileName', true);
			$path = $this->input->post('path', true);
			$fullPath = $this->input->post('fullPath', true);
			$size = $this->input->post('size', true);
			$is_image = $this->input->post('is_image', true);

			if (!empty($fileName)) {
				foreach ($fileName as $key => $name) {
					$old['fileName'] = $name;
					$old['path'] = $path[$key];
					$old['fullPath'] = $fullPath[$key];
					$old['size'] = $size[$key];
					$old['is_image'] = $is_image[$key];

					array_push($upload_file, $old);
				}
			}
			if (!empty($upload_file)) {
				$data['upload_file'] = json_encode($upload_file);
			} else {
				$data['upload_file'] = null;
			}

			$sub_total = $data['unit_cost'] * $data['quantity'];
			$data['item_tax_total'] = ($total_tax / 100) * $sub_total;
			$data['total_cost'] = $sub_total + $data['item_tax_total'];

			$this->items_model->_table_name = 'tbl_saved_items';
			$this->items_model->_primary_key = 'saved_items_id';
			$return_id = $this->items_model->save($data, $id);
			$_data['warehouse_id'] = $warehouse_id ?? 1;
			$_data['quantity'] = $data['quantity'];
			$_data['product_id'] = $return_id;

			$check = get_row('tbl_warehouses_products', array('product_id' => $_data['product_id']));
			$this->items_model->_table_name = 'tbl_warehouses_products';
			$this->items_model->_primary_key = 'id';
			if (!empty($check)) {
				$_data['product_id'] = $return_id;
				$_data_id = $check->id;
				$this->items_model->save($_data, $_data_id);
			} else {

				$this->items_model->save($_data);
			}
			//
			if (!empty($id)) {
				$id = $id;
				$action = 'activity_update_items';
				$msg = lang('update_items');
			} else {
				$id = $return_id;
				$action = 'activity_save_items';
				$msg = lang('save_items');
			}
			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'items',
				'module_field_id' => $id,
				'activity' => $action,
				'icon' => 'fa-circle-o',
				'value1' => $data['item_name']
			);
			$this->items_model->_table_name = 'tbl_activities';
			$this->items_model->_primary_key = 'activities_id';
			$this->items_model->save($activity);
			// messages for user

			$type = "success";
		}
		$message = $msg;
		set_message($type, $message);
		redirect('admin/items/items_list');
	}

	public function get_warehouse_product()
	{
		$warehouse_id = $this->input->post('warehouse_id', true);
		$product_id = $this->input->post('item_id', true);
		$warehouse_product_info = $this->db->where('warehouse_id', $warehouse_id)->where('product_id', $product_id)->get('tbl_warehouses_products')->row();
		if (!empty($warehouse_product_info)) {
			$data['quantity'] = $warehouse_product_info->quantity;
		} else {
			$data['quantity'] = 0;
		}
		echo json_encode($data);
		exit();
	}

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

	public function delete_items($id, $bulk = null)
	{
		$deleted = can_action('39', 'deleted');
		if (!empty($deleted)) {
			$items_info = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'items',
				'module_field_id' => $id,
				'activity' => 'activity_items_deleted',
				'icon' => 'fa-circle-o',
				'value1' => $items_info->item_name
			);
			$this->items_model->_table_name = 'tbl_activities';
			$this->items_model->_primary_key = 'activities_id';
			$this->items_model->save($activity);

			$this->items_model->_table_name = 'tbl_saved_items';
			$this->items_model->_primary_key = 'saved_items_id';
			$this->items_model->delete($id);
			$type = 'success';
			$message = lang('items_deleted');
		} else {
			$type = "error";
			$message = lang('no_permission');
		}
		if (!empty($bulk)) {
			return (array("status" => $type, 'message' => $message));
		}
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	public function items_group()
	{
		$data['title'] = lang('lead_source');
		$this->load->view('admin/items/items_group', $data, FALSE);
	}

	public function update_group($id = null)
	{
		$this->items_model->_table_name = 'tbl_customer_group';
		$this->items_model->_primary_key = 'customer_group_id';

		$cate_data['customer_group'] = $this->input->post('customer_group', TRUE);
		$cate_data['description'] = $this->input->post('description', TRUE);
		$cate_data['type'] = 'items';
		$id = $this->items_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->items_model->_table_name = 'tbl_activities';
		$this->items_model->_primary_key = 'activities_id';
		$this->items_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'],
				'text' => $cate_data['customer_group'],
				'name' => $cate_data['customer_group'],
				'status' => $type,
				'message' => $msg,
			);
		} else {
			$result = array(
				'group' => $cate_data['customer_group'],
				'text' => $cate_data['customer_group'],
				'name' => $cate_data['customer_group'],
				'status' => $type,
				'message' => $msg,
			);
		}
		echo json_encode($result);
		exit();
	}

	public function saved_group($id = null)
	{
		$this->items_model->_table_name = 'tbl_customer_group';
		$this->items_model->_primary_key = 'customer_group_id';

		$cate_data['customer_group'] = $this->input->post('customer_group', TRUE);
		$cate_data['description'] = $this->input->post('description', TRUE);
		$cate_data['type'] = 'items';

		if (!empty($_FILES['image']['name'])) {
			$old_path = $this->input->post('image_path', true);
			if ($old_path) {
				unlink($old_path);
			}
			$val = $this->items_model->uploadImage('image');
			$val == TRUE || redirect('admin/items/newitems_group');
			$cate_data['image'] = json_encode($val);
		}


		$id = $this->items_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->items_model->_table_name = 'tbl_activities';
		$this->items_model->_primary_key = 'activities_id';
		$this->items_model->save($activity);

		// messages for user
		$type = "success";
		$msg = lang('customer_group_added');
		$message = $msg;
		set_message($type, $message);
		redirect('admin/items/newitems_group');
	}

	public function items_manufacturerlist($id = null, $opt = null)
	{
		$data['title'] = lang('all_items');
		if (!empty($id)) {
			if ($id == 'manufacturer') {
				$data['active'] = 4;
				$data['manufacturer_info'] = $this->items_model->check_by(array('manufacturer_id' => $opt), 'tbl_manufacturer');
			}
		} else {
			$data['active'] = 1;
		}
		$data['subview'] = $this->load->view('admin/items/manufactureerlist', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function delete_group($id)
	{
		$customer_group = $this->items_model->check_by(array('customer_group_id' => $id), 'tbl_customer_group');
		$activity = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'settings',
			'module_field_id' => $id,
			'activity' => ('activity_delete_a_customer_group'),
			'value1' => $customer_group->customer_group,
		);
		$this->items_model->_table_name = 'tbl_activities';
		$this->items_model->_primary_key = 'activities_id';
		$this->items_model->save($activity);

		$this->items_model->_table_name = 'tbl_customer_group';
		$this->items_model->_primary_key = 'customer_group_id';
		$this->items_model->delete($id);
		// messages for user
		$type = "success";
		$message = lang('category_deleted');
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	public function import()
	{
		$header = lang('items');
		$data['title'] = lang('import') . ' ' . $header;
		$data['permission_user'] = $this->items_model->all_permission_user('187');
		$data['type'] = 'items';
		$data['subview'] = $this->load->view('admin/items/import', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}


	public function save_imported()
	{
		$this->load->library('excel');
		$files = $this->excel->import($_FILES['upload_file']['tmp_name']);
		if (!empty($files['message'])) {
			set_message('error', $files['message']);
			redirect('admin/items/import');
		}
		if (!empty($files)) {
			$all_data = array();
			foreach ($files as $key => $value) {
				$data['item_name'] = trim($value[0]);
				$data['item_desc'] = (!empty($value[1]) ? $value[1] : '');
				$data['quantity'] = trim($value[2]);
				$unit_cost = str_replace(',', '.', trim($value[3]));
				$data['unit_cost'] = preg_replace("/[^0-9,.]/", "", $unit_cost);
				$data['unit_type'] = (!empty($value[4]) ? $value[4] : '');
				$data['barcode_symbology'] = 'code128';
				$taxtname = $this->remove_numbers($value[5]);
				$taxtname = explode("_", $taxtname);
				$taxtname = array_map('trim', $taxtname);
				$taxtname = array_filter($taxtname);

				$tax_id = array();
				if (is_array($taxtname)) {
					if (!empty($taxtname)) {
						foreach ($taxtname as $val) {
							$taxName = $this->db->where('tax_rate_name', $val)->get('tbl_tax_rates')->row('tax_rates_id');
							if (!empty($taxName)) {
								array_push($tax_id, $taxName);
							}
						}
					}
				} else {
					$tax_id = $this->db->where('tax_rate_name', $taxtname)->get('tbl_tax_rates')->row('tax_rates_id');
				}

				if (!empty($tax_id)) {
					$data['tax_rates_id'] = json_encode($tax_id);
				} else {
					$data['tax_rates_id'] = '-';
				}

				$category_code = trim($value[6]);
				$category_code_info = $this->items_model->check_by(array('type' => 'items', 'customer_group' => $category_code), 'tbl_customer_group');
				if (!empty($category_code_info)) {
					$data['customer_group_id'] = $category_code_info->customer_group_id;
				} else {
					$category['type'] = 'items';
					$category['customer_group'] = $category_code;
					$this->items_model->_table_name = "tbl_customer_group"; //table name
					$this->items_model->_primary_key = "customer_group_id";
					$data['customer_group_id'] = $this->items_model->save($category);
				}
				$all_data[] = $data;
			}
			if (!empty($all_data)) {
				$this->db->insert_batch('tbl_saved_items', $all_data);
			}
			$type = 'success';
			$message = lang('save_new_items');
			$redirect = 'items';
		} else {
			$type = 'error';
			$message = "Sorry your uploaded file type not allowed ! please upload XLS/CSV File ";
		}

		set_message($type, $message);
		redirect('admin/items/items_list');
	}

	function remove_numbers($string)
	{
		$string = preg_replace("/\([^)]+\)/", "", $string);
		$num = array('0.', '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.');
		return str_replace($num, '_', $string);
	}

	private function get_items_details_data($id = NULL)
	{
		$data['title'] = lang('items_details');
		if (empty($id)) {
			show_404();
		}
		$staffwarehouse = $this->session->userdata('warehouse_id');
		$data['items_info'] = $this->items_model->check_by(array('saved_items_id' => $id), 'tbl_saved_items');
		if (empty($data['items_info'])) {
			show_404();
		}
		$data['warehouse_info'] = $this->items_model->warehouse_porduct($id);
		if (!empty($staffwarehouse)) {
			$data['staff_warehouse_info'] = $this->items_model->warehouse_porduct($id, $staffwarehouse);
		}
		$data['barcode'] = $this->product_barcode($data['items_info']->code, $data['items_info']->barcode_symbology, 60);
		return $data;
	}

	public function items_details($id = NULL)
	{
		$data = $this->get_items_details_data($id);
		$data['subview'] = $this->load->view('admin/items/items_details', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load

	}

	public function items_details_pdf($id = NULL)
	{
		$data = $this->get_items_details_data($id);
		$this->load->helper('dompdf');
		$viewfile = $this->load->view('admin/items/items_details_pdf', $data, TRUE);
		$item_name = !empty($data['items_info']->item_name) ? $data['items_info']->item_name : lang('items_details');
		$filename = preg_replace('/[^A-Za-z0-9_-]+/', '_', $item_name . '_details');
		pdf_create($viewfile, trim($filename, '_'), true, 'p', null, null, null, true);
	}

	public function single_barcode($id)
	{
		$currency = $this->db->where('code', config_item('default_currency'))->get('tbl_currencies')->row();
		$product = get_row('tbl_saved_items', array('saved_items_id' => $id));
		if (empty($product)) {
			show_404();
		}
		$label_count = !empty($product->quantity) && (int) $product->quantity > 0 ? (int) $product->quantity : 10;
		$site_name = html_escape(config_item('website_name'));
		$item_name = html_escape($product->item_name);
		$price_text = lang('price') . ': ' . display_money($product->unit_cost, $currency->symbol ?? '');
		$html = '<div class="barcode-sheet grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-4">';
		for ($r = 0; $r < $label_count; $r++) {
			$html .= '<article class="barcode-card rounded-xl border border-slate-200 bg-white px-3 py-2 text-center shadow-sm dark:border-slate-700 dark:bg-slate-900">'
				. '<p class="text-[11px] font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400">' . $site_name . '</p>'
				. '<p class="mt-1 text-sm font-semibold text-slate-900 dark:text-slate-100">' . $item_name . '</p>'
				. '<div class="mt-2 flex justify-center rounded-lg bg-white px-2 py-1">' . $this->product_barcode($product->code, $product->barcode_symbology, 60) . '</div>'
				. '<p class="mt-2 text-xs font-medium text-slate-700 dark:text-slate-300">' . $price_text . '</p>'
				. '</article>';
		}
		$html .= '</div>';
		$data['html'] = $html;
		$data['title'] = lang("print_barcodes") . ' (' . $product->item_name . ')';
		$data['subview'] = $this->load->view('admin/items/single_barcode', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	function product_barcode($product_code = NULL, $bcs = 'code128', $height = 60)
	{
		$src = site_url('admin/items/gen_barcode') . '?' . http_build_query(array(
			'code' => (string) $product_code,
			'bcs' => !empty($bcs) ? (string) $bcs : 'code128',
			'height' => (int) $height,
		));
		return "<img src='" . html_escape($src) . "' alt='" . html_escape((string) $product_code) . "' class='bcimg' />";
	}

	function gen_barcode($product_code = NULL, $bcs = 'code128', $height = 60, $text = 1)
	{
		$get_code = $this->input->get('code', false);
		$get_bcs = $this->input->get('bcs', false);
		$get_height = $this->input->get('height', false);
		$product_code = $get_code !== NULL ? $get_code : $product_code;
		$bcs = $get_bcs !== NULL ? $get_bcs : $bcs;
		$height = $get_height !== NULL ? $get_height : $height;
		$product_code = (string) $product_code;
		$allowed_symbologies = array('code25', 'code39', 'code128', 'ean8', 'ean13', 'upca', 'upce');
		$bcs = strtolower((string) $bcs);
		$bcs = in_array($bcs, $allowed_symbologies, true) ? $bcs : 'code128';
		$height = max(20, (int) $height);
		if ($product_code === '') {
			show_error('Missing barcode value', 400);
		}
		$drawText = ($text != 1) ? FALSE : TRUE;
		$type_map = array(
			'code25' => 'S25',
			'code39' => 'C39',
			'code128' => 'C128B',
			'ean8' => 'EAN8',
			'ean13' => 'EAN13',
			'upca' => 'UPCA',
			'upce' => 'UPCE',
		);
		$type = $type_map[$bcs] ?? 'C128B';
		$this->render_mpdf_barcode_png($product_code, $type, $height, $drawText);
		exit();
	}

	private function render_mpdf_barcode_png($product_code, $type, $height, $drawText = TRUE)
	{
		try {
			$barcode = new \Mpdf\Barcode();
			$barcode_data = $barcode->getBarcodeArray($product_code, $type);
			if (empty($barcode_data)) {
				$barcode_data = $barcode->getBarcodeArray($product_code, 'C128B');
			}
		} catch (\Throwable $e) {
			log_message('error', 'Barcode generation failed: ' . $e->getMessage());
			show_error('Unable to generate barcode', 400);
		}

		$scale = 2;
		$padding_x = 12;
		$padding_y = 8;
		$text_height = $drawText ? 14 : 0;
		$image_width = max(1, ((int) $barcode_data['maxw'] * $scale) + ($padding_x * 2));
		$image_height = max(1, (int) $height + ($padding_y * 2) + $text_height);
		$image = imagecreatetruecolor($image_width, $image_height);
		$white = imagecolorallocate($image, 255, 255, 255);
		$black = imagecolorallocate($image, 0, 0, 0);
		imagefilledrectangle($image, 0, 0, $image_width, $image_height, $white);

		$x = $padding_x;
		foreach ($barcode_data['bcode'] as $bar) {
			$bar_width = max(1, (int) $bar['w'] * $scale);
			if (!empty($bar['t'])) {
				$bar_height = max(1, (int) round($height * (float) $bar['h']));
				$bar_top = $padding_y + (int) round($height * (float) $bar['p']);
				imagefilledrectangle($image, $x, $bar_top, $x + $bar_width - 1, $bar_top + $bar_height, $black);
			}
			$x += $bar_width;
		}

		if ($drawText) {
			$font = 2;
			$text = (string) $product_code;
			$text_width = imagefontwidth($font) * strlen($text);
			$text_x = max(0, (int) (($image_width - $text_width) / 2));
			imagestring($image, $font, $text_x, $padding_y + (int) $height + 2, $text, $black);
		}

		if (ob_get_length()) {
			ob_clean();
		}
		header('Content-Type: image/png');
		header('Cache-Control: public, max-age=604800');
		imagepng($image);
		imagedestroy($image);
	}

	public function transferItem()
	{
		$data['title'] = lang("transferItem");
		$data['page_title'] = lang('transferItem');
		$data['page_description'] = lang('manage') . ' ' . lang('transferItem');
		$data['header_actions'] = array();
		if (!empty(can_action('187', 'created')) || !empty(can_action('187', 'edited'))) {
			$data['header_actions'][] = array(
				'label' => lang('new') . ' ' . lang('transferItem'),
				'icon' => 'plus',
				'style' => 'primary',
				'href' => base_url('admin/items/createTransferItem'),
			);
		}
		$data['dataTables'] = true;
		$data['subview'] = $this->load->view('admin/items/transferItem/manage', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}


	public function transferItemList()
	{
		if (!empty($this->input->is_ajax_request())) {

			$this->load->model('datatables');
			$this->datatables->set_sql_mode();
			$this->datatables->table = 'tbl_transfer_itemlist';
			$this->datatables->join_table = array('tbl_transfer_item');
			$this->datatables->join_where = array('tbl_transfer_item.transfer_item_id=tbl_transfer_itemlist.transfer_item_id');

			$custom_field = custom_form_table_search(18);
			$action_array = array('transfer_itemList_id');
			$main_column = array('tbl_transfer_item.reference_no', 'tbl_transfer_item.status', 'tbl_transfer_item.from_warehouse_id', 'tbl_transfer_item.to_warehouse_id', 'tbl_transfer_item.status');
			$result = array_merge($main_column, $custom_field, $action_array);
			$this->datatables->column_order = $result;
			$this->datatables->column_search = $result;
			$this->db->group_by('reference_no');
			$this->datatables->order = array('transfer_itemList_id' => 'desc');
			$fetch_data = make_datatables();
			$data = array();
			$edited = can_action('187', 'edited');
			$deleted = can_action('187', 'deleted');
			foreach ($fetch_data as $_key => $v_items) {
				$action = null;
				$can_edit = $this->items_model->can_action('tbl_transfer_itemlist', 'edit', array('transfer_itemList_id' => $v_items->transfer_itemList_id));
				$can_delete = $this->items_model->can_action('tbl_transfer_itemlist', 'delete', array('transfer_itemList_id' => $v_items->transfer_itemList_id));


				$item_name = !empty($v_items->reference_no) ? $v_items->reference_no : $v_items->reference_no;
				$formmane = get_row('tbl_warehouse', array('warehouse_id' => $v_items->from_warehouse_id));
				$tomane = get_row('tbl_warehouse', array('warehouse_id' => $v_items->to_warehouse_id));
				$from_warehouse_name = !empty($formmane) && !empty($formmane->warehouse_name) ? $formmane->warehouse_name : '-';
				$to_warehouse_name = !empty($tomane) && !empty($tomane->warehouse_name) ? $tomane->warehouse_name : '-';

				$sub_array = array();
				if (!empty($deleted)) {
					$sub_array[] = '<div class="checkbox c-checkbox" ><label class="needsclick"> <input value="' . $v_items->transfer_itemList_id . '" type="checkbox"></label></div>';
				}
				//                $sub_array[] = '<a data-toggle="modal" data-target="#myModal_extra_lg" href="' . base_url('admin/items/transfer_details/' . $v_items->transfer_itemList_id) . '"><strong class="block">' . $item_name .'</strong>';
				$sub_array[] = '<a class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300" href="' . base_url() . 'admin/items/transfer_details/' . $v_items->transfer_itemList_id . '"><strong class="block">' . $item_name . '</strong></a>';
				$sub_array[] = display_date($v_items->date);
				$sub_array[] = $from_warehouse_name;
				$sub_array[] = $to_warehouse_name;
				$invoice_view = config_item('invoice_view');
				if (!empty($invoice_view) && $invoice_view == '2') {
					$sub_array[] = $v_items->hsn_code;
				}

				$sub_array[] = display_money($this->items_model->transfer_calculate_to('transfer_cost', $v_items->transfer_item_id));
				//                $sub_array[] = $v_items->status;

				$statusss = null;
				if (!empty($v_items->status)) {
					if ($v_items->status == 'complete') {
						$statusss = "<span class='inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'>" . lang($v_items->status) . "</span>";
					} elseif ($v_items->status == 'approved') {
						$statusss = "<span class='inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300'>" . lang($v_items->status) . "</span>";
					} elseif ($v_items->status == 'rejected') {
						$statusss = "<span class='inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300'>" . lang($v_items->status) . "</span>";
					} else {
						$statusss = "<span class='inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'>" . lang($v_items->status) . "</span>";
					}
				}
				$change_status = null;
				if (!empty($can_edit) && !empty($edited)) {
					$ch_url = base_url() . 'admin/items/change_status/';
					$items = '';
					$transfer_statuses = array(
						array('value' => 'pending', 'label' => lang('pending')),
						array('value' => 'complete', 'label' => lang('completed')),
						array('value' => 'approved', 'label' => lang('approved')),
						array('value' => 'rejected', 'label' => lang('rejected')),
					);

					foreach ($transfer_statuses as $v_status) {
						$status_key = $v_status['value'];
						$status_label = $v_status['label'];
						$is_active = ($v_items->status == $status_key);
						$active_class = $is_active
							? 'bg-slate-100 font-medium text-slate-900 dark:bg-gray-700 dark:text-white'
							: 'text-slate-700 dark:text-gray-300';

						$items .= '<li>
                    <a class="block px-4 py-2 transition-colors hover:bg-slate-50 dark:hover:bg-gray-700 ' . $active_class . '"
                       href="' . $ch_url . $v_items->transfer_item_id . '/' . $status_key . '">
                       ' . $status_label . '
                    </a>
                   </li>';
					}

					$change_status = '<details class="group relative inline-flex ml-2">
        <summary class="inline-flex cursor-pointer list-none items-center justify-center gap-1 rounded-md border border-slate-200 bg-white px-2 py-1 text-slate-500 shadow-sm transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200">
            <i data-lucide="chevron-down" class="h-3.5 w-3.5 transition-transform duration-200 group-open:rotate-180"></i>
        </summary>

        <ul class="absolute right-0 top-full z-50 mt-1 min-w-[160px] overflow-hidden rounded-lg border border-slate-200 bg-white py-1 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-800">
            ' . $items . '
        </ul>
    </details>';
				}
				$sub_array[] = $statusss . ' ' . $change_status;

				$custom_form_table = custom_form_table(18, $v_items->saved_items_id);

				if (!empty($custom_form_table)) {
					foreach ($custom_form_table as $c_label => $v_fields) {
						$sub_array[] = $v_fields;
					}
				}

				if (!empty($can_edit) && !empty($edited)) {
					$action .= btn_edit('admin/items/createTransferItem/' . $v_items->transfer_item_id) . ' ';
				}
				if (!empty($can_delete) && !empty($deleted)) {
					$action .= ajax_anchor(base_url("admin/items/delete_transfer/" . $v_items->transfer_item_id), lang('delete'), array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#table_" . $_key)) . ' ';
				}
				if (!empty($can_edit) && !empty($edited)) {
					$action .= btn_view('admin/items/transfer_details/' . $v_items->transfer_itemList_id) . ' ';
				}
				if (!empty($edited) || !empty($deleted)) {
					$sub_array[] = $action;
				}

				$data[] = $sub_array;
			}

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

	//cloned_transferitem
	public function cloned_transferitem($id)
	{
		$created = can_action_by_label('transferItem', 'created');
		$edited = can_action_by_label('transferItem', 'edited');
		if (empty($created) && empty($edited)) {
			$type = 'error';
			$message = lang('no_permission');
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}
			set_message($type, $message);
			redirect('admin/items/transferItem');
		}

		$source_row = $this->items_model->check_by(array('transfer_itemList_id' => $id), 'tbl_transfer_itemlist');
		if (empty($source_row)) {
			$type = 'error';
			$message = lang('there_in_no_value');
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}
			set_message($type, $message);
			redirect('admin/items/transferItem');
		}

		$source_transfer = $this->items_model->check_by(array('transfer_item_id' => $source_row->transfer_item_id), 'tbl_transfer_item');
		if (empty($source_transfer)) {
			$type = 'error';
			$message = lang('there_in_no_value');
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}
			set_message($type, $message);
			redirect('admin/items/transferItem');
		}

		$new_to_warehouse_id = (int) $this->input->post('warehouse_id', true);
		$transfer_date_input = $this->input->post('transfer_date', true);
		$transfer_date = !empty($transfer_date_input) ? date('Y-m-d', safe_strtotime($transfer_date_input)) : date('Y-m-d');
		if (empty($new_to_warehouse_id)) {
			$type = 'error';
			$message = lang('please_select_warehouse');
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}
			set_message($type, $message);
			redirect('admin/items/transfer_details/' . $id);
		}

		if ((int) $source_transfer->from_warehouse_id === $new_to_warehouse_id) {
			$type = 'error';
			$message = lang('please_select_different_warehouse');
			if ($this->input->is_ajax_request()) {
				echo json_encode(array("status" => $type, 'message' => $message));
				exit();
			}
			set_message($type, $message);
			redirect('admin/items/transfer_details/' . $id);
		}

		$new_reference_no = '';
		if (!empty(config_item('transfer_prefix'))) {
			$new_reference_no .= config_item('transfer_prefix');
		}
		$new_reference_no .= $this->items_model->generateTransferItemNumber();

		$new_transfer = array(
			'reference_no' => $new_reference_no,
			'date' => $transfer_date,
			'from_warehouse_id' => $source_transfer->from_warehouse_id,
			'to_warehouse_id' => $new_to_warehouse_id,
			'status' => 'pending',
			'notes' => $source_transfer->notes,
			'show_quantity_as' => !empty($source_transfer->show_quantity_as) ? $source_transfer->show_quantity_as : null,
			'permission' => !empty($source_transfer->permission) ? $source_transfer->permission : 'all',
			'user_id' => my_id(),
			'attachment' => !empty($source_transfer->attachment) ? $source_transfer->attachment : null,
			'shipping_cost' => !empty($source_transfer->shipping_cost) ? $source_transfer->shipping_cost : 0,
			'total_tax' => !empty($source_transfer->total_tax) ? $source_transfer->total_tax : null,
			'tax' => !empty($source_transfer->tax) ? $source_transfer->tax : 0,
		);

		$this->items_model->_table_name = 'tbl_transfer_item';
		$this->items_model->_primary_key = 'transfer_item_id';
		$new_transfer_id = $this->items_model->save($new_transfer);

		$source_items = get_result('tbl_transfer_itemlist', array('transfer_item_id' => $source_transfer->transfer_item_id));
		$new_transfer_item_list_id = null;
		if (!empty($source_items)) {
			$this->items_model->_table_name = 'tbl_transfer_itemlist';
			$this->items_model->_primary_key = 'transfer_itemList_id';
			foreach ($source_items as $source_item) {
				$item_payload = (array) $source_item;
				unset($item_payload['transfer_itemList_id']);
				$item_payload['transfer_item_id'] = $new_transfer_id;
				$item_payload['warehouse_id'] = $new_to_warehouse_id;
				$new_row_id = $this->items_model->save($item_payload);
				if (empty($new_transfer_item_list_id)) {
					$new_transfer_item_list_id = $new_row_id;
				}
			}
		}

		$activity = array(
			'user' => $this->session->userdata('user_id'),
			'module' => 'Items',
			'module_field_id' => $new_transfer_id,
			'activity' => 'activity_invoice_created',
			'icon' => 'fa-shopping-cart',
			'link' => !empty($new_transfer_item_list_id) ? 'admin/items/transfer_details/' . $new_transfer_item_list_id : 'admin/items/transferItem',
			'value1' => $new_reference_no
		);
		$this->items_model->_table_name = 'tbl_activities';
		$this->items_model->_primary_key = 'activities_id';
		$this->items_model->save($activity);

		$type = 'success';
		$message = lang('item_cloned');
		$redirect_url = !empty($new_transfer_item_list_id)
			? base_url('admin/items/transfer_details/' . $new_transfer_item_list_id)
			: base_url('admin/items/transferItem');
		if ($this->input->is_ajax_request()) {
			echo json_encode(array("status" => $type, 'message' => $message, 'redirect' => $redirect_url));
			exit();
		}
		set_message($type, $message);
		redirect($redirect_url);
	}

	public function transfer_details($id = NULL)
	{
		$data['title'] = 'Transfer Details';
		if (!empty($id)) {

			$data['item_info'] = $this->db->query("SELECT tbl_transfer_itemlist.*, tbl_transfer_item.*,
            (select  tbl_warehouse.warehouse_name from tbl_warehouse where tbl_transfer_item. from_warehouse_id = tbl_warehouse.warehouse_id) as from_warehouse_name,
            (select  tbl_warehouse.warehouse_name from tbl_warehouse where tbl_transfer_item. to_warehouse_id = tbl_warehouse.warehouse_id) as to_warehouse_name,
            (select  tbl_warehouse.warehouse_code from tbl_warehouse where tbl_transfer_itemlist. warehouse_id = tbl_warehouse.warehouse_id) as warehouse_code
            FROM tbl_transfer_itemlist
            JOIN tbl_transfer_item ON tbl_transfer_itemlist.transfer_item_id = tbl_transfer_item.transfer_item_id
                WHERE transfer_itemList_id= ? ", array($id))->row();
		}


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


	public function createTransferItem($id = null)
	{
		$data['title'] = lang("transferItem");
		$data['dropzone'] = true;
		if (!empty($id)) {
			$data['items_info'] = get_row('tbl_transfer_item', array('transfer_item_id' => $id));
		}
		$data['items_info'] = get_row('tbl_transfer_item', array('transfer_item_id' => $id));
		$data['permission_user'] = $this->items_model->all_permission_user('30');



		$data['warehouseList'] = $this->items_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published'));
		$data['subview'] = $this->load->view('admin/items/transferItem/create', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load
	}

	public function saveTransferItem($id = null)
	{
		$created = can_action_by_label('transferItem', 'created');
		$edited = can_action_by_label('transferItem', 'edited');
		if (!empty($created) || !empty($edited) && !empty($id)) {
			$this->load->model('invoice_model');
			$data = $this->items_model->array_from_post(array('reference_no', 'date', 'from_warehouse_id', 'to_warehouse_id', 'status', 'notes', 'show_quantity_as'));


			$upload_file = array();

			$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,
							);
							array_push($upload_file, $up_data);
						}
					}
				}
			}

			$fileName = $this->input->post('fileName', true);
			$path = $this->input->post('path', true);
			$fullPath = $this->input->post('fullPath', true);
			$size = $this->input->post('size', true);
			$is_image = $this->input->post('is_image', true);

			if (!empty($fileName)) {
				foreach ($fileName as $key => $name) {
					$old['fileName'] = $name;
					$old['path'] = $path[$key];
					$old['fullPath'] = $fullPath[$key];
					$old['size'] = $size[$key];
					$old['is_image'] = $is_image[$key];

					array_push($upload_file, $old);
				}
			}
			if (!empty($upload_file)) {
				$data['attachment'] = json_encode($upload_file);
			} else {
				$data['attachment'] = null;
			}

			$data['shipping_cost'] = $this->input->post('adjustment', true);
			$from_warehouse_id = $this->input->post('from_warehouse_id', true);
			$to_warehouse_id = $this->input->post('to_warehouse_id', true);
			if (empty($from_warehouse_id) || empty($to_warehouse_id)) {
				set_message('error', lang('please_select_warehouse'));
				redirect('admin/items/createTransferItem' . (!empty($id) ? '/' . $id : ''));
			}
			$data['from_warehouse_id'] = $from_warehouse_id;
			$data['to_warehouse_id'] = $to_warehouse_id;

			if ($data['from_warehouse_id'] == $data['to_warehouse_id']) {
				set_message('error', lang('please_select_different_warehouse'));
				redirect('admin/items/createTransferItem' . (!empty($id) ? '/' . $id : ''));
			}
			if (!empty($data['to_warehouse_id'])) {
				$data['user_id'] = my_id();

				$tax['tax_name'] = $this->input->post('total_tax_name', TRUE);
				$tax['total_tax'] = $this->input->post('total_tax', TRUE);
				$data['total_tax'] = json_encode($tax);
				$i_tax = 0;
				if (!empty($tax['total_tax'])) {
					foreach ($tax['total_tax'] as $v_tax) {
						$i_tax += $v_tax;
					}
				}
				$data['tax'] = $i_tax;

				$permission = $this->input->post('permission', true);
				if (!empty($permission)) {
					if ($permission == 'everyone') {
						$assigned = 'all';
					} else {
						$assigned_to = $this->items_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';
					}
					$data['permission'] = $assigned;
				} else {
					set_message('error', lang('assigned_to') . ' Field is required');
					if (empty($_SERVER['HTTP_REFERER'])) {
						redirect('admin/items/createTransferItem');
					} else {
						redirect($_SERVER['HTTP_REFERER']);
					}
				}

				$this->invoice_model->_table_name = 'tbl_transfer_item';
				$this->invoice_model->_primary_key = 'transfer_item_id';

				if (!empty($id)) {
					$invoice_id = $id;

					$can_edit = $this->invoice_model->can_action('tbl_invoices', 'edit', array('invoices_id' => $id));
					if (!empty($can_edit)) {
						$this->invoice_model->save($data, $id);
					} else {
						set_message('error', lang('there_in_no_value'));
						redirect('admin/items/createTransferItem');
					}
					$action = ('activity_invoice_updated');
					$description = 'not_invoice_updated';
					$msg = lang('invoice_updated');
				} else {
					$this->invoice_model->_table_name = 'tbl_transfer_item';
					$this->invoice_model->_primary_key = 'transfer_item_id';
					$invoice_id = $this->invoice_model->save($data);

					$action = ('activity_invoice_created');
					$description = 'not_invoice_created';
					$msg = lang('invoice_created');
				}
				$qty_calculation = config_item('qty_calculation_from_items');
				$removed_items = $this->input->post('removed_items', TRUE);
				if (!empty($removed_items)) {
					foreach ($removed_items as $r_id) {
						if ($r_id != 'undefined') {
							if (!empty($qty_calculation) && $qty_calculation == 'Yes') {
								$itemInfo = get_row('tbl_items', array('items_id' => $r_id));
								if (!$this->invoice_model->return_items($itemInfo->saved_items_id, $itemInfo->quantity, $data['from_warehouse_id'])) {
									set_message('error', lang('stock_update_failed'));
									redirect($_SERVER['HTTP_REFERER']);
								}
							}
							$this->db->where('items_id', $r_id);
							$this->db->delete('tbl_items');
						}
					}
				}

				$itemsid = $this->input->post('items_id', TRUE);
				$items_data = $this->input->post('items', true);

				if (!empty($items_data)) {
					$valid_items_count = 0;
					$transfer_itemList_id = null;
					$index = 0;
					foreach ($items_data as $items) {
						$has_saved_item = !empty($items['saved_items_id']) && $items['saved_items_id'] != '0' && $items['saved_items_id'] != 'undefined';
						$has_manual_name = !empty($items['item_name']) && trim($items['item_name']) !== '';
						$has_positive_qty = !empty($items['quantity']) && (float) $items['quantity'] > 0;
						if (!$has_positive_qty || (!$has_saved_item && !$has_manual_name)) {
							continue;
						}

						$valid_items_count++;
						unset($items['invoice_items_id']);
						unset($items['total_qty']);
						$items['transfer_item_id'] = $invoice_id;
						$tax = 0;
						if (!empty($items['taxname'])) {
							foreach ($items['taxname'] as $tax_name) {
								$tax_rate = explode("|", $tax_name);
								$tax += $tax_rate[1];
							}
							$items['item_tax_name'] = $items['taxname'];
							unset($items['taxname']);
							$items['item_tax_name'] = json_encode($items['item_tax_name']);
						}
						if (empty($items['saved_items_id'])) {
							$items['saved_items_id'] = 0;
						}

						$price = $items['quantity'] * $items['unit_cost'];
						$items['item_tax_total'] = ($price / 100 * $tax);
						$items['total_cost'] = $price;
						$items['warehouse_id'] = $data['to_warehouse_id'];
						// get all client

						if ($has_saved_item && !empty($data['to_warehouse_id']) && !empty($data['from_warehouse_id']) && $data['status'] == 'approved') {
							$this->items_model->_table_name = 'tbl_warehouses_products';
							$this->items_model->_primary_key = 'id';
							$check = get_row('tbl_warehouses_products', array('warehouse_id' => $data['to_warehouse_id'], 'product_id' => $items['saved_items_id']));
							$check2 = get_row('tbl_warehouses_products', array('warehouse_id' => $data['from_warehouse_id'], 'product_id' => $items['saved_items_id']));

							if (!empty($check)) {
								$_data['quantity'] = $items['quantity'] + $check->quantity;
								$_data_id = $check->id;
								$this->items_model->save($_data, $_data_id);
								$_data['quantity'] = $items['quantity'] - $check->quantity;
								$_data_id = $check2->id;
								$this->items_model->save($_data, $_data_id);
							} else {
								$_data['quantity'] = $items['quantity'];
								$_data['warehouse_id'] = $data['to_warehouse_id'];
								$_data['product_id'] = $items['saved_items_id'];
								$this->items_model->save($_data);
								$_data['quantity'] = $items['quantity'] - $check2->quantity;
								$_data_id = $check2->id;
								$this->items_model->save($_data, $_data_id);
							}
						}


						$this->invoice_model->_table_name = 'tbl_transfer_itemlist';
						$this->invoice_model->_primary_key = 'transfer_itemList_id';

						$existing_item_id = !empty($items['items_id']) ? $items['items_id'] : null;
						if (isset($items['items_id'])) {
							unset($items['items_id']);
						}
						if (!empty($existing_item_id)) {
							if (!empty($qty_calculation) && $qty_calculation == 'Yes') {
								// $this->check_existing_qty($items_id, $items['quantity']);
							}
							$this->invoice_model->save($items, $existing_item_id);
						} else {
							if (!empty($items['saved_items_id']) && $items['saved_items_id'] != 'undefined') {
								// $this->invoice_model->reduce_items($items['saved_items_id'], $items['quantity']);
							}

							$transfer_itemList_id = $this->invoice_model->save($items);
						}
						$index++;
					}

					if (empty($valid_items_count)) {
						set_message('error', lang('please_select_item'));
						redirect('admin/items/createTransferItem' . (!empty($id) ? '/' . $id : ''));
					}
				} else {
					set_message('error', lang('please_select_item'));
					redirect('admin/items/createTransferItem' . (!empty($id) ? '/' . $id : ''));
				}

				if (empty($transfer_itemList_id)) {
					$first_transfer_item = $this->db->where('transfer_item_id', $invoice_id)->limit(1)->get('tbl_transfer_itemlist')->row();
					if (!empty($first_transfer_item)) {
						$transfer_itemList_id = $first_transfer_item->transfer_itemList_id;
					}
				}
				$activity = array(
					'user' => $this->session->userdata('user_id'),
					'module' => 'Items',
					'module_field_id' => $invoice_id,
					'activity' => $action,
					'icon' => 'fa-shopping-cart',
					'link' => !empty($transfer_itemList_id) ? 'admin/items/transfer_details/' . $transfer_itemList_id : 'admin/items/transferItem',
					'value1' => $data['reference_no']
				);
				$this->invoice_model->_table_name = 'tbl_activities';
				$this->invoice_model->_primary_key = 'activities_id';
				$this->invoice_model->save($activity);

				// messages for user
				$type = "success";
				$message = $msg;
				set_message($type, $message);
				redirect('admin/items/transferItem');
			} else {
				redirect('admin/items/createTransferItem');
			}
		} else {

			set_message('error', lang('please_select_warehouse'));


			redirect('admin/items/createTransferItem');
		}
	}


	function check_existing_qty($items_id, $qty)
	{
		$items_info = $this->db->where('items_id', $items_id)->get('tbl_items')->row();
		if ($items_info->quantity != $qty) {
			if ($qty > $items_info->quantity) {
				$reduce_qty = $qty - $items_info->quantity;
				if (!empty($items_info->saved_items_id)) {
					if (!$this->invoice_model->reduce_items($items_info->saved_items_id, $reduce_qty)) {
						return false;
					}
				}
			}
			if ($qty < $items_info->quantity) {
				$return_qty = $items_info->quantity - $qty;
				if (!empty($items_info->saved_items_id)) {
					if (!$this->invoice_model->return_items($items_info->saved_items_id, $return_qty)) {
						return false;
					}
				}
			}
		}
		return true;
	}

	function getItemBywarehouse($warehouse_id)
	{
		$saved_items = $this->items_model->select_group_data('tbl_saved_items', 'customer_group', 'saved_items_id', 'saved_items_id,item_name,item_desc,unit_cost', ['tbl_customer_group.type' => 'items', 'tbl_saved_items.warehouse_id' => $warehouse_id], ['tbl_customer_group' => 'tbl_customer_group.customer_group_id = tbl_saved_items.customer_group_id'], true);
		$html = '<option value=""></option>';
		if (!empty($saved_items)) {
			foreach ($saved_items as $group => $v_saved_items) {
				$html .= '<optgroup label="' . $group . '">';
				foreach ($v_saved_items as $v_saved_item) {
					$html .= '<option  data-subtext="' . strip_html_tags(mb_substr($v_saved_item->item_desc, 0, 200)) . '...' . '" value="' . $v_saved_item->saved_items_id . '" >' . '(' . display_money($v_saved_item->unit_cost, default_currency()) . ')' . $v_saved_item->item_name . '</option>';
				}
				$html .= '</optgroup>';
			}
		}
		echo json_encode($html);
		exit();
	}

	public function manuallyItems()
	{
		$data['title'] = lang('added') . ' ' . lang('manually');
		$this->load->view('admin/items/manually_items', $data, false);
	}

	public function openItems()
	{
		$data['title'] = lang('search') . ' ' . lang('items');
		$this->load->view('admin/items/open_items', $data, false);
	}

	public function saved_manufacturer($id = null)
	{
		$is_update = !empty($id);
		$data = $this->items_model->array_from_post(array('manufacturer', 'description'));
		$this->items_model->_table_name = "tbl_manufacturer"; //table name
		$this->items_model->_primary_key = "manufacturer_id";
		$manufacturer_id = $this->items_model->save($data, $id);
		// messages for user
		$type = "success";
		if ($is_update) {
			$message = lang('manufacturer_updated');
		} else {
			$message = lang('manufacturer_added');
		}

		if ($this->input->is_ajax_request()) {
			echo json_encode(array(
				"status" => $type,
				"message" => $message,
				"id" => $manufacturer_id,
				"manufacturer" => $data['manufacturer'],
				"text" => $data['manufacturer'],
				"name" => $data['manufacturer'],
			));
			exit();
		}

		set_message($type, $message);
		redirect('admin/items/items_manufacturerlist');
	}

	// delete manufacturer
	public function delete_manufacturer($id)
	{
		$this->items_model->_table_name = "tbl_manufacturer"; //table name
		$this->items_model->_primary_key = "manufacturer_id";
		$this->items_model->delete($id);

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

	public function TransferItemDetails($id = null)
	{
		$data['title'] = lang("transferItem");
		$data['dropzone'] = true;
		$data['warehouseList'] = $this->items_model->select_data('tbl_warehouse', 'warehouse_id', 'warehouse_name', array('status' => 'published'));
		$data['subview'] = $this->load->view('admin/items/transferItem/TransferItemDetails', $data, TRUE);
		$this->load->view('admin/_layout_main', $data); //page load

	}

	public
	function clone_transfer_item($item_id)
	{
		$created = can_action_by_label('transferItem', 'created');
		$edited = can_action_by_label('transferItem', 'edited');
		$can_edit = $this->items_model->can_action('tbl_transfer_itemlist', 'edit', array('transfer_itemList_id' => $item_id));

		if (!empty($can_edit) && (!empty($created) || !empty($edited))) {

			$data['item_info'] = $this->items_model->check_by(array('transfer_itemList_id' => $item_id), 'tbl_transfer_itemlist');
			$data['all_warehouse'] = $this->items_model->get_permission('tbl_warehouse');


			$data['modal_subview'] = $this->load->view('admin/items/transferItem/_modal_clone_transferitem', $data, FALSE);
		} else {
			set_message('error', lang('no_permission'));
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public function manufacturer()
	{
		$data['title'] = lang('manufacturer');
		$this->load->view('admin/items/manufacturer', $data, FALSE);
	}

	public function update_manufacturer($id = null)
	{
		$this->items_model->_table_name = 'tbl_manufacturer';
		$this->items_model->_primary_key = 'manufacturer_id';

		$cate_data['manufacturer'] = $this->input->post('manufacturer', TRUE);
		// update root category
		$where = array('manufacturer' => $cate_data['manufacturer']);
		// duplicate value check in DB
		if (!empty($id)) { // if id exist in db update data
			$manufacturer_id = array('manufacturer_id !=' => $id);
		} else { // if id is not exist then set id as null
			$manufacturer_id = null;
		}
		// check whether this input data already exist or not
		$check_category = $this->items_model->check_update('tbl_manufacturer', $where, $manufacturer_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['manufacturer'] . '</strong>  ' . lang('already_exist');
		} else { // save and update query
			$id = $this->items_model->save($cate_data, $id);

			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'settings',
				'module_field_id' => $id,
				'activity' => ('manufacturer_added'),
				'value1' => $cate_data['manufacturer']
			);
			$this->items_model->_table_name = 'tbl_activities';
			$this->items_model->_primary_key = 'activities_id';
			$this->items_model->save($activity);

			// messages for user
			$type = "success";
			$msg = lang('manufacturer_added');
		}

		if (!empty($id)) {
			$result = array(
				'id' => $id,
				'manufacturer' => $cate_data['manufacturer'],
				'text' => $cate_data['manufacturer'],
				'name' => $cate_data['manufacturer'],
				'status' => $type,
				'message' => $msg,
			);
		} else {
			$result = array(
				'manufacturer' => $cate_data['manufacturer'],
				'text' => $cate_data['manufacturer'],
				'name' => $cate_data['manufacturer'],
				'status' => $type,
				'message' => $msg,
			);
		}
		echo json_encode($result);
		exit();
	}

	public function pdf_transferitem($id)
	{
		$data['item_info'] = $this->db->query("SELECT tbl_transfer_itemlist.*, tbl_transfer_item.*,
        (select  tbl_warehouse.warehouse_name from tbl_warehouse where tbl_transfer_item. from_warehouse_id = tbl_warehouse.warehouse_id) as from_warehouse_name,
        (select  tbl_warehouse.warehouse_name from tbl_warehouse where tbl_transfer_item. to_warehouse_id = tbl_warehouse.warehouse_id) as to_warehouse_name,
        (select  tbl_warehouse.warehouse_code from tbl_warehouse where tbl_transfer_itemlist. warehouse_id = tbl_warehouse.warehouse_id) as warehouse_code
        FROM tbl_transfer_itemlist
        JOIN tbl_transfer_item ON tbl_transfer_itemlist.transfer_item_id = tbl_transfer_item.transfer_item_id
            WHERE transfer_itemList_id= ? ", array($id))->row();

		$data['title'] = lang('transfer') . ' ' . "PDF"; //Page title
		$this->load->helper('dompdf');
		$viewfile = $this->load->view('admin/items/transferItem/transfer_pdf', $data, TRUE);

		pdf_create($viewfile, lang('transfer') . '# ' . $data['item_info']->reference_no);
	}

	public function change_status($id, $status)
	{
		$edited = can_action('39', 'edited');
		$can_edit = $this->invoice_model->can_action('tbl_transfer_item', 'edit', array('transfer_item_id' => $id));
		if (!empty($can_edit) && !empty($edited)) {
			$item_info = $this->items_model->check_by(array('transfer_item_id' => $id), 'tbl_transfer_item');
			$now_status = $item_info->status;
			$to_warehouse_id = $item_info->to_warehouse_id;
			$from_warehouse_id = $item_info->from_warehouse_id;
			$product_list = get_result('tbl_transfer_itemlist', array('transfer_item_id' => $item_info->transfer_item_id));

			if ($now_status == 'approved' && $status != 'approved') {
				if ($status != "complete") {

					$this->UpdateProductQty($product_list, $from_warehouse_id, $to_warehouse_id);
				}
			} elseif ($now_status == 'complete' && $status != 'complete') {
				$this->UpdateProductQty($product_list, $from_warehouse_id, $to_warehouse_id);
			} elseif ($status == 'approved' || $status == 'complete') {
				$this->UpdateProductQty($product_list, $to_warehouse_id, $from_warehouse_id);
			}

			$data['status'] = $status;
			$this->items_model->_table_name = 'tbl_transfer_item';
			$this->items_model->_primary_key = 'transfer_item_id';
			$lastid = $this->items_model->save($data, $id);
			// messages for user
			$type = "success";
			$message = lang('change_status');
			set_message($type, $message);
		}
		if (empty($_SERVER['HTTP_REFERER'])) {
			redirect('admin/projects');
		} else {
			redirect($_SERVER['HTTP_REFERER']);
		}
	}
	// to_warehouse_id is increase productQty in warehouse
	// from_warehouse_id is decrease productQty in warehouse
	public function UpdateProductQty($product_list, $to_warehouse_id, $from_warehouse_id)
	{
		$this->items_model->_table_name = 'tbl_warehouses_products';
		$this->items_model->_primary_key = 'id';

		foreach ($product_list as $key) {

			$check_already_exist_by_to_id = get_row('tbl_warehouses_products', array('warehouse_id' => $to_warehouse_id, 'product_id' => $key->saved_items_id));
			$check_already_exist_by_from_id = get_row('tbl_warehouses_products', array('warehouse_id' => $from_warehouse_id, 'product_id' => $key->saved_items_id));

			if (!empty($check_already_exist_by_to_id)) {
				$_data['quantity'] = $key->quantity + $check_already_exist_by_to_id->quantity;
				$_data_id = $check_already_exist_by_to_id->id;
				$this->items_model->save($_data, $_data_id);
				$_data2['quantity'] = $check_already_exist_by_from_id->quantity - $key->quantity;
				$data2_id = $check_already_exist_by_from_id->id;
				$this->items_model->save($_data2, $data2_id);
			} else {

				$_data['quantity'] = $key->quantity;
				$_data['warehouse_id'] = $to_warehouse_id;
				$_data['product_id'] = $key->saved_items_id;
				$this->items_model->save($_data);

				$data['quantity'] = $check_already_exist_by_from_id->quantity - $key->quantity;
				$_data_id = $check_already_exist_by_from_id->id;
				$this->items_model->save($data, $_data_id);
			}
		}
	}

	public function delete_transfer($id)
	{
		$deleted = can_action('39', 'deleted');
		if (!empty($deleted)) {
			$items_info = $this->items_model->check_by(array('transfer_item_id' => $id), 'tbl_transfer_item');
			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'items',
				'module_field_id' => $id,
				'activity' => 'activity_transfer_items_deleted',
				'icon' => 'fa-circle-o',
				'value1' => $items_info->reference_no
			);
			$this->items_model->_table_name = 'tbl_activities';
			$this->items_model->_primary_key = 'activities_id';
			//$this->items_model->save($activity);

			$this->items_model->_table_name = 'tbl_transfer_item';
			$this->items_model->_primary_key = 'transfer_item_id';
			$this->items_model->delete($id);
			$to_warehouse_id = $items_info->to_warehouse_id;
			$from_warehouse_id = $items_info->from_warehouse_id;
			$transfer_info = get_result('tbl_transfer_itemlist', array('transfer_item_id' => $items_info->transfer_item_id));
			if (!empty($transfer_info)) {
				$this->UpdateProductQty($transfer_info, $from_warehouse_id, $to_warehouse_id);

				foreach ($transfer_info as $t_v_files) {
					$this->items_model->_table_name = "tbl_transfer_itemlist"; //table name
					$this->items_model->delete_multiple(array('transfer_item_id' => $t_v_files->transfer_item_id));
				}
			}

			$type = 'success';
			$message = lang('items_deleted');
		} else {
			$type = "error";
			$message = lang('no_permission');
		}
		if (!empty($bulk)) {
			return (array("status" => $type, 'message' => $message));
		}
		echo json_encode(array("status" => $type, 'message' => $message));
		exit();
	}

	// modifiers
	public function modifiers()
	{
		$data['title'] = lang('modifiers');
		$data['all_modifiers'] = get_order_by('tbl_restaurant_modifiers', array('status' => 'active'), 'created_at');
		$data['subview'] = $this->load->view('admin/items/modifiers', $data, true);
		// $get_modifiers = $this->common_model->get_all_modifiers_by_item(1);
		// $data['all_modifiers'] = $get_modifiers;
		// $data['subview'] = $this->load->view('admin/items/open_modifier', $data, true);
		$this->load->view('admin/_layout_main', $data);
	}
	// create modifiers
	public function create_modifier($id = null)
	{
		$data['title'] = lang('modifier');
		if (!empty($id)) {
			$modifier_info = $this->items_model->check_by(array('modifier_id' => $id), 'tbl_restaurant_modifiers');
			if (!empty($modifier_info)) {
				$modifier_info->modifier_items = (!empty($modifier_info->modifier_items) ? json_decode($modifier_info->modifier_items) : []);
				$modifier_info->linked_categories = (!empty($modifier_info->linked_categories) ? json_decode($modifier_info->linked_categories) : []);
				$modifier_info->linked_items = (!empty($modifier_info->linked_items) ? json_decode($modifier_info->linked_items) : []);
			}
			$data['modifier_info'] = $modifier_info;
		}
		$data['subview'] = $this->load->view('admin/items/create_modifier', $data, true);
		$this->load->view('admin/_layout_main', $data);
	}

	// save modifiers
	public function save_modifier($id = null)
	{
		$modifier_name = $this->input->post('modifier_name', true);
		if (empty($modifier_name)) {
			set_message('error', lang('please_enter_modifier_name'));
			redirect('admin/items/modifiers');
		}

		$data['modifier_name'] = $modifier_name;
		$auto_popup = $this->input->post('auto_popup', true);
		$linked_categories = $this->input->post('linked_categories', true);
		$linked_items = $this->input->post('linked_items', true);
		$item_name = $this->input->post('item_name', true);
		$item_description = $this->input->post('item_description', true);
		$item_price = $this->input->post('item_price', true);
		$default_selected = $this->input->post('default_selected', true);
		$item_order = $this->input->post('item_order', true);
		$data['linked_categories'] = !empty($linked_categories) ? json_encode($linked_categories) : null;
		$data['linked_items'] = !empty($linked_items) ? json_encode($linked_items) : null;
		$data['auto_popup'] = !empty($auto_popup) ? 'Yes' : 'No';
		$data['status'] = 'active';

		$this->items_model->_table_name = "tbl_restaurant_modifiers"; //table name
		$this->items_model->_primary_key = "modifier_id";
		$id = $this->items_model->save($data, $id);
		// save modifier items
		$items = array();
		if (!empty($item_name)) {
			foreach ($item_name as $key => $name) {
				if (!empty($name)) {
					$items[] = array(
						'item_id' => $id . '_' . ($key + 1),
						'item_name' => $name,
						'item_description' => (!empty($item_description[$key]) ? $item_description[$key] : ''),
						'item_price' => (!empty($item_price[$key]) ? $item_price[$key] : 0),
						'default_selected' => (!empty($default_selected[$key]) && $default_selected[$key] == 'Yes' ? 'Yes' : 'No'),
						'item_order' => (!empty($item_order[$key]) ? $item_order[$key] : $key),
					);
				}
			}
		}
		$data['modifier_items'] = json_encode($items);
		$this->items_model->save($data, $id);

		// messages for user
		$type = "success";
		if (!empty($id)) {
			$message = lang('modifiers_added');
		} else {
			$message = lang('modifiers_updated');
			$this->items_model->save($data, $id);
		}
		set_message($type, $message);
		redirect('admin/items/modifiers');
	}
	// delete modifier
	public function delete_modifier($id)
	{
		$modifier_info = $this->items_model->check_by(array('modifier_id' => $id), 'tbl_restaurant_modifiers');
		if (!empty($modifier_info)) {
			$this->items_model->_table_name = "tbl_restaurant_modifiers"; //table name
			$this->items_model->_primary_key = "modifier_id";
			$this->items_model->delete($id);


			// save activities
			$activity = array(
				'user' => $this->session->userdata('user_id'),
				'module' => 'items',
				'module_field_id' => $id,
				'activity' => 'activity_modifier_deleted',
				'icon' => 'fa-circle-o',
				'value1' => $modifier_info->modifier_name
			);
			$this->items_model->_table_name = 'tbl_activities';
			$this->items_model->_primary_key = 'activities_id';
			$this->items_model->save($activity);

			$type = 'success';
			$message = lang('modifiers_deleted');
		} else {
			$type = 'error';
			$message = lang('no_modifier_found');
		}
		set_message($type, $message);
		redirect('admin/items/modifiers');
	}

	// copy_modifier
	public function copy_modifier($id)
	{
		$modifier_info = $this->items_model->check_by(array('modifier_id' => $id), 'tbl_restaurant_modifiers');
		if (!empty($modifier_info)) {
			$data = array(
				'modifier_name' => $modifier_info->modifier_name . ' ' . lang('copy'),
				'modifier_items' => $modifier_info->modifier_items,
				'linked_categories' => $modifier_info->linked_categories,
				'linked_items' => $modifier_info->linked_items,
				'auto_popup' => $modifier_info->auto_popup,
				'status' => $modifier_info->status,
			);
			$this->items_model->_table_name = "tbl_restaurant_modifiers"; //table name
			$this->items_model->_primary_key = "modifier_id";
			$this->items_model->save($data);
			// messages for user
			$type = "success";
			$message = lang('modifiers_copied');
		} else {
			$type = "error";
			$message = lang('no_modifier_found');
		}
		set_message($type, $message);
		redirect('admin/items/modifiers');
	}
}
