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 :  /proc/self/root/var/www/laciasmara.com/public_html/shop/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

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



class Orders 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');

		$this->load->model('voucher_m');

		$this->load->model('log_m');

		$this->load->helper('rajaongkir');

	}



	public function cek_kota()

	{

		$data = get_rajaongkir_data('city');

		echo "<pre>";

		print_r($data);

		echo "</pre>";

	}



	public function cek_subdistrict()

	{

		$data = get_rajaongkir_data('subdistrict?city=67');

		echo "<pre>";

		print_r($data);

		echo "</pre>";

	}



	// public function insert_subdistrict()

	// {

	// 	$city = [];

	// 	$data = get_rajaongkir_data('subdistrict?city=117');

	// 	if (isset($data['rajaongkir']['results']) && is_array($data['rajaongkir']['results'])) {

	// 		$results = $data['rajaongkir']['results'];



	// 		// Loop hasilnya

	// 		foreach ($results as $row) {

	// 			$city_id = $row['city_id'];

	// 			$subdistrict_id = $row['subdistrict_id'];

	// 			$subdistrict_name = $row['subdistrict_name'];



	// 			$this->db->insert('indonesia_subdistricts', [

	// 				'indonesia_id_district' => $city_id,

	// 				'rajaongkir_id_subdistrict' => $subdistrict_id,

	// 				'subdistrict' => $subdistrict_name

	// 			]);

	// 			echo "<br>City: " . $city_id;

	// 			echo "<br>inserted: " . $subdistrict_name;

	// 		}

	// 		echo "<br>Berhasil insert semua subdistrict.";

	// 	} else {

	// 		echo "Data tidak ditemukan atau format salah.";

	// 	}

	// }



	public function insert_subdistrict($cities = [])

	{

		// Jika parameter kosong, gunakan default cities

		if (empty($cities)) {

			$cities = []; // contoh default city IDs

		}



		// Pastikan $cities adalah array

		if (!is_array($cities)) {

			$cities = [$cities];

		}



		$total_inserted = 0;



		foreach ($cities as $city_id) {

			echo "<br><strong>Processing City ID: " . $city_id . "</strong>";



			$data = get_rajaongkir_data('subdistrict?city=' . $city_id);



			if (isset($data['rajaongkir']['results']) && is_array($data['rajaongkir']['results'])) {

				$results = $data['rajaongkir']['results'];

				$city_count = 0;



				// Loop hasil untuk city ini

				foreach ($results as $row) {

					$subdistrict_id = $row['subdistrict_id'];

					$subdistrict_name = $row['subdistrict_name'];



					// Cek apakah sudah ada di database untuk menghindari duplikasi

					$existing = $this->db->get_where('indonesia_subdistricts', [

						'rajaongkir_id_subdistrict' => $subdistrict_id

					])->row();



					if (!$existing) {

						$this->db->insert('indonesia_subdistricts', [

							'indonesia_id_district' => $city_id,

							'rajaongkir_id_subdistrict' => $subdistrict_id,

							'subdistrict' => $subdistrict_name

						]);



						echo "<br>&nbsp;&nbsp;Inserted: " . $subdistrict_name;

						$city_count++;

						$total_inserted++;

					} else {

						echo "<br>&nbsp;&nbsp;Skipped (exists): " . $subdistrict_name;

					}

				}



				echo "<br>&nbsp;&nbsp;Total inserted for City " . $city_id . ": " . $city_count;



				sleep(1);

			} else {

				echo "<br>&nbsp;&nbsp;Data tidak ditemukan untuk City ID: " . $city_id;

			}

		}



		echo "<br><br><strong>Total keseluruhan inserted: " . $total_inserted . "</strong>";

		echo "<br>Berhasil memproses " . count($cities) . " cities.";

	}



	public function process_multiple_cities()

	{

		$cities = range(1, 501);



		$this->insert_subdistrict($cities);

	}



	public function add_order()

	{



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

		$data['title'] = 'Tambah Pesanan | Laciasmara';

		$data['customers'] = $this->customer_m->fetch_all_customers();

		$data['products'] = $this->product_m->all_products();

		$data['shippingMethods'] = $this->product_m->get_all_shipping_methods();

		$data['paymentMethods'] = $this->product_m->get_all_payment_methods();

		$data['vouchers'] = $this->voucher_m->fetch_all_vouchers();



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/add_order');

		$this->load->view('admin_new/layouts/footer');

	}



	public function add_retailer_order()

	{

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

		$data['title'] = 'Tambah Pesanan Retailer | Laciasmara';

		$data['retailers'] = $this->customer_m->fetch_all_retailers();

		$data['products'] = $this->product_m->all_products();

		$data['shippingMethods'] = $this->product_m->get_all_shipping_methods();

		$data['paymentMethods'] = $this->product_m->get_all_payment_methods();

		$data['vouchers'] = $this->voucher_m->fetch_all_vouchers();



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/retailer/add_order');

		$this->load->view('admin_new/layouts/footer');

	}



	public function manage()

	{

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

		$data['title'] = 'Daftar Pesanan | Laciasmara';

		$data['customers'] = $this->customer_m->fetch_all_customers();

		$data['products'] = $this->product_m->all_products();

		$data['shippingMethods'] = $this->product_m->get_all_shipping_methods();

		$data['paymentMethods'] = $this->product_m->get_all_payment_methods();

		$data['vouchers'] = $this->voucher_m->fetch_all_vouchers();





		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/manage_order');

		$this->load->view('admin_new/layouts/footer');

	}



	public function manage_retailer()

	{

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

		$data['title'] = 'Daftar Pesanan Retailer | Laciasmara';

		$data['customers'] = $this->customer_m->fetch_all_retailers();

		$data['products'] = $this->product_m->all_products();

		$data['shippingMethods'] = $this->product_m->get_all_shipping_methods();

		$data['paymentMethods'] = $this->product_m->get_all_payment_methods();

		$data['vouchers'] = $this->voucher_m->fetch_all_vouchers();



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/retailer/manage_order');

		$this->load->view('admin_new/layouts/footer');

	}



	public function detail($id_order = NULL)

	{

		if (!$id_order) {

			redirect('admin/orders/manage-order');

		}

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

		$data['title'] = 'Detail Pesanan | Laciasmara';

		// Fetch data order

		$data['order'] = $this->order_m->fetch_order_by_id($id_order);

		if (!$data['order']) {

			$this->session->set_flashdata('message', 'Order ID tidak ditemukan.');

			$this->session->set_flashdata('message_type', 'error');

			redirect('admin/orders/manage-order');

		}



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/detail_order');

		$this->load->view('admin_new/layouts/footer');

	}



	public function create_order()

	{

		if ($this->input->server('REQUEST_METHOD') !== 'POST') {

			show_error('Method Not Allowed', 405);

		}

		$userdata = $this->session->userdata();

		$postData = $this->input->post();

		$grandTotal = (int) $postData['total_price'];

		$tokopediaInvoice = empty($postData['tokopedia_invoice']) ? '' : $postData['tokopedia_invoice'];



		// Data untuk tabel orders

		$orderData = [

			'customer_id' => (!empty($postData['is_marketplace']) && $postData['is_marketplace'] == 1) ? 2615 : $postData['customer'],

			'payment_status' => 1,

			'grand_total_amount' => (int) $postData['total_price'],

			'total_amount' => (int) $postData['subtotal_price'],

			'payment_type' => ($postData['paymentMethod'] == 1) ? 'bank transfer BCA' : (($postData['paymentMethod'] == 2) ? 'bank transfer MANDIRI' : (($postData['paymentMethod'] == 3) ? 'Free' : 'not yet')),

			'recipient_name' => $postData['name'],

			'address' => empty($postData['address']) ? $postData['address'] : $postData['address'],

			'district'    => !empty($postData['shipping_district']) ? $postData['shipping_district'] : $postData['shipping_district'],

			'subdistrict' => !empty($postData['shipping_subdistrict']) ? $postData['shipping_subdistrict'] : $postData['shipping_subdistrict'],

			'province'    => !empty($postData['shipping_province']) ? $postData['shipping_province'] : $postData['shipping_province'],

			'phone'       => !empty($postData['shipping_phone']) ? $postData['shipping_phone'] : $postData['shipping_phone'],

			'admin_note'       => !empty($postData['admin_note']) ? $postData['admin_note'] : $postData['admin_note'],

			'customer_invoice_note'       => !empty($postData['customer_invoice_note']) ? $postData['customer_invoice_note'] : $postData['customer_invoice_note'],

			'email' => $postData['email'],

			'country' => 'Indonesia',

			'redeemed_voucher_code'  => !empty($postData['redeemed_voucher_code']) ? $postData['redeemed_voucher_code'] : null,

			'redeemed_voucher_type'  => !empty($postData['redeemed_voucher_type']) ? $postData['redeemed_voucher_type'] : null,

			'redeemed_voucher_value' => !empty($postData['redeemed_voucher_value']) ? (int) $postData['redeemed_voucher_value'] : 0,

			'redeemed_voucher_amount' => !empty($postData['redeemed_voucher_amount']) ? (int) $postData['redeemed_voucher_amount'] : 0,

			'shipping_fee' => (int) $postData['shipping_fee'],

			'created_by' => $userdata['name'],

			'source' => empty($postData['tokopedia_invoice']) ? 'www.laciasmara.com' : 'Tokopedia',

			'tokopedia_invoice' => empty($postData['tokopedia_invoice']) ? '' : $postData['tokopedia_invoice']

		];

		// Ambil data pelanggan untuk is_first

		$customer = $this->db->get_where('customers', ['id_customers' => $postData['customer']])->row();

		if ($customer) {

			$orderData['first'] = $customer->is_first + 1;

		}



		$warehouse_id = 1;

		if ($customer->id_customers == 2615) {

			$warehouse_id = 13;

		}

		if ($customer->reseller_id == 8) {

			$warehouse_id = 12;

		}



		if ($customer->reseller_id == 7) {

			$warehouse_id = 14;

		}

		// Mulai transaksi database

		$this->db->trans_start();



		// Insert ke tabel orders

		$this->db->insert('orders', $orderData);

		$orderId = $this->db->insert_id();



		// Simpan stok awal untuk setiap produk

		$initial_stock_data = [];



		// Insert ke orders_detail

		$orderDetails = json_decode($postData['selected_products_data'], true);



		// Simpan stok awal untuk setiap produk

		foreach ($orderDetails as $item) {

			$this->db->select('id, stock');

			$this->db->where('id_product', $item['id_products']);

			$this->db->where('id_product_detail', $item['id_detail']);

			$this->db->where('warehouse_id', 1);

			$stock = $this->db->get('stock')->row();



			$initial_stock_data[$item['id_detail']] = $stock->stock;

		}



		foreach ($orderDetails as $item) {

			$orderDetailData = [

				'orders_id' => $orderId,

				'item_id' => $item['id_detail'],

				'product_id' => $item['id_products'],

				'item_name' => $item['product'],

				'item_price' => (int) $item['price'],

				'quantity' => (int) $item['qty'],

				'subtotal' => (int) $item['subtotal'],

				'sku' => $item['sku'],

				'attributes' => $item['atribut'],

				'warehouse_id' => $warehouse_id,

				'chosen_shipping_id' => $postData['shippingMethod'],

				'shipping_fee' => (int) $postData['shipping_fee']

			];



			$insert_result = $this->db->insert('orders_detail', $orderDetailData);



			// Update Stock

			if ($insert_result) {

				$this->db->select('id, stock');

				$this->db->where('id_product', $item['id_products']);

				$this->db->where('id_product_detail', $item['id_detail']);

				$this->db->where('warehouse_id', $warehouse_id);

				$stock = $this->db->get('stock')->row();



				if ($stock) {

					$stock_id = $stock->id;

					$old_stock = $initial_stock_data[$item['id_detail']]; // Gunakan stok awal yang disimpan sebelumnya



					// Update Stock

					$this->db->set('stock', 'stock - ' . (int) $item['qty'], false)

						->where('id_product', $item['id_products'])

						->where('id_product_detail', $item['id_detail'])

						->where('warehouse_id', $warehouse_id);

					$update_stock_result = $this->db->update('stock');



					if ($update_stock_result) {

						// Ambil stok setelah perubahan

						$this->db->select('stock');

						$this->db->where('id', $stock_id);

						$new_stock = $this->db->get('stock')->row()->stock;



						// Insert stock movement

						$movement_data = [

							'stock_id' => $stock_id,

							'type' => '-',

							'stock_change' => $item['qty'],

							'remark' => 'Sales Order No: ' . $orderId,

							'total' => $new_stock,

							'name' => 'System',

							'datetime' => date('Y-m-d H:i:s')

						];

						$insert_movement_result = $this->db->insert('stock_movement', $movement_data);



						// Panggil log stok dengan stok sebelum dan sesudah perubahan

						$this->log_m->log_stock_update($orderId, $item['id_detail'], $item['product'], $old_stock, $new_stock, base_url('admin/products/stock-product?tab=all'), null, 'stock', 'orders');



						if (!$insert_movement_result) {

							log_message('error', 'Stock Movement Insert Failed: ' . print_r($this->db->error(), true));

						}

					} else {

						log_message('error', 'Stock Update Failed: ' . print_r($this->db->error(), true));

					}

				} else {

					log_message('error', 'Stock ID Not Found for Product: ' . $item['product']);

				}

			} else {

				$db_error = $this->db->error();

				log_message('error', 'Order Detail Insert Failed: ' . print_r($db_error, true));

			}

		}



		// Update is_first pelanggan

		$this->db->set('is_first', 'is_first + 1', false)

			->where('id_customers', (!empty($postData['is_marketplace']) && $postData['is_marketplace'] == 1) ? 2615 : $postData['customer'])

			->update('customers');



		// Selesaikan transaksi

		$this->db->trans_complete();



		if ($this->db->trans_status() === false) {

			$this->db->trans_rollback();



			$this->session->set_flashdata('message', 'Failed to add order');

			$this->session->set_flashdata('message_type', 'error');



			// Redirect to add-order page

			redirect('admin/orders/add-order');

		} else {

			$name = $this->session->userdata('name');

			if (!empty($postData['tokopedia_invoice'])) {

				$description = "Pesanan Baru dari Tokopedia telah ditambahkan dengan No. Invoice {$tokopediaInvoice} senilai {$grandTotal}. Pesanan ini dibuat oleh {$name}.";

			} else {

				$description = "Pesanan Baru telah ditambahkan dengan Order ID {$orderId} senilai {$grandTotal}. Pesanan ini dibuat oleh {$name}.";

			};



			$reference_url = base_url('admin/orders/manage-order?tab=pending');

			$log_id = $this->log_m->log_order_create($orderId, $description, $reference_url);

			$this->log_m->send_order_notifications('CREATE_ORDER', $log_id, $description);

			$this->session->set_flashdata('message', 'Berhasil menambah pesanan baru dengan ID: ' . $orderId);

			$this->session->set_flashdata('message_type', 'success');



			// Redirect to manage-order page

			redirect('admin/orders/manage-order');

		}

	}



	// Fetch Orders Data

	public function get_orders()

	{

		// Get filter parameters

		$tab = $this->input->get('tab', true);

		$sort = $this->input->get('sort', true);

		$marketplace = $this->input->get('marketplace', true);

		$department = $this->input->get('department', true);

		$dateFilter = $this->input->get('date_filter', true);

		$startDate = $this->input->get('start_date', true);

		$endDate = $this->input->get('end_date', true);



		$isBCATransfer = filter_var($this->input->get('isBCATransfer', true), FILTER_VALIDATE_BOOLEAN);

		$isMandiriTransfer = filter_var($this->input->get('isMandiriTransfer', true), FILTER_VALIDATE_BOOLEAN);

		$isPaypal = filter_var($this->input->get('isPaypal', true), FILTER_VALIDATE_BOOLEAN);

		$isDoku = filter_var($this->input->get('isDoku', true), FILTER_VALIDATE_BOOLEAN);



		$usingInsurance = filter_var($this->input->get('usingInsurance', true), FILTER_VALIDATE_BOOLEAN);

		$notUsingInsurance = filter_var($this->input->get('notUsingInsurance', true), FILTER_VALIDATE_BOOLEAN);



		$useShippingFee = filter_var($this->input->get('usingShippingFee', true), FILTER_VALIDATE_BOOLEAN);

		$notUseShippingFee = filter_var($this->input->get('notUsingShippingFee', true), FILTER_VALIDATE_BOOLEAN);



		$isRegularShipping = filter_var($this->input->get('isRegularShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isTwoHourShipping = filter_var($this->input->get('isTwoHourShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isOneDayShipping = filter_var($this->input->get('isOneDayShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isNextDayShipping = filter_var($this->input->get('isNextDayShipping', true), FILTER_VALIDATE_BOOLEAN);





		$page = (int) ($this->input->get('page', true) ?? 1);

		$limit = (int) ($this->input->get('limit', true) ?? 10);

		$offset = ($page - 1) * $limit;



		$searchTerm = $this->input->get('search', true);





		// Build main query

		$this->db->select('

			o.id_orders, 

			o.customer_id, 

			o.order_date, 

			o.payment_status, 

			o.payment_confirm, 

			o.grand_total_amount, 

			o.payment_type, 

			o.recipient_name, 

			o.address, 

			o.district, 

			o.subdistrict, 

			o.province, 

			o.phone, 

			o.email, 

			o.redeemed_voucher_code, 

			o.redeemed_voucher_type, 

			o.redeemed_voucher_value, 

			o.redeemed_voucher_amount, 

			o.shipping_fee, 

			o.customer_note,

			o.admin_note, 

			o.created_by, 

			o.admin_note, 

			o.first, 

			o.gift_receiver_name, 

			o.gift_receiver_phone, 

			o.insurance_status, 

			o.insurance_cost,

			o.source, 

			o.medium, 

			o.campaign, 

			o.tokopedia_invoice, 

			o.no_resi,

			o.referral,

			o.distribution_department,

			o.distribution_purpose

		');

		$this->db->from('orders o');

		$this->db->join('customers c', 'o.customer_id = c.id_customers', 'left');

		$this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'left');

		$this->db->where("(c.reseller_id IS NULL OR c.reseller_id = '')", NULL, FALSE);



		// Apply filter based on tab

		if ($tab) {

			switch ($tab) {

				case 'pending':

					$this->db->where_in('o.payment_status', [0, 1, 3]);

					break;

				case 'cancelled':

					$this->db->where('o.payment_status', 2);

					break;

				case 'processing':

					$this->db->where('o.payment_status', 4);

					$this->db->group_start();

					$this->db->where('o.no_resi', NULL);

					$this->db->or_where('o.no_resi', '');

					$this->db->group_end();

					break;

				case 'shipping':  // Tab baru untuk pesanan sedang dikirim

					$this->db->where('o.payment_status', 4);

					$this->db->where('o.no_resi !=', NULL);

					$this->db->where('o.no_resi !=', '');

					break;

				case 'done':

					$this->db->where_in('o.payment_status', [5, 8]);

					break;

			}

		}



		// Array untuk menyimpan kondisi pembayaran yang valid

		$paymentTypes = [];



		if ($isBCATransfer) {

			$paymentTypes[] = 'bank transfer BCA';

		}

		if ($isMandiriTransfer) {

			$paymentTypes[] = 'bank transfer MANDIRI';

		}

		if ($isPaypal) {

			$paymentTypes[] = 'Paypal';

		}

		if ($isDoku) {

			$paymentTypes[] = 'DOKU';

		}



		// Tambahkan filter shipping method di sini

		$shippingMethods = [];



		if ($isRegularShipping) {

			$shippingMethods[] = 3; // Regular shipping

		}

		if ($isTwoHourShipping) {

			$shippingMethods[] = 2; // Two hour shipping

		}

		if ($isOneDayShipping) {

			$shippingMethods[] = 1; // One day shipping

		}

		if ($isNextDayShipping) {

			$shippingMethods[] = 4; // Next day shipping

		}



		// Jika ada filter shipping method, tambahkan where clause

		if (!empty($shippingMethods)) {

			$this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'inner');

			$this->db->where_in('od.chosen_shipping_id', $shippingMethods);

			$this->db->group_by('o.id_orders'); // Penting untuk menghindari duplikasi orders

		}



		// Jika ada tipe pembayaran yang valid, terapkan filter

		if (!empty($paymentTypes)) {

			$this->db->where_in('o.payment_type', $paymentTypes);

		}



		// Filter berdasarkan status shipping fee

		if ($useShippingFee && $notUseShippingFee) {

			$this->db->group_start();

			$this->db->or_where('o.shipping_fee >', 0);

			$this->db->or_where('o.shipping_fee', 0);

			$this->db->group_end();

		} elseif ($useShippingFee) {

			$this->db->where('o.shipping_fee >', 0);

		} elseif ($notUseShippingFee) {

			$this->db->where('o.shipping_fee', 0);

		}



		// Filter berdasarkan status asuransi

		if ($usingInsurance && $notUsingInsurance) {

			$this->db->group_start();

			$this->db->or_where('o.insurance_status', 'Yes');

			$this->db->or_where('o.insurance_status', 'No');

			$this->db->group_end();

		} elseif ($usingInsurance) {

			$this->db->where('o.insurance_status', 'Yes');

		} elseif ($notUsingInsurance) {

			$this->db->where('o.insurance_status', 'No');

		}



		if ($marketplace === 'tokopedia') {

			$this->db->where('o.tokopedia_invoice !=', '');

		}



		if ($marketplace === 'website') {

			$this->db->group_start(); // mulai grup kondisi untuk invoice kosong/null

			$this->db->where('o.tokopedia_invoice', '');

			$this->db->or_where('o.tokopedia_invoice IS NULL');

			$this->db->group_end();



			// exclude reseller

			$this->db->group_start(); // mulai grup kondisi untuk non-reseller

			$this->db->where('c.reseller_id', NULL);

			$this->db->or_where('c.reseller_id', '');

			$this->db->group_end();

		}



		if ($department === 'marketing') {

			$this->db->where('o.distribution_department', 'marketing');

		}



		if ($dateFilter) {

			switch ($dateFilter) {

				case 'today':

					$this->db->where('DATE(o.order_date) = CURDATE()');

					break;

				case 'yesterday':

					$this->db->where('DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');

					break;

				case 'last7days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');

					break;

				case 'last30days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');

					break;

				case 'thisMonth':

					$this->db->where('MONTH(o.order_date) = MONTH(CURDATE()) AND YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'thisYear':

					$this->db->where('YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'custom':

					if ($startDate && $endDate) {



						$startDate = date('Y-m-d', strtotime($startDate));

						$endDate = date('Y-m-d', strtotime($endDate));

						if ($startDate && $endDate) {

							$this->db->where('DATE(o.order_date) >=', $startDate);

							$this->db->where('DATE(o.order_date) <=', $endDate);

						}

					}

					break;

			}

		}



		if (!empty($searchTerm)) {

			$this->db->group_start();

			$this->db->like('o.id_orders', $searchTerm);

			$this->db->or_like('o.tokopedia_invoice', $searchTerm);

			$this->db->or_like('o.recipient_name', $searchTerm);

			$this->db->or_like('o.email', $searchTerm);

			$this->db->or_like('o.redeemed_voucher_code', $searchTerm);

			$this->db->or_like('o.payment_type', $searchTerm);

			$this->db->or_like('o.address', $searchTerm);

			$this->db->or_like('o.province', $searchTerm);

			$this->db->or_like('o.district', $searchTerm);

			$this->db->or_like('o.subdistrict', $searchTerm);

			$this->db->or_like('od.item_name', $searchTerm);



			$this->db->group_end();

		}



		// Apply sorting

		if ($sort) {

			switch ($sort) {

				case 'paling_baru':

					$this->db->order_by('o.order_date', 'DESC');

					break;

				case 'paling_lama':

					$this->db->order_by('o.order_date', 'ASC');

					break;

				default:

					// Default sort by newest

					$this->db->order_by('o.order_date', 'DESC');

			}

		} else {

			// Default sort by newest

			$this->db->order_by('o.order_date', 'DESC');

		}



		$this->db->limit($limit, $offset);

		$this->db->group_by('o.id_orders');



		// Execute query

		$query = $this->db->get();

		$all_orders = $query->result();



		// Post-processing: Get order details for each order

		foreach ($all_orders as $order) {



			$order->is_referral = false;

			$order->referred_by = '';



			// Check if referral exists in orders table

			if (!empty($order->referral)) {

				// Query to check if referral matches with any affiliator's referral code (case insensitive)

				$this->db->select('nama');

				$this->db->from('affiliator_register');

				$this->db->where('LOWER(referral) = LOWER("' . $order->referral . '")');

				$referral_query = $this->db->get();



				if ($referral_query->num_rows() > 0) {

					$affiliator = $referral_query->row();

					$order->is_referral = true;

					$order->referred_by = $affiliator->nama;

				}

			}



			// If not found by referral, check redeemed_voucher_code

			if (!$order->is_referral && !empty($order->redeemed_voucher_code)) {

				$this->db->select('nama');

				$this->db->from('affiliator_register');

				$this->db->where('LOWER(referral) = LOWER("' . $order->redeemed_voucher_code . '")');

				$voucher_referral_query = $this->db->get();



				if ($voucher_referral_query->num_rows() > 0) {

					$affiliator = $voucher_referral_query->row();

					$order->is_referral = true;

					$order->referred_by = $affiliator->nama;

				}

			}



			// Get order details

			$this->db->select('

				od.id_orders_detail,

				od.item_id, 

				od.product_id, 

				od.item_name, 

				od.item_price, 

				od.quantity, 

				od.subtotal, 

				od.sku, 

				od.attributes, 

				od.chosen_shipping_id,

				sm.name as shipping_method_name,

				pi.image as product_image

			');

			$this->db->from('orders_detail od');

			$this->db->join('shipment_method sm', 'od.chosen_shipping_id = sm.id', 'left');

			$this->db->join('product_images pi', 'od.item_id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1', 'left');

			$this->db->where('od.orders_id', $order->id_orders);

			$details_query = $this->db->get();

			$order->items = $details_query->result();



			// Calculate total items

			$order->total_items = 0;

			foreach ($order->items as $item) {

				$order->total_items += $item->quantity;

			}



			// Format some data if needed

			$order->order_date_formatted = date('d M Y H:i', strtotime($order->order_date));



			// Set payment status text

			switch ($order->payment_status) {

				case 0:

					$order->payment_status_text = 'Pending';

					$order->payment_status_class = 'bg-yellow-100 text-yellow-700 px-2 py-1 rounded';

					break;

				case 1:

					if ($order->payment_confirm == 1) {

						$order->payment_status_text = 'Menunggu Verifikasi Pembayaran';

						$order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';

					} else {

						$order->payment_status_text = 'Menunggu Pembayaran';

						$order->payment_status_class = 'bg-orange-100 text-orange-700 px-2 py-1 rounded';

					}

					break;

				case 2:

					$order->payment_status_text = 'Dibatalin';

					$order->payment_status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded';

					break;

				case 3:

					$order->payment_status_text = 'Sudah Dibayar';

					$order->payment_status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded';

					break;

				case 4:

					if (!empty($order->no_resi)) {

						$order->payment_status_text = 'Sedang Dikirim';

						$order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';

					} else {

						$order->payment_status_text = 'Diproses';

						$order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';

					}

					break;

				case 5:

					$order->payment_status_text = 'Selesai';

					$order->payment_status_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded';

					break;

				case 8:

					$order->payment_status_text = 'Selesai (Retailer)';

					$order->payment_status_class = 'bg-purple-100 text-purple-700 px-2 py-1 rounded';

					break;

				default:

					$order->payment_status_text = 'Unknown';

					$order->payment_status_class = 'bg-gray-300 text-gray-800 px-2 py-1 rounded';

			}

		}



		// Return JSON response

		echo json_encode($all_orders);

	}



	public function get_marketing_orders()

	{

		$tab = $this->input->get('tab', true);

		$sort = $this->input->get('sort', true);

		$distributionType = $this->input->get('distribution_type', true);

		$dateFilter = $this->input->get('date_filter', true);

		$startDate = $this->input->get('start_date', true);

		$endDate = $this->input->get('end_date', true);



		$page = (int) ($this->input->get('page', true) ?? 1);

		$limit = (int) ($this->input->get('limit', true) ?? 10);

		$offset = ($page - 1) * $limit;



		$searchTerm = $this->input->get('search', true);



		// Build main query (sebelumnya sudah benar)

		$this->db->select('

			o.id_orders, 

			o.customer_id,

			o.order_date, 

			o.distribution_type,

			o.distribution_purpose,

			o.created_by,

			o.updated_by,

			o.recipient_name,

			o.address,

			o.province,

			o.district,

			o.subdistrict,

			o.phone,

			o.email,

			o.payment_status,

			o.no_resi,

			c.name as customer_name,

			c.email as customer_email,

			c.shipping_phone as customer_phone

		');

		$this->db->from('orders o');

		$this->db->join('customers c', 'o.customer_id = c.id_customers', 'left');

		$this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'left');



		// Filter for marketing distribution

		$this->db->group_start();

		$this->db->where('LOWER(o.distribution_department)', 'marketing');

		$this->db->or_where('LOWER(o.distribution_department)', 'Marketing');

		$this->db->group_end();



		// Tab filter

		if ($tab) {

			switch ($tab) {

				case 'processing':

					$this->db->where('o.payment_status', 4);

					$this->db->group_start();

					$this->db->where('o.no_resi', NULL);

					$this->db->or_where('o.no_resi', '');

					$this->db->group_end();

					break;

				case 'shipping':

					$this->db->where('o.payment_status', 4);

					$this->db->where('o.no_resi !=', NULL);

					$this->db->where('o.no_resi !=', '');

					break;

				case 'delivered':

					$this->db->where('o.payment_status', 5);

					break;

				case 'cancelled':

					$this->db->where('o.payment_status', 2);

					break;

			}

		}



		// Date filter (sama seperti get_orders)

		if ($dateFilter) {

			switch ($dateFilter) {

				case 'today':

					$this->db->where('DATE(o.order_date) = CURDATE()');

					break;

				case 'yesterday':

					$this->db->where('DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');

					break;

				case 'last7days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');

					break;

				case 'last30days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');

					break;

				case 'thisMonth':

					$this->db->where('MONTH(o.order_date) = MONTH(CURDATE()) AND YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'thisYear':

					$this->db->where('YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'custom':

					if ($startDate && $endDate) {

						$startDate = date('Y-m-d', strtotime($startDate));

						$endDate = date('Y-m-d', strtotime($endDate));

						if ($startDate && $endDate) {

							$this->db->where('DATE(o.order_date) >=', $startDate);

							$this->db->where('DATE(o.order_date) <=', $endDate);

						}

					}

					break;

			}

		}



		// Search functionality

		if (!empty($searchTerm)) {

			$this->db->group_start();

			$this->db->like('o.distribution_purpose', $searchTerm);

			$this->db->or_like('o.created_by', $searchTerm);

			$this->db->or_like('o.updated_by', $searchTerm);

			$this->db->or_like('od.item_name', $searchTerm);

			$this->db->group_end();

		}



		// Apply sorting

		if ($sort) {

			switch ($sort) {

				case 'paling_baru':

					$this->db->order_by('o.order_date', 'DESC');

					break;

				case 'paling_lama':

					$this->db->order_by('o.order_date', 'ASC');

					break;

				default:

					$this->db->order_by('o.order_date', 'DESC');

			}

		} else {

			$this->db->order_by('o.order_date', 'DESC');

		}



		$this->db->limit($limit, $offset);



		// Execute query

		$query = $this->db->get();

		$marketing_orders = $query->result();



		// Post-processing for each order

		foreach ($marketing_orders as $order) {

			// Get order details



			$this->db->select('

				od.id_orders_detail,

				od.item_id, 

				od.product_id, 

				od.item_name, 

				od.item_price, 

				od.quantity, 

				od.subtotal, 

				od.sku, 

				od.attributes, 

				od.chosen_shipping_id,

				sm.name as shipping_method_name,

				pi.image as product_image

			');

			$this->db->from('orders_detail od');

			$this->db->join('shipment_method sm', 'od.chosen_shipping_id = sm.id', 'left');

			$this->db->join('product_images pi', 'od.item_id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1', 'left');

			$this->db->where('od.orders_id', $order->id_orders);



			$details_query = $this->db->get();

			$order->items = $details_query->result();



			// Calculate total items

			$order->total_items = 0;

			foreach ($order->items as $item) {

				$order->total_items += $item->quantity;

			}



			// Format order date

			$order->order_date_formatted = date('d M Y H:i', strtotime($order->order_date));

		}



		// Return JSON response

		echo json_encode($marketing_orders);

	}



	// Fetch Retailer Orders Data

	public function get_retailer_orders()

	{

		// Get filter parameters

		$tab = $this->input->get('tab', true);

		$sort = $this->input->get('sort', true);

		$marketplace = $this->input->get('marketplace', true);

		$dateFilter = $this->input->get('date_filter', true);

		$startDate = $this->input->get('start_date', true);

		$endDate = $this->input->get('end_date', true);



		$isBCATransfer = filter_var($this->input->get('isBCATransfer', true), FILTER_VALIDATE_BOOLEAN);

		$isMandiriTransfer = filter_var($this->input->get('isMandiriTransfer', true), FILTER_VALIDATE_BOOLEAN);

		$isPaypal = filter_var($this->input->get('isPaypal', true), FILTER_VALIDATE_BOOLEAN);

		$isDoku = filter_var($this->input->get('isDoku', true), FILTER_VALIDATE_BOOLEAN);



		$usingInsurance = filter_var($this->input->get('usingInsurance', true), FILTER_VALIDATE_BOOLEAN);

		$notUsingInsurance = filter_var($this->input->get('notUsingInsurance', true), FILTER_VALIDATE_BOOLEAN);



		$isRegularShipping = filter_var($this->input->get('isRegularShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isTwoHourShipping = filter_var($this->input->get('isTwoHourShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isOneDayShipping = filter_var($this->input->get('isOneDayShipping', true), FILTER_VALIDATE_BOOLEAN);

		$isNextDayShipping = filter_var($this->input->get('isNextDayShipping', true), FILTER_VALIDATE_BOOLEAN);



		$page = (int) ($this->input->get('page', true) ?? 1);

		$limit = (int) ($this->input->get('limit', true) ?? 10);

		$offset = ($page - 1) * $limit;



		$searchTerm = $this->input->get('search', true);

		$retailerIds = $this->input->get('retailerId', true);



		// Build main query

		$this->db->select('

			o.id_orders, 

			o.customer_id, 

			o.order_date, 

			o.payment_status, 

			o.payment_confirm, 

			o.grand_total_amount, 

			o.payment_type, 

			o.recipient_name, 

			o.address, 

			o.district, 

			o.subdistrict, 

			o.province, 

			o.phone, 

			o.email, 

			o.redeemed_voucher_code, 

			o.redeemed_voucher_type, 

			o.redeemed_voucher_value, 

			o.redeemed_voucher_amount, 

			o.shipping_fee, 

			o.customer_note,

			o.admin_note, 

			o.created_by, 

			o.admin_note, 

			o.first, 

			o.gift_receiver_name, 

			o.gift_receiver_phone, 

			o.insurance_status, 

			o.insurance_cost,

			o.source, 

			o.medium, 

			o.campaign, 

			o.tokopedia_invoice, 

			o.no_resi,

			c.reseller_id

		');

		$this->db->from('orders o');

		$this->db->join('customers c', 'o.customer_id = c.id_customers', 'inner');

		$this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'left');



		// Hanya ambil order dengan customer yang memiliki reseller_id tidak null

		$this->db->where('c.reseller_id IS NOT NULL');

		$this->db->where("c.reseller_id != ''");



		// Filter berdasarkan reseller_id spesifik jika diberikan

		if ($retailerIds) {

			$retailerIdArray = explode(',', $retailerIds);

			if (!empty($retailerIdArray)) {

				$this->db->where_in('c.id_customers', $retailerIdArray);

			}

		}



		// Apply filter based on tab

		if ($tab) {

			switch ($tab) {

				case 'pending':

					$this->db->where_in('o.payment_status', [0, 1, 3]);

					break;

				case 'cancelled':

					$this->db->where('o.payment_status', 2);

					break;

				case 'processing':

					$this->db->where('o.payment_status', 4);

					$this->db->group_start();

					$this->db->where('o.no_resi', NULL);

					$this->db->or_where('o.no_resi', '');

					$this->db->group_end();

					break;

				case 'shipping':  // Tab baru untuk pesanan sedang dikirim

					$this->db->where('o.payment_status', 4);

					$this->db->where('o.no_resi !=', NULL);

					$this->db->where('o.no_resi !=', '');

					break;

				case 'done':

					$this->db->where_in('o.payment_status', [5, 8]);

					break;

			}

		}



		// Array untuk menyimpan kondisi pembayaran yang valid

		$paymentTypes = [];



		if ($isBCATransfer) {

			$paymentTypes[] = 'bank transfer BCA';

		}

		if ($isMandiriTransfer) {

			$paymentTypes[] = 'bank transfer MANDIRI';

		}

		if ($isPaypal) {

			$paymentTypes[] = 'Paypal';

		}

		if ($isDoku) {

			$paymentTypes[] = 'DOKU';

		}



		// Tambahkan filter shipping method di sini

		$shippingMethods = [];



		if ($isRegularShipping) {

			$shippingMethods[] = 3; // Regular shipping

		}

		if ($isTwoHourShipping) {

			$shippingMethods[] = 2; // Two hour shipping

		}

		if ($isOneDayShipping) {

			$shippingMethods[] = 1; // One day shipping

		}

		if ($isNextDayShipping) {

			$shippingMethods[] = 4; // Next day shipping

		}



		// Jika ada filter shipping method, tambahkan where clause

		if (!empty($shippingMethods)) {

			$this->db->join('orders_detail od', 'o.id_orders = od.orders_id', 'inner');

			$this->db->where_in('od.chosen_shipping_id', $shippingMethods);

			$this->db->group_by('o.id_orders'); // Penting untuk menghindari duplikasi orders

		}



		// Jika ada tipe pembayaran yang valid, terapkan filter

		if (!empty($paymentTypes)) {

			$this->db->where_in('o.payment_type', $paymentTypes);

		}



		// Filter berdasarkan status asuransi

		if ($usingInsurance && $notUsingInsurance) {

			$this->db->group_start();

			$this->db->or_where('o.insurance_status', 'Yes');

			$this->db->or_where('o.insurance_status', 'No');

			$this->db->group_end();

		} elseif ($usingInsurance) {

			$this->db->where('o.insurance_status', 'Yes');

		} elseif ($notUsingInsurance) {

			$this->db->where('o.insurance_status', 'No');

		}



		if ($marketplace === 'tokopedia') {

			$this->db->where('o.tokopedia_invoice !=', '');

		}





		if ($dateFilter) {

			switch ($dateFilter) {

				case 'today':

					$this->db->where('DATE(o.order_date) = CURDATE()');

					break;

				case 'yesterday':

					$this->db->where('DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');

					break;

				case 'last7days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');

					break;

				case 'last30days':

					$this->db->where('o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');

					break;

				case 'thisMonth':

					$this->db->where('MONTH(o.order_date) = MONTH(CURDATE()) AND YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'thisYear':

					$this->db->where('YEAR(o.order_date) = YEAR(CURDATE())');

					break;

				case 'custom':

					if ($startDate && $endDate) {

						$startDate = date('Y-m-d', strtotime($startDate));

						$endDate = date('Y-m-d', strtotime($endDate));

						if ($startDate && $endDate) {

							$this->db->where('DATE(o.order_date) >=', $startDate);

							$this->db->where('DATE(o.order_date) <=', $endDate);

						}

					}

					break;

			}

		}



		if (!empty($searchTerm)) {

			$this->db->group_start();

			$this->db->like('o.id_orders', $searchTerm);

			$this->db->or_like('o.tokopedia_invoice', $searchTerm);

			$this->db->or_like('o.recipient_name', $searchTerm);

			$this->db->or_like('o.email', $searchTerm);

			$this->db->or_like('o.redeemed_voucher_code', $searchTerm);

			$this->db->or_like('o.payment_type', $searchTerm);

			$this->db->or_like('o.address', $searchTerm);

			$this->db->or_like('o.province', $searchTerm);

			$this->db->or_like('o.district', $searchTerm);

			$this->db->or_like('o.subdistrict', $searchTerm);

			$this->db->or_like('c.reseller_id', $searchTerm);

			$this->db->or_like('od.item_name', $searchTerm);

			$this->db->group_end();

		}



		// Apply sorting

		if ($sort) {

			switch ($sort) {

				case 'paling_baru':

					$this->db->order_by('o.order_date', 'DESC');

					break;

				case 'paling_lama':

					$this->db->order_by('o.order_date', 'ASC');

					break;

				default:

					// Default sort by newest

					$this->db->order_by('o.order_date', 'DESC');

			}

		} else {

			// Default sort by newest

			$this->db->order_by('o.order_date', 'DESC');

		}



		$this->db->limit($limit, $offset);

		$this->db->group_by('o.id_orders');



		// Execute query

		$query = $this->db->get();

		$all_orders = $query->result();



		// Post-processing: Get order details for each order

		foreach ($all_orders as $order) {

			// Get order details

			$this->db->select('

            od.id_orders_detail,

            od.item_id, 

            od.product_id, 

            od.item_name, 

            od.item_price, 

            od.quantity, 

            od.subtotal, 

            od.sku, 

            od.attributes, 

            od.chosen_shipping_id,

            sm.name as shipping_method_name,

            pi.image as product_image

        ');

			$this->db->from('orders_detail od');

			$this->db->join('shipment_method sm', 'od.chosen_shipping_id = sm.id', 'left');

			$this->db->join('product_images pi', 'od.item_id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1', 'left');

			$this->db->where('od.orders_id', $order->id_orders);

			$details_query = $this->db->get();

			$order->items = $details_query->result();



			// Calculate total items

			$order->total_items = 0;

			foreach ($order->items as $item) {

				$order->total_items += $item->quantity;

			}



			// Format some data if needed

			$order->order_date_formatted = date('d M Y H:i', strtotime($order->order_date));



			// Set payment status text

			switch ($order->payment_status) {

				case 0:

					$order->payment_status_text = 'Pending';

					$order->payment_status_class = 'bg-yellow-100 text-yellow-700 px-2 py-1 rounded';

					break;

				case 1:

					$order->payment_status_text = 'Menunggu Pembayaran';

					$order->payment_status_class = 'bg-orange-100 text-orange-700 px-2 py-1 rounded';

					break;

				case 2:

					$order->payment_status_text = 'Dibatalin';

					$order->payment_status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded';

					break;

				case 3:

					$order->payment_status_text = 'Sudah Dibayar';

					$order->payment_status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded';

					break;

				case 4:

					if (!empty($order->no_resi)) {

						$order->payment_status_text = 'Sedang Dikirim';

						$order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';

					} else {

						$order->payment_status_text = 'Diproses';

						$order->payment_status_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';

					}

					break;

				case 5:

					$order->payment_status_text = 'Selesai';

					$order->payment_status_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded';

					break;

				case 8:

					$order->payment_status_text = 'Selesai (Retailer)';

					$order->payment_status_class = 'bg-purple-100 text-purple-700 px-2 py-1 rounded';

					break;

				default:

					$order->payment_status_text = 'Unknown';

					$order->payment_status_class = 'bg-gray-300 text-gray-800 px-2 py-1 rounded';

			}



			// Dapatkan informasi reseller

			if ($order->reseller_id) {

				$this->db->select('reseller_name, minimum_order');

				$this->db->from('resellers');

				$this->db->where('id_resellers', $order->reseller_id);

				$reseller_query = $this->db->get();

				$order->reseller_info = $reseller_query->row();

			}

		}



		// Return JSON response

		echo json_encode($all_orders);

	}



	public function get_products()

	{

		$products = $this->product_m->all_products();

		echo json_encode($products);

	}

	public function get_tokopedia_products()

	{

		$products = $this->product_m->all_tokopedia_products();

		echo json_encode($products);

	}



	public function get_products_by_retailer()

	{

		$retailer_id = $this->input->get('retailer_id');



		if (!$retailer_id) {

			echo json_encode(['error' => 'Retailer ID diperlukan']);

			return;

		}



		$products = $this->product_m->get_products_by_retailer($retailer_id);

		echo json_encode($products);

	}

	public function updateNotes()

	{

		if (!$this->input->is_ajax_request()) {

			show_error('No direct script access allowed', 403);

			return;

		}



		$order_id = $this->input->post('order_id', true);

		$notes = $this->input->post('notes', true);



		$this->db->trans_begin();



		try {

			// Ambil payment_type dan no_resi sebelum update

			$this->db->select('admin_note');

			$this->db->where('id_orders', $order_id);

			$query = $this->db->get('orders');



			if ($query->num_rows() > 0) {

				$order_data = $query->row();

				$old_notes = $order_data->admin_note;

			} else {

				throw new Exception('Gagal mengambil data pesanan sebelum update');

			}



			// Update table orders

			$orders_data = [

				'admin_note' => $notes,

				'updated_at' => date('Y-m-d H:i:s'),

				'updated_by' => $this->session->userdata('name')

			];



			$this->db->where('id_orders', $order_id);

			$update_orders = $this->db->update('orders', $orders_data);



			if (!$update_orders) {

				throw new Exception('Gagal mengupdate notes di tabel orders');

			}



			$description_notes = "Catatan pada Pesanan {$order_id} telah diubah oleh {$this->session->userdata('name')}.";

			$this->log_m->log_order_update(

				$order_id,

				$description_notes,

				'admin_note',

				$old_notes,

				$notes

			);



			// Commit transaksi jika semua berhasil

			$this->db->trans_commit();



			$response = [

				'success' => true,

				'message' => 'Catatan berhasil diperbarui',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		} catch (Exception $e) {

			// Rollback transaksi jika ada error

			$this->db->trans_rollback();



			$response = [

				'success' => false,

				'message' => $e->getMessage(),

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		}



		// Kirim response dalam format JSON

		echo json_encode($response);

	}



	public function updateInvoiceNotes()

	{

		if (!$this->input->is_ajax_request()) {

			show_error('No direct script access allowed', 403);

			return;

		}



		$order_id = $this->input->post('order_id', true);

		$notes = $this->input->post('notes', true);



		$this->db->trans_begin();



		try {

			// Ambil payment_type dan no_resi sebelum update

			$this->db->select('customer_invoice_note');

			$this->db->where('id_orders', $order_id);

			$query = $this->db->get('orders');



			if ($query->num_rows() > 0) {

				$order_data = $query->row();

				$old_notes = $order_data->customer_invoice_note;

			} else {

				throw new Exception('Gagal mengambil data pesanan sebelum update');

			}



			// Update table orders

			$orders_data = [

				'customer_invoice_note' => $notes,

				'updated_at' => date('Y-m-d H:i:s'),

				'updated_by' => $this->session->userdata('name')

			];



			$this->db->where('id_orders', $order_id);

			$update_orders = $this->db->update('orders', $orders_data);



			if (!$update_orders) {

				throw new Exception('Gagal mengupdate notes di tabel orders');

			}



			$description_notes = "Catatan Invoice pada Pesanan {$order_id} telah diubah oleh {$this->session->userdata('name')}.";

			$this->log_m->log_order_update(

				$order_id,

				$description_notes,

				'admin_note',

				$old_notes,

				$notes

			);



			// Commit transaksi jika semua berhasil

			$this->db->trans_commit();



			$response = [

				'success' => true,

				'message' => 'Catatan Invoice berhasil diperbarui',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		} catch (Exception $e) {

			// Rollback transaksi jika ada error

			$this->db->trans_rollback();



			$response = [

				'success' => false,

				'message' => $e->getMessage(),

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		}



		// Kirim response dalam format JSON

		echo json_encode($response);

	}



	public function updateResi()

	{

		if (!$this->input->is_ajax_request()) {

			show_error('No direct script access allowed', 403);

			return;

		}



		// Ambil data dari POST

		$order_id = $this->input->post('order_id', true);

		$no_resi = $this->input->post('no_resi', true);



		// Validasi input

		if (empty($order_id) || empty($no_resi) || $no_resi === '-') {

			$response = [

				'success' => false,

				'message' => 'Data tidak lengkap',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

			echo json_encode($response);

			return;

		}



		// Mulai transaksi database

		$this->db->trans_begin();



		try {

			// Ambil payment_type dan no_resi sebelum update

			$this->db->select('payment_status, no_resi, shipping_fee, customer_id');

			$this->db->where('id_orders', $order_id);

			$query = $this->db->get('orders');

			$order_data = $query->row();



			if ($query->num_rows() > 0) {

				$old_status = $order_data->payment_status; // Simpan payment_type sebagai old_status

				$old_resi = $order_data->no_resi; // Simpan no_resi sebelum update

			} else {

				throw new Exception('Gagal mengambil data pesanan sebelum update');

			}





			// Update table orders

			$orders_data = [

				'no_resi' => $no_resi,

				'payment_status' => 4, // Set status menjadi 'Diproses'

				'updated_at' => date('Y-m-d H:i:s'),

				'updated_by' => $this->session->userdata('name')

			];



			$this->db->where('id_orders', $order_id);

			$update_orders = $this->db->update('orders', $orders_data);



			if (!$update_orders) {

				throw new Exception('Gagal mengupdate nomor resi di tabel orders');

			}



			// Update semua orders_detail yang terkait

			$orders_detail_data = [

				'no_resi' => $no_resi,

				'status' => 2, // Dikirim ,

				'shipping_date' => date('Y-m-d H:i:s'),

				'updated_at' => date('Y-m-d H:i:s'),

				'updated_by' => $this->session->userdata('name')

			];



			$this->db->where('orders_id', $order_id);

			$update_details = $this->db->update('orders_detail', $orders_detail_data);



			if (!$update_details) {

				throw new Exception('Gagal mengupdate nomor resi di tabel orders_detail');

			}



			// Submit ke shipping table

			$this->db->where('order_id', $order_id);

			$shipping_exists = $this->db->get('shipping')->num_rows();



			if ($shipping_exists > 0) {

				// Update data yang sudah ada

				$shipping_data = [

					'tracking_number' => $no_resi,

					'updated_at' => date('Y-m-d H:i:s')

				];

				$this->db->where('order_id', $order_id);

				$update_shipping = $this->db->update('shipping', $shipping_data);

			} else {

				// Insert data baru

				$shipping_data = [

					'order_id' => $order_id,

					'warehouse_id' => 1,

					'shipping_fee' => $order_data->shipping_fee,

					'tracking_number' => $no_resi,

					'created_at' => date('Y-m-d H:i:s')

				];

				$update_shipping = $this->db->insert('shipping', $shipping_data);

			}



			if (!$update_shipping) {

				throw new Exception('Gagal mengupdate nomor resi di tabel shipping');

			}



			$new_status = 4;

			$description_payment = "Status Pesanan dengan Order ID {$order_id} diubah menjadi 'Sedang Dikirim' oleh {$this->session->userdata('name')}.";

			$this->log_m->log_order_update(

				$order_id,

				$description_payment,

				'payment_status',

				$old_status,

				$new_status

			);

			$description_resi = "No. Resi pada Pesanan dengan Order ID {$order_id} telah diupdate dari {$old_resi} menjadi {$no_resi} oleh {$this->session->userdata('name')}.";

			$this->log_m->log_order_update(

				$order_id,

				$description_resi,

				'no_resi',

				$old_resi,

				$no_resi,

				base_url('admin/orders/manage-order?tab=shipping')

			);



			// $email_result = $this->sendShippingNotificationEmail($order_id, $no_resi, $customer_id);



			// Commit transaksi jika semua berhasil

			$this->db->trans_commit();



			$response = [

				'success' => true,

				'message' => 'Nomor resi berhasil diperbarui.',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		} catch (Exception $e) {

			// Rollback transaksi jika ada error

			$this->db->trans_rollback();



			$response = [

				'success' => false,

				'message' => $e->getMessage(),

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		}



		// Kirim response dalam format JSON

		echo json_encode($response);

	}



	public function updateOrderStatus()

	{

		if (!$this->input->is_ajax_request()) {

			show_error('No direct script access allowed', 403);

			return;

		}



		$order_id = $this->input->post('order_id', true);

		$status = $this->input->post('status', true);



		// Validasi input

		if (empty($order_id) || empty($status) || $status === '-') {

			$response = [

				'success' => false,

				'message' => 'Data tidak lengkap',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

			echo json_encode($response);

			return;

		}



		$this->db->trans_begin();



		try {

			$this->db->select('payment_status, customer_id, total_amount, referral, redeemed_voucher_code');

			$this->db->where('id_orders', $order_id);

			$query = $this->db->get('orders');



			if ($query->num_rows() === 0) {

				throw new Exception('Gagal mengambil data pesanan sebelum update');

			}



			$order_data = $query->row();

			$customer_id = (int) $order_data->customer_id;

			$old_status = $order_data->payment_status;

			$name = $this->session->userdata('name');



			// Persiapan data dasar untuk update

			$orders_data = [

				'payment_status' => $status,

				'updated_at' => date('Y-m-d H:i:s'),

				'updated_by' => $this->session->userdata('name')

			];



			switch ($status) {

				case '1': // NOT PAID

					$orders_data['payment_date'] = date('Y-m-d');

					break;



				case '2': // CANCEL

					$orders_data['cancel_date'] = date('Y-m-d');



					// Handle pengurangan komisi

					$this->order_m->handleCancelCommission($order_id, $order_data);



					// Return stock ke inventory

					$this->order_m->returnStockToInventory($order_id, $customer_id);



					// Return customer point reward

					$this->order_m->returnCustomerPointReward($order_id, $customer_id);

					break;



				case '3': // PAID

					break;



				case '4': // PROCESS

					$description = "Status pesanan dengan No. {$order_id} diubah menjadi 'Diproses'.";

					$reference_url = base_url('admin/orders/manage-order?tab=processing');



					$log_id = $this->log_m->log_order_update($order_id, 'payment_status', $old_status, $status, $description, $reference_url);

					$this->log_m->send_order_notifications('UPDATE_ORDER', $log_id, $description, 'payment_status', $status);

					$this->handleAffiliatorCommission($order_id, $order_data);



					// Update customer point rewards

					$this->updateCustomerPointRewards($order_id, $customer_id);

					break;



				case '5': // DELIVERED

					break;

			}



			// Update tabel orders

			$this->db->where('id_orders', $order_id);

			$update_orders = $this->db->update('orders', $orders_data);



			if (!$update_orders) {

				throw new Exception('Gagal mengupdate status pesanan');

			}



			// Kirim email berdasarkan status

			$this->sendEmailNotification($order_id, $status);



			// Commit transaksi jika semua berhasil

			$this->db->trans_commit();



			$response = [

				'success' => true,

				'message' => 'Status pesanan berhasil diperbarui',

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		} catch (Exception $e) {

			// Rollback transaksi jika ada error

			$this->db->trans_rollback();



			$response = [

				'success' => false,

				'message' => $e->getMessage(),

				'csrf_hash' => $this->security->get_csrf_hash()

			];

		}



		// Kirim response dalam format JSON

		echo json_encode($response);

	}



	/**

	 * Menangani komisi affiliator saat pesanan diproses

	 */

	private function handleAffiliatorCommission($order_id, $order_data)

	{

		// Ambil product_id dari orders_detail

		$this->db->select('product_id')

			->from('orders_detail')

			->where('orders_id', $order_id);

		$order_details = $this->db->get()->result();



		// Ambil kategori affiliator berdasarkan referral

		$this->db->select('kategori')

			->from('affiliator_register')

			->where('referral', !empty($order_data->referral) ? $order_data->referral : $order_data->redeemed_voucher_code);

		$affiliator = $this->db->get()->row();



		// Ambil kategori affiliator berdasarkan redeemed_voucher_code

		$this->db->select('kategori')

			->from('affiliator_register')

			->where('referral', $order_data->redeemed_voucher_code);

		$doctor_affiliator = $this->db->get()->row();



		// Hitung komisi

		$commission_rate = ($affiliator && $affiliator->kategori == 'asmarasana') ? 0.20 : 0.10;



		// Update komisi untuk affiliator asmarasana

		if ($doctor_affiliator && $doctor_affiliator->kategori == 'asmarasana') {

			$commission = $order_data->total_amount * 0.20;

			$this->db->set('komisi', "komisi + ($commission)", FALSE);

			$this->db->where('referral', $order_data->redeemed_voucher_code);

			$this->db->update('affiliator_register');

		}



		// Update komisi untuk affiliator asmaradoor

		if ($affiliator && $affiliator->kategori == 'asmaradoor') {

			$commission = $order_data->total_amount * 0.10;

			$this->db->set('komisi', "komisi + ($commission)", FALSE);

			$this->db->where('referral', !empty($order_data->referral) ? $order_data->referral : $order_data->redeemed_voucher_code);

			$this->db->update('affiliator_register');



			// Update komisi untuk affiliator asmaradoor per link product

			foreach ($order_details as $od) {

				$this->db->set('`order`', '`order` + 1', FALSE); // Increment order count

				$this->db->set('komisi_order', "komisi_order + ({$order_data->total_amount} * {$commission_rate})", FALSE);

				$this->db->where('product_id', $od->product_id);

				$this->db->where('unique_id', $order_data->referral);

				$this->db->update('affiliator_link');

			}

		}

	}



	/**

	 * Update point rewards saat pesanan diproses

	 */

	private function updateCustomerPointRewards($order_id, $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;



		// Get plus point from order

		$this->db->select('plus_reward')->from('orders')->where('id_orders', $order_id);

		$rewards = $this->db->get()->row();

		$plus_point = (int)$rewards->plus_reward;



		// Calculate updated point

		$updated_point = $current_point + $plus_point;



		// Check if plus reward already given

		$this->db->select('plus_reward_given')->from('orders')->where('id_orders', $order_id);

		$plus_reward_given = $this->db->get()->row();



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

			// Update customer points

			$data = ['current_pointreward' => $updated_point];

			$this->db->where('id_customers', $customer_id);

			$this->db->update('customers', $data);



			// Mark plus reward as given

			$data_order = ['plus_reward_given' => 'yes'];

			$this->db->where('id_orders', $order_id);

			$this->db->update('orders', $data_order);

		}

	}

	/**

	 * Kirim email notifikasi berdasarkan status pesanan

	 */

	private function sendEmailNotification($order_id, $status)

	{



		// Get order data

		$order = $this->order_m->get_order($order_id);

		$customer = $this->customer_m->get_customer($order->customer_id);



		// Get website configuration

		$this->db->select('logo, from_email, website_name')->from('configuration')->where('id_configuration', 1);

		$website_data = $this->db->get()->row();



		$email_data = [

			'order' => $order,

			'customer' => $customer,

			'logo' => $website_data->logo,

			'website_name' => $website_data->website_name,

			'emails' => $this->configuration_m->get_emails(),

			'email' => $customer->email

		];



		// Determine email template and subject based on status

		switch ($status) {

			case '1': // NOT PAID

				$payment_type = $order->payment_type;



				// Add required data for payment type-specific email

				$this->prepareNotPaidEmailData($email_data, $order_id, $payment_type);



				// Determine view file based on language and payment type

				$view_file = $this->getNotPaidEmailTemplate($order->order_language, $payment_type);

				break;



			case '2': // CANCEL

				$email_data['minus_point'] = $order->minus_reward;

				$email_data['title'] = 'Order Cancel';



				if ($order->order_language == 'english') {

					$email_data['subject'] = 'Canceling Your Order';

					$view_file = 'email/english/order_cancel';

				} else {

					$email_data['subject'] = 'Kok Batal?';

					$view_file = 'email/indonesian/order_cancel';

				}

				break;



			case '3': // PAID

				$email_data['title'] = 'Payment Confirmation';

				$email_data['order_details'] = $this->order_detail_m->get_orders_detail($order_id);

				$email_data['plus_point'] = $order->plus_reward;



				if ($order->order_language == 'english') {

					$email_data['subject'] = 'Payment Received';

					$view_file = 'email/english/payment_confirmation';

				} else {

					$email_data['subject'] = 'Pembayaran Telah Diterima';

					$view_file = 'email/indonesian/payment_confirmation';

				}

				break;



			case '4': // PROCESS

			case '5': // DELIVERED

				// Email tidak perlu dikirim untuk status ini

				return;

		}



		// Log activity

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

		$status_texts = [

			'1' => 'Belum Bayar',

			'2' => 'Batal',

			'3' => 'Sudah Bayar',

			'4' => 'Dalam Proses',

			'5' => 'Terkirim'

		];



		$activity = "User mengubah status order {$order_id} menjadi {$status_texts[$status]}";

		log_activity($user_id, $activity);



		$old_status = $order->payment_status;



		// Catat log perubahan

		$description_notes = "Status Pesanan {$order_id} diubah menjadi {$status_texts[$status]} oleh {$this->session->userdata('name')}.";

		$this->log_m->log_order_update(

			$order_id,

			$description_notes,

			'payment_status',

			$old_status,

			$status

		);



		// Send email

		$this->send_email($view_file, $email_data);

	}



	/**

	 * Menyiapkan data email untuk status NOT PAID

	 */

	private function prepareNotPaidEmailData(&$email_data, $order_id, $payment_type)

	{

		$email_data['order_details'] = $this->order_detail_m->get_orders_detail($order_id);



		// Get shipping fee

		$this->db->select('shipping_fee')->from('orders')->where('id_orders', $order_id);

		$shipping_fee = $this->db->get()->row();

		$email_data['total_shipping_fee'] = $shipping_fee;



		// Add bank data for bank transfers

		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;

		}



		// Set subject based on language

		if ($email_data['order']->order_language == 'english') {

			$email_data['subject'] = 'Order Confirmation';

		} else {

			$email_data['subject'] = 'Konfirmasi Pesanan';

		}



		// Add voucher data if exists

		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');

		}



		$email_data['carrier_name'] = $this->session->userdata('carrier_name');



		// Add tax data if exists

		if ($this->session->userdata('tax')) {

			$email_data['tax'] = $this->session->userdata('tax');

		}



		// Add point data if exists

		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');

		}

	}



	/**

	 * Menentukan template email untuk status NOT PAID berdasarkan payment type

	 */

	private function getNotPaidEmailTemplate($language, $payment_type)

	{

		switch ($payment_type) {

			case 'bank transfer BCA':

			case 'bank transfer MANDIRI':

			case 'midtrans':

				return ($language == 'english') ? 'email/english/bank_transfer_english' : 'email/indonesian/bank_transfer_indo';



			case 'cod':

				return ($language == 'english') ? 'email/english/cod' : 'email/indonesian/cod';



			default:

				return ($language == 'english') ? 'email/english/bank_transfer_english' : 'email/indonesian/bank_transfer_indo';

		}

	}



	/**

	 * Generate invoice PDF based on order ID

	 * 

	 * @param int $order_id Order ID

	 * @return void

	 */

	public function generate_invoice($order_id)

	{

		// Validate order existence

		if (!$this->is_valid_order($order_id)) {

			redirect('admin/orders');

			return;

		}



		// Prepare data for PDF

		$pdf_data = $this->prepare_invoice_data($order_id);



		// Generate and output PDF

		$this->generate_invoice_pdf($pdf_data);

	}



	public function generate_delivery_receipt($order_id)

	{

		// Validate order existence

		if (!$this->is_valid_order($order_id)) {

			redirect('admin/orders');

			return;

		}



		$pdf_data = $this->prepare_delivery_receipt_data($order_id);



		$this->generate_delivery_receipt_pdf($pdf_data);

	}



	/**

	 * Check if order ID is valid

	 * 

	 * @param int $order_id Order ID

	 * @return bool

	 */

	private function is_valid_order($order_id)

	{

		if ($order_id === NULL) {

			return false;

		}



		$count_order = $this->db->select('id_orders')

			->from('orders')

			->where('id_orders', $order_id)

			->get()

			->num_rows();



		return $count_order > 0;

	}



	/**

	 * Prepare all data needed for invoice

	 * 

	 * @param int $order_id Order ID

	 * @return array

	 */

	private function prepare_invoice_data($order_id)

	{

		$data = [];



		// Get website info

		$data['website_data'] = $this->db->select('logo, website_name')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		// Set PDF title

		$data['title'] = 'Invoice No: ' . $order_id;



		// Get order data

		$data['order'] = $this->db->select('*')

			->from('orders')

			->where('id_orders', $order_id)

			->get()

			->row();



		// Get customer details

		$data['customer'] = $this->db->select('*')

			->from('customers')

			->where('id_customers', $data['order']->customer_id)

			->get()

			->row();



		// Get order details

		$data['orders_detail'] = $this->db->select('*')

			->from('orders_detail')

			->where('orders_id', $order_id)

			->get()

			->result();



		return $data;

	}



	/**

	 * Prepare all data needed for delivery receipt

	 * 

	 * @param int $order_id Order ID

	 * @return array

	 */

	private function prepare_delivery_receipt_data($order_id)

	{

		$data = [];



		// Get website info

		$data['website_data'] = $this->db->select('logo, website_name')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		// Set PDF title

		$data['title'] = 'Delivery Receipt No: ' . $order_id;



		// Get order data

		$data['order'] = $this->db->select('*')

			->from('orders')

			->where('id_orders', $order_id)

			->get()

			->row();



		// Get customer details

		$data['customer'] = $this->db->select('*')

			->from('customers')

			->where('id_customers', $data['order']->customer_id)

			->get()

			->row();



		// Get order details

		$data['orders_detail'] = $this->db->select('*')

			->from('orders_detail')

			->where('orders_id', $order_id)

			->get()

			->result();



		return $data;

	}



	/**

	 * Generate PDF from prepared data

	 * 

	 * @param array $pdf_data Data for PDF generation

	 * @return void

	 */

	private function generate_invoice_pdf($pdf_data)

	{

		// Load DOMPDF library

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



		// Load view template with data

		$html = $this->load->view('pdf/invoice', $pdf_data, true);



		// Configure and render PDF

		$this->dompdf->loadHtml($html);

		$this->dompdf->setPaper('A4', 'portrait');

		$this->dompdf->render();



		// Output to browser

		$this->dompdf->stream('invoice.pdf', ['Attachment' => 0]);



		// Save to file

		$output = $this->dompdf->output();

		$file_path = 'uploads/pdf/invoice.pdf';

		file_put_contents($file_path, $output);

	}



	/**

	 * Generate PDF from prepared data

	 * 

	 * @param array $pdf_data Data for PDF generation

	 * @return void

	 */

	private function generate_delivery_receipt_pdf($pdf_data)

	{

		// Load DOMPDF library

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



		// Load view template with data

		$html = $this->load->view('pdf/deliveryreceipt', $pdf_data, true);



		// Configure and render PDF

		$this->dompdf->loadHtml($html);

		$this->dompdf->setPaper('A4', 'portrait');

		$this->dompdf->render();



		// Output to browser

		$this->dompdf->stream('deliveryreceipt.pdf', ['Attachment' => 0]);



		// Save to file

		$output = $this->dompdf->output();

		$file_path = 'uploads/pdf/deliveryreceipt.pdf';

		file_put_contents($file_path, $output);

	}





	// Marketing

	public function manage_promotion_products()

	{

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

		$data['title'] = 'Daftar Produk Promosi | Laciasmara';

		$data['customers'] = $this->customer_m->fetch_all_customers();

		$data['products'] = $this->product_m->all_products();



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/marketing/manage_product');

		$this->load->view('admin_new/layouts/footer');

	}



	public function send_promotion_products()

	{



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

		$data['title'] = 'Kirim Produk | Laciasmara';

		$data['customers'] = $this->customer_m->fetch_all_customers();

		$data['products'] = $this->product_m->all_products();

		$data['shippingMethods'] = $this->product_m->get_all_shipping_methods();



		$this->load->view('admin_new/layouts/header', $data);

		$this->load->view('admin_new/orders/marketing//add_product');

		$this->load->view('admin_new/layouts/footer');

	}



	public function send_product()

	{

		if ($this->input->server('REQUEST_METHOD') !== 'POST') {

			show_error('Method Not Allowed', 405);

		}

		$userdata = $this->session->userdata();

		$postData = $this->input->post();

		$grandTotal = (int) $postData['total_price'];

		$subTotal = (int) $postData['subtotal_price'];



		// Data untuk tabel orders

		$orderData = [

			'customer_id' => $postData['customer'],

			'payment_status' => 0,

			'grand_total_amount' => $grandTotal,

			'total_amount' => $subTotal,

			'payment_type' => 'bank transfer BCA',

			'recipient_name' => $postData['nama'],

			'address' => $postData['address'],

			'district'    => !empty($postData['shipping_district']) ? $postData['shipping_district'] : $postData['district'],

			'subdistrict' => !empty($postData['shipping_subdistrict']) ? $postData['shipping_subdistrict'] : $postData['subdistrict'],

			'province'    => !empty($postData['shipping_province']) ? $postData['shipping_province'] : $postData['province'],

			'phone'       => !empty($postData['shipping_phone']) ? $postData['shipping_phone'] : $postData['phone'],

			'email' => $postData['email'],

			'country' => 'Indonesia',

			'shipping_fee' => 0,

			'created_by' => $userdata['name'],

			'source' => 'marketing',

			'distribution_type' => 'marketing_send_product',

			'distribution_department' => 'marketing',

			'distribution_purpose' => $postData['purpose']

		];



		// Ambil data pelanggan untuk is_first

		$customer = $this->db->get_where('customers', ['id_customers' => $postData['customer']])->row();

		if ($customer) {

			$orderData['first'] = $customer->is_first + 1;

		}



		// Mulai transaksi database

		$this->db->trans_start();



		// Insert ke tabel orders

		$this->db->insert('orders', $orderData);

		$orderId = $this->db->insert_id();



		// Insert ke orders_detail

		$orderDetails = json_decode($postData['selected_products_data'], true);

		foreach ($orderDetails as $item) {

			$orderDetailData = [

				'orders_id' => $orderId,

				'item_id' => $item['id_detail'],

				'product_id' => $item['id_products'],

				'item_name' => $item['product'],

				'item_price' => (int) $item['price'],

				'quantity' => (int) $item['qty'],

				'subtotal' => (int) $item['subtotal'],

				'sku' => $item['sku'],

				'attributes' => $item['atribut'],

				'warehouse_id' => 1,

				'chosen_shipping_id' => $postData['shippingMethod'],

				'shipping_fee' => 0

			];



			$insert_result = $this->db->insert('orders_detail', $orderDetailData);



			// Update Stock

			if ($insert_result) {



				$this->db->select('id, stock');

				$this->db->where('id_product', $item['id_products']);

				$this->db->where('id_product_detail', $item['id_detail']);

				$this->db->where('warehouse_id', 1);

				$stock = $this->db->get('stock')->row();





				if ($stock) {

					$stock_id = $stock->id;

					$old_stock = $stock->stock; // Simpan stok sebelum perubahan



					// Update Stock

					$this->db->set('stock', 'stock - ' . (int) $item['qty'], false)

						->where('id_product', $item['id_products'])

						->where('id_product_detail', $item['id_detail'])

						->where('warehouse_id', 1);

					$update_stock_result = $this->db->update('stock');



					if ($update_stock_result) {

						// Ambil stok setelah perubahan

						$this->db->select('stock');

						$this->db->where('id', $stock_id);

						$new_stock = $this->db->get('stock')->row()->stock;



						// Insert stock movement

						$movement_data = [

							'stock_id' => $stock_id,

							'type' => '-',

							'stock_change' => $item['qty'],

							'remark' => 'Sales Order No: ' . $orderId,

							'total' => $new_stock,

							'name' => 'System',

							'datetime' => date('Y-m-d H:i:s')

						];

						$insert_movement_result = $this->db->insert('stock_movement', $movement_data);



						$productName = $item['product'];

						$productId = $item['id_detail'];

						$username = $this->session->userdata('name');

						$purpose = $postData['purpose'];

						$description = "Stok produk {$productName} (ID: {$productId}) telah diperbarui dari {$old_stock} menjadi {$new_stock} oleh {$username}. Dengan catatan: {$purpose}";



						// Panggil log stok dengan stok sebelum dan sesudah perubahan

						$this->log_m->log_stock_update(

							$orderId,

							$item['id_detail'],

							$item['product'],

							$old_stock,

							$new_stock,

							base_url('admin/products/stock-product?tab=all'),

							$description,

							null,

							'stock',

							'orders'

						);



						if (!$insert_movement_result) {

							log_message('error', 'Stock Movement Insert Failed: ' . print_r($this->db->error(), true));

						}

					} else {

						log_message('error', 'Stock Update Failed: ' . print_r($this->db->error(), true));

					}

				} else {

					log_message('error', 'Stock ID Not Found for Product: ' . $item['product']);

				}

			} else {

				$db_error = $this->db->error();

				log_message('error', 'Order Detail Insert Failed: ' . print_r($db_error, true));

			}

		}



		// Update is_first pelanggan

		$this->db->set('is_first', 'is_first + 1', false)

			->where('id_customers', $postData['customer'])

			->update('customers');



		// Selesaikan transaksi

		$this->db->trans_complete();



		if ($this->db->trans_status() === false) {

			$this->db->trans_rollback();



			$this->session->set_flashdata('message', 'Failed to add order');

			$this->session->set_flashdata('message_type', 'error');



			redirect('admin/marketing/promotion-product/add');

		} else {

			$nama = $postData['nama'];



			$description = "Pesanan Baru dari Marketing telah ditambahkan dengan Order ID {$orderId} senilai {$grandTotal}. Pesanan ini dikirim untuk {$nama}.";



			$reference_url = base_url('admin/orders/manage-order?tab=pending');

			$log_id = $this->log_m->log_order_create($orderId, $description, $reference_url);

			$this->log_m->send_order_notifications('CREATE_ORDER', $log_id, $description);

			$this->session->set_flashdata('message', 'Berhasil menambah pesanan baru dari marketing untuk ' . $nama);

			$this->session->set_flashdata('message_type', 'success');



			// Redirect to manage-order page

			redirect('admin/marketing/promotion-product');

		}

	}



	// Print Label

	public function print_label()

	{

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

		$data['title'] = 'Print Label | Laciasmara';



		$this->load->view('admin_new/orders/print_label', $data);

	}



	public function get_print_label_data($id_order)

	{

		try {

			if (empty($id_order) || !is_numeric($id_order)) {

				$this->send_error_response('Invalid order ID', 400);

				return;

			}



			if (!$this->is_valid_order($id_order)) {

				$this->send_error_response('Order not found', 404);

				return;

			}



			$label_data = $this->prepare_label_data($id_order);



			$this->send_success_response($label_data);

		} catch (Exception $e) {

			log_message('error', 'Error in get_print_label_data: ' . $e->getMessage());



			$this->send_error_response('Internal server error', 500);

		}

	}



	/**

	 * Prepare data untuk shipping label sesuai format JavaScript

	 */

	private function prepare_label_data($order_id)

	{

		$data = array();



		// 1. Ambil data website/configuration

		$data['website_data'] = $this->get_website_data();



		// 2. Ambil data order

		$data['order'] = $this->get_order_data($order_id);



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



		// 4. Ambil detail order items

		$data['orders_detail'] = $this->get_order_details($order_id);



		return $data;

	}



	/**

	 * Ambil data website/toko

	 */

	private function get_website_data()

	{

		$query = $this->db->select('logo, website_name')

			->from('configuration')

			->where('id_configuration', 1)

			->get();



		$website = $query->row();



		if (!$website) {

			return array(

				'logo' => 'Logo',

				'website_name' => 'Laciasmara.com'

			);

		}



		return array(

			'logo' => $website->logo ?: 'Logo',

			'website_name' => $website->website_name ?: 'Laci Asmara',

		);

	}



	/**

	 * Ambil data order

	 */

	private function get_order_data($order_id)

	{

		$query = $this->db->select('id_orders, customer_id, order_date, grand_total_amount, shipping_fee, district, subdistrict, province, phone, email, country')

			->from('orders')

			->where('id_orders', $order_id)

			->get();



		$order = $query->row();



		if (!$order) {

			throw new Exception("Order not found");

		}



		// Ambil satu chosen_shipping_id dari orders_detail untuk order ini

		$shipment_query = $this->db->select('sm.name AS shipment_type, sm.shipper as shipment_name, sm.service_code as shipment_code')

			->from('orders_detail od')

			->join('shipment_method sm', 'sm.id = od.chosen_shipping_id', 'left')

			->where('od.orders_id', $order_id)

			->limit(1) // ambil satu saja

			->get();



		$shipment = $shipment_query->row();

		$shipment_name = $shipment ? $shipment->shipment_name : 'Unknown';

		$shipment_type = $shipment ? $shipment->shipment_type : 'Unknown';

		$shipment_code = $shipment ? $shipment->shipment_code : 'Unknown';



		return array(

			'id_orders' => $order->id_orders,

			'customer_id' => $order->customer_id,

			'order_date' => $order->order_date,

			'grand_total_amount' => floatval($order->grand_total_amount),

			'shipping_fee' => $order->shipping_fee ?: 0,

			'district' => $order->district,

			'subdistrict' => $order->subdistrict,

			'province' => $order->province,

			'phone' => $order->phone,

			'email' => $order->email,

			'shipment_name' => $shipment_name,

			'shipment_type' => $shipment_type,

			'shipment_code' => $shipment_code,

		);

	}





	/**

	 * Ambil detail order items

	 */

	private function get_order_details($order_id)

	{

		$query = $this->db->select('od.item_name, od.quantity, od.item_price, od.attributes, od.sku, sm.name AS shipment_name')

			->from('orders_detail od')

			->join('shipment_method sm', 'sm.id = od.chosen_shipping_id', 'left')

			->where('od.orders_id', $order_id)

			->get();



		$details = $query->result();



		if (!$details) {

			return array();

		}



		$order_details = array();

		foreach ($details as $detail) {

			$order_details[] = array(

				'product_name' => $detail->item_name,

				'attribute' => $detail->attributes,

				'quantity' => intval($detail->quantity),

				'price' => floatval($detail->item_price),

				'shipment_name' => $detail->shipment_name ?: 'Unknown',

				'sku' => $detail->sku ?: 'N/A'

			);

		}





		return $order_details;

	}

	private function get_customer_data($customer_id)

	{

		$query = $this->db->select('shipping_name, email, shipping_phone, shipping_address, shipping_district, shipping_subdistrict, shipping_province')

			->from('customers')

			->where('id_customers', $customer_id)

			->get();



		$customer = $query->row();



		if (!$customer) {

			throw new Exception("Customer not found");

		}



		return array(

			'name' => $customer->shipping_name,

			'email' => $customer->email,

			'phone' => $customer->shipping_phone ?: '',

			'address' => $customer->shipping_address,

			'province' => $customer->shipping_province,

			'district' => $customer->shipping_district,

			'subdistrict' => $customer->shipping_subdistrict,

		);

	}



	/**

	 * Kirim response sukses

	 */

	private function send_success_response($data)

	{

		$response = array(

			'success' => true,

			'message' => 'Data retrieved successfully',

			'data' => $data

		);



		$this->output

			->set_status_header(200)

			->set_output(json_encode($response));

	}



	/**

	 * Kirim response error

	 */

	private function send_error_response($message, $status_code = 400)

	{

		$response = array(

			'success' => false,

			'message' => $message,

			'data' => null

		);



		$this->output

			->set_status_header($status_code)

			->set_output(json_encode($response));

	}



	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->filterdata($search, $filterkey, $dataenter, $this->session->userdata('admin')['id'], $length, $start);



		$jum = $this->order_m->filterdata($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;

			$referral = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;



			if ($order->first == 1) {

				// Jika referral kosong, beri diskon default 5%

				if (empty($referral)) {

					$first_discount = $order->total_amount * 0.05;

				} else {

					// Cek kategori affiliator jika referral ada

					$affiliator = $this->db->select('kategori')

						->from('affiliator_register')

						->where('referral', $referral)

						->get()

						->row();



					if (!empty($affiliator)) {

						// Tentukan diskon berdasarkan kategori affiliator

						if ($affiliator->kategori == 'asmarasana') {

							$first_discount = $order->total_amount * 0.05; // Diskon 5%

						} elseif ($affiliator->kategori == 'asmaradoor') {

							$first_discount = $order->total_amount * 0.10; // Diskon 10%

						}

					} else {

						// Jika affiliator tidak ditemukan, beri diskon default 5%

						$first_discount = $order->total_amount * 0.05;

					}

				}

			} else {

				// Jika ini bukan pembelian pertama, diskon adalah 0

				$first_discount = 0;

			}





			$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;

			} 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 = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;

			$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/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 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 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;

			$referral = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;



			if ($order->first == 1) {

				// Jika referral kosong, beri diskon default 5%

				if (empty($referral)) {

					$first_discount = $order->total_amount * 0.05;

				} else {

					// Cek kategori affiliator jika referral ada

					$affiliator = $this->db->select('kategori')

						->from('affiliator_register')

						->where('referral', $referral)

						->get()

						->row();



					if (!empty($affiliator)) {

						// Tentukan diskon berdasarkan kategori affiliator

						if ($affiliator->kategori == 'asmarasana') {

							$first_discount = $order->total_amount * 0.05; // Diskon 5%

						} elseif ($affiliator->kategori == 'asmaradoor') {

							$first_discount = $order->total_amount * 0.10; // Diskon 10%

						}

					} else {

						// Jika affiliator tidak ditemukan, beri diskon default 5%

						$first_discount = $order->total_amount * 0.05;

					}

				}

			} else {

				// Jika ini bukan pembelian pertama, diskon adalah 0

				$first_discount = 0;

			}





			$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;

			} 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 = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;

			$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/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 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 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;

			$referral = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;



			if ($order->first == 1) {

				// Jika referral kosong, beri diskon default 5%

				if (empty($referral)) {

					$first_discount = $order->total_amount * 0.05;

				} else {

					// Cek kategori affiliator jika referral ada

					$affiliator = $this->db->select('kategori')

						->from('affiliator_register')

						->where('referral', $referral)

						->get()

						->row();



					if (!empty($affiliator)) {

						// Tentukan diskon berdasarkan kategori affiliator

						if ($affiliator->kategori == 'asmarasana') {

							$first_discount = $order->total_amount * 0.05; // Diskon 5%

						} elseif ($affiliator->kategori == 'asmaradoor') {

							$first_discount = $order->total_amount * 0.10; // Diskon 10%

						}

					} else {

						// Jika affiliator tidak ditemukan, beri diskon default 5%

						$first_discount = $order->total_amount * 0.05;

					}

				}

			} else {

				// Jika ini bukan pembelian pertama, diskon adalah 0

				$first_discount = 0;

			}





			$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;

			} 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 = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;

			$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/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 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 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;

			$referral = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;



			if ($order->first == 1) {

				// Jika referral kosong, beri diskon default 5%

				if (empty($referral)) {

					$first_discount = $order->total_amount * 0.05;

				} else {

					// Cek kategori affiliator jika referral ada

					$affiliator = $this->db->select('kategori')

						->from('affiliator_register')

						->where('referral', $referral)

						->get()

						->row();



					if (!empty($affiliator)) {

						// Tentukan diskon berdasarkan kategori affiliator

						if ($affiliator->kategori == 'asmarasana') {

							$first_discount = $order->total_amount * 0.05; // Diskon 5%

						} elseif ($affiliator->kategori == 'asmaradoor') {

							$first_discount = $order->total_amount * 0.10; // Diskon 10%

						}

					} else {

						// Jika affiliator tidak ditemukan, beri diskon default 5%

						$first_discount = $order->total_amount * 0.05;

					}

				}

			} else {

				// Jika ini bukan pembelian pertama, diskon adalah 0

				$first_discount = 0;

			}





			$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;

			} 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 = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;

			$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/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/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(

			$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();

		$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/index';

		$this->load->view('admin/templates/header', $this->data_header);

		$this->load->view('admin/_layout_main', $this->data);

		$this->load->view('admin/templates/footer');

	}



	//get all successful orders for specific customer only

	public function customer($customer_id)

	{

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

		$config['base_url'] = base_url() . 'admin/orders/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)');



		// 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', 'ASC');

		$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/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/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/index';

		$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/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/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, pd.discounted_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');

		}



		//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();

		}



		$this->db->select('*')->from('orders')->where('id_orders', $id);

		$current_order = $this->db->get()->row();



		if ($current_order->payment_status != 2) {

			if ($current_order->referral == 'laciput') {

				$query = $this->db->select('COUNT(*) as count')

					->from('orders_detail')

					->where('orders_id', $current_order->id_orders)

					->where_in('product_id', [67, 68])

					->get()

					->row();



				if ($query->count > 0) {

					$check_insert = $this->db->select('COUNT(*) as count')

						->from('orders_detail')

						->where('orders_id', $current_order->id_orders)

						->where('product_id', 410)

						->get()

						->row();



					if ($check_insert->count == 0) {

						$od_auto_free = array(

							'orders_id' => $current_order->id_orders,

							'item_id' => 807,

							'product_id' => 410,

							'item_name' => 'Mirai - Natural Lubricant 30ml - FREE ITEM',

							'item_price' => 0,

							'quantity' => 1,

							'subtotal' => 0,

							'sku' => 'MIRAI009',

							'attributes' => '1 Size',

							'warehouse_id' => 1,

							'chosen_shipping_id' => 3,

							'shipping_fee' => 0,

							'is_backorder' => 'no',

							'status' => 0,

							'no_resi' => "",

						);

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



						$item_id = 807;

						$qty = 1;



						$curent_stock = $this->db->select('stock')->from('stock')->where('id_product_detail', $item_id)->where('warehouse_id', 1)->get()->row();



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



						if ($warehouse->warehouse_type == 'virtual') {

							$final_stock = array(

								'stock_virtual' => $curent_stock->stock_virtual - $qty,

							);

							$this->db->where('id_product_detail', $item_id);

							$this->db->where('warehouse_id', 1);

							$this->db->update('stock', $final_stock);

						} else {

							$final_stock = array(

								'stock' => $curent_stock->stock - $qty,

							);

							$this->db->where('id_product_detail', $item_id);

							$this->db->where('warehouse_id', 1);

							$this->db->update('stock', $final_stock);



							$id_stock = $this->db->select('id')->from('stock')->where('id_product_detail', $item_id)->where('warehouse_id', 1)->get()->row();



							$last_stock = $curent_stock->stock - $qty;



							$insert_mov_stock = array(

								'stock_id' => $id_stock->id,

								'type' => '-',

								'stock_change' => $qty,

								'remark' => 'Automatic Free Item For PutriPai: ' . $current_order->id_orders,

								'total' => $last_stock,

								'name' => 'System',

								'datetime' => date("Y-m-d H:i:s"),

							);

							$this->db->insert('stock_movement', $insert_mov_stock);

						}

					}

				}

			}

		}



		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/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);





				// Mengurangi komisi

				$this->db->select('referral, redeemed_voucher_code, total_amount');

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

				$this->db->where('id_orders', $id);

				$order = $this->db->get()->row();



				if ($order) {

					// Tentukan kode affiliator berdasarkan prioritas

					$referral_code = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;



					if (!empty($referral_code)) {

						// Ambil kategori affiliator berdasarkan kode

						$this->db->select('kategori, id_customer');

						$this->db->from('affiliator_register');

						$this->db->where('referral', $referral_code);

						$affiliator = $this->db->get()->row();



						if ($affiliator) {

							// Hitung pengurangan komisi berdasarkan kategori affiliator

							$deduction = 0;

							if ($affiliator->kategori == 'asmaradoor') {

								$deduction = 0.10 * $order->total_amount; // 10% dari total amount

							} elseif ($affiliator->kategori == 'asmarasana') {

								$deduction = 0.20 * $order->total_amount; // 20% dari total amount

							}



							// Kurangi komisi di tabel affiliator_link

							$this->db->set('komisi_order', "komisi_order - $deduction", FALSE);

							$this->db->where('customer_id', $affiliator->id_customer);

							$this->db->update('affiliator_link');



							// Kurangi komisi di tabel affiliator_register

							$this->db->set('komisi', "komisi - $deduction", FALSE);

							$this->db->where('id_customer', $affiliator->id_customer);

							$this->db->update('affiliator_register');

						}

					}

				}



				//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 CUSTOMER 

				//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);



				$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/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);



				$this->db->select('payment_type')->from('orders')->where('id_orders', $id);

				$payment_type = $this->db->get()->row();



				$this->db->select('shipping_fee')->from('orders')->where('id_orders', $id);

				$shipping_fee_fixed_retailer = $this->db->get()->row();



				$email_data['order'] = $this->order_m->get_order($id);

				$email_data['order_details'] = $this->order_detail_m->get_orders_detail($id);



				$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();



				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 ($email_data['order']->order_language == 'english') {

					$email_data['subject'] = 'Order Confirmation';

				} else {

					$email_data['subject'] = 'Konfirmasi Pesanan';

				}



				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'

					);

				}



				$email_data['carrier_name'] = $this->session->userdata('carrier_name');

				$email_data['total_shipping_fee'] = $shipping_fee_fixed_retailer;



				if ($this->session->userdata('tax')) {

					$email_data['tax'] = $this->session->userdata('tax');

				}



				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 ($email_data['order']->order_language == 'english') {

							$view_file = 'email/english/bank_transfer_english';

						} else {

							$view_file = 'email/indonesian/bank_transfer_indo';

						}

						break;

					case 'bank transfer MANDIRI':

						if ($email_data['order']->order_language == 'english') {

							$view_file = 'email/english/bank_transfer_english';

						} else {

							$view_file = 'email/indonesian/bank_transfer_indo';

						}

						break;

					case 'cod':

						if ($email_data['order']->order_language == 'english') {

							$view_file = 'email/english/cod';

						} else {

							$view_file = 'email/indonesian/cod';

						}

						break;

					case 'midtrans':

						if ($email_data['order']->order_language == '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 mengubah status order ' . $id . ' menjadi Belum 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/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';

				} else {

					$view_file = 'email/indonesian/payment_confirmation';

				}



				//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/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';

				} else {

					$view_file = 'email/indonesian/payment_confirmation';

				}



				$this->send_email($view_file, $email_data);

				// var_dump($this->email->print_debugger());  

				// exit();

				//----end send email   



				//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->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');

				redirect('admin/orders/view/' . $id);

			}



			// Update status menjadi proses

			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);



				// Ambil total_amount dan referral dari order yang baru diupdate

				$this->db->select('customer_id, total_amount, referral, redeemed_voucher_code')

					->from('orders')

					->where('id_orders', $id);

				$order_data = $this->db->get()->row();



				// Ambil voucher code yang gagal di redeem karena itemnya ada yang discount, ambil dari log 





				// Ambil product_id dari orders_detail untuk mendapatkan data yang relevan

				$this->db->select('product_id')

					->from('orders_detail')

					->where('orders_id', $id);

				$order_details = $this->db->get()->result();



				// Ambil kategori affiliator berdasarkan referral dari table orders

				$this->db->select('kategori')

					->from('affiliator_register')

					->where('referral', !empty($order_data->referral) ? $order_data->referral : $order_data->redeemed_voucher_code);

				$affiliator = $this->db->get()->row();



				// Dibalik ini tuh setelah redeemed vouchernya udah di set

				// Ambil kategori affiliator berdasarkan redeemed_voucher_code dari table orders

				$this->db->select('kategori')

					->from('affiliator_register')

					->where('referral', $order_data->redeemed_voucher_code);

				$doctor_affiliator = $this->db->get()->row();



				// Hitung Komisi

				$commission_rate = ($affiliator && $affiliator->kategori == 'asmarasana') ? 0.20 : 0.10;



				// Update komisi untuk affiliator asmarasana

				if ($doctor_affiliator->kategori == 'asmarasana') {

					$commission = $order_data->total_amount * 0.20;

					$this->db->set('komisi', 'komisi + (' . $commission . ')', FALSE);

					$this->db->where('referral', $order_data->redeemed_voucher_code);

					$this->db->update('affiliator_register');

				}



				if ($affiliator->kategori == 'asmaradoor') {

					$commission = $order_data->total_amount * 0.10;

					$this->db->set('komisi', 'komisi + (' . $commission . ')', FALSE);

					$this->db->where('referral', !empty($order_data->referral) ? $order_data->referral : $order_data->redeemed_voucher_code);

					$this->db->update('affiliator_register');

				}



				// Update komisi untuk affiliator asmaradoor per link product

				foreach ($order_details as $od) {

					// Update table affiliator_link dengan jumlah order dan komisi

					$this->db->set('`order`', '`order` + 1', FALSE); // Increment order

					$this->db->set('komisi_order', 'komisi_order + (' . $order_data->total_amount . ' * ' . $commission_rate . ')', FALSE);

					$this->db->where('product_id', $od->product_id);

					$this->db->where('unique_id', $order_data->referral);

					$this->db->update('affiliator_link');

				}

				//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/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/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['product_free'] = $this->db->select(' p.id_products, pc.product_details_id , p.title,pa.product_attribute,pad.attribute_detail, pd.sku, pd.price, pd.sku')

			->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['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/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 - shipping*/

	public function update_status()

	{



		if (!$this->input->post('id_order')) {

			redirect('admin/orders');

		}



		$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/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/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');

		}



		$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');

		}



		//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');

		}



		$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');

		}



		//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/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';

						} else {

							$view_file = 'email/indonesian/payment_confirmation';

						}

						$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) {

							$upd2 = $this->db->update("orders", array(

								"payment_status" => 5,

							), array(

								"id_orders" => $orderid,

							));

							if ($upd2) {

								$msg = "Sukses";



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



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



								log_activity($user_id, $activity);

							} 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 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);

		}



		$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;'>Ongkir berhasil di update</p>");

		redirect('admin/orders/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/view/' . $id);

	}



	function free_product($id)

	{

		if ($id == NULL) {

			show_404();

		}



		$data['product_free'] = $this->product_m->get_product();



		//check if id is exist

		$this->db->select('id_orders')->from('orders')->where('id_orders', $id);

		$count_id = $this->db->get()->num_rows();



		$this->db->select('*')->from('orders_detail')->where('orders_id', $id);

		$orders_detail = $this->db->get()->row();



		// Now $orders_detail contains the data, and you can access the individual fields like $orders_detail->field_name





		if ($count_id == 0) {

			show_404();

		}





		$order_detail = array(

			'orders_id'			=> $id,

			'item_id' 			=> $this->input->post('product_free_choose'),

			'product_id'		=> $this->input->post('pf_id_products'),

			'item_name'			=> $this->input->post('pf_title') . ' - FREE ITEM',

			'item_price'		=> 0,

			'quantity'			=> $this->input->post('product_free_choose_qty'),

			/*'subtotal'			=> ($marketplace_price[$c] * $quantitas_beli[$c]) + $shipping_fee_info['total_shipping_fee'],*/

			'subtotal'          => 0,

			'sku'				=> $this->input->post('pf_sku'),

			'attributes'		=> $this->input->post('pf_product_attribute'),

			'warehouse_id'		=> $orders_detail->warehouse_id,

			'chosen_shipping_id' => $orders_detail->chosen_shipping_id,

			/* 'shipping_fee'		=> $shipping_fee_info['total_shipping_fee'], */

			'shipping_fee'      => $orders_detail->shipping_fee,

			'is_backorder'		=> 'no',

			'status'			=> 0,

			'no_resi'			=> "",

		);



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



		$item_id = $this->input->post('product_free_choose');

		$qty = $this->input->post('product_free_choose_qty');



		$curent_stock 	= $this->db->select('stock')->from('stock')->where('id_product_detail', $item_id)->where('warehouse_id', 1)->get()->row();



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



		if ($warehouse->warehouse_type == 'virtual') {

			$final_stock = array(

				'stock_virtual' => $curent_stock->stock_virtual - $qty,

			);

			$this->db->where('id_product_detail', $item_id);

			$this->db->where('warehouse_id', 1);

			$this->db->update('stock', $final_stock);

		} else {

			$final_stock = array(

				'stock' => $curent_stock->stock - $qty,

			);

			$this->db->where('id_product_detail', $item_id);

			$this->db->where('warehouse_id', 1);

			$this->db->update('stock', $final_stock);



			// insert mov stock

			$id_stock = $this->db->select('id')->from('stock')->where('id_product_detail', $item_id)->where('warehouse_id', 1)->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 - $qty;



			$insert_mov_stock = array(

				'stock_id' 		=> $id_stock->id,

				'type' 			=> '-',

				'stock_change' 	=> $qty,

				'remark' 		=> 'Free Item For Sales Order No: ' . $id,

				'total' 		=> $last_stock,

				'name' 			=> $user_name,

				'datetime' 		=> date("Y-m-d H:i:s"),

			);

			$this->db->insert('stock_movement', $insert_mov_stock);

		}



		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Add Free Product Success.</p>");

		redirect('admin/orders/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');

		}



		$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/view/' . $order_detail->orders_id);

	}



	// public function generate_invoice($id)

	// {

	// 	if ($id == NULL) {

	// 		redirect('admin/orders');

	// 	}



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

	// 	if ($count_order < 1) {

	// 		redirect('admin/orders');

	// 	}



	// 	//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');

	// 	}

	// }



	public function generate_deliveryreceipt($id)

	{

		if ($id == NULL) {

			redirect('admin/orders');

		}



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

		if ($count_order < 1) {

			redirect('admin/orders');

		}



		//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');

		}

	}



	public function process_send_email($payment_type)

	{

		//----SEND EMAIL TO CUSTOMER

		//get customer name

		if ($this->session->userdata('customer')['customer_id'] != null) {

			$customer_id = (int) $this->session->userdata('customer')['customer_id'];

		} else {

			$customer_id = $this->db

				->select('customer_id')

				->from('orders')

				->where('id_orders', $this->order_id)

				->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();



		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;

		}

		$data['order'] = $this->order_m->get_order($id);



		if ($this->session->userdata('site_lang') == 'english') {

			$email_data['subject'] = 'Order Confirmation';

		} else {

			$email_data['subject'] = 'Konfirmasi Pesanan';

		}



		//get order detail and customer detail

		$email_data['order'] = $this->order_m->get_order($this->order_id);

		$email_data['order_details'] = $this->order_detail_m->get_orders_detail(

			$this->order_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/english/bank_transfer_english';

				} else {

					$view_file = 'email/indonesian/bank_transfer_indo';

				}

				break;

			case 'bank transfer MANDIRI':

				if ($this->session->userdata('site_lang') == 'english') {

					$view_file = 'email/english/bank_transfer_english';

				} else {

					$view_file = 'email/indonesian/bank_transfer_indo';

				}

				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;

		}

	}

}


https://t.me/RX1948 - 2025