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

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

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

class Resellers extends Admin_Controller
{

	//this property is used for validating existing reseller title on call back edit reseller
	private $reseller_current_id = NULL;
	private $customer_current_id = NULL;

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

	//this is to list all resellers
	public function index()
	{
		redirect('admin/resellers/manage');
	}

	//to add a new reseller 
	// public function add()
	// {

	// 	$this->data['resellers'] = $this->reseller_m->get_new();

	// 	$config = $this->reseller_m->admin_rules;

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

	// 	if ($this->form_validation->run($this) == TRUE) {

	// 		$data = array(
	// 			'reseller_name' => $this->security->xss_clean($this->input->post('reseller_name')),
	// 			//		'voucher_valid' => $this->input->post('voucher_valid'),
	// 			'minimum_order' => $this->input->post('minimum_order'),
	// 			'target_point' => $this->input->post('target_point'),
	// 			//	'pointrewards_valid' => $this->input->post('pointrewards_valid'),
	// 			'active' => $this->input->post('active')
	// 		);

	// 		//	if ($this->input->post('global_discount')) {
	// 		//		$data['global_discount'] = $this->security->xss_clean($this->input->post('global_discount'));
	// 		//	} else {
	// 		//		$data['global_discount'] = NULL;
	// 		//	}

	// 		//save reseller data
	// 		$this->db->insert('resellers', $data);

	// 		$reseller_name = $this->input->post('reseller_name');

	// 		$user_id = $this->session->userdata('admin')['id'];
	// 		$activity = 'User menambah tier retailer (' . $reseller_name . ')';

	// 		log_activity($user_id, $activity);

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

	// 		redirect('admin/resellers');
	// 	}

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

	public function add()
	{

		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Tambah Retailer | Laciasmara';
		$data['provinces'] = $this->getProvinces();
		$data['reseller_types'] = $this->getResellerTypes();

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

	public function manage()
	{
		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Daftar Retailer | Laciasmara';
		$data['retailers'] = $this->customer_m->fetch_all_retailers();

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

	public function add_type()
	{

		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Tambah Jenis Retailer | Laciasmara';

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

	public function type()
	{
		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Daftar Retailer | Laciasmara';
		$data['reseller_types'] = $this->getResellerTypes();

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

	public function detail_type($type_reseller_id = NULL)
	{
		if (!$type_reseller_id) {
			redirect('admin/retailers/type');
		}
		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Detail Jenis Retailer | Laciasmara';
		$data['reseller_type'] = $this->getResellerTypeById($type_reseller_id);

		// Fetch data jenis
		if (!$data['reseller_type']) {
			$this->session->set_flashdata('message', 'Customer ID tidak ditemukan.');
			$this->session->set_flashdata('message_type', 'error');
			redirect('admin/retailers/type');
		}

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

	public function detail($id_customer = NULL)
	{
		if (!$id_customer) {
			redirect('admin/retailers/manage');
		}
		$data['userdata'] = $this->session->userdata();
		$data['title'] = 'Detail Retailer | Laciasmara';
		$data['reseller_types'] = $this->getResellerTypes();


		// Fetch data order
		$data['customer'] = $this->customer_m->fetch_customer_by_id($id_customer);
		if (!$data['customer']) {
			$this->session->set_flashdata('message', 'Customer ID tidak ditemukan.');
			$this->session->set_flashdata('message_type', 'error');
			redirect('admin/retailers/manage');
		}
		$data['customer_addresses'] = $this->customer_m->get_customer_addresses($id_customer);


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

	public function create_retailer()
	{
		$this->load->model('customer_m');
		$email = $this->input->post('customer_email', true);
		$status = (int) $this->input->post('customer_status', true);
		$reseller_id = (int) $this->input->post('reseller_type_id', true);

		// Cek apakah email atau nomor telepon sudah terdaftar
		$existing_customer = $this->db->where('email', $email)
			->get('customers')
			->row();

		if ($existing_customer) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', 'Email sudah digunakan, coba pakai email yang lain.');
			redirect(base_url('admin/resellers/add'));
			return;
		}

		// Data customer
		$data = [
			'name' => $this->input->post('customer_name', true),
			'email' => $this->input->post('customer_email', true),
			'phone' => $this->input->post('customer_phone', true),
			'birthday' => $this->input->post('customer_birthdate', true),
			'sex_type' => $this->input->post('customer_gender', true),
			'password' => $this->customer_m->hash($this->input->post('customer_password', true)),
			'shipping_country' => 'Indonesia',
			'shipping_phone' => $this->input->post('customer_phone', true),
			'reseller_id' => $reseller_id,
			'status' => $status,
			'current_pointreward' => 0,
			'type' => 'regular',
			'is_first' => 0,
			'source' => 'www.laciasmara.com',
			'country' => 'Indonesia',
			'join_date' => date('Y-m-d H:i:s'),
		];
		$this->db->trans_begin();

		// Simpan data ke tabel customers
		$this->db->insert('customers', $data);
		$customer_id = $this->db->insert_id();

		// Ambil dan decode customer_addresses
		$addresses_json = $this->input->post('customer_addresses');
		$addresses = json_decode($addresses_json, true);

		if ($addresses && is_array($addresses)) {
			foreach ($addresses as $address) {
				$address_data = [
					'customer_id' => $customer_id,
					'label' => $address['label'],
					'recipient_name' => $address['receiverName'],
					'phone' => $address['receiverPhone'],
					'address' => $address['fullAddress'],
					'notes' => $address['notes'] ?? null,
					'latitude' => $address['latitude'] ?? null,
					'longitude' => $address['longitude'] ?? null,
					'province' => $address['province'],
					'city' => $address['city'],
					'district' => $address['district'],
					'subdistrict' => $address['subdistrict'],
					'postal_code' => $address['postalCode'],
					'is_default' => !empty($address['isMainAddress']) ? 1 : 0,
					'created_at' => date('Y-m-d H:i:s'),
					'updated_at' => date('Y-m-d H:i:s'),
				];

				$this->db->insert('customer_addresses', $address_data);
			}
		}

		// Commit atau rollback transaksi
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$this->session->set_flashdata('error', 'Gagal menyimpan data customer.');
		} else {
			$this->db->trans_commit();
			$this->session->set_flashdata('success', 'Customer berhasil ditambahkan.');
		}
		redirect('admin/resellers/manage');
	}

	public function create_retailer_type()
	{

		// Ambil data dari POST request
		$type_name = $this->input->post('type_name', true);
		$type_minimum_purchase = (int) $this->input->post('type_minimum_purchase', true);
		$type_target_point = (int) $this->input->post('type_target_point', true);
		$type_status = $this->input->post('type_status', true);

		// Nilai default
		$global_discount = null;
		$voucher_valid = 'no';
		$pointrewards_valid = 'no';
		$reseller_company = '';

		// Mulai transaksi database
		$this->db->trans_start();

		try {
			$data = [
				'reseller_name' => $type_name,
				'global_discount' => $global_discount,
				'voucher_valid' => $voucher_valid,
				'pointrewards_valid' => $pointrewards_valid,
				'active' => $type_status,
				'reseller_company' => $reseller_company,
				'minimum_order' => $type_minimum_purchase,
				'target_point' => $type_target_point,
			];

			// Insert ke tabel resellers
			$this->db->insert('resellers', $data);

			// Periksa apakah transaksi berhasil
			if ($this->db->trans_status() === false) {
				throw new Exception('Terjadi kesalahan saat menambahkan reseller.');
			}

			$this->db->trans_commit();

			// Set flashdata dan redirect
			$this->session->set_flashdata('message_type', 'success');
			$this->session->set_flashdata('message', 'Reseller berhasil ditambahkan!');
			redirect(base_url('admin/resellers/type'));
		} catch (Exception $e) {
			$this->db->trans_rollback();

			// Set flashdata untuk error dan redirect
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', $e->getMessage());
			redirect(base_url('admin/resellers/type/add'));
		}
	}


	public function update_retailer()
	{
		$this->load->model('customer_m');
		$customer_id = $this->input->post('customer_id', true);
		$email = $this->input->post('customer_email', true);
		$status = (int) $this->input->post('customer_status', true);
		$reseller_id = (int) $this->input->post('reseller_type_id', true);

		// Cek apakah email sudah digunakan oleh customer lain
		$existing_customer = $this->db->where('email', $email)
			->where('id_customers !=', $customer_id)
			->get('customers')
			->row();

		if ($existing_customer) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', 'Email sudah digunakan oleh customer lain.');
			redirect(base_url('admin/resellers/detail/' . $customer_id));
			return;
		}

		$this->db->trans_start();
		$province_id = (int) $this->input->post('province_id', true);
		$district_id = (int) $this->input->post('district_id', true);
		$subdistrict_id = (int) $this->input->post('subdistrict_id', true);
		$shipping_province = $this->get_province_name($province_id);
		$shipping_district = $this->get_district_name($district_id);
		$shipping_subdistrict = $this->get_subdistrict_name($subdistrict_id);

		try {
			$data = [
				'name' => $this->input->post('customer_name', true),
				'email' => $this->input->post('customer_email', true),
				'phone' => $this->input->post('customer_phone', true),
				'birthday' => $this->input->post('customer_birthdate', true),
				'sex_type' => $this->input->post('customer_gender', true),
				'recipient_name' => $this->input->post('customer_name', true),
				'shipping_name' => $this->input->post('customer_name', true),
				'shipping_address' => $this->input->post('customer_address', true),
				'shipping_id_province' => $province_id,
				'shipping_id_district' => $district_id,
				'shipping_id_subdistrict' => $subdistrict_id,
				'shipping_province' => $shipping_province,
				'shipping_district' => $shipping_district,
				'shipping_subdistrict' => $shipping_subdistrict,
				'shipping_country' => 'Indonesia',
				'shipping_phone' => $this->input->post('customer_phone', true),
				'shipping_postcode' => $this->input->post('customer_postcode', true),
				'reseller_id' => $reseller_id,
				'status' => $status,
			];

			// Jika password diisi, update password
			$password = $this->input->post('customer_password', true);
			if (!empty($password)) {
				$data['password'] = $this->customer_m->hash($password);
			}

			// Update data customer berdasarkan ID
			$this->db->where('id_customers', $customer_id);
			$this->db->update('customers', $data);

			if ($this->db->trans_status() === false) {
				throw new Exception('Database error occurred');
			}

			$this->db->trans_commit();

			// Set flashdata dan redirect
			$this->session->set_flashdata('message_type', 'success');
			$this->session->set_flashdata('message', 'Data retailer berhasil diperbarui!');
			redirect(base_url('admin/resellers/manage'));
		} catch (Exception $e) {
			$this->db->trans_rollback();

			// Set flashdata untuk error dan redirect
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', $e->getMessage());
			redirect(base_url('admin/resellers/detail/' . $customer_id));
		}
	}

	public function update_retailer_type()
	{
		// Ambil data dari POST request
		$reseller_id = (int) $this->input->post('reseller_id', true);
		$type_name = $this->input->post('type_name', true);
		$type_minimum_purchase = (int) $this->input->post('type_minimum_purchase', true);
		$type_target_point = (int) $this->input->post('type_target_point', true);
		$type_status = $this->input->post('type_status', true);

		// Pastikan reseller_id valid
		if ($reseller_id <= 0) {
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', 'ID reseller tidak valid.');
			redirect(base_url('admin/resellers/type'));
			return;
		}

		// Data yang akan diupdate
		$data = [
			'reseller_name' => $type_name,
			'minimum_order' => $type_minimum_purchase,
			'target_point' => $type_target_point,
			'active' => $type_status,
		];

		// Mulai transaksi database
		$this->db->trans_start();

		try {
			// Update data reseller berdasarkan reseller_id
			$this->db->where('id_resellers', $reseller_id);
			$this->db->update('resellers', $data);

			// Periksa apakah transaksi berhasil
			if ($this->db->trans_status() === false) {
				throw new Exception('Terjadi kesalahan saat memperbarui reseller.');
			}

			$this->db->trans_commit();

			// Set flashdata dan redirect
			$this->session->set_flashdata('message_type', 'success');
			$this->session->set_flashdata('message', 'Jenis Retailer berhasil diperbarui!');
			redirect(base_url('admin/resellers/type'));
		} catch (Exception $e) {
			$this->db->trans_rollback();

			// Set flashdata untuk error dan redirect
			$this->session->set_flashdata('message_type', 'error');
			$this->session->set_flashdata('message', $e->getMessage());
			redirect(base_url('admin/resellers/type/detail/' . $reseller_id));
		}
	}


	// Fetch customer data
	public function get_retailers()
	{
		$sort = $this->input->get('sort', true);
		$dateFilter = $this->input->get('date_filter', true);
		$startDate = $this->input->get('start_date', true);
		$endDate = $this->input->get('end_date', true);

		$isMale = filter_var($this->input->get('isMale', true), FILTER_VALIDATE_BOOLEAN);
		$isFemale = filter_var($this->input->get('isFemale', true), FILTER_VALIDATE_BOOLEAN);
		$isOther = filter_var($this->input->get('isOther', true), FILTER_VALIDATE_BOOLEAN);

		$bornJan = filter_var($this->input->get('bornJan', true), FILTER_VALIDATE_BOOLEAN);
		$bornFeb = filter_var($this->input->get('bornFeb', true), FILTER_VALIDATE_BOOLEAN);
		$bornMar = filter_var($this->input->get('bornMar', true), FILTER_VALIDATE_BOOLEAN);
		$bornApr = filter_var($this->input->get('bornApr', true), FILTER_VALIDATE_BOOLEAN);
		$bornMay = filter_var($this->input->get('bornMay', true), FILTER_VALIDATE_BOOLEAN);
		$bornJun = filter_var($this->input->get('bornJun', true), FILTER_VALIDATE_BOOLEAN);
		$bornJul = filter_var($this->input->get('bornJul', true), FILTER_VALIDATE_BOOLEAN);
		$bornAug = filter_var($this->input->get('bornAug', true), FILTER_VALIDATE_BOOLEAN);
		$bornSep = filter_var($this->input->get('bornSep', true), FILTER_VALIDATE_BOOLEAN);
		$bornOct = filter_var($this->input->get('bornOct', true), FILTER_VALIDATE_BOOLEAN);
		$bornNov = filter_var($this->input->get('bornNov', true), FILTER_VALIDATE_BOOLEAN);
		$bornDec = filter_var($this->input->get('bornDec', 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('
				c.id_customers,
				c.name,
				c.title,
				c.sex_type,
				c.email,
				c.birthday,
				c.shipping_address as address,
				c.shipping_phone as phone,
				c.join_date,
				c.shipping_province,
				c.shipping_district,
				c.shipping_subdistrict,
				c.shipping_country,
				c.shipping_postcode,
				c.current_pointreward,
				c.status,
				COUNT(CASE WHEN o.payment_status = 5 THEN o.id_orders ELSE NULL END) as total_orders,
				SUM(CASE WHEN o.payment_status = 5 THEN o.grand_total_amount ELSE 0 END) as total_spent
			');
		$this->db->from('customers c');
		$this->db->join('orders o', 'c.id_customers = o.customer_id', 'left');
		$this->db->where('(c.reseller_id IS NOT NULL OR c.reseller_id != "")');
		$this->db->where('c.type', 'regular');

		// Filter berdasarkan jenis kelamin
		if ($isMale || $isFemale || $isOther) {
			$sexTypes = [];

			if ($isMale) {
				$sexTypes[] = 'male';
			}
			if ($isFemale) {
				$sexTypes[] = 'female';
			}
			if ($isOther) {
				$sexTypes[] = 'others';
			}

			if (!empty($sexTypes)) {
				$this->db->where_in('c.sex_type', $sexTypes);
			}
		}

		// Filter berdasarkan bulan lahir
		if (
			$bornJan || $bornFeb || $bornMar || $bornApr || $bornMay || $bornJun ||
			$bornJul || $bornAug || $bornSep || $bornOct || $bornNov || $bornDec
		) {

			$months = [];

			if ($bornJan) $months[] = '01';
			if ($bornFeb) $months[] = '02';
			if ($bornMar) $months[] = '03';
			if ($bornApr) $months[] = '04';
			if ($bornMay) $months[] = '05';
			if ($bornJun) $months[] = '06';
			if ($bornJul) $months[] = '07';
			if ($bornAug) $months[] = '08';
			if ($bornSep) $months[] = '09';
			if ($bornOct) $months[] = '10';
			if ($bornNov) $months[] = '11';
			if ($bornDec) $months[] = '12';

			if (!empty($months)) {
				$this->db->group_start();
				foreach ($months as $month) {
					$this->db->or_like('c.birthday', '-' . $month . '-');
				}
				$this->db->group_end();
			}
		}

		// Filter berdasarkan tanggal join
		if ($dateFilter) {
			switch ($dateFilter) {
				case 'today':
					$this->db->where('DATE(c.join_date) = CURDATE()');
					break;
				case 'yesterday':
					$this->db->where('DATE(c.join_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');
					break;
				case 'last7days':
					$this->db->where('c.join_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');
					break;
				case 'last30days':
					$this->db->where('c.join_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');
					break;
				case 'thisMonth':
					$this->db->where('MONTH(c.join_date) = MONTH(CURDATE()) AND YEAR(c.join_date) = YEAR(CURDATE())');
					break;
				case 'thisYear':
					$this->db->where('YEAR(c.join_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(c.join_date) >=', $startDate);
							$this->db->where('DATE(c.join_date) <=', $endDate);
						}
					}
					break;
			}
		}

		if (!empty($searchTerm)) {
			$this->db->group_start();
			$this->db->like('c.name', $searchTerm);
			$this->db->like('c.recipient_name', $searchTerm);
			$this->db->or_like('c.sex_type', $searchTerm);
			$this->db->or_like('c.email', $searchTerm);
			$this->db->or_like('c.address', $searchTerm);
			$this->db->or_like('c.shipping_address', $searchTerm);
			$this->db->or_like('c.shipping_province', $searchTerm);
			$this->db->or_like('c.shipping_district', $searchTerm);
			$this->db->or_like('c.shipping_subdistrict', $searchTerm);
			$this->db->or_like('c.shipping_phone', $searchTerm);

			// Untuk bulan lahir, perlu logika ekstra
			// Mari coba pencocokan dengan nama bulan (January, February, dll.)
			$monthMap = [
				'january' => '01',
				'februari' => '02',
				'march' => '03',
				'april' => '04',
				'may' => '05',
				'june' => '06',
				'july' => '07',
				'august' => '08',
				'september' => '09',
				'october' => '10',
				'november' => '11',
				'december' => '12'
			];

			$lowerSearchTerm = strtolower($searchTerm);
			foreach ($monthMap as $monthName => $monthNum) {
				if (strpos($monthName, $lowerSearchTerm) !== false) {
					$this->db->or_like('c.birthday', '-' . $monthNum . '-');
				}
			}

			$this->db->group_end();
		}

		// Group by untuk menghindari duplikasi data customer
		$this->db->group_by('c.id_customers');

		// Apply sorting
		if ($sort) {
			switch ($sort) {
				case 'paling_baru':
					$this->db->order_by('c.join_date', 'DESC');
					break;
				case 'paling_lama':
					$this->db->order_by('c.join_date', 'ASC');
					break;
				case 'royal':
					$this->db->order_by('total_spent', 'DESC');
					break;
				case 'loyal':
					$this->db->order_by('total_orders', 'DESC');
					break;
				default:
					// Default sort by newest
					$this->db->order_by('c.join_date', 'DESC');
			}
		} else {
			// Default sort by newest join date
			$this->db->order_by('c.join_date', 'DESC');
		}

		// Apply pagination
		$this->db->limit($limit, $offset);

		// Execute query
		$query = $this->db->get();
		$all_customers = $query->result();

		// Post-processing data
		foreach ($all_customers as $customer) {
			// Format tanggal
			$customer->join_date_formatted = date('d M Y H:i', strtotime($customer->join_date));

			// Format birthday jika ada
			if (!empty($customer->birthday) && strtotime($customer->birthday)) {
				$customer->birthday_formatted = date('d M Y', strtotime($customer->birthday));
				$customer->birth_month = date('F', strtotime($customer->birthday));

				$birthDate = new DateTime($customer->birthday);
				$today = new DateTime();
				$age = $today->diff($birthDate)->y;
				$customer->age = $age;
			} else {
				$customer->birthday_formatted = 'Not set';
				$customer->birth_month = 'Unknown';
				$customer->age = null;
			}

			// Format sex_type untuk tampilan
			switch ($customer->sex_type) {
				case 'male':
					$customer->sex_type_text = 'Male';
					$customer->sex_type_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded';
					break;
				case 'female':
					$customer->sex_type_text = 'Female';
					$customer->sex_type_class = 'bg-pink-100 text-pink-700 px-2 py-1 rounded';
					break;
				case 'other':
					$customer->sex_type_text = 'Other';
					$customer->sex_type_class = 'bg-purple-100 text-purple-700 px-2 py-1 rounded';
					break;
				default:
					$customer->sex_type_text = 'Not specified';
					$customer->sex_type_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded';
			}

			// Format status
			if ($customer->status == 1) {
				$customer->status_text = 'Active';
				$customer->status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded';
			} else {
				$customer->status_text = 'Inactive';
				$customer->status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded';
			}

			// Tambahkan informasi alamat lengkap
			$customer->full_address = trim($customer->address);

			if (!empty($customer->subdistrict)) {
				$customer->full_address .= ', ' . $customer->subdistrict;
			}

			if (!empty($customer->district)) {
				$customer->full_address .= ', ' . $customer->district;
			}

			if (!empty($customer->province)) {
				$customer->full_address .= ', ' . $customer->province;
			}

			if (!empty($customer->country)) {
				$customer->full_address .= ', ' . $customer->country;
			}

			if (!empty($customer->postcode)) {
				$customer->full_address .= ' ' . $customer->postcode;
			}

			// Default jika tidak ada order
			if ($customer->total_orders === null) {
				$customer->total_orders = 0;
				$customer->total_spent = 0;
			}

			// Format total spent
			$customer->total_spent_formatted = 'Rp ' . number_format($customer->total_spent, 0, ',', '.');
		}

		// Get total number of customers (for pagination)
		$this->db->select('COUNT(DISTINCT c.id_customers) as total');
		$this->db->from('customers c');

		// Apply the same filters for counting
		if ($isMale || $isFemale || $isOther) {
			$sexTypes = [];

			if ($isMale) {
				$sexTypes[] = 'male';
			}
			if ($isFemale) {
				$sexTypes[] = 'female';
			}
			if ($isOther) {
				$sexTypes[] = 'other';
			}

			if (!empty($sexTypes)) {
				$this->db->where_in('c.sex_type', $sexTypes);
			}
		}

		// Filter berdasarkan bulan lahir untuk counting
		if (
			$bornJan || $bornFeb || $bornMar || $bornApr || $bornMay || $bornJun ||
			$bornJul || $bornAug || $bornSep || $bornOct || $bornNov || $bornDec
		) {

			$months = [];

			if ($bornJan) $months[] = '01';
			if ($bornFeb) $months[] = '02';
			if ($bornMar) $months[] = '03';
			if ($bornApr) $months[] = '04';
			if ($bornMay) $months[] = '05';
			if ($bornJun) $months[] = '06';
			if ($bornJul) $months[] = '07';
			if ($bornAug) $months[] = '08';
			if ($bornSep) $months[] = '09';
			if ($bornOct) $months[] = '10';
			if ($bornNov) $months[] = '11';
			if ($bornDec) $months[] = '12';

			if (!empty($months)) {
				$this->db->group_start();
				foreach ($months as $month) {
					$this->db->or_like('c.birthday', '-' . $month . '-');
				}
				$this->db->group_end();
			}
		}

		// Filter berdasarkan tanggal join untuk counting
		if ($dateFilter) {
			switch ($dateFilter) {
				case 'today':
					$this->db->where('DATE(c.join_date) = CURDATE()');
					break;
				case 'yesterday':
					$this->db->where('DATE(c.join_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)');
					break;
				case 'last7days':
					$this->db->where('c.join_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');
					break;
				case 'last30days':
					$this->db->where('c.join_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)');
					break;
				case 'thisMonth':
					$this->db->where('MONTH(c.join_date) = MONTH(CURDATE()) AND YEAR(c.join_date) = YEAR(CURDATE())');
					break;
				case 'thisYear':
					$this->db->where('YEAR(c.join_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(c.join_date) >=', $startDate);
							$this->db->where('DATE(c.join_date) <=', $endDate);
						}
					}
					break;
			}
		}

		$count_query = $this->db->get();
		$count_result = $count_query->row();
		$total_customers = $count_result->total;

		// Prepare pagination info
		$total_pages = ceil($total_customers / $limit);

		$pagination = [
			'current_page' => $page,
			'total_pages' => $total_pages,
			'total_records' => $total_customers,
			'limit' => $limit
		];

		foreach ($all_customers as $customer) {
			$customer->_pagination = $pagination;
		}

		// Return JSON response langsung dari all_customers
		echo json_encode($all_customers);
	}

	public function get_types()
	{
		$all_types = $this->db->select('*')
			->from('resellers')
			->order_by('id_resellers', 'ASC')
			->get()
			->result();

		echo json_encode($all_types);
	}

	private function getProvinces()
	{
		return $this->db->select('rajaongkir_province_id as id, province as name')
			->from('indonesia_provinces')
			->order_by('province', 'ASC')
			->get()
			->result();
	}

	public function get_province_name($id)
	{
		return $this->db->select('province')
			->where('rajaongkir_province_id', $id)
			->get('indonesia_provinces')
			->row('province');
	}

	public function get_district_name($id)
	{
		return $this->db->select('district')
			->where('rajaongkir_id_district', $id)
			->get('indonesia_districts')
			->row('district');
	}

	public function get_subdistrict_name($id)
	{
		return $this->db->select('subdistrict')
			->where('rajaongkir_id_subdistrict', $id)
			->get('indonesia_subdistricts')
			->row('subdistrict');
	}

	private function getResellerTypes()
	{
		return $this->db->select('*')
			->from('resellers')
			->order_by('id_resellers', 'ASC')
			->get()
			->result();
	}

	private function getResellerTypeById($type_id)
	{
		return $this->db->select('*')
			->from('resellers')
			->where('id_resellers', $type_id)
			->get()
			->row();
	}

	private function getDistrictsByProvince($provinceId)
	{
		if (!$provinceId) return [];

		return $this->db->select('rajaongkir_id_district as id, district as name')
			->from('indonesia_districts')
			->where('indonesia_id_province', $provinceId)
			->order_by('district', 'ASC')
			->get()
			->result();
	}

	private function getSubdistrictsByDistrict($districtId)
	{
		if (!$districtId) return [];

		return $this->db->select('rajaongkir_id_subdistrict as id, subdistrict as name')
			->from('indonesia_subdistricts')
			->where('indonesia_id_district', $districtId)
			->order_by('subdistrict', 'ASC')
			->get()
			->result();
	}

	//to edit reseller in admin
	public function edit($id = NULL)
	{

		//check if id exist. If not exist, show 404.
		$this->db->select('id_resellers')->from('resellers')->where('id_resellers', $id);
		$count_reseller = $this->db->get()->num_rows();

		if ($count_reseller == 0) {
			//reseller not exist
			show_404();
		}

		//get reseller detail data
		$this->db->select('*')->from('resellers')->where('id_resellers', $id);
		$this->data['resellers'] = $this->db->get()->row();

		$this->reseller_current_id = (int) $id;

		//validation check in action 

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

		if ($this->form_validation->run($this) == TRUE) {

			$data = array(
				'reseller_name' => $this->security->xss_clean($this->input->post('reseller_name')),
				'minimum_order' => $this->input->post('minimum_order'),
				'target_point' => $this->input->post('target_point'),
				//'voucher_valid' => $this->input->post('voucher_valid'),
				//'pointrewards_valid' => $this->input->post('pointrewards_valid'),
				'active' => $this->input->post('active')
			);

			//if ($this->input->post('global_discount')) {
			//	$data['global_discount'] = $this->security->xss_clean($this->input->post('global_discount'));
			//} else {
			//	$data['global_discount'] = NULL;
			//}

			$this->db->where('id_resellers', $id);
			$this->db->update('resellers', $data);

			$reseller_name = $this->input->post('reseller_name');

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User mengedit tier retailer (' . $reseller_name . ')';

			log_activity($user_id, $activity);

			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Reseller Edit Successful</p>');

			redirect('admin/resellers');
		}

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


	//to delete a reseller
	public function delete($id)
	{

		//check if id exist. If not exist, show 404.
		$this->db->select('id_resellers')->from('resellers')->where('id_resellers', $id);
		$count = $this->db->get()->num_rows();
		if ($count == 0) {
			show_404();
		}

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

		$this->db->select('reseller_name');
		$this->db->from('resellers');
		$this->db->where('id_resellers', $id);
		$query = $this->db->get();
		$data = $query->row();

		if ($data) {
			$activity = 'User menghapus tier retailer (' . $data->reseller_name . ')';
		} else {
			$activity = 'User menghapus tier retailer (' . $id . ')';
		}
		log_activity($user_id, $activity);

		//delete reseller
		$this->reseller_m->delete($id);

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

	//callback function validation register new email
	public function cek_reseller_name($str)
	{

		$num_rows = $this->reseller_m->cek_existing_reseller($str,  $this->reseller_current_id);

		if ($num_rows != 0) {
			$this->form_validation->set_message('cek_reseller_name', 'Reseller Type already exist !');
			return FALSE;
		} else {
			return TRUE;
		}
	}

	public function product_price()
	{
		// Jika form pencarian dikirimkan
		if ($this->input->post('keyword')) {
			$keyword = $this->input->post('keyword');

			// Lakukan pencarian dengan menggunakan keyword pada kolom 'title'
			$this->db->select('*');
			$this->db->from('product_details');
			$this->db->join('products', 'product_details.product_id = products.id_products');
			$this->db->like('products.title', $keyword); // Mengubah kolom yang dicari menjadi 'title'
			$query = $this->db->get();

			$this->data['products'] = $query->result();
		} else {
			//pagination in action. 100 results per page
			$this->load->library('pagination');
			$config = array();
			$this->load->helper('pagination_helper');
			$config = pagination_format(); //function from helper file
			$config['base_url'] = base_url() . 'admin/resellers/product_price/';
			$config['per_page'] = 50;
			$config['uri_segment'] = 4;
			//get total rows record count
			$this->db->select('id')->from('product_details');
			$config['total_rows'] = $this->db->get()->num_rows();
			$this->pagination->initialize($config);
			//get products
			$this->db->select('*')->from('product_details')->limit($config['per_page'], $this->uri->segment($config['uri_segment']));
			$this->data['products'] = $this->db->get()->result();
			$this->data['use_pagination'] = 'yes';
		}

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



	public function update_product_price()
	{

		if (!isset($_POST['update_price'])) {
			redirect('admin/resellers/product_price');
		}

		$price_array = $this->input->post('price');

		$quantity_array = $this->input->post('quantity');

		foreach ($price_array as $product_detail_id => $item_array) {

			foreach ($item_array as $reseller_id => $price) {

				//check if product detail id and reseller id already exist, if yes, then update, else insert
				$this->db->select('id_resellers_price')->from('resellers_price')->where('reseller_id', $reseller_id)->where('product_detail_id', $product_detail_id);
				$count = $this->db->get()->num_rows();

				if ($count == 0) {
					//not exist yet. so insert new data
					$data = array(
						'product_detail_id' => $this->security->xss_clean($product_detail_id),
						'reseller_id' => $this->security->xss_clean($reseller_id), //get the key only,
						'price' => $this->security->xss_clean($price[0])
					);
					$this->db->insert('resellers_price', $data);
				} else {
					//already exist yet. so update data
					$data = array(
						'price' => $this->security->xss_clean($price[0])
					);
					$this->db->where('product_detail_id', $product_detail_id);
					$this->db->where('reseller_id', $reseller_id);
					$this->db->update('resellers_price', $data);
				}
			}
		}

		foreach ($quantity_array as $product_detail_id => $item_array) {

			foreach ($item_array as $reseller_id => $quantity) {

				$data = array(
					'min_quantity' => $this->security->xss_clean($quantity[0])
				);
				$this->db->where('product_detail_id', $product_detail_id);
				$this->db->where('reseller_id', $reseller_id);
				$this->db->update('resellers_price', $data);
			}
		}

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

		$activity = 'User mengubah harga retailer';

		log_activity($user_id, $activity);

		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Reseller Price & Quantity Edit Successful</p>');

		redirect('admin/resellers/product_price');
	}
	public function special_price_rule()
	{

		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config = array();
		$this->load->helper('pagination_helper');
		$config = pagination_format(); //function from helper file
		$config['base_url'] = base_url() . 'admin/resellers/product_price/';
		$config['per_page'] = 50;
		$config['uri_segment'] = 4;
		//get total rows record count
		$this->db->select('id')->from('product_details');
		$config['total_rows'] = $this->db->get()->num_rows();
		$this->pagination->initialize($config);
		//get products
		$this->db->select('*')->from('product_details')->limit($config['per_page'], $this->uri->segment($config['uri_segment']));
		$this->data['products'] = $this->db->get()->result();
		$this->data['use_pagination'] = 'yes';

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

	public function lists()
	{

		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config = array();
		$this->load->helper('pagination_helper');
		$config = pagination_format();
		$config['base_url'] = base_url() . 'admin/resellers/lists';

		//get total rows
		$this->db->select('id_customers')->from('customers')->where('reseller_id !=', NULL);
		$config['total_rows'] = $this->db->get()->num_rows();

		$config['per_page'] = 200;
		$config['uri_segment'] = 4;
		$this->pagination->initialize($config);

		//fetch all customers
		$this->db->select('*')->from('customers')->where('reseller_id !=', NULL)->order_by('join_date', 'DESC')->limit($config['per_page'], $this->uri->segment(4));
		$this->data['customers'] = $this->db->get()->result();

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

	public function add_reseller()
	{

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

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

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

		//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['provinces'] = $this->db->get()->result();

		//get all countries data from countries table
		$this->db->select('*')->from('countries')->order_by('id_countries', 'ASC');
		$this->data['countries'] = $this->db->get()->result();

		//validation in action
		//if country id 0 (indonesia) regular validation rule
		if ($this->input->post('country') == '0') {
			$config = $this->customer_m->admin_rules_add;
		} else {
			//rules for international country
			$config = $this->customer_m->admin_rules_international;
		}

		$config['register_password']['rules'] .= '|required'; //for new user password is required
		$config['retype_register_password']['rules'] .= '|required|matches[register_password]'; //for new user password is required

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

		if ($this->form_validation->run($this) == TRUE) {

			//hash input password
			$password = $this->customer_m->hash($this->input->post('register_password'));

			$data = array(
				'name' => $this->security->xss_clean($this->input->post('name')),
				'shipping_name' => $this->security->xss_clean($this->input->post('name')),
				'recipient_name' => $this->security->xss_clean($this->input->post('name')),
				'title' => $this->input->post('title'),
				'email' => $this->security->xss_clean($this->input->post('email')),
				'password' => $password,
				'birthday' => $this->security->xss_clean($this->input->post('birthday')),
				'address' => $this->security->xss_clean($this->input->post('address')),
				'shipping_address' => $this->security->xss_clean($this->input->post('address')),
				'postcode' => $this->security->xss_clean($this->input->post('postcode')),
				'shipping_postcode' => $this->security->xss_clean($this->input->post('postcode')),
				'phone' => $this->security->xss_clean($this->input->post('phone')),
				'shipping_phone' => $this->security->xss_clean($this->input->post('phone')),
				'status' => $this->input->post('status'),
				'dropship' => $this->input->post('dropship'),
				'is_first' => '1'
			);

			if ($this->input->post('reseller_id')) {
				$data['reseller_id'] = $this->input->post('reseller_id');
			} else {
				$data['reseller_id'] = NULL;
			}

			if ($this->input->post('country') == '0') {

				//this is indonesia
				$data['id_province'] = (int) $this->input->post('province');
				$data['shipping_id_province'] = (int) $this->input->post('province');
				$data['id_district'] = (int) $this->input->post('district');
				$data['shipping_id_district'] = (int) $this->input->post('district');
				$data['id_subdistrict'] = (int) $this->input->post('subdistrict');
				$data['shipping_id_subdistrict'] = (int) $this->input->post('subdistrict');
				$data['id_country'] =  0;
				$data['shipping_id_country'] =  0;
				$data['country'] =  'Indonesia';
				$data['shipping_country'] =  'Indonesia';

				//get province name
				$this->db->select('province')->from('indonesia_provinces')->where('rajaongkir_province_id', (int) $this->input->post('province'));
				$data['province'] = $this->db->get()->row()->province;
				$data['shipping_province'] = $data['province'];

				//get district name
				$this->db->select('district')->from('indonesia_districts')->where('rajaongkir_id_district', (int) $this->input->post('district'));
				$data['district'] = $this->db->get()->row()->district;
				$data['shipping_district'] = $data['district'];

				//get subdistrict name
				$this->db->select('subdistrict')->from('indonesia_subdistricts')->where('rajaongkir_id_subdistrict', (int) $this->input->post('subdistrict'));
				$data['subdistrict'] = $this->db->get()->row()->subdistrict;
				$data['shipping_subdistrict'] = $data['subdistrict'];
			} else {

				//this is not indonesia
				//get country name
				$this->db->select('country')->from('countries')->where('id_countries', $this->input->post('country'));
				$data['country'] = $this->db->get()->row()->country;
				$data['shipping_country'] = $data['country'];
				$data['id_country'] =  (int) $this->input->post('country');
				$data['shipping_id_country'] =  (int) $this->input->post('country');
			}

			//add new point rewards to customer if rule exist
			$this->db->select('first_customer')->from('point_rewards')->where('id_point_rewards', 1);
			$point_rewards = (int) $this->db->get()->row()->first_customer;

			if ($point_rewards > 0) {
				$data['current_pointreward'] = $point_rewards;
			}

			//save customer data
			$this->db->insert('customers', $data);
			$customer_id = $this->db->insert_id();

			//email welcome message to customer..
			//get customer data
			$this->db->select('name, email, reseller_id')->from('customers')->where('id_customers', $customer_id);
			$customer_data = $this->db->get()->row();
			$data['customer_name'] = $customer_data->name;
			$data['customer_email'] = $customer_data->email;
			$data['customer_status'] = $customer_data->reseller_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['register_password'] = $this->input->post('register_password');

			//get bonus pointrewards
			if ($point_rewards > 0) {
				$data['pointrewards'] = $point_rewards;
			}
			//Send Mail
			$email_data['customer_name'] = $customer_data->name;
			$email_data['email'] = $customer_data->email;
			$email_data['customer_status'] = $customer_data->reseller_id;
			$email_data['subject'] = 'Selamat Datang Teman Bisnis Asmara';
			$view_file = 'email/indonesian/account_retailer';

			$resellers_name = $this->input->post('name');
			$resellers_tier = $this->input->post('reseller_id');

			$this->db->select('reseller_name');
			$this->db->from('resellers');
			$this->db->where('id_resellers', $resellers_tier);
			$query = $this->db->get();
			$data = $query->row();

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User menambah retailer ' . $resellers_name .  ' (' . $data->reseller_name . ')';

			log_activity($user_id, $activity);

			$this->send_email($view_file, $email_data);
			//$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($website_data->from_email, $website_data->website_name);
			//$this->email->to($data['customer_email']);
			//$this->email->subject('Welcome');
			//$email = $this->load->view('email/indonesian/account', $data, TRUE);
			//$this->email->message($email);
			//$this->email->send();
			//----end send email 



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

			redirect('admin/resellers/lists');
		}

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


	//to edit customer in admin
	public function edit_reseller($id = NULL)
	{

		//check if id exist. If not exist, show 404.
		$this->db->select('id_customers')->from('customers')->where('id_customers', $id);
		$count_customer = $this->db->get()->num_rows();

		if ($count_customer == 0) {
			//customer not exist
			show_404();
		}

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

		$this->data['shipping'] = $this->customer_m->get_shipping($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['provinces'] = $this->db->get()->result();

		//get all countries data from countries table
		$this->db->select('*')->from('countries')->order_by('id_countries', 'ASC');
		$this->data['countries'] = $this->db->get()->result();

		//get current country
		$current_country_id = $this->data['shipping']->id_country;
		$this->data['current_country_id'] = $current_country_id;

		//get current province
		$current_province_id = $this->data['shipping']->id_province;
		$this->data['current_province_id'] = $current_province_id;

		//get district lists
		$this->db->select('rajaongkir_id_district, district')->from('indonesia_districts')->where('indonesia_id_province', $current_province_id);
		$this->data['district_lists'] = $this->db->get()->result();

		$current_district_id = $this->data['shipping']->id_district;
		$this->data['current_district_id'] = $current_district_id;

		//get all initial subdistricts lists
		$this->db->select('rajaongkir_id_subdistrict, subdistrict')->from('indonesia_subdistricts')->where('indonesia_id_district', $current_district_id);
		$this->data['subdistrict_lists'] = $this->db->get()->result();

		$current_subdistrict_id = $this->data['shipping']->id_subdistrict;
		$this->data['current_subdistrict_id'] = $current_subdistrict_id;

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

		$this->customer_current_id = (int) $id;

		//validation check in action 
		//if country id 0 (indonesia) regular validation rule
		if ($this->input->post('country') == '0') {
			$config = $this->customer_m->admin_rules_edit;
		} else {
			//rules for international country
			$config = $this->customer_m->admin_rules_international;
		}

		if ($this->input->post('register_password')) {
			$config['retype_register_password']['rules'] .= '|matches[register_password]'; //for new user password is required
		}

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

		if ($this->form_validation->run($this) == TRUE) {

			$data = array(
				'name' => $this->security->xss_clean($this->input->post('name')),
				'shipping_name' => $this->security->xss_clean($this->input->post('name')),
				'recipient_name' => $this->security->xss_clean($this->input->post('name')),
				'title' => $this->input->post('title'),
				'email' => $this->security->xss_clean($this->input->post('email')),
				'birthday' => $this->security->xss_clean($this->input->post('birthday')),
				'address' => $this->security->xss_clean($this->input->post('address')),
				'shipping_address' => $this->security->xss_clean($this->input->post('address')),
				'postcode' => $this->security->xss_clean($this->input->post('postcode')),
				'shipping_postcode' => $this->security->xss_clean($this->input->post('postcode')),
				'phone' => $this->security->xss_clean($this->input->post('phone')),
				'shipping_phone' => $this->security->xss_clean($this->input->post('phone')),
				'status' => $this->input->post('status'),
				'current_pointreward' => $this->input->post('credit'),
				'dropship' => $this->input->post('dropship')
			);

			if ($this->input->post('reseller_id')) {
				$data['reseller_id'] = $this->input->post('reseller_id');
			} else {
				$data['reseller_id'] = NULL;
			}

			if ($this->input->post('register_password')) {
				//hash input password
				$password = $this->customer_m->hash($this->input->post('register_password'));
				$data['password'] = $password;
			}

			if ($this->input->post('country') == '0') {

				//this is indonesia
				$data['id_province'] = (int) $this->input->post('province');
				$data['shipping_id_province'] = (int) $this->input->post('province');
				$data['id_district'] = (int) $this->input->post('district');
				$data['shipping_id_district'] = (int) $this->input->post('district');
				$data['id_subdistrict'] = (int) $this->input->post('subdistrict');
				$data['shipping_id_subdistrict'] = (int) $this->input->post('subdistrict');
				$data['id_country'] =  0;
				$data['shipping_id_country'] =  0;
				$data['country'] =  'Indonesia';
				$data['shipping_country'] =  'Indonesia';

				//get province name
				$this->db->select('province')->from('indonesia_provinces')->where('rajaongkir_province_id', (int) $this->input->post('province'));
				$data['province'] = $this->db->get()->row()->province;
				$data['shipping_province'] = $data['province'];

				//get district name
				$this->db->select('district')->from('indonesia_districts')->where('rajaongkir_id_district', (int) $this->input->post('district'));
				$data['district'] = $this->db->get()->row()->district;
				$data['shipping_district'] = $data['district'];

				//get subdistrict name
				$this->db->select('subdistrict')->from('indonesia_subdistricts')->where('rajaongkir_id_subdistrict', (int) $this->input->post('subdistrict'));
				$data['subdistrict'] = $this->db->get()->row()->subdistrict;
				$data['shipping_subdistrict'] = $data['subdistrict'];
			} else {

				//this is not indonesia
				//get country name by country from RajaOngkir 
				//get country name
				$this->db->select('country')->from('countries')->where('id_countries', $this->input->post('country'));
				$data['country'] = $this->db->get()->row()->country;
				$data['shipping_country'] = $data['country'];
				$data['id_country'] =  (int) $this->input->post('country');
				$data['shipping_id_country'] =  (int) $this->input->post('country');
				$data['id_province'] = NULL;
				$data['id_district'] = NULL;
				$data['id_subdistrict'] = NULL;
				$data['province'] = NULL;
				$data['district'] = NULL;
				$data['subdistrict'] = NULL;
				$data['shipping_id_province'] = NULL;
				$data['shipping_id_district'] = NULL;
				$data['shipping_id_subdistrict'] = NULL;
				$data['shipping_province'] = NULL;
				$data['shipping_district'] = NULL;
				$data['shipping_subdistrict'] = NULL;
			}

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

			$resellers_name = $this->input->post('name');
			$resellers_tier = $this->input->post('reseller_id');

			$this->db->select('reseller_name');
			$this->db->from('resellers');
			$this->db->where('id_resellers', $resellers_tier);
			$query = $this->db->get();
			$data = $query->row();

			$user_id = $this->session->userdata('admin')['id'];
			$activity = 'User mengedit retailer ' . $resellers_name .  ' (' . $data->reseller_name . ')';

			log_activity($user_id, $activity);

			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Reseller Edit Successful</p>');

			redirect('admin/resellers/lists');
		}

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


	//to delete a reseller
	public function delete_reseller($id)
	{

		//check if id exist. If not exist, show 404.
		$this->db->select('id_customers')->from('customers')->where('id_customers', $id);
		$count = $this->db->get()->num_rows();

		if ($count == 0) {
			show_404();
		}

		$this->db->select('name, reseller_id');
		$this->db->from('customers');
		$this->db->where('id_customers', $id);
		$query = $this->db->get();
		$data = $query->row();

		$this->db->select('reseller_name');
		$this->db->from('resellers');
		$this->db->where('id_resellers', $data->reseller_id);
		$query1 = $this->db->get();
		$data1 = $query1->row();

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

		if ($data) {
			$activity = 'User menghapus retailer ' . $data->name .  ' (' . $data1->reseller_name . ')';
		} else {
			$activity = 'User menghapus retailer (' . $id . ')';
		}

		log_activity($user_id, $activity);

		//delete customer
		$this->load->model('customer_m');
		$this->customer_m->delete($id);

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



	//callback function validation register new email
	public function cek_email($str)
	{

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

		$num_rows = $this->customer_m->cek_existing_email($str,  $this->customer_current_id);

		if ($num_rows != 0) {
			$this->form_validation->set_message('cek_email', 'Email already exist !');
			return FALSE;
		} else {
			return TRUE;
		}
	}
}

https://t.me/RX1948 - 2025