https://t.me/RX1948
Server : Apache/2.4.18 (Ubuntu)
System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64
User : oppastar ( 1041)
PHP Version : 7.0.33-0ubuntu0.16.04.15
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Directory :  /var/www/laciasmara.com/public_html/shop/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/laciasmara.com/public_html/shop/application/controllers/admin/Orders_retailer.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Orders_retailer extends Admin_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->model('order_m');
		$this->load->model('order_detail_m');
		$this->load->model('configuration_m');
		$this->load->model('customer_m');
		$this->load->model('product_m');
	}

	public function alldata()
	{

		$draw = $_REQUEST['draw'];
		$length = $_REQUEST['length'];
		$start = $_REQUEST['start'];
		$search = $_REQUEST['search']["value"];
		$total = $this->db->count_all_results("users");

		$filterkey = $this->security->xss_clean($this->input->post('filterkey'));
		$dataenter = $this->security->xss_clean($this->input->post('dataenter'));

		$output = array();

		$output['draw'] = $draw;
		$output['recordsTotal'] = $output['recordsFiltered'] = $total;
		$output['data'] = array();

		if ($filterkey == 'date') {
			$ex = explode('_', $dataenter);
			$startdate = $ex[0] . ' 00:00:00';
			$enddate = $ex[1] . ' 23:59:59';
			$dataenter = $startdate . '_' . $enddate;
		}

		$query = $this->order_m->filterdataretailer($search, $filterkey, $dataenter, $this->session->userdata('admin')['id'], $length, $start);

		$jum = $this->order_m->filterdataretailer($search, $filterkey, $dataenter, $this->session->userdata('admin')['id'], '', '');
		$output['recordsTotal'] = $output['recordsFiltered'] = $jum->num_rows();

		$nomor_urut = $start + 1;
		foreach ($query->result() as $order) {
			$first_discount = 0;

			if ($order->first == 1) {
				if ($order->order_date >= '2024-08-01') {
					if (empty($order->refferal)) {
						$first_discount = $order->total_amount * 0.05;
					} else {
						if ($order->referral == 'laciput') {
							$first_discount = $order->total_amount * 0.05;
						} else {
							$first_discount = $order->total_amount * 0.1;
						}
					}
				} else {
					$first_discount = $order->total_amount * 0.05;
				}
			}

			$final_grand_total = 0;
			$finalshippingfee = 0;
			$calculate_finalshippingfee = $order->shipping_fee - $order->free_shipping_fee;
			if ($calculate_finalshippingfee > 0) {
				$finalshippingfee = $calculate_finalshippingfee;
			}
			if ($order->insurance_status == 'Yes') {
				$insurace = $order->insurance_cost;
			} else {
				$insurace = 0;
			}
			$grand_total =  ($order->total_amount + $insurace - $order->redeemed_voucher_amount - $order->minus_reward_amount) + ($finalshippingfee);
			if ($grand_total > 0) {
				$final_grand_total = $grand_total - $first_discount;
			} else {
				//check if finalshippingfee is > 0
				if ($finalshippingfee > 0) {
					$final_grand_total = $finalshippingfee;
				}
			}

			//check this order if it does contain indent item
			$count_indent = $this->db->select('is_backorder')->from('orders_detail')->where('orders_id', $order->id_orders)->where('is_backorder', 'yes')->get()->num_rows();

			if ($count_indent > 0) {
				//indent exist.
				$is_indent = 'ya';
			} else {
				$is_indent = 'tidak';
			}

			$wareid = $this->order_m->warestats($order->id_orders);
			$status = $this->order_m->paystats($order->payment_status);

			if ($order->doku_payment_channel == 15) {
				$doku_payment_channel = 'Credit Card';
				$paycon = $order->doku_approval_result . ' ' . $doku_payment_channel;
			} else {
				$paycon = $this->order_m->paymettype($order->payment_type, $order->payment_confirm, $order->payment_status_message);
			}

			$output['data'][] = array(
				$nomor_urut,
				$order->id_orders,
				date('j M Y H:i:s', strtotime($order->order_date)),
				ucwords($order->recipient_name),
				'<div style="text-align: right;">' . number_format($final_grand_total) . '</div>',
				ucwords($order->payment_type),
				$status,
				$paycon,
				//$wareid,
				$is_indent,
				'<a style="text-decoration: underline;" href="' . base_url('admin/orders_retailer/view') . '/' . $order->id_orders . '">Lihat</a>',
				$order->created_by
			);
			$nomor_urut++;
		}

		echo json_encode($output);
	}

	public function incoming()
	{
		$draw = $_REQUEST['draw'];
		$length = $_REQUEST['length'];
		$start = $_REQUEST['start'];


		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(0, 1, 3));
		$total = $this->db->count_all_results();

		$output = array();
		$output['draw'] = $draw;
		$output['recordsTotal'] = $output['recordsFiltered'] = $total;
		$output['data'] = array();

		$this->db->select('orders.*, customers.reseller_id');
		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(0, 1, 3));
		$this->db->order_by('orders.order_date', 'DESC');
		$this->db->limit($length, $start);
		$query = $this->db->get();

		$nomor_urut = $start + 1;
		foreach ($query->result() as $order) {
			$first_discount = 0;

			if ($order->first == 1) {
				if ($order->order_date >= '2024-08-01') {
					if (empty($order->referral)) {
						$first_discount = $order->total_amount * 0.05;
					} else {
						if ($order->referral == 'laciput') {
							$first_discount = $order->total_amount * 0.05;
						} else {
							$first_discount = $order->total_amount * 0.1;
						}
					}
				} else {
					$first_discount = $order->total_amount * 0.05;
				}
			}


			$final_grand_total = 0;
			$finalshippingfee = 0;
			$calculate_finalshippingfee = $order->shipping_fee - $order->free_shipping_fee;
			if ($calculate_finalshippingfee > 0) {
				$finalshippingfee = $calculate_finalshippingfee;
			}
			if ($order->insurance_status == 'Yes') {
				$insurace = $order->insurance_cost;
			} else {
				$insurace = 0;
			}
			$grand_total =  ($order->total_amount + $insurace - $order->redeemed_voucher_amount - $order->minus_reward_amount) + ($finalshippingfee);
			if ($grand_total > 0) {
				$final_grand_total = $grand_total - $first_discount;
			} else {
				//check if finalshippingfee is > 0
				if ($finalshippingfee > 0) {
					$final_grand_total = $finalshippingfee;
				}
			}

			//check this order if it does contain indent item
			$count_indent = $this->db->select('is_backorder')->from('orders_detail')->where('orders_id', $order->id_orders)->where('is_backorder', 'yes')->get()->num_rows();

			if ($count_indent > 0) {
				//indent exist.
				$is_indent = 'ya';
			} else {
				$is_indent = 'tidak';
			}

			$wareid = $this->order_m->warestats($order->id_orders);
			$status = $this->order_m->paystats($order->payment_status);
			$referral = $order->referral;
			$affiliate = '';

			$query = "SELECT COUNT(*) as count FROM affiliator_register WHERE referral = ?";
			$result_referral = $this->db->query($query, array($referral))->row();

			if ($result_referral->count > 0) {
				$affiliate = '<br><span style="background-color:green;" class="badge badge-pill badge-success">Affiliate</span>';
			}

			if ($order->doku_payment_channel == 15) {
				$doku_payment_channel = 'Credit Card';
				$paycon = $order->doku_approval_result . ' ' . $doku_payment_channel;
			} else {
				$paycon = $this->order_m->paymettype($order->payment_type, $order->payment_confirm, $order->payment_status_message);
			}

			$output['data'][] = array(
				$nomor_urut,
				$order->id_orders . $affiliate,
				date('j M Y H:i:s', strtotime($order->order_date)),
				ucwords($order->recipient_name),
				'<div style="text-align: right;">' . number_format($final_grand_total) . '</div>',
				ucwords($order->payment_type),
				$status,
				$paycon,
				//$wareid,
				$is_indent,
				'<a style="text-decoration: underline;" href="' . base_url('admin/orders_retailer/view') . '/' . $order->id_orders . '">Lihat</a>',
				$order->created_by
			);
			$nomor_urut++;
		}

		echo json_encode($output);
	}

	public function processing()
	{
		$draw = $_REQUEST['draw'];
		$length = $_REQUEST['length'];
		$start = $_REQUEST['start'];

		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(4));
		$total = $this->db->count_all_results();

		$output = array();
		$output['draw'] = $draw;
		$output['recordsTotal'] = $output['recordsFiltered'] = $total;
		$output['data'] = array();

		$this->db->select('orders.*, customers.reseller_id');
		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(4));
		$this->db->order_by('orders.order_date', 'DESC');
		$this->db->limit($length, $start);
		$query = $this->db->get();

		$nomor_urut = $start + 1;
		foreach ($query->result() as $order) {
			$first_discount = 0;

			if ($order->first == 1) {
				if ($order->order_date >= '2024-08-01') {
					if (empty($order->refferal)) {
						$first_discount = $order->total_amount * 0.05;
					} else {
						if ($order->referral == 'laciput') {
							$first_discount = $order->total_amount * 0.05;
						} else {
							$first_discount = $order->total_amount * 0.1;
						}
					}
				} else {
					$first_discount = $order->total_amount * 0.05;
				}
			}


			$final_grand_total = 0;
			$finalshippingfee = 0;
			$calculate_finalshippingfee = $order->shipping_fee - $order->free_shipping_fee;
			if ($calculate_finalshippingfee > 0) {
				$finalshippingfee = $calculate_finalshippingfee;
			}
			if ($order->insurance_status == 'Yes') {
				$insurace = $order->insurance_cost;
			} else {
				$insurace = 0;
			}
			$grand_total =  ($order->total_amount + $insurace - $order->redeemed_voucher_amount - $order->minus_reward_amount) + ($finalshippingfee);
			if ($grand_total > 0) {
				$final_grand_total = $grand_total - $first_discount;
			} else {
				//check if finalshippingfee is > 0
				if ($finalshippingfee > 0) {
					$final_grand_total = $finalshippingfee;
				}
			}

			//check this order if it does contain indent item
			$count_indent = $this->db->select('is_backorder')->from('orders_detail')->where('orders_id', $order->id_orders)->where('is_backorder', 'yes')->get()->num_rows();

			if ($count_indent > 0) {
				//indent exist.
				$is_indent = 'ya';
			} else {
				$is_indent = 'tidak';
			}

			$wareid = $this->order_m->warestats($order->id_orders);
			$status = $this->order_m->paystats($order->payment_status);
			$referral = $order->referral;
			$affiliate = '';

			$query = "SELECT COUNT(*) as count FROM affiliator_register WHERE referral = ?";
			$result_referral = $this->db->query($query, array($referral))->row();

			if ($result_referral->count > 0) {
				$affiliate = '<br><span style="background-color:green;" class="badge badge-pill badge-success">Affiliate</span>';
			}

			if ($order->doku_payment_channel == 15) {
				$doku_payment_channel = 'Credit Card';
				$paycon = $order->doku_approval_result . ' ' . $doku_payment_channel;
			} else {
				$paycon = $this->order_m->paymettype($order->payment_type, $order->payment_confirm, $order->payment_status_message);
			}

			$output['data'][] = array(
				$nomor_urut,
				$order->id_orders . $affiliate,
				date('j M Y H:i:s', strtotime($order->order_date)),
				ucwords($order->recipient_name),
				'<div style="text-align: right;">' . number_format($final_grand_total) . '</div>',
				ucwords($order->payment_type),
				$status,
				$paycon,
				//$wareid,
				$is_indent,
				'<a style="text-decoration: underline;" href="' . base_url('admin/orders_retailer/view') . '/' . $order->id_orders . '">Lihat</a>',
				$order->created_by
			);
			$nomor_urut++;
		}

		echo json_encode($output);
	}

	public function completed()
	{
		$draw = $_REQUEST['draw'];
		$length = $_REQUEST['length'];
		$start = $_REQUEST['start'];

		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(2, 5));
		$total = $this->db->count_all_results();

		$output = array();
		$output['draw'] = $draw;
		$output['recordsTotal'] = $output['recordsFiltered'] = $total;
		$output['data'] = array();

		$this->db->select('orders.*, customers.reseller_id');
		$this->db->from('orders');
		$this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
		$this->db->where('customers.reseller_id IS NOT NULL');
		$this->db->where_in('orders.payment_status', array(2, 5));
		$this->db->order_by('orders.order_date', 'DESC');
		$this->db->limit($length, $start);
		$query = $this->db->get();

		$nomor_urut = $start + 1;
		foreach ($query->result() as $order) {
			$first_discount = 0;

			if ($order->first == 1) {
				if ($order->order_date >= '2024-08-01') {
					if (empty($order->refferal)) {
						$first_discount = $order->total_amount * 0.05;
					} else {
						if ($order->referral == 'laciput') {
							$first_discount = $order->total_amount * 0.05;
						} else {
							$first_discount = $order->total_amount * 0.1;
						}
					}
				} else {
					$first_discount = $order->total_amount * 0.05;
				}
			}


			$final_grand_total = 0;
			$finalshippingfee = 0;
			$calculate_finalshippingfee = $order->shipping_fee - $order->free_shipping_fee;
			if ($calculate_finalshippingfee > 0) {
				$finalshippingfee = $calculate_finalshippingfee;
			}
			if ($order->insurance_status == 'Yes') {
				$insurace = $order->insurance_cost;
			} else {
				$insurace = 0;
			}
			$grand_total =  ($order->total_amount + $insurace - $order->redeemed_voucher_amount - $order->minus_reward_amount) + ($finalshippingfee);
			if ($grand_total > 0) {
				$final_grand_total = $grand_total - $first_discount;
			} else {
				//check if finalshippingfee is > 0
				if ($finalshippingfee > 0) {
					$final_grand_total = $finalshippingfee;
				}
			}

			//check this order if it does contain indent item
			$count_indent = $this->db->select('is_backorder')->from('orders_detail')->where('orders_id', $order->id_orders)->where('is_backorder', 'yes')->get()->num_rows();

			if ($count_indent > 0) {
				//indent exist.
				$is_indent = 'ya';
			} else {
				$is_indent = 'tidak';
			}

			$wareid = $this->order_m->warestats($order->id_orders);
			$status = $this->order_m->paystats($order->payment_status);
			$referral = $order->referral;
			$affiliate = '';

			$query = "SELECT COUNT(*) as count FROM affiliator_register WHERE referral = ?";
			$result_referral = $this->db->query($query, array($referral))->row();

			if ($result_referral->count > 0) {
				$affiliate = '<br><span style="background-color:green;" class="badge badge-pill badge-success">Affiliate</span>';
			}

			if ($order->doku_payment_channel == 15) {
				$doku_payment_channel = 'Credit Card';
				$paycon = $order->doku_approval_result . ' ' . $doku_payment_channel;
			} else {
				$paycon = $this->order_m->paymettype($order->payment_type, $order->payment_confirm, $order->payment_status_message);
			}

			$output['data'][] = array(
				$nomor_urut,
				$order->id_orders . $affiliate,
				date('j M Y H:i:s', strtotime($order->order_date)),
				ucwords($order->recipient_name),
				'<div style="text-align: right;">' . number_format($final_grand_total) . '</div>',
				ucwords($order->payment_type),
				$status,
				$paycon,
				//$wareid,
				$is_indent,
				'<a style="text-decoration: underline;" href="' . base_url('admin/orders_retailer/view') . '/' . $order->id_orders . '">Lihat</a>',
				$order->created_by
			);
			$nomor_urut++;
		}

		echo json_encode($output);
	}

	//this is to list all orders
	public function index()
	{

		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders_retailer/index';
		$config['per_page'] = 100;
		$config["uri_segment"] = 4;

		//fetch all orders
		$config['total_rows'] = $this->order_m->record_count();
		$this->pagination->initialize($config);
		$this->data['orders'] = $this->order_m->get_all_orders_retailer(
			$config["per_page"],
			$this->uri->segment(4)
		);

		$this->data['total_sales_order'] = $this->order_m->record_count();
		$this->data['total_incoming_order'] = $this->order_m->record_count_incoming_retailer();
		$this->data['marketplaces']	= $this->db->distinct()->select('marketplace_name')->from('orders')->where('marketplace_name !=', null)->order_by('marketplace_name', 'ASC')->get()->result();
		$this->data['customers'] 	= $this->db->distinct()->select('customer_id')->from('orders')->order_by('recipient_name', 'ASC')->get()->result();
		$this->data['product']	= $this->db->select('title,id_products')->from('products')->get()->result();
		//load view
		$this->data['subview'] = 'admin/orders_retailer/index';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	public function update_ongkir_modal($order_id)
	{
		$data['order'] = $this->OrderModel->get_order_by_id($order_id); // Ambil data order berdasarkan id
		$this->load->view('update_ongkir_modal', $data); // Load view untuk modal
	}

	public function update_creditclaimamount()
	{
		$orderID = $this->input->post('order_id');
		$newCreditClaimAmount = $this->input->post('new_creditclaimamount');

		// Validasi dan keamanan lainnya

		$this->db->where('id_orders', $orderID);
		$update_data = array(
			'creditclaimamount' => $newCreditClaimAmount
		);

		$result = $this->db->update('orders', $update_data);

		if ($result) {
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Jumlah credit claim berhasil diperbarui</p>');
			redirect('admin/orders_retailer/view/' . $orderID);
		} else {
			echo json_encode(array('status' => 'error', 'message' => 'Terjadi kesalahan saat memperbarui credit claim.'));
		}
	}


	public function update_ongkir()
	{
		$orderid = $this->input->post('orders_id');
		$shipping_fee = array(
			'shipping_fee' => $this->input->post('shipping_fee'),
		);
		$this->db->where('id_orders', $orderid);
		$this->db->update('orders', $shipping_fee);

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Ongkir Updated</p>');
		redirect('admin/orders_retailer/view/' . $orderid);
	}


	//get all successful orders for specific customer only
	public function customer($customer_id)
	{
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders_retailer/customer';
		$config['per_page'] = 100;
		$config['uri_segment'] = 4;

		$this->db->select('*');
		$this->db->from('orders');
		$this->db->where('customer_id', $customer_id);
		$this->db->where('(payment_status=3 or payment_status=4 or payment_status=5 or payment_status=8)');

		// Get start_date and end_date from GET parameters
		$start_date = $this->input->get('start_date');
		$end_date = $this->input->get('end_date');

		// Add date filters to the queries
		if ($start_date && $end_date) {
			$this->db->where('order_date >=', $start_date);
			$this->db->where('order_date <=', $end_date);
		}

		$this->db->order_by('order_date', 'DESC');
		$this->data['orders'] = $this->db->get()->result();


		foreach ($this->data['orders'] as $order) {
			$order->item_summary = array();
			$order->order_details = $this->order_detail_m->get_orders_detail($order->id_orders);

			foreach ($order->order_details as $order_detail) {
				$product = $this->db->select('id_products, title')->from('products')->where('id_products', $order_detail->product_id)->get()->row();

				if (!isset($order->item_summary[$order->id_orders][$product->id_products])) {
					$order->item_summary[$order->id_orders][$product->id_products] = array(
						'product_id' => $product->id_products,
						'product_name' => $product->title,
						'total_quantity' => $order_detail->quantity,
						'attributes' => $order_detail->attributes,
						'subtotal' => $order_detail->subtotal,
						'sku' => $order_detail->sku
					);
				} else {
					$order->item_summary[$order->id_orders][$product->id_products]['total_quantity'] += $order_detail->quantity;
				}
			}
		}
		$product_qty = array(); // Initialize an array to store product quantities

		// Loop through each order
		foreach ($this->data['orders'] as $order) {
			foreach ($order->order_details as $order_detail) {
				$product_id = $order_detail->product_id;
				$product_name = $order_detail->item_name;
				$qty = $order_detail->quantity;

				// If the product ID is not in the array, add it with the initial qty
				if (!isset($product_qty[$product_id])) {
					$product_qty[$product_id] = array(
						'product_id' => $product_id,
						'product_name' => $product_name,
						'total_qty' => $qty
					);
				} else {
					// If the product ID is already in the array, add the qty to the existing value
					$product_qty[$product_id]['total_qty'] += $qty;
				}
			}
		}

		// Remove products with total qty 0
		$product_qty = array_filter($product_qty, function ($product) {
			return $product['total_qty'] > 0;
		});

		// Pass the product quantities data to the view
		$this->data['product_qty'] = $product_qty;

		$this->db->select('*')->from('customers')->where('id_customers', $customer_id);
		$this->data['customer'] = $this->db->get()->row();

		$this->data['subview'] = 'admin/orders_retailer/customer_orders';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	/*filter order by*/
	public function filter_order_by()
	{

		if ($this->security->xss_clean($this->input->post('filter_key'))) {
			$filter_key = $this->security->xss_clean($this->input->post('filter_key'));
		} else {
			$filter_key	= $this->session->userdata('filter_key');
		}

		$this->data['marketplaces']	= $this->db->distinct()->select('marketplace_name')->from('orders')->where('marketplace_name !=', null)->order_by('marketplace_name', 'ASC')->get()->result();
		$this->data['customers'] 	= $this->db->distinct()->select('customer_id')->from('orders')->order_by('id_orders', 'ASC')->get()->result();
		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders_retailer/filter_order_by';
		$config['per_page'] = 100;
		$config["uri_segment"] = 4;

		if ($filter_key == 'order_id') {
			//fetch all orders
			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('id_orders', $this->security->xss_clean($this->input->post('order_id')));
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('id_orders', $this->security->xss_clean($this->input->post('order_id')));
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();
		} elseif ($filter_key == 'voucher') {
			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('redeemed_voucher_code !=', null);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('redeemed_voucher_code !=', null);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();
		} elseif ($filter_key == 'payment_status') {
			if ($this->security->xss_clean($this->input->post('payment_status'))) {
				$this->session->unset_userdata('filter_payment_status');
				$payment_status = $this->security->xss_clean($this->input->post('payment_status'));
			} else {
				$payment_status = $this->session->userdata('filter_payment_status');
			}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_status', $payment_status);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_status', $payment_status);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_payment_status', $payment_status);
		} elseif ($filter_key == 'payment_type') {
			if ($this->security->xss_clean($this->input->post('payment_type'))) {
				$this->session->unset_userdata('filter_payment_type');
				$payment_type = $this->security->xss_clean($this->input->post('payment_type'));
			} else {
				$payment_type = $this->session->userdata('filter_payment_type');
			}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_type', $payment_type);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_type', $payment_type);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_payment_type', $payment_type);
		} elseif ($filter_key == 'flashsale') {
			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail', 'orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_flashsale', 'yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail', 'orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_flashsale', 'yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();
		} elseif ($filter_key == 'sale') {
			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail', 'orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_sale', 'yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail', 'orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_sale', 'yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();
		} elseif ($filter_key == "date") {
			if ($this->security->xss_clean($this->input->post('start_date'))) {
				$this->session->unset_userdata('filter_start_date');
				$start_date = $this->security->xss_clean($this->input->post('start_date'));
			} else {
				$start_date = $this->session->userdata('filter_start_date');
			}

			if ($this->security->xss_clean($this->input->post('end_date'))) {
				$this->session->unset_userdata('filter_end_date');
				$end_date = $this->security->xss_clean($this->input->post('end_date'));
			} else {
				$end_date = $this->session->userdata('filter_end_date');
			}


			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('order_date >=', date('Y-m-d 00:00:00', strtotime($start_date)));
			$this->db->where('order_date <=', date('Y-m-d 23:59:59', strtotime($end_date)));
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('order_date >=', date('Y-m-d 00:00:00', strtotime($start_date)));
			$this->db->where('order_date <=', date('Y-m-d 23:59:59', strtotime($end_date)));
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_start_date', $start_date);
			$this->session->set_userdata('filter_end_date', $end_date);
		} elseif ($filter_key == "totalorder") {
			if ($this->security->xss_clean($this->input->post('start_amt'))) {
				$this->session->unset_userdata('filter_start_amt');
				$start_amt = $this->security->xss_clean($this->input->post('start_amt'));
			} else {
				$start_amt = $this->session->userdata('filter_start_amt');
			}

			if ($this->security->xss_clean($this->input->post('end_amt'))) {
				$this->session->unset_userdata('filter_end_amt');
				$end_amt = $this->security->xss_clean($this->input->post('end_amt'));
			} else {
				$end_amt = $this->session->userdata('filter_end_amt');
			}


			$this->db->select('*');
			$this->db->from('orders');

			if ($start_amt <> "") {
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) >=', $start_amt);
			}
			if ($end_amt <> "") {
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) <=', $end_amt);
			}

			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			if ($start_amt <> "") {
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) >=', $start_amt);
			}
			if ($end_amt <> "") {
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) <=', $end_amt);
			}

			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_start_amt', $start_amt);
			$this->session->set_userdata('filter_end_amt', $end_amt);
		} elseif ($filter_key == "marketplace") {
			if ($this->security->xss_clean($this->input->post('marketplace_name'))) {
				$this->session->unset_userdata('filter_marketplace_name');
				$marketplace_name = $this->security->xss_clean($this->input->post('marketplace_name'));
			} else {
				$marketplace_name = $this->session->userdata('filter_marketplace_name');
			}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('marketplace_name', $marketplace_name);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('marketplace_name', $marketplace_name);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_marketplace_name', $marketplace_name);
		} elseif ($filter_key == "customer") {
			if ($this->security->xss_clean($this->input->post('customer_id'))) {
				$this->session->unset_userdata('filter_customer_id');
				$customer_id = $this->security->xss_clean($this->input->post('customer_id'));
			} else {
				$customer_id = $this->session->userdata('filter_customer_id');
			}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('customer_id', $customer_id);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('customer_id', $customer_id);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_customer_id', $customer_id);
		}
		$this->session->set_userdata('filter_key', $filter_key);

		$rowcount = $config['total_rows'];
		$this->data['total_sales_order'] = $rowcount;

		//load view
		$this->data['subview'] = 'admin/orders_retailer/index';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	//add order form marketplace
	public function add_order()
	{

		/*$this->data['customer_marketplace'] = $this->db->select('*')->from('customers')->where('(type="marketplace" or type="regular")')->order_by('id_customers','ASC')->get()->result();*/
		$this->data['customer_marketplace'] = $this->db->select('*')->from('customers')->order_by('name', 'ASC')->get()->result();
		$this->data['products'] = $this->db->select(' p.id_products, pc.product_details_id ,pc.attribute_detail_id , p.title,pa.product_attribute,pad.attribute_detail, pd.sku,pd.price')
			->from('product_combination pc, products p, product_details pd, product_attributes pa, product_attributes_detail pad')
			->where('pc.product_id = p.id_products and pc.product_details_id = pd.id and pa.id = pc.attribute_id and pad.id = pc.attribute_detail_id')
			->order_by('title', 'ASC')
			->get()->result();
		$this->data['warehouses']           = $this->db->select('*')->from('warehouse')->order_by('id', 'ASC')->get()->result();
		$this->data['metode_pengiriman']           = $this->db->select('*')->from('shipment_method')->order_by('id', 'ASC')->get()->result();

		$config = $this->order_m->add_order_rules;

		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); //above is to add class to form validation error, to be styled

		$this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');

		if ($this->form_validation->run($this) == TRUE) {
			/*get customer info detail*/
			$customer_id 	= $this->security->xss_clean($this->input->post('customer_id'));
			$customer 		= $this->db->select('*')->from('customers')->where('id_customers', $customer_id)->get()->row();
			/*get customer info detail*/

			/*cek shipping customer untuk yang guest */
			if ($customer->shipping_district == "" || $customer->shipping_district == null) {
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">District Empty</p>');
				redirect('admin/orders_retailer/add_order');
			}

			if ($customer->shipping_subdistrict == "" || $customer->shipping_subdistrict == null) {
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Sub-District Empty</p>');
				redirect('admin/orders_retailer/add_order');
			}

			if ($customer->shipping_province == "" || $customer->shipping_province == null) {
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Province Emptyr');
			}
			// cek shipping customer untuk yang guest 

			/*get marketplace name*/
			$marketplace_name 		= null;
			$marketplace_id 		= $this->input->post('marketplace_id');
			$get_marketplace_name	= $this->db->select('name')->from('marketplace')->where('id', $marketplace_id)->get()->row();
			if ($get_marketplace_name != null) {
				$marketplace_name 	= $get_marketplace_name->name;
			}
			/*get marketplace name*/

			$product 			= $this->security->xss_clean($this->input->post('id_product_detail'));
			$count_product		= count($product);
			$marketplace_price 	= $this->security->xss_clean($this->input->post('harga'));
			$quantitas_beli 	= $this->security->xss_clean($this->input->post('kuantitas'));

			$warehouse_id       = $this->security->xss_clean($this->input->post('warehouse_id'));
			$kurir_id       = $this->security->xss_clean($this->input->post('kurir_id'));

			/*cek product dan qty kosong*/
			if ($product != 0) {
				for ($a = 0; $a < $count_product; $a++) {
					if ($quantitas_beli[$a] == "" || $quantitas_beli[$a] == 0) {
						$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Set Product Quantity</p>');
						redirect('admin/orders_retailer/add_order');
					}
				}
			} else {
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Product Found</p>');
				redirect('admin/orders_retailer/add_order');
			}

			$total_amount	= 0;
			$subtotal		= 0;

			for ($sf = 0; $sf < $count_product; $sf++) {
				/*$shipping_fee_info =  calculate_shipping_fee(3, 1, $product[$sf], $quantitas_beli[$sf], $customer->shipping_id_subdistrict);*/
				/*$subtotal 		= ($marketplace_price[$sf] * $quantitas_beli[$sf]) + $shipping_fee_info['total_shipping_fee'];*/
				$subtotal       = ($marketplace_price[$sf] * $quantitas_beli[$sf]);
				$total_amount	= $total_amount + $subtotal;
			}

			// get customer district


			/*hitung total amount*/

			$order = array(
				'customer_id' 				=> $customer_id,
				'order_date'				=> date("Y-m-d H:i:s"),
				'payment_status' 			=> 1,
				'payment_status_message'	=> NULL,
				'payment_confirm' 			=> 0,
				'payment_confirm_details' 	=> NULL,
				'total_amount' 				=> $total_amount,
				'payment_type' 				=> 'Bank Transfer',
				'payment_method' 			=> NULL,
				'payment_date' 				=> NULL,
				'cancel_date' 				=> NULL,
				'sent_date' 				=> NULL,
				'airway_bill' 				=> NULL,
				'recipient_name' 			=> $customer->recipient_name,
				'address' 					=> $customer->shipping_address,
				'district' 					=> $customer->shipping_district,
				'subdistrict'				=> $customer->shipping_subdistrict,
				'province'					=> $customer->shipping_province,
				'postcode'					=> $customer->shipping_postcode,
				'phone'						=> $customer->shipping_phone,
				'email'                     => $customer->email,
				'country'					=> $customer->shipping_country,
				'redeemed_voucher_code'		=> NULL,
				'redeemed_voucher_amount'	=> NULL,
				'shipping_type'				=> "",
				'shipping_fee'				=> $this->input->post('shipping_fee'),
				'ppn'						=> 0,
				'plus_reward'				=> 0,
				'minus_reward'				=> 0,
				'minus_reward_amount'		=> NULL,
				'no_resi'					=> NULL,
				'customer_note'				=> "",
				'marketplace_name'			=> $marketplace_name,
				'admin_note'				=> $this->security->xss_clean($this->input->post('admin_note')),
				'created_by'                => $this->session->userdata('admin')['name']

			);

			$order_id = (int) $this->order_m->add_order($order);

			/*insert into order detail*/
			for ($c = 0; $c < $count_product; $c++) {
				$product_item = $this->db->select('p.id_products, pc.product_details_id ,pc.attribute_detail_id , p.title,pa.product_attribute,pad.attribute_detail, pd.sku,pd.price, s.stock, s.warehouse_id')
					->from('product_combination pc, products p, product_details pd, product_attributes pa, product_attributes_detail pad, stock s')
					->where('pc.product_id = p.id_products and pc.product_details_id = pd.id and pa.id = pc.attribute_id and pad.id = pc.attribute_detail_id and s.id_product_detail = pc.product_details_id')
					->where('pc.product_details_id', $product[$c])
					->get()->row();
				/*$shipping_fee_info =  calculate_shipping_fee(3, 1, $product[$c], $quantitas_beli[$c], $customer->shipping_id_subdistrict);*/

				$order_detail = array(
					'orders_id'			=> $order_id,
					'item_id' 			=> $product[$c],
					'product_id'		=> $product_item->id_products,
					'item_name'			=> $product_item->title,
					'item_price'		=> $marketplace_price[$c],
					'quantity'			=> $quantitas_beli[$c],
					/*'subtotal'			=> ($marketplace_price[$c] * $quantitas_beli[$c]) + $shipping_fee_info['total_shipping_fee'],*/
					'subtotal'          => ($marketplace_price[$c] * $quantitas_beli[$c]),
					'sku'				=> $product_item->sku,
					'attributes'		=> $product_item->attribute_detail,
					'warehouse_id'		=> $warehouse_id,
					'chosen_shipping_id' => $kurir_id,
					/* 'shipping_fee'		=> $shipping_fee_info['total_shipping_fee'], */
					'shipping_fee'      => $this->input->post('shipping_fee'),
					'is_backorder'		=> 'no',
					'status'			=> 0,
					'no_resi'			=> "",
				);

				$this->db->insert('orders_detail', $order_detail);
			}
			/*insert into order detail*/

			/*kurangi stock pada warehouse*/
			for ($d = 0; $d < $count_product; $d++) {

				$curent_stock 	= $this->db->select('stock')->from('stock')->where('id_product_detail', $product[$d])->where('warehouse_id', $warehouse_id)->get()->row();

				$warehouse = $this->db->select('*')->from('warehouse')->where('id', $warehouse_id)->get()->row();

				if ($warehouse->warehouse_type == 'virtual') {
					$final_stock = array(
						'stock_virtual' => $curent_stock->stock_virtual - $quantitas_beli[$d],
					);
					$this->db->where('id_product_detail', $product[$d]);
					$this->db->where('warehouse_id', $warehouse_id);
					$this->db->update('stock', $final_stock);
				} else {
					$final_stock = array(
						'stock' => $curent_stock->stock - $quantitas_beli[$d],
					);
					$this->db->where('id_product_detail', $product[$d]);
					$this->db->where('warehouse_id', $warehouse_id);
					$this->db->update('stock', $final_stock);

					// insert mov stock
					$id_stock = $this->db->select('id')->from('stock')->where('id_product_detail', $product[$d])->where('warehouse_id', $warehouse_id)->get()->row();
					$this->db->select('name')->from('users')->where('id', $this->session->userdata('admin')['id']);
					$user_name = $this->db->get()->row()->name;

					$last_stock = $curent_stock->stock - $quantitas_beli[$d];

					$insert_mov_stock = array(
						'stock_id' 		=> $id_stock->id,
						'type' 			=> '-',
						'stock_change' 	=> $quantitas_beli[$d],
						'remark' 		=> 'Sales Order No: ' . $order_id,
						'total' 		=> $last_stock,
						'name' 			=> $user_name,
						'datetime' 		=> date("Y-m-d H:i:s"),
					);
					$this->db->insert('stock_movement', $insert_mov_stock);
					// insert mov stock


				}
			}
			/*kurangi stock pada warehouse*/



			/*insert shipping session to shipping table*/
			$insert_shipping_session = array(
				'order_id' 		=> $order_id,
				'warehouse_id' 	=> $warehouse_id,
				'shipping_fee' 	=> $this->input->post('shipping_fee'),
				'is_indent' 	=> 'no',
			);
			$this->db->insert('shipping', $insert_shipping_session);
			/*insert shipping session to shipping table*/

			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Add Order Successful</p>');
			redirect('admin/orders_retailer');
		}

		//load view
		$this->data['subview'] = 'admin/orders_retailer/add_order';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	function ajax_get_product_marketplace()
	{
		$id 			= (int) $this->input->post('id_marketplace');
		$data['product'] = $this->db->select('*')->from('products')->join('marketplace_product_price', 'marketplace_product_price.product_id = products.id_products')->where('marketplace_product_price.marketplace_id', $id)->get()->result();
		$this->load->view('admin/orders_retailer/ajax_get_product_marketplace', $data);
	}

	function ajax_get_address_customer()
	{
		$id = (int) $this->input->post('id_customers');
		$data['customers'] = $this->db->select('*')->from('customers')->where('customers.id_customers', $id)->get()->result();
		$this->load->view('admin/orders_retailer/ajax_get_address_customer', $data);
	}

	function ajax_get_product_detail()
	{
		$id 			= (int) $this->input->post('id_product_detail');
		// $id_marketplace	= (int) $this->input->post('id_marketplace');
		$id_warehouse	= (int) $this->input->post('id_warehouse');
		$data['stock'] = $this->db->select("p.id_products, pc.product_details_id ,pc.attribute_detail_id , p.title,pa.product_attribute,pad.attribute_detail, pd.sku,pd.price, s.stock")
			->from("product_combination pc, products p, product_details pd, product_attributes pa, product_attributes_detail pad, stock s")
			->where("pc.product_id = p.id_products and pc.product_details_id = pd.id and pa.id = pc.attribute_id and pad.id = pc.attribute_detail_id and s.id_product_detail = pc.product_details_id")
			->where("pc.product_details_id", $id)
			->where("s.warehouse_id", $id_warehouse)->get()->row();
		echo json_encode($data);
	}

	//to VIEW and EDIT order in admin
	public function view($id)
	{

		if ($id == null) {
			redirect('admin/orders_retailer');
		}

		//get orders
		$this->db->select('id_orders')->from('orders')->where('id_orders', $id);
		$current_order_count = $this->db->get()->num_rows();

		if ($current_order_count < 1) {
			show_404();
		}

		if (isset($_POST['payment_status'])) {

			/* if($this->order_m->cek_order($id,$_POST['payment_status']) == FALSE){
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Order telah diproses</p>');
				redirect('admin/orders_retailer/view/' . $id);
			} */

			//var_dump($this->input->post('payment_status')); exit();

			if ($this->input->post('payment_status') == 2) {

				//Status CANCEL
				$data = array(
					'payment_status' => 2,
					'cancel_date' => date('Y-m-d')
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//return the quantity back to stock
				//get order details
				$order_details =  $this->order_detail_m->get_orders_detail($id);

				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;


				foreach ($order_details as $item) {

					//get current stock
					$this->db->select('stock, id')->from('stock')->where('id_product', $item->product_id)->where('id_product_detail', $item->item_id)->where('warehouse_id', $item->warehouse_id);
					$current_stock = $this->db->get()->row();
					$qty = 0;
					if ($item->is_backorder == 'yes') {
						$qty = $qty + 0;
					} else {
						$qty = $qty + $item->quantity;
					}

					$data = array(
						'stock' => $current_stock->stock + $qty,
					);
					$this->db->where('id_product', $item->product_id);
					$this->db->where('id_product_detail', $item->item_id);
					$this->db->where('warehouse_id', $item->warehouse_id);
					$this->db->update('stock', $data);

					//get $stock_id
					$stock_id = $current_stock->id;
					$last_stock = $current_stock->stock + $qty;

					$this->db->select('name')->from('users')->where('id', $this->session->userdata('admin')['id']);
					$user_name = $this->db->get()->row()->name;

					//update stock_movement_table
					$movement_data = array(
						'stock_id' => $stock_id,
						'type' => '+',
						'stock_change' => (int) $qty,
						'remark' => 'Cancel Order No: ' . $id,
						'total' => $last_stock,
						'name' => $user_name
					);
					$this->db->insert('stock_movement', $movement_data);

					if ($item->is_flashsale != 0) {
						//return flashsale counter & customer purchase
						/*get purchase qty from flashsale_customer*/
						$flashsale_purchase = $this->db->select('purchase_qty')->from('flashsale_customer')->where('customer_id', $customer_id)->where('flashsale_id', $item->is_flashsale)->where('flashsale_product_id', $item->item_id)->get()->row()->purchase_qty;
						/*return counter and terjual from flashsale product*/
						$current_flashsale_product = $this->db->select('counter,terjual')->from('flashsale_products')->where('flashsale_id', $item->is_flashsale)->where('product_id', $item->item_id)->get()->row();
						$return_counter_terjual = array(
							'counter' => $current_flashsale_product->counter + $flashsale_purchase,
							'terjual' => $current_flashsale_product->terjual - $flashsale_purchase,
						);
						$this->db->where('flashsale_id', $item->is_flashsale);
						$this->db->where('product_id', $item->item_id);
						$this->db->update('flashsale_products', $return_counter_terjual);
						/*delete flashsale customer record*/
						$this->db->where('customer_id', $customer_id);
						$this->db->where('flashsale_id', $item->is_flashsale);
						$this->db->delete('flashsale_customer');
					}
				}

				//return customer point reward back to customers table because he cancel
				//get customer current point
				$this->db->select('current_pointreward')->from('customers')->where('id_customers', $customer_id);
				$current_point = (int) $this->db->get()->row()->current_pointreward;

				//get minus point from order
				$this->db->select('current_reward,sisa_reward,minus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$minus_point 	= (int) $rewards->minus_reward;
				$current_reward = (int) $rewards->current_reward;
				$sisa_reward 	= (int) $rewards->sisa_reward;
				if (($sisa_reward + $minus_point) == $current_reward) {
					$updated_point = $current_point + $minus_point;

					//update point reward
					$data = array(
						'current_pointreward' => $updated_point
					);
					$this->db->where('id_customers', $customer_id);
					$this->db->update('customers', $data);
				}

				//----SEND EMAIL TO Retailer 
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);
				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
				$data['minus_point'] = $minus_point;

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;

				$data['emails'] = $this->configuration_m->get_emails();
				$data['title'] = 'Order Cancel';

				$email_data = $data;
				$email_data['email'] = $data['customer']->email;

				if ($data['order']->order_language == 'english') {
					$email_data['subject'] = 'Canceling Your Order';
				} else {
					$email_data['subject'] = 'Kok Batal?';
				}

				if ($data['order']->order_language == 'english') {
					$view_file = 'email/english/order_cancel';
				} else {
					$view_file = 'email/indonesian/order_cancel';
				}

				//logging
				$user_id = $this->session->userdata('admin')['id'];

				$activity = 'User mengubah status order ' . $id . ' menjadi Batal';

				log_activity($user_id, $activity);

				$this->send_email($view_file, $email_data);
				//----end send email 

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			if ($this->input->post('payment_status') == 1) {

				//Status NOT PAID
				$data = array(
					'payment_status' => 1,
					'payment_date' => date('Y-m-d')
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//----SEND EMAIL TO CUSTOMER
				//get customer name

				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;


				$this->db
					->select('name,phone,type,email')
					->from('customers')
					->where('id_customers', $customer_id);
				$email_data['customer'] = $this->db->get()->row();
				$email_data['email'] = $email_data['customer']->email;

				$email_data['emails'] = $this->configuration_m->get_emails();
				$order_data = $this->db->select('*')->from('orders')->where('id_orders', $id)->get()->row();
				$payment_type = $order_data->payment_type;
				if ($payment_type == 'bank transfer BCA') {
					$email_data['bank'] = $this->db
						->select('bank')
						->from('configuration')
						->where('id_configuration', 1)
						->get()
						->row()->bank;
				} elseif ($payment_type == 'bank transfer MANDIRI') {
					$email_data['bank'] = $this->db
						->select('bank1')
						->from('configuration')
						->where('id_configuration', 1)
						->get()
						->row()->bank1;
				}

				if ($this->session->userdata('site_lang') == 'english') {
					$email_data['subject'] = 'Konfirmasi Pesanan';
				} else {
					$email_data['subject'] = 'Konfirmasi Pesanan';
				}

				//get order detail and customer detail
				$email_data['order'] = $this->order_m->get_order($id);
				$email_data['order_details'] = $this->order_detail_m->get_orders_detail($id);

				//get vouchers detail
				if ($this->session->userdata('chosen_voucher_code')) {
					$email_data['chosen_voucher_code'] = $this->session->userdata(
						'chosen_voucher_code'
					);
					$email_data['chosen_voucher_type'] = $this->session->userdata(
						'chosen_voucher_type'
					);
					$email_data['chosen_voucher_discount'] = $this->session->userdata(
						'chosen_voucher_discount'
					);
					$email_data['redeemed_voucher_amount'] = $this->session->userdata(
						'redeemed_voucher_amount'
					);
				}

				//get shipping fee total
				$email_data['carrier_name'] = $this->session->userdata('carrier_name');
				$email_data['total_shipping_fee'] = $this->session->userdata(
					'total_shipping_fee'
				);

				//add tax to email, if exist..
				if ($this->session->userdata('tax')) {
					$email_data['tax'] = $this->session->userdata('tax');
				}

				//add point reward to email, if exist..
				if ($this->session->userdata('chosen_point')) {
					$email_data['chosen_point'] = $this->session->userdata('chosen_point');
					$email_data['chosen_point_discount'] = $this->session->userdata(
						'chosen_point_discount'
					);
				}

				switch ($payment_type) {
					case 'bank transfer BCA':
						if ($this->session->userdata('site_lang') == 'english') {
							$view_file = 'email/indonesian/bank_transfer_indo_retailer';
						} else {
							$view_file = 'email/indonesian/bank_transfer_indo_retailer';
						}
						break;
					case 'bank transfer MANDIRI':
						if ($this->session->userdata('site_lang') == 'english') {
							$view_file = 'email/indonesian/bank_transfer_indo_retailer';
						} else {
							$view_file = 'email/indonesian/bank_transfer_indo_retailer';
						}
						break;
					case 'cod':
						if ($this->session->userdata('site_lang') == 'english') {
							$view_file = 'email/english/cod';
						} else {
							$view_file = 'email/indonesian/cod';
						}
						break;
					case 'midtrans':
						if ($this->session->userdata('site_lang') == 'english') {
							/*$email = $this->load->view('email/english/bank_transfer', $data, TRUE);   */
							$view_file = 'email/english/bank_transfer_english';
						} else {
							$view_file = 'email/indonesian/bank_transfer_indo';
						}
						break;
				}

				//logging
				$user_id = $this->session->userdata('admin')['id'];

				$activity = 'User menerima pesanan dan status order ' . $id . ' berubah menjadi Belum Bayar';

				log_activity($user_id, $activity);

				$this->send_email($view_file, $email_data); //function in My_Controller

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			if ($this->input->post('payment_status') == 3) {

				//Status PAID
				$data = array(
					'payment_status' => 3,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get add and minus point from order
				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				//SEND EMAIL TO CUSTOMER
				$data['title'] = 'Payment Confirmation';
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);
				$data['order_details'] = $this->order_detail_m->get_orders_detail($id);


				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;
				$data['emails'] = $this->configuration_m->get_emails();
				$data['plus_point'] = $plus_point;

				$email_data = $data;
				$email_data['email'] = $data['customer']->email;
				if ($data['order']->order_language == 'english') {
					$email_data['subject'] = 'Payment Received';
				} else {
					$email_data['subject'] = 'Pembayaran Telah Diterima';
				}

				if ($data['order']->order_language == 'english') {
					$view_file = 'email/english/payment_confirmation_retailer';
				} else {
					$view_file = 'email/indonesian/payment_confirmation_retailer';
				}

				//logging
				$user_id = $this->session->userdata('admin')['id'];

				$activity = 'User memverifikasi pembayaran dan status order ' . $id . ' berubah menjadi Sudah Bayar';

				log_activity($user_id, $activity);

				$this->send_email($view_file, $email_data);
				//----end send email   

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			//CONDITION FOR PARTIAL PAID
			if ($this->input->post('payment_status') == 6) {

				//Status PAID
				$data = array(
					'payment_status' => 6,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get add and minus point from order
				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				//SEND EMAIL TO CUSTOMER
				$data['title'] = 'Payment Confirmation';
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);
				$data['order_details'] = $this->order_detail_m->get_orders_detail($id);

				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;
				$data['emails'] = $this->configuration_m->get_emails();
				$data['plus_point'] = $plus_point;

				$email_data = $data;
				$email_data['email'] = $data['customer']->email;
				$email_data['subject'] = 'Payment Received';

				if ($data['order']->order_language == 'english') {
					$view_file = 'email/english/payment_confirmation_retailer';
				} else {
					$view_file = 'email/indonesian/payment_confirmation_retailer';
				}

				//logging
				$user_id = $this->session->userdata('admin')['id'];

				$activity = 'User mengubah status order ' . $id . ' menjadi Sudah Bayar (Hanya DP)';

				log_activity($user_id, $activity);

				$this->send_email($view_file, $email_data);
				// var_dump($this->email->print_debugger());  
				// exit();
				//----end send email   

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			if ($this->input->post('payment_status') == 4) {


				//Status PROCESS
				$data = array(
					'payment_status' => 4,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get customer current point
				$this->db->select('current_pointreward')->from('customers')->where('id_customers', $customer_id);
				$current_point = (int) $this->db->get()->row()->current_pointreward;

				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				$updated_point = $current_point + $plus_point;

				//get plus reward already given status
				$this->db->select('plus_reward_given')->from('orders')->where('id_orders', $id);
				$plus_reward_given = $this->db->get()->row();

				if ($plus_reward_given->plus_reward_given == 'no' || $plus_reward_given->plus_reward_given == NULL) {

					//update point reward
					$data = array(
						'current_pointreward' => $updated_point,
					);
					$this->db->where('id_customers', $customer_id);
					$this->db->update('customers', $data);

					$data_order = array(
						'plus_reward_given' => 'yes',
					);
					$this->db->where('id_orders', $id);
					$this->db->update('orders', $data_order);
				}
				//logging
				$user_id = $this->session->userdata('admin')['id'];

				$activity = 'User mengubah status order ' . $id . ' menjadi Dalam Proses';

				log_activity($user_id, $activity);

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			if ($this->input->post('payment_status') == 5) {

				//Status DELIVERED
				$data = array(
					'payment_status' => 5,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);


				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}

			if ($this->input->post('payment_status') == 8) {

				// Ambil creditclaimamount dari tabel orders
				$this->db->select('creditclaimamount, customer_id');
				$this->db->from('orders');
				$this->db->where('id_orders', $id);
				$query = $this->db->get();
				$order = $query->row();
				$creditClaimAmount = $order->creditclaimamount;
				$customer_id = $order->customer_id;

				// Update creditclaimamount di tabel orders
				$data = array(
					'payment_status' => 8
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				// Update current_pointreward di tabel customers
				$this->db->set('current_pointreward', 'current_pointreward + ' . $creditClaimAmount, FALSE);
				$this->db->where('id_customers', $customer_id);
				$this->db->update('customers');

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders_retailer/view/' . $id);
			}
		}

		//get all provinces data from provinces table...
		$this->db->select('rajaongkir_province_id, province')->from('indonesia_provinces')->order_by('rajaongkir_province_id', 'ASC');
		$this->data['shipping_provinces'] = $this->db->get()->result();

		//get order detail and customer detail
		$this->data['order'] = $this->order_m->get_order($id);
		$this->data['customer'] = $this->customer_m->get_customer($this->data['order']->customer_id);
		$this->data['order_details'] = $this->order_detail_m->get_orders_detail($id);

		$this->data['subview'] = 'admin/orders_retailer/view';
		$this->load->view('admin/templates/header', $this->data_header);
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
	}

	/*update order detail*/
	public function update_status()
	{

		if (!$this->input->post('id_order')) {
			redirect('admin/orders_retailer');
		}

		$id 		= $this->security->xss_clean($this->input->post('id_product_detail'));
		$id_order 	= $this->security->xss_clean($this->input->post('id_order'));
		$status		= $this->input->post('status');
		if ($status == 0) {
			$order_details = array(
				'status' => $status,
			);
		} elseif ($status == 1) {

			if ($this->security->xss_clean($this->input->post('backed_order')) == 'yes') {
				$cek_stock =
					$this->db
					->select('stock')
					->from('stock')
					->where('id_product', $this->security->xss_clean($this->input->post('item_order')))
					->where('warehouse_id', $this->security->xss_clean($this->input->post('warehouse_order')))
					->get()
					->row()
					->stock;
				if ($this->security->xss_clean($this->input->post('qty_order')) <= $cek_stock) {
					$order_details = array(
						'status' => $status,
					);
					$new_stock = array(
						'stock' => $cek_stock - $this->security->xss_clean($this->input->post('qty_order')),
					);
					$this->db->where('id_product', $this->security->xss_clean($this->input->post('item_order')));
					$this->db->where('warehouse_id', $this->security->xss_clean($this->input->post('warehouse_order')));
					$this->db->update('stock', $new_stock);
				} else {
					$this->session->set_flashdata('success' . $this->security->xss_clean($this->input->post('id')), '<p style="color:red; font-weight:bold;">Stock Tidak Cukup</p>');
					redirect('admin/orders_retailer/view/' . $id_order);
				}
			} else {
				$order_details = array(
					'status' => $status,
					'no_resi' => $this->security->xss_clean($this->input->post('no_resi')),
				);
			}
		} elseif ($status == 2) {

			$order_details = array(
				'status' => $status,
				'no_resi' => $this->security->xss_clean($this->input->post('no_resi')),
				'shipping_date' => date('Y-m-d H:i:s')
			);

			//SEND EMAIL TO CUSTOMER
			$data['title'] 			= 'Product Picked Up';
			//get order detail and customer detail
			$data['product_detail'] = $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $id)->get()->row();
			$data['warehouse']		= $this->db->select('name')->from('warehouse')->where('id', $data['product_detail']->warehouse_id)->get()->row()->name;
			$data['shipping_method'] = $this->db->select('name')->from('shipment_method')->where('id', $data['product_detail']->chosen_shipping_id)->get()->row()->name;
			$data['nama_kurir'] 	= $this->db->select('carrier')->from('shipment_method')->where('id', $data['product_detail']->chosen_shipping_id)->get()->row()->carrier;
			$data['no_resi']		= $this->security->xss_clean($this->input->post('no_resi'));
			$customer_id 			= $this->db->select('customer_id')->from('orders')->where('id_orders', $id_order)->get()->row()->customer_id;
			$data['customer']		= $this->customer_m->get_customer($customer_id);

			//get website data
			$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
			$website_data 			= $this->db->get()->row();
			$data['logo'] 			= $website_data->logo;
			$data['website_name'] 	= $website_data->website_name;
			$data['emails'] 		= $this->configuration_m->get_emails();

			//temporary comment 
			/*$this->load->library('email');
			//get email setting 
			$config['protocol'] 	= 'smtp';
			$config['smtp_host'] 	= $website_data->email_smtp_host; 
			$config['smtp_port'] 	= $website_data->email_smtp_port;
			$config['smtp_user'] 	= $website_data->email_smtp; 
			$config['smtp_pass'] 	= $website_data->email_smtp_password;
			$config['mailtype'] 	= 'html';
			$config['charset'] 		= 'iso-8859-1';
			$config['wordwrap'] 	= TRUE;
			$config['newline'] 		= "\r\n"; //use double quotes to comply with RFC 822 standard 
			$this->email->initialize($config);
			$this->email->from($data['emails']->from_email, $data['emails']->website_name);
			$this->email->to($data['customer']->email); 
			$this->email->subject('Payment Confirmation'); 
			$email = $this->load->view('email/indonesian/pickedup_confirmation', $data, TRUE);
			$this->email->message($email);	
			$this->email->send();    */
			//----end send email
		}

		$this->db->where('id_orders_detail', $id);
		$this->db->update('orders_detail', $order_details);

		//add no resi to shipping table
		$data_resi = array(
			'tracking_number' => $this->security->xss_clean($this->input->post('no_resi'))
		);
		$this->db->where('order_id', $this->security->xss_clean($this->input->post('id_order')));
		$this->db->where('warehouse_id', $this->security->xss_clean($this->input->post('warehouse_order')));
		$this->db->update('shipping', $data_resi);

		/*cek detail status to update order status*/
		$cek_status = 0;
		$all_order_detail_status = $this->db->select('status')->from('orders_detail')->where('orders_id', $id_order)->get()->result();
		foreach ($all_order_detail_status as $item) {
			if ($item->status != 2) {
				$cek_status = $cek_status + 1;
			} else {
				$cek_status = $cek_status;
			}
		}
		if ($cek_status == 0) {
			$data = array(
				'payment_status' => 5,
			);
			$this->db->where('id_orders', $id_order);
			$this->db->update('orders', $data);

			//$this->sync_this_order($id_order);
		}

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Update Order Status Success</p>');
		redirect('admin/orders_retailer/view/' . $id_order);
	}

	public function generate_invoice_pdf($id)
	{

		//add PDF attachment DOMPDF 

		$data['title'] = 'Invoice';

		//get order
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$data['order'] = $this->db->get()->row();
		$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
		$data['emails'] = $this->configuration_m->get_emails();

		$data['bank'] = $this->configuration_m->get_bank();

		$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
		$data['logo'] = $this->db->get()->row()->logo;

		//get order detail and customer detail
		$this->db->select('*')->from('orders_detail')->where('orders_id', $id);
		$data['order_details'] = $this->db->get()->result();

		$this->load->library('dompdf_gen');
		$html = $this->load->view('invoice_pdf', $data, true);
		$this->dompdf->load_html($html);
		$this->dompdf->render();
		$this->dompdf->stream('invoice.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output();
		$file_to_save = 'uploads/pdf/invoice.pdf';
		file_put_contents($file_to_save, $output);
	}

	public function generate_multiple_invoices()
	{

		if (!$this->input->post('generate_invoices')) {
			redirect('admin/orders_retailer');
		}

		$start_date_array = explode('-', $this->security->xss_clean($this->input->post('start_date')));
		$end_date_array = explode('-', $this->security->xss_clean($this->input->post('end_date')));
		//change to YYYY-MM-DD format for database insertion, and use php DatePeriod class
		$begin = new DateTime($start_date_array[2] . '-' . $start_date_array[1] . '-' . $start_date_array[0]);
		$end = new DateTime($end_date_array[2] . '-' . $end_date_array[1] . '-' . $end_date_array[0]);
		$end = $end->modify('+1 day');
		$interval = new DateInterval('P1D');
		$daterange = new DatePeriod($begin, $interval, $end);

		$this->load->library('dompdf_gen');

		//create a new directory inside pdf folder
		if (!is_dir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'))) { //check if directory already exist
			mkdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));
			chmod('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'), 0777);  //change permission to writable 777, so can be deleted
		}

		$total_orders_found = 0;

		foreach ($daterange as $date) {

			//get orders from each particular date
			//DATE(order_date) is a mysql function, to get onlye date from timestamp, exclude h-m-s
			$this->db->select('*')->from('orders');
			$this->db->where('DATE(order_date)', $date->format('Y-m-d'));
			if ($this->input->post('include_unpaid_orders') == 'no') {
				$this->db->group_start();
				$this->db->where('payment_status', 1);
				$this->db->or_where('payment_status', 3);
				$this->db->group_end();
			}
			$orders = $this->db->get()->result();

			if (count($orders) > 0) {

				//orders are available..then proceed 
				$total_orders_found = $total_orders_found + count($orders);

				foreach ($orders as $data['order']) {

					//generate pdf for each order in this particular date
					//add PDF attachment DOMPDF 
					$data['title'] = 'Invoice ' . $data['order']->id_orders;
					$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
					$data['emails'] = $this->configuration_m->get_emails();
					$data['bank'] = $this->configuration_m->get_bank();
					$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
					$data['logo'] = $this->db->get()->row()->logo;
					//get order detail and customer detail
					$this->db->select('*')->from('orders_detail')->where('orders_id', $data['order']->id_orders);
					$data['order_details'] = $this->db->get()->result();

					$html = $this->load->view('invoice_pdf', $data, true);
					//create a new dompdf instance (this is the crucial step)
					$this->dompdf = new DOMPDF();
					$this->dompdf->load_html($html);
					$this->dompdf->render();  //render html as pdf
					/* $this->dompdf->stream('invoice.pdf', array("Attachment" => 0)); //display to browser*/
					$output = $this->dompdf->output();

					//add pdf file into directory
					$file_to_save = 'uploads/pdf/invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '/invoice-orderid-' . $data['order']->id_orders . '.pdf';
					file_put_contents($file_to_save, $output);  //$output function to add files to folder

				}
			}
		}

		if ($total_orders_found == 0) {
			//dont download files, but go back to orders page and give error notice..
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No orders are found</p>');
			redirect('admin/orders_retailer');
		}

		//zip the generated pds and downlod the zip file
		$this->load->library('zip');
		$path = './uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date');
		$this->zip->read_dir($path, FALSE); //FALSE is to exclude entir path
		// Download the files to desktop. Name it "my_backup.zip"
		$this->zip->download('invoices-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '.zip');

		//finally, delete the directory
		//THIS NOT WORKING YET......
		//rmdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));

	}



	public function generate_multiple_deliveryslips()
	{

		if (!$this->input->post('generate_deliveryslips')) {
			redirect('admin/orders_retailer');
		}

		$start_date_array = explode('-', $this->security->xss_clean($this->input->post('start_date')));
		$end_date_array = explode('-', $this->security->xss_clean($this->input->post('end_date')));
		//change to YYYY-MM-DD format for database insertion, and use php DatePeriod class
		$begin = new DateTime($start_date_array[2] . '-' . $start_date_array[1] . '-' . $start_date_array[0]);
		$end = new DateTime($end_date_array[2] . '-' . $end_date_array[1] . '-' . $end_date_array[0]);
		$end = $end->modify('+1 day');
		$interval = new DateInterval('P1D');
		$daterange = new DatePeriod($begin, $interval, $end);

		$this->load->library('dompdf_gen');

		//create a new directory inside pdf folder
		if (!is_dir('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'))) { //check if directory already exist
			mkdir('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));
			chmod('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'), 0777);  //change permission to writable 777, so can be deleted
		}

		$total_orders_found = 0;

		foreach ($daterange as $date) {

			//get orders from each particular date
			//DATE(order_date) is a mysql function, to get onlye date from timestamp, exclude h-m-s
			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('DATE(order_date)', $date->format('Y-m-d'));
			if ($this->input->post('include_unpaid_orders') == 'no') {
				$this->db->group_start();
				$this->db->where('payment_status', 1);
				$this->db->or_where('payment_status', 3);
				$this->db->group_end();
			}
			$orders = $this->db->get()->result();

			if (count($orders) > 0) {

				$total_orders_found = $total_orders_found + count($orders);

				foreach ($orders as $data['order']) {

					//add PDF attachment DOMPDF 
					$data['title'] = 'Delivery Slip';

					//get order
					$this->db->select('*')->from('orders')->where('id_orders', $data['order']->id_orders);
					$data['order'] = $this->db->get()->row();

					if ($data['order']->dropship == 'yes') {
						//use dropshipper 
						$this->db->select('id_customers, name, email, phone, reseller_id, dropship, dropship_shop_name, dropship_shop_address, dropship_shop_phone, dropship_shop_email, dropship_shop_logo');
						$this->db->from('customers');
						$this->db->where('id_customers', $data['order']->customer_id);
						$data['customer'] = $this->db->get()->row();
						$data['logo'] = $data['customer']->dropship_shop_logo;
						$data['dropship_status'] = 'yes';
					} else {
						//non dropshipper
						$this->db->select('id_customers, name, email, phone, reseller_id');
						$this->db->from('customers');
						$this->db->where('id_customers', $data['order']->customer_id);
						$data['customer'] = $this->db->get()->row();
						$data['dropship_status'] = 'no';
						$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
						$data['logo'] = $this->db->get()->row()->logo;
					}

					$data['emails'] = $this->configuration_m->get_emails();

					//$data['bank'] = $this->configuration_m->get_bank();   

					//get order detail and customer detail
					$this->db->select('*')->from('orders_detail')->where('orders_id', $data['order']->id_orders);
					$data['order_details'] = $this->db->get()->result();

					$html = $this->load->view('deliveryslip_pdf', $data, true);
					//create a new dompdf instance (this is the crucial step)
					$this->dompdf = new DOMPDF();
					$this->dompdf->load_html($html);
					$this->dompdf->render();
					//$this->dompdf->stream('deliveryslip.pdf', array("Attachment" => 0));
					$output = $this->dompdf->output();

					//add pdf file into directory
					$file_to_save = 'uploads/pdf/deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '/deliveryslip-orderid-' . $data['order']->id_orders . '.pdf';
					file_put_contents($file_to_save, $output);  //$output function to add files to folder

				}
			}
		}

		if ($total_orders_found == 0) {
			//dont download files, but go back to orders page and give error notice..
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No orders are found</p>');
			redirect('admin/orders_retailer');
		}

		//zip the generated pds and downlod the zip file
		$this->load->library('zip');
		$path = './uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date');
		$this->zip->read_dir($path, FALSE); //FALSE is to exclude entir path
		// Download the files to desktop. 
		$this->zip->download('deliveryslips-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '.zip');

		//finally, delete the directory
		//THIS NOT WORKING YET......
		//rmdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));

	}

	public function generate_shipping_mark($id)
	{
		/*get order data*/
		$data['orders_detail'] 	= $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $id)->get()->row();
		$data['orders']			= $this->db->select('*')->from('orders')->where('id_orders', $data['orders_detail']->orders_id)->get()->row();

		/*get customer id with order id*/
		$customer_id			= $this->db->select('customer_id')->from('orders')->where('id_orders', $data['orders_detail']->orders_id)->get()->row()->customer_id;

		/*get customer detail*/
		$data['customer']		= $this->db->select('*')->from('customers')->where('id_customers', $customer_id)->get()->row();

		/*get warehouse detail*/
		$data['warehouse']		= $this->db->select('*')->from('warehouse')->where('id', $data['orders_detail']->warehouse_id)->get()->row();
		$data['district']		= $this->db->select('district')->from('indonesia_districts')->where('rajaongkir_id_district', $data['warehouse']->id_district)->get()->row()->district;
		$data['subdistrict']	= $this->db->select('subdistrict')->from('indonesia_subdistricts')->where('rajaongkir_id_subdistrict', $data['warehouse']->id_subdistrict)->get()->row()->subdistrict;
		$data['province']		= $this->db->select('province')->from('indonesia_provinces')->where('rajaongkir_province_id', $data['warehouse']->id_province)->get()->row()->province;

		//get websote name
		$data['website_name'] = $this->db->select('website_name')->from('configuration')->where('id_configuration', 1)->get()->row()->website_name;

		//add PDF attachment DOMPDF 
		$data['title'] 		= 'Shipping Mark';

		$this->load->library('dompdf_gen');
		$html = $this->load->view('shipping_mark_pdf', $data, true);
		echo $html;
		die();
		$this->dompdf->load_html($html);
		$this->dompdf->set_paper('A4', 'landscape');
		$this->dompdf->render();
		$this->dompdf->stream('shipping_mark.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output();
		$file_to_save = 'uploads/pdf/shipping_mark.pdf';
		file_put_contents($file_to_save, $output);
	}

	public function update_noresi()
	{
		$order_detail_id = $this->input->post('id_orders_detail');
		/*get order id & warehouse*/
		$id_order = $this->db->select('orders_id')->from('orders_detail')->where('id_orders_detail', $order_detail_id)->get()->row()->orders_id;
		$warehouse_id = $this->db->select('warehouse_id')->from('orders_detail')->where('id_orders_detail', $order_detail_id)->get()->row()->warehouse_id;
		$is_backorder = $this->db->select('is_backorder')->from('orders_detail')->where('id_orders_detail', $order_detail_id)->get()->row()->is_backorder;
		/*get order id & warehouse*/
		$new_resi = array(
			'no_resi' => $this->input->post('no_resi'),
		);

		$this->db->where('id_orders_detail', $order_detail_id);
		$this->db->update('orders_detail', $new_resi);

		$new_tracking_number = array(
			'tracking_number' => $this->input->post('no_resi'),
		);

		$this->db->where('order_id', $id_order);
		$this->db->where('warehouse_id', $warehouse_id);
		$this->db->where('is_indent', $is_backorder);
		$this->db->update('shipping', $new_tracking_number);
		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No. Resi Updated</p>');
		redirect('admin/orders_retailer/view/' . $id_order);
	}

	function jx_update_stt_withbutton()
	{
		$p_act = $this->input->post('p_act');
		$msg = "Gagal";
		$res = "";
		if (isset($p_act)) {
			switch ($p_act) {
				case 'ready to send':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$witch = $this->input->post('witch');

					if ($witch === "indent") {

						//get warehouse id
						$order_detail = $this->db->select('warehouse_id, quantity')->from('orders_detail')->where('id_orders_detail', $order_detailid)->get()->row();
						$warehouse_id = $order_detail->warehouse_id;
						$qty = $order_detail->quantity;

						//deduct stock
						//get current stock
						$this->db->select('stock, id')->from('stock')->where('id_product', $productid)->where('id_product_detail', $itemid)->where('warehouse_id', $warehouse_id);
						$current_stock = $this->db->get()->row();

						$data = array(
							'stock' => $current_stock->stock - $qty,
						);

						$query_update = $this->db->where('id_product', $productid)
							->where('id_product_detail', $itemid)
							->where('warehouse_id', $warehouse_id)
							->update('stock', $data);

						//get $stock_id
						$stock_id = $current_stock->id;
						$last_stock = $current_stock->stock + $qty;

						//update stock_movement_table
						$movement_data = array(
							'stock_id' => $stock_id,
							'type' => '-',
							'stock_change' => (int) $qty,
							'remark' => 'Indent Order No: ' . $orderid . ' (' . $last_stock . ')'
						);
						$this->db->insert('stock_movement', $movement_data);

						//send email
						$indent_uniqe = $this->customer_m->hash($productid . ' ' .  $order_detailid . ' ' . $orderid);
						$data = array(
							'indent_uniqe_id' => $indent_uniqe
						);
						$this->db->where('id_orders', $orderid);
						$this->db->update('orders', $data);

						//get order data
						$order_data = $this->db->select('*')->from('orders')->where('id_orders', $orderid)->get()->row();
						$customer_id = $order_data->customer_id;

						$data['order'] = $order_data;
						$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

						$check_bank_bca =
							$this->db->select('bank')
							->from('configuration')
							->where('id_configuration', 1)
							->where('bank_transfer', 1)
							->get();

						$check_bank_mandiri =
							$this->db->select('bank1')
							->from('configuration')
							->where('id_configuration', 1)
							->where('bank_transfer1', 1)
							->get();

						$data['bank_active'] = [];
						if ($check_bank_bca->num_rows() > 0) {
							$data['bank_active'][0] =
								$check_bank_bca->row()->bank;
						}
						if ($check_bank_mandiri->num_rows() > 0) {
							$data['bank_active'][1] =
								$check_bank_mandiri->row()->bank1;
						}

						$email_data = $data;
						//get order details only contain indent
						$email_data['order_details'] = $this->db->select('*')->from('orders_detail')->where('orders_id', $orderid)->where('id_orders_detail', $order_detailid)->where('is_backorder', 'yes')->get()->result();
						// var_dump($email_data);
						// exit();
						//----SEND EMAIL TO CUSTOMER TO PAY FOR INDENT
						$this->db->select('name,customers.phone,type,email')->from('customers')->where('id_customers', $customer_id);
						$email_data['customer'] = $this->db->get()->row();

						$data['order_details'] = $email_data['order_details'];

						if ($order_data->payment_type !== "midtran") {
							$data['bank'] = $order_data->payment_type;
							if ($data['bank'] == 'bank transfer BCA') {
								$bank_info = $this->db->select('bank')->from('configuration')->where('id_configuration', 1)->get()->row()->bank;
								$data['bank_info'] = $bank_info;
							} else {
								$bank_info = $this->db->select('bank1')->from('configuration')->where('id_configuration', 1)->get()->row()->bank1;
								$data['bank_info'] = $bank_info;
							}
						}

						$email_data['email'] = $email_data['customer']->email;

						$email_data['emails'] = $this->configuration_m->get_emails();

						$payment_type = $order_data->payment_type;

						if ($payment_type == 'bank transfer BCA') {
							$email_data['bank'] = $this->db->select('bank')->from('configuration')->where('id_configuration', 1)->get()->row()->bank;
						}
						if ($payment_type == 'bank transfer MANDIRI') {
							$email_data['bank'] = $this->db->select('bank1')->from('configuration')->where('id_configuration', 1)->get()->row()->bank1;
						}

						$email_data['subject'] = 'Indent Product Ready';

						//get order detail and customer detail
						$email_data['order'] = $this->order_m->get_order($orderid);

						if ($data['order']->order_language == 'english') {
							$view_file = 'email/english/indent_ready';
						} else {
							$view_file = 'email/indonesian/indent_ready';
						}
						// echo "<pre>";
						// var_dump($email_data['bank']);
						// exit();

						// $this->load->view('email/indonesian/indent_ready', $email_data);
						// echo "<pre>";
						// var_dump($data['bank_active']);
						// exit();

						$this->send_email($view_file, $email_data); //function in My_Controller		

					}
					if ($witch === "instock") {
					}
					$w = array(
						"id_orders_detail" => $order_detailid,
						"orders_id" => $orderid,
						"item_id" => $itemid,
						"product_id" => $productid,
					);
					$dt = array(
						"status" => 1,
					);
					$res = $w;
					$upd = $this->db->update("orders_detail", $dt, $w);
					if ($upd) {
						$msg = "Sukses";
					}
					break;

				case 'fully paid':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');

					$w = array(
						"id_orders_detail" => $order_detailid,
						"orders_id" => $orderid,
						"item_id" => $itemid,
						"product_id" => $productid,
						"status" => 1,
					);
					$res = $w;
					$dt = array(
						"status" => 3,
					);
					$upd = $this->db->update("orders_detail", $dt, $w);
					if ($upd) {
						$msg = "Sukses";
						// $this->db->select('customer_id')->from('orders')->where('id_orders', $orderid);
						// $customer_id = (int) $this->db->get()->row()->customer_id;

						//get add and minus point from order
						$this->db->select('plus_reward')->from('orders')->where('id_orders', $orderid);
						$rewards = $this->db->get()->row();
						$plus_point = (int) $rewards->plus_reward;

						$data['title'] = 'Fully Paid';
						$data['order'] = $this->order_m->get_order($orderid);
						$data['order_details'] = $this->order_detail_m->get_orders_detail($orderid);

						$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

						//get website data
						$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);

						$website_data = $this->db->get()->row();
						$data['logo'] = $website_data->logo;
						$data['website_name'] = $website_data->website_name;
						$data['emails'] = $this->configuration_m->get_emails();
						$data['plus_point'] = $plus_point;

						$email_data = $data;
						$email_data['email'] = $data['customer']->email;
						$email_data['subject'] = 'Payment Fully Paid';
						if ($data['order']->order_language == 'english') {
							$view_file = 'email/english/payment_confirmation_retailer';
						} else {
							$view_file = 'email/indonesian/payment_confirmation_retailer';
						}
						$this->send_email($view_file, $email_data);
					}
					break;
				case 'save noresi':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$inp_noresi = $this->input->post('inp_noresi');
					$witch = $this->input->post('witch');
					$set_stt = 3;

					if ($witch === "indent") {
						$set_stt = 3;
					}
					if ($witch === "instock") {
						$set_stt = 1;
					}
					$w = array(
						"id_orders_detail" => $order_detailid,
						"orders_id" => $orderid,
						"item_id" => $itemid,
						"product_id" => $productid,
						"status" => $set_stt,
					);
					$res = $w;
					$dt = array(
						"no_resi" => $inp_noresi,
					);
					$upd = $this->db->update("orders_detail", $dt, $w);
					if ($upd) {
						$msg = "Sukses";
					}
					break;
				case 'sent':


					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$inp_noresi = $this->input->post('inp_noresi');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$witch = $this->input->post('witch');
					$set_stt = 3;

					$data['order'] = $this->db->select('*')->from('orders')->where('id_orders', $orderid)->get()->row();

					if ($witch === "indent") {
						$set_stt = 3;
					}
					if ($witch === "instock") {
						$set_stt = 1;
					}

					$w = array(
						"id_orders_detail" => $order_detailid,
						"orders_id" => $orderid,
						"item_id" => $itemid,
						"product_id" => $productid,
						"status" => $set_stt,
					);

					$res = $w;
					$dt = array(
						"status" => 2,
					);
					$upd = $this->db->update("orders_detail", $dt, $w);

					//SEND EMAIL TO CUSTOMER
					$data['product_detail'] = $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $order_detailid)->get()->row();
					$data['title'] 			= 'Product Picked Up';
					//get order detail and customer detail
					$data['orders_detail'] = $this->db->select('*')->from('orders_detail')
						->where('id_orders_detail', $order_detailid)
						->get()->row();

					$data['warehouse']		= $this->db->select('name')->from('warehouse')
						->where('id', $data['orders_detail']->warehouse_id)->get()->row()->name;

					$data['shipping_method'] = $this->db->select('name')->from('shipment_method')
						->where('id', $data['orders_detail']->chosen_shipping_id)->get()->row()->name;

					$data['nama_kurir'] = $this->db->select('carrier')->from('shipment_method')
						->where('id', $data['orders_detail']->chosen_shipping_id)->get()->row()->carrier;

					$data['no_resi']		= $this->security->xss_clean($inp_noresi);

					$customer_id 			= $this->db->select('customer_id')->from('orders')->where('id_orders', $orderid)->get()->row()->customer_id;

					$data['customer']		= $this->customer_m->get_customer($customer_id);

					//get website data
					$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
					$website_data 			= $this->db->get()->row();
					$data['logo'] 			= $website_data->logo;
					$data['website_name'] 	= $website_data->website_name;
					$data['emails'] 		= $this->configuration_m->get_emails();

					$email_data = $data;
					$email_data['email'] = $email_data['customer']->email;
					if ($data['order']->order_language == 'english') {
						$email_data['subject'] = 'Product Sent';
					} else {
						$email_data['subject'] = 'Pesananmu Sudah Dijalan';
					}



					if ($data['order']->order_language == 'english') {
						$view_file = 'email/english/pickedup_confirmation';
					} else {
						$view_file = 'email/indonesian/pickedup_confirmation';
					}
					$this->send_email($view_file, $email_data); //function in My_Controller	
					//----end send email

					if ($upd) {
						$msg = "Sukses";
						$w = array(
							// "id_orders_detail"=>$order_detailid,
							"orders_id" => $orderid,
							// "item_id"=>$itemid,
							// "product_id"=>$productid,
							// "status"=>2
						);
						$cek_sttnow = 2;
						$query_sttwo = $this->db->get_where('orders_detail', $w);

						// $res['data_order_details']= $query_sttwo->result();
						foreach ($query_sttwo->result() as $key) {
							if ((int)$key->status !== 2) {
								$cek_sttnow = (int)$key->status;
								$res['hasil_status'][] = (int)$key->status;
							}
						}

						$res['akhir_hasil_status'] = $cek_sttnow;
						if ($cek_sttnow === 2) {
							$user_id = $this->session->userdata('admin')['id'];

							$activity = 'User mengubah status order ' . $orderid . ' menjadi Terkirim';

							log_activity($user_id, $activity);
							$upd2 = $this->db->update("orders", array(
								"payment_status" => 5,
							), array(
								"id_orders" => $orderid,
							));
							if ($upd2) {
								$msg = "Sukses";
							} else {
								$msg = "Gagal";
							}
						}
					}

					break;

				default:
					# code...
					break;
			}
		}

		$rs = $res;
		$rs["msg"] = $msg;
		echo json_encode($rs);
	}

	function ajax_update_status()
	{

		$return 			= 'false';
		$id_orders 			= $this->input->post('id_orders');
		$barcode_validate 	= $this->input->post('barcode_validate');
		$item_id			= $this->input->post('id_products');
		$is_backorder		= $this->input->post('is_backorder');
		$warehouse_id		= $this->input->post('warehouse_id');
		$id_order_detail	= $this->input->post('id_order_detail');

		//get product id
		$product_id = $this->db->select('product_id')->from('orders_detail')->where('item_id', $item_id)->where('orders_id', $id_orders)->get()->row()->product_id;

		//get product code
		$this->db->select('sku')->from('product_details')->where('id', $item_id);
		$product_code = $this->db->get()->row()->sku;

		$this->db->select('orders.*,orders_detail.*,warehouse.*');
		$this->db->from('orders');
		$this->db->join('orders_detail', 'id_orders=orders_id');
		$this->db->join('warehouse', 'orders_detail.warehouse_id=warehouse.id');
		$this->db->where('id_orders', $id_orders);
		$this->db->where('id_orders_detail', $id_order_detail);
		$this->db->where('orders_detail.is_backorder', $is_backorder);
		$this->db->where('orders_detail.warehouse_id', $warehouse_id);
		$order = $this->db->get()->row();

		if ($product_code == $barcode_validate) {

			if ($this->order_m->cek_orderdetail($order->id_orders_detail, 0) == true) {
				$return = 'false';
				if ($order->is_backorder == 'yes') {
					$cek_stock =
						$this->db
						->select('stock,stock_virtual')
						->from('stock')
						->where('id_product', $product_id)
						->where('id_product_detail', $item_id)
						->where('warehouse_id', $order->warehouse_id)
						->get()
						->row();

					if ($order->warehouse_type == 'virtual') {
						if ($order->quantity <= $cek_stock->stock_virtual) {
							$order_details = array(
								'status' => 1,
							);
							$new_stock = array(
								'stock_virtual' => $cek_stock->stock - $order->quantity,
							);
							$return = "true";
						} else {
							$return = "stok tidak cukup";
						}
					} else {
						if ($order->quantity <= $cek_stock->stock) {
							$order_details = array(
								'status' => 1,
							);
							$new_stock = array(
								'stock' => $cek_stock->stock - $order->quantity,
							);

							$return = "true";
						} else {
							$return = "stok tidak cukup";
						}
					}

					if ($return == "true") {
						$this->db->where('id_product', $product_id);
						$this->db->where('id_product_detail', $order->item_id);
						$this->db->where('warehouse_id', $order->warehouse_id);
						$this->db->update('stock', $new_stock);
					}
				} else {
					$order_details = array(
						'status' => 1,
					);
					$return = "true";
				}
			} else {
				$return = "order telah proses";
			}

			if ($return == "true") {
				$this->db->where('id_orders_detail', $order->id_orders_detail);
				$this->db->update('orders_detail', $order_details);
			}

			echo $return;
		} else {
			echo "Barcode salah, harap cek kembali";
		}
	}
	function ongkir_change($id)
	{

		if (!isset($_POST['shipping_fee'])) {
			show_404();
		}
		if ($id == NULL) {
			show_404();
		}

		//load library security
		$this->load->library('security');

		//check if id is exist
		$this->db->select('id_orders')->from('orders')->where('id_orders', $id);
		$count_id = $this->db->get()->num_rows();
		if ($count_id == 0) {
			show_404();
		}

		$data = array(
			'shipping_fee' => $this->security->xss_clean($this->input->post('shipping_fee'))
		);
		$this->db->where('id_orders', $id);
		$this->db->update('orders', $data);


		//logging
		$user_id = $this->session->userdata('admin')['id'];

		$activity = 'User mengubah ongkos kirim (' . $id . ')';

		log_activity($user_id, $activity);
		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Ongkir berhasil di update</p>");
		redirect('admin/orders_retailer/view/' . $id);
	}

	function update_resi_all($id)
	{

		if (!isset($_POST['resi'])) {
			show_404();
		}
		if ($id == NULL) {
			show_404();
		}

		//load library security
		$this->load->library('security');

		//check if id is exist
		$this->db->select('id_orders')->from('orders')->where('id_orders', $id);
		$count_id = $this->db->get()->num_rows();
		if ($count_id == 0) {
			show_404();
		}

		$order_details = $this->order_detail_m->get_orders_detail($id);
		foreach ($order_details as $od) {

			$data = array(
				'status' => $this->security->xss_clean($this->input->post('status')),
				'no_resi' => $this->security->xss_clean($this->input->post('resi'))

			);
			$this->db->where('id_orders_detail', $od->id_orders_detail);
			$this->db->update('orders_detail', $data);
		}
		$order_details_1 = $this->order_detail_m->get_orders_detail_1($id);
		$order_detailid = $order_details_1->id_orders_detail;
		$inp_noresi = $this->input->post('resi');
		$orderid = $this->input->post('orders_id');
		$data['order'] = $this->db->select('*')->from('orders')->where('id_orders', $orderid)->get()->row();

		//SEND EMAIL TO CUSTOMER
		$data['product_detail'] = $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $order_detailid)->get()->row();
		$data['title'] 			= 'Product Sent';

		//get order detail and customer detail
		$data['orders_detail'] = $this->db->select('*')->from('orders_detail')
			->where('id_orders_detail', $order_detailid)
			->get()->row();

		$data['shipping_method'] = $this->db->select('name')->from('shipment_method')
			->where('id', $data['orders_detail']->chosen_shipping_id)->get()->row()->name;

		$data['nama_kurir'] = $this->db->select('carrier')->from('shipment_method')
			->where('id', $data['orders_detail']->chosen_shipping_id)->get()->row()->carrier;

		$data['no_resi']		= $this->security->xss_clean($inp_noresi);

		$customer_id 			= $this->db->select('customer_id')->from('orders')->where('id_orders', $orderid)->get()->row()->customer_id;

		$data['customer']		= $this->customer_m->get_customer($customer_id);

		//get website data
		$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
		$website_data 			= $this->db->get()->row();
		$data['logo'] 			= $website_data->logo;
		$data['website_name'] 	= $website_data->website_name;
		$data['emails'] 		= $this->configuration_m->get_emails();

		$email_data = $data;
		$email_data['email'] = $email_data['customer']->email;
		if ($data['order']->order_language == 'english') {
			$email_data['subject'] = 'Product Sent';
		} else {
			$email_data['subject'] = 'Pesananmu Sudah Dijalan';
		}

		if ($data['order']->order_language == 'english') {
			$view_file = 'email/english/pickedup_confirmation_all';
		} else {
			$view_file = 'email/indonesian/pickedup_confirmation_all';
		}
		$this->send_email($view_file, $email_data); //function in My_Controller	
		//----end send email

		$data = array(
			'payment_status' => $this->security->xss_clean($this->input->post('status_order'))
		);
		$this->db->where('id_orders', $id);
		$this->db->update('orders', $data);


		//logging
		$user_id = $this->session->userdata('admin')['id'];

		$activity = 'User mengubah ongkos kirim (' . $id . ')';

		log_activity($user_id, $activity);
		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Resi berhasil di update</p>");
		redirect('admin/orders_retailer/view/' . $id);
	}

	function add_note($id)
	{

		if (!isset($_POST['add_note'])) {
			show_404();
		}
		if ($id == NULL) {
			show_404();
		}

		//check if id is exist
		$this->db->select('id_orders')->from('orders')->where('id_orders', $id);
		$count_id = $this->db->get()->num_rows();
		if ($count_id == 0) {
			show_404();
		}

		$data = array(
			'admin_note' => $this->security->xss_clean($this->input->post('admin_note'))
		);
		$this->db->where('id_orders', $id);
		$this->db->update('orders', $data);

		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Update Note Success.</p>");
		redirect('admin/orders_retailer/view/' . $id);
	}

	function ajax_check_stock()
	{
		$pr 	= $this->input->post('prod');
		$qty 	= $this->input->post('qty');
		$wh 	=  $this->input->post('wh');

		if (!$this->order_m->cek_stok($pr, $qty, $wh)) {
			echo  '<span class="label label-semi">stock tidak cukup</span>';
		} else {
			echo '';
		}
	}

	function change_indent_address()
	{

		if (!$_POST['change_indent_address']) {
			redirect('admin/orders_retailer');
		}

		$order_id = $this->input->post('inp_order_id');
		$customer_id = $this->input->post('inp_customer_id');
		$order_detail_id = $this->input->post('order_detail_id');
		$address = $this->security->xss_clean($this->input->post('address'));
		$province_id = $this->input->post('shipping_province');
		$district_id = $this->input->post('shipping_district');
		$subdistrict_id = $this->input->post('shipping_subdistrict');

		//calculate new shipping fee 
		$this->load->helper('shipping');
		$this->load->helper('rajaongkir');

		$free_shipping_type =
			$this->db->select('free_shipping_type')
			->from('configuration')
			->where('id_configuration', 1)->get()->row()
			->free_shipping_type;

		$condition_freeshipping = false;
		if ($free_shipping_type == 'region') {
			$selected_region_province =
				$this->db->select('*')
				->from('free_shipping_region')
				->where('configuration_id', 1)
				->where('province_id', $province_id)
				->get();

			if ($selected_region_province->num_rows() > 0) {
				$condition_freeshipping = true;
			}
		}

		//get product detail info
		$order_detail = $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $order_detail_id)->get()->row();

		$shipping_info = calculate_shipping_fee($order_detail->chosen_shipping_id, $order_detail->warehouse_id, $order_detail->product_id, $order_detail->item_id, $order_detail->quantity, $subdistrict_id);

		//add new info into orders_detail table
		$data = array(
			'new_address' => $address,
			'new_province_id' => $province_id,
			'new_district_id' => $district_id,
			'new_subdistrict_id' => $subdistrict_id,
			'shipping_fee' => $shipping_info['total_shipping_fee']
		);

		$query_customers = $this->db->select("*")
			->from("customers")
			->where('id_customers', $customer_id)
			->get();

		$query_orders = $this->db->select("*")
			->from("orders")
			->where('id_orders', $order_id)
			->get();

		$indent_shipping_fee_remaining = $data['shipping_fee'];

		if ($query_customers->num_rows() > 0) {
			if ($query_customers->row()->type == "regular") {
				if ($condition_freeshipping == true) {
					$data['shipping_fee'] = 0;
					$indent_shipping_fee_remaining = $data['shipping_fee'];
				}
			}
		}

		// echo "<pre>";
		// var_dump($indent_shipping_fee_remaining); 
		// exit();

		$this->db->where('id_orders_detail', $order_detail_id);
		$this->db->update('orders_detail', $data);

		$this->db->where('id_orders', $order_id);
		$this->db->update('orders', array(
			"indent_shipping_fee" => $indent_shipping_fee_remaining,
		));

		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Indent Address Changed.</p>");
		redirect('admin/orders_retailer/view/' . $order_detail->orders_id);
	}

	public function generate_invoice($id)
	{
		if ($id == NULL) {
			redirect('admin/orders_retailer');
		}

		$count_order = $this->db->select('id_orders')->from('orders')->where('id_orders', $id)->get()->num_rows();
		if ($count_order < 1) {
			redirect('admin/orders_retailer');
		}

		//get website info
		$pdf_data['website_data'] = $this->db->select('logo, website_name')->from('configuration')->where('id_configuration', 1)->get()->row();

		//add PDF attachment DOMPDF 	  
		$pdf_data['title'] = 'Invoice No: ' . $id;

		//get order
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$pdf_data['order'] = $this->db->get()->row();

		if ($count_order > 0) {
			//get customer detail
			$pdf_data['customer'] = $this->db->select('*')->from('customers')->where('id_customers', $pdf_data['order']->customer_id)->get()->row();

			// get order detail
			$pdf_data['orders_detail'] 	= $this->db->select('*')->from('orders_detail')->where('orders_id', $id)->get()->result();

			//Print Pdf Invoice
			$this->load->library('dompdf_gen');
			$html = $this->load->view('pdf/invoice', $pdf_data, true);
			$this->dompdf->loadHtml($html);
			$this->dompdf->setPaper('A4', 'portrait');
			$this->dompdf->render();
			$this->dompdf->stream('invoice.pdf', array("Attachment" => 0));
			$output = $this->dompdf->output();
			$file_to_save = 'uploads/pdf/invoice.pdf';
			file_put_contents($file_to_save, $output);
		} else {
			redirect('admin/orders_retailer');
		}
	}

	public function generate_deliveryreceipt($id)
	{
		if ($id == NULL) {
			redirect('admin/orders_retailer');
		}

		$count_order = $this->db->select('id_orders')->from('orders')->where('id_orders', $id)->get()->num_rows();
		if ($count_order < 1) {
			redirect('admin/orders_retailer');
		}

		//get website info
		$pdf_data['website_data'] = $this->db->select('logo, website_name')->from('configuration')->where('id_configuration', 1)->get()->row();

		//add PDF attachment DOMPDF 	  
		$pdf_data['title'] = 'Delivery Receipt No: ' . $id;

		//get order
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$pdf_data['order'] = $this->db->get()->row();

		if ($count_order > 0) {
			//get customer detail
			$pdf_data['customer'] = $this->db->select('*')->from('customers')->where('id_customers', $pdf_data['order']->customer_id)->get()->row();

			// get order detail
			$pdf_data['orders_detail'] 	= $this->db->select('*')->from('orders_detail')->where('orders_id', $id)->get()->result();

			//Print Pdf Delivery Receipt
			$this->load->library('dompdf_gen');
			$html = $this->load->view('pdf/deliveryreceipt', $pdf_data, true);
			$this->dompdf->loadHtml($html);
			$this->dompdf->setPaper('A4', 'portrait');
			$this->dompdf->render();
			$this->dompdf->stream('deliveryreceipt.pdf', array("Attachment" => 0));
			$output = $this->dompdf->output();
			$file_to_save = 'uploads/pdf/deliveryreceipt.pdf';
			file_put_contents($file_to_save, $output);
		} else {
			redirect('admin/orders_retailer');
		}
	}


	// public function add_order_admin() {

	// 	// echo $this->input->post('admin_note');
	// 	$total_amount = 0;
	// 	for ($i=0; $i < count($this->input->post('id_product')) ; $i++) { 
	// 		// echo $this->input->post('harga')[$i].' jum '.$this->input->post('kuantitas')[$i];
	// 		// echo "<br>";
	// 		$total_amount += $this->input->post('harga')[$i] * $this->input->post('kuantitas')[$i];
	// 	}
	// 	// echo $total_amount;
	// 	// echo "<br>";
	// 	$grand_total_amount = $total_amount+$this->input->post('shipping_fee');
	// 	$id_customer = $this->input->post('customer_id');
	// 	$customer = $this->db->select('*')->from('customers')->where('id_customers', $id_customer)->get()->row();
	// 	// echo $customer->recipient_name;

	// 	$data = array(
	//         'customer_id' => $this->input->post('customer_id'),
	//         'order_date' => date("Y-m-d H:i:s"),
	//         'payment_status' => 0,
	//         'grand_total_amount' => $grand_total_amount,
	//         'total_downpayment' => $grand_total_amount,
	//         'indent_remaining' => 0,
	//         'indent_shipping_fee' => 0,
	//         'total_amount' => $total_amount,
	//         'recipient_name' => $customer->recipient_name,
	//         'address' => $customer->address,
	//         'district' => $customer->district,
	//         'subdistrict' => $customer->subdistrict,
	//         'province' => $customer->province,
	//         'postcode' => $customer->postcode,
	//         'phone' => $customer->phone,
	//         'email' => $customer->email,
	//         'country' => $customer->country,
	//         'shipping_fee' => $this->input->post('shipping_fee'),
	//         'admin_note' => $this->input->post('admin_note'),
	//         'created_by' => 'admin',
	// 	);

	// 	$this->db->insert('orders', $data);
	// 	$insert_id = $this->db->insert_id();

	// 	for ($i=0; $i < count($this->input->post('id_product')) ; $i++) { 
	// 		$data = array(
	// 	        'orders_id' => $insert_id,
	// 		);

	// 		$this->db->insert('orders_detail', $data);

	// 		$total_amount += $this->input->post('harga')[$i] * $this->input->post('kuantitas')[$i];
	// 	}



	// }

}

https://t.me/RX1948 - 2025