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/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //proc/self/root/var/www/laciasmara.com/public_html/shop/application/controllers/Account.php
<?php

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



class Account extends Customer_Controller

{

	function __construct()

	{



		parent::__construct();



		if (isset($this->session->userdata('customer')['customer_type'])) {

			if ($this->session->userdata('customer')['customer_type'] == 'guest') {

				redirect('welcome');

			}

		}

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

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

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

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

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

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

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

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

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

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

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

		}

		$loginUrl = $this->googleclient->getLoginUrl();



		$this->data_footer['googleUrl'] = $loginUrl;

		$this->data_footer = [

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];

	}





	function index()

	{

		$this->visitortracking->trackVisitor();



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

		}

		$data['content_view'] = 'account/profile_new';



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Personalize your profile and start the pleasure adventure! All the fun is in your account!"

			: "Personalisasi profilmu dan mulailah petualangan kenikmatan! Semua kesenangan ada di akunmu!";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Account',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}





	// Profile Page

	public function profile()

	{

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

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

		$data['reseller_id'] = $data['customer']->reseller_id;

		$data['content_view'] = 'account/profile_new';

		$this->visitortracking->trackVisitor();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Personalize your profile and start the pleasure adventure! All the fun is in your account!"

			: "Personalisasi profilmu dan mulailah petualangan kenikmatan! Semua kesenangan ada di akunmu!";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Profile',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}

	function invite_friend()

	{

		$this->data_header['page_title'] = 'Invite Friend';



		$id_customer = (int) $this->session->userdata('customer')['customer_id'];



		/*get friends email*/

		$data['friends_email'] = $this->db->select('*')->from('invite_friend')->where('id_customers', $id_customer)->order_by('id_invite_friend', 'ASC')->get()->result();



		//LOAD LANGUAGE FILES FOR profile

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('myprofile', 'english');

		} else {

			$this->lang->load('myprofile', 'indonesian');

		}



		//get SEO

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

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

		$this->data_header['browser_title'] =  ucwords($website_name->website_name) . ' - My Account';

		$this->data_header['meta_description'] = ucwords($website_name->website_name) . ' - My Account';

		$this->data_header['meta_keywords'] = $website_name->meta_keywords;



		$this->load->view("themes/$this->theme_no/header", $this->data_header);

		$this->load->view('account/invite_friend', $data);

		$this->load->view("themes/$this->theme_no/footer", $this->data_footer);

	}



	function invite_friend_add()

	{

		$data = array(

			'id_customers' 	=> (int) $this->session->userdata('customer')['customer_id'],

			'email'			=> $this->security->xss_clean($this->input->post('email'))

		);



		/*cek email pribad*/

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

		if ($data['email'] == $cek_email_pribadi) {

			$this->session->set_flashdata('success', '<br>

				<p style="background:red; color:white; padding:5px; font-weight:bold;">Cannot Add Your Email.</p>');

			redirect('account/invite_friend');

		}



		/*cek duplikat email*/

		$cek_email = $this->db->select('email')->from('invite_friend')->where('id_customers', $data['id_customers'])->where('email', $data['email'])->get()->row()->email;

		if ($cek_email == null) {

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

			$this->session->set_flashdata('success', '<br>

				<p style="background:green; color:white; padding:5px; font-weight:bold;">Add Friends Email Success.</p>');

			redirect('account/invite_friend');

		} else {

			$this->session->set_flashdata('success', '<br>

				<p style="background:red; color:white; padding:5px; font-weight:bold;">Email Already Added.</p>');

			redirect('account/invite_friend');

		}

	}



	function invite_friend_send_email($id)

	{

		/*get friends email*/

		$data['customer_email'] = $this->db->select('email')->from('invite_friend')->where('id_invite_friend', $id)->get()->row()->email;



		//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;



		$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('Anda Telah Diundang');



		$email = $this->load->view('email/invite_friend', $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;">Email Has Been Send.</p>');

		redirect('account/invite_friend');

	}



	function affiliate()

	{

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

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

		// Cek status affiliate

		$affiliate_status = $this->_check_customer_affiliate_status($id_customer);

		$data['affiliate_status'] = $affiliate_status;



		$data['content_view'] = 'account/affiliate';



		$referral_code = null;

		// Ambil referral kalau udah approve

		if ($affiliate_status == 'approve') {

			$referral_code = $this->_get_referral($id_customer);

			$data['referral_code'] = $referral_code;

		}



		// Data Dashboard

		$affiliate_data = $this->_get_affiliate_data($id_customer);

		$affiliate_category = $affiliate_data->kategori;

		$affiliate_transactions = $this->_get_affiliate_orders($referral_code);

		$affiliate_transactions_data = $this->_get_affiliate_orders_data($referral_code);

		$affiliate_link_sales = $this->_get_affiliate_link_sales($referral_code);

		$affiliate_clicks = $this->_get_affiliate_total_clicks($referral_code);



		$affiliate_withdrawals_data = $this->_get_affiliate_withrdrawals_data($affiliate_data->id_daftar);



		$total_sales = 0;

		$total_sales_commission = 0;

		$click_commission = $affiliate_clicks * 50;

		$link_commission = 0;

		$total_commission = 0;



		foreach ($affiliate_transactions_data as $transaction) {

			$total_sales += $transaction['total_amount'];



			if ($affiliate_category === 'asmaradoor') {

				$total_sales_commission += $transaction['total_amount'] * 0.1;

			} elseif ($affiliate_category === 'asmarasana') {

				$total_sales_commission += $transaction['total_amount'] * 0.2;

			}

		}



		foreach ($affiliate_link_sales as $link_sale) {

			$link_commission += isset($link_sale['komisi_order']) ? $link_sale['komisi_order'] : 0;

		}



		$total_commission = $click_commission + $total_sales_commission + $link_commission;

		$pending_commission = 0;

		$earned_commission = 0;



		// Withdrawn

		$earned_commission_data = $this->_get_affiliate_earned_commission($affiliate_data->id_daftar);

		if ($earned_commission_data) {

			$earned_commission = (int) $earned_commission_data;

		}

		$pending_commission = ($affiliate_data->komisi + $click_commission) - $earned_commission;



		$data['affiliate_data'] = $affiliate_data;

		$data['affiliate_transactions'] = $affiliate_transactions;

		$data['affiliate_transactions_data'] = $affiliate_transactions_data;

		$data['affiliate_withdrawals_data'] = $affiliate_withdrawals_data;

		$data['affiliate_link_sales'] = $affiliate_link_sales;

		$data['total_affiliate_transactions'] = count($affiliate_transactions);

		$data['total_affiliate_link_clicks'] = $affiliate_clicks;

		$data['total_affiliate_earnings'] = $affiliate_data->komisi + $click_commission;

		$data['affiliate_conversion_rate'] = $affiliate_clicks > 0 ? round(count($affiliate_transactions) / $affiliate_clicks * 100, 2) : 0;



		$data['total_sales'] = $total_sales;

		$data['total_sales_commission'] = $total_sales_commission;

		$data['click_commission'] = $click_commission;

		$data['link_commission'] = $link_commission + $click_commission;

		$data['earned_commission'] = $earned_commission;

		$data['pending_commission'] = $pending_commission;





		// Data referred customers

		$total_referred_customers = $this->_get_total_referred_customers($referral_code);

		$data['total_referred_customers'] = $total_referred_customers;

		$data['referred_customers'] = $this->_get_referred_customers_data($referral_code);



		$this->visitortracking->trackVisitor();



		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

			$this->lang->load('myprofile', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

			$this->lang->load('myprofile', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Share the love, stack the cash! Become Asmaradoor and earn commissions on every sale. No investment, just pure profit!"

			: "Bantu orang dan dapetin cuan! Gabung jadi Asmaradoor Laci Asmara, langsung dapet komisi dari setiap penjualan. Tanpa modal, langsung untung!";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Affiliate Program',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	private function _get_affiliate_earned_commission($id_affiliator)

	{

		$earned_commission_data = $this->db->select_sum('commission')

			->from('affiliator_commision')

			->where('id_affiliator', $id_affiliator)

			->get()

			->row();

		return $earned_commission_data->commission;

	}



	private function _get_referral($id_customer)

	{

		$referral_code = $this->db->select('referral')

			->from('affiliator_register')

			->where('id_customer', $id_customer)

			->get()

			->row();

		return $referral_code ? $referral_code->referral : NULL;

	}



	private function _check_customer_affiliate_status($id_customer)

	{

		$affiliate_status = $this->db->select('affiliate')

			->from('customers')

			->where('id_customers', $id_customer)

			->get()

			->row();

		return $affiliate_status ? $affiliate_status->affiliate : NULL;

	}



	private function _get_affiliate_orders($referral_code)

	{

		$affiliate_orders = $this->db->select('*')

			->from('orders')

			->group_start()

			->where('redeemed_voucher_code', $referral_code)

			->or_where('referral', $referral_code)

			->group_end()

			->where('payment_status', 5)

			->get()

			->result_array();

		return $affiliate_orders;

	}



	private function _get_affiliate_withrdrawals_data($id_affiliator)

	{

		$withdrawal_data = $this->db->select('*')

			->from('affiliator_commision')

			->where('id_affiliator', $id_affiliator)

			->get()

			->result_array();

		return $withdrawal_data;

	}



	private function _get_affiliate_total_clicks($referral_code)

	{

		$unique_visits = $this->db->select('COUNT(DISTINCT ip_address) AS unique_visits')

			->from('visits')

			->where('referral', $referral_code)

			->get()

			->row()

			->unique_visits;



		return $unique_visits;

	}



	private function _get_affiliate_link_clicks($link)

	{

		$unique_visits = $this->db->select('COUNT(DISTINCT ip_address) AS unique_visits')

			->from('link_tracks')

			->where('link_url', $link)

			->get()

			->row()

			->unique_visits;



		return $unique_visits;

	}



	private function _get_affiliate_daily_clicks($referral_code, $start_date, $end_date)

	{

		$daily_clicks = $this->db->select('DATE(date) AS date, COUNT(DISTINCT ip_address) AS unique_visits')

			->from('visits')

			->where('referral', $referral_code)

			->where('DATE(date) >=', $start_date)

			->where('DATE(date) <=', $end_date)

			->group_by('DATE(date)')

			->order_by('date', 'ASC')

			->get()

			->result_array();



		return $daily_clicks;

	}



	private function _get_affiliate_data($id_customer)

	{

		$affiliate_data = $this->db->select('*')

			->from('affiliator_register')

			->where('id_customer', $id_customer)

			->get()

			->row();

		return $affiliate_data;

	}



	private function _get_total_referred_customers($referral_code)

	{

		$total_referred_customer = $this->db->select('COUNT(*) as total')

			->from('customers')

			->where('refferal', $referral_code)

			->get()

			->row()

			->total;

		return $total_referred_customer;

	}



	private function _get_referred_customers_data($referral_code)

	{

		$referred_customers_data = $this->db->select('name, email, join_date')

			->from('customers')

			->where('refferal', $referral_code)

			->get()

			->result_array();

		return $referred_customers_data;

	}



	public function get_affiliate_clicks()

	{

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

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

		$referral_code = $this->input->get('referral');



		$daily_clicks = $this->_get_affiliate_daily_clicks($referral_code, $start_date, $end_date);



		echo json_encode($daily_clicks);

	}



	private function _get_affiliate_orders_data($referral_code)

	{

		$this->db->select('

			orders.*,

			orders_detail.id_orders_detail,

			orders_detail.item_id,

			orders_detail.product_id,

			orders_detail.item_name,

			orders_detail.item_price,

			orders_detail.quantity,

			orders_detail.subtotal,

			orders_detail.sku,

			orders_detail.attributes,

			orders_detail.status as order_detail_status,

			customers.name as customer_name,

			customers.email as customer_email,

			customers.phone as customer_phone

		');



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



		// Join with orders_detail

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



		// Join with customers

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



		// Group condition for referral code

		$this->db->group_start()

			->where('orders.redeemed_voucher_code', $referral_code)

			->or_where('orders.referral', $referral_code)

			->group_end();



		// Only get completed payments

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

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



		$affiliate_orders = $this->db->get()->result_array();



		return $affiliate_orders;

	}



	private function _get_affiliate_link_sales($referral_code)

	{

		$affiliate_link_sales = $this->db->select('*')

			->from('affiliator_link')

			->where('unique_id', $referral_code)

			->where('status', 'Active')

			->get()

			->result_array();

		foreach ($affiliate_link_sales as &$link) {

			$link['clicks'] = $this->_get_affiliate_link_clicks($link['link']);

		}

		return $affiliate_link_sales;

	}





	function affiliator()

	{

		$this->data_header['page_title'] = 'Affiliate Program';

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

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

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



		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

		if (!$this->session->userdata('customer')) {

			// Jika belum login, encode data UTM dan redirect ke halaman login

			$utm_data = base64_encode(json_encode([

				'utm_source' => $utm_source,

				'utm_medium' => $utm_medium,

				'utm_campaign' => $utm_campaign

			]));

			$this->visitortracking->trackVisitor();

			redirect('login?utm_data=' . urlencode($utm_data));

		}

		// data customer

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

		// data affiliator

		$data['affiliator'] = $this->affiliator_m->get_affiliator_customer($id_customer);

		// data link diambil dari model

		$data['link'] = $this->affiliator_m->get_unique_link($id_customer);



		// Data order ambil nama pemesan, tanggal order, total penjualan sama total komisi, buat function baru di model order

		// ambil dulu referral dari table affiliator register yang sesuai dengan id customer yang lagi login. untuk nantinya ngambil order sesuai voucher codenya dia

		// asmarasana

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

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

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

		$affiliator_referral = $this->db->get()->row()->referral;



		$data['affiliator_ref'] = $affiliator_referral;

		// ambil order yang voucher_redeemed_codenya sesuai dengan affiliator_referral

		$this->db->select('o.*, c.name as nama_pemesan');

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

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

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

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

		$data['orders'] = $order_data;





		$this->db->select('od.*, o.redeemed_voucher_code');

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

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

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

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

		$data['order_details'] = $order_details_data;



		// Data total sales

		$total_sales = $this->db->select_sum('total_amount')

			->from('orders')

			->where('redeemed_voucher_code', $affiliator_referral)

			->where('payment_status', 5)

			->get()

			->row()

			->total_amount;



		$data['total_sales_dokter'] = $total_sales;

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

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

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

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



		$data['progressreport'] = $progressreport;



		// Ambil data misi dengan status 1

		$this->db->select('id_mission, name, quest, target, type, customer_id');

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

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

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



		// Affiliator Biasa

		if (is_object($data['affiliator']) && isset($data['affiliator']->voucher)) {

			// Hitung jumlah kunjungan

			$count_visit = $this->db->select('id')

				->from('visits')

				->where('referral', $data['affiliator']->voucher)

				->where('date >=', '2024-08-01')

				->group_by('ip_address')

				->get()

				->num_rows();



			$total_sales_biasa = $this->db->select_sum('total_amount')

				->from('orders')

				->where('referral', $data['affiliator']->voucher)

				->where('payment_status', 5)

				->get()

				->row()

				->total_amount;



			// Hitung total komisi yang sudah dicairkan

			$this->db->select_sum('commission');

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

			$this->db->where('id_affiliator', $data['affiliator']->id_daftar);

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

			$result = $query->row();

			$count_already_earned = $result->commission ?? 0; // Gunakan 0 jika tidak ada hasil



			// Hitung komisi yang diperoleh

			if ($data['affiliator']->voucher == 'laciput') {

				$earned = $count_visit * 0;

			} else {

				$earned = $count_visit * 50;

			}



			$this->db->select_sum('komisi_order');

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

			$this->db->where('customer_id', $data['affiliator']->id_customer); // Pastikan ini sesuai dengan relasi

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

			$komisi_order = $query->row()->komisi_order ?? 0; // Gunakan 0 jika tidak ada hasil



			$earned += $komisi_order;

			// Hitung komisi yang masih pending

			$pending = $earned - $count_already_earned;



			// Assign nilai ke data

			$data['total_sales_biasa'] = $total_sales_biasa;

			$data['earned'] = $earned;

			$data['pending'] = $pending;

		} else {

			// Jika data affiliator tidak valid, set nilai default

			$data['earned'] = 0;

			$data['pending'] = 0;

		}



		// Hitung komisi yang diperoleh untuk affiliator asmarasana

		$earned_asmarasana = 0;

		$pending_asmarasana = 0;



		$this->db->select_sum('komisi');

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

		$this->db->where('id_customer', $data['affiliator']->id_customer);

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

		$result = $query->row();

		$komisi_register_asmarasana = $result->komisi ?? 0; // Gunakan 0 jika tidak ada hasil



		$earned_asmarasana += $komisi_register_asmarasana;



		// Hitung komisi yang sudah dicairkan untuk affiliator asmarasana

		$this->db->select_sum('commission');

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

		$this->db->where('id_affiliator', $data['affiliator']->id_daftar);

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

		$result = $query->row();

		$count_already_earned_asmarasana = $result->commission ?? 0; // Gunakan 0 jika tidak ada hasil



		$pending_asmarasana = $earned_asmarasana - $count_already_earned_asmarasana;



		// Assign nilai ke data

		$data['earned_asmarasana'] = $earned_asmarasana;

		$data['pending_asmarasana'] = $pending_asmarasana;



		// Ambil data progress detail hanya untuk customer yang login

		$this->db->select('id_customer, id_mission, progress');

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

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

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



		// Gabungkan data misi dengan progress detail

		foreach ($missions as $mission) {

			// Filter progress detail untuk misi saat ini

			$mission_progress = array_filter($progress_details, function ($progress) use ($mission) {

				return $progress->id_mission == $mission->id_mission;

			});



			// Jika tidak ada progress, set default 0%

			if (empty($mission_progress)) {

				$mission->progress_details = [

					(object)[

						'id_customer' => $id_customer,

						'id_mission' => $mission->id_mission,

						'progress' => 0

					]

				];

			} else {

				$mission->progress_details = $mission_progress;

			}

		}



		// Pass data to view

		$data['missions'] = $missions;



		//LOAD LANGUAGE FILES FOR profile

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('myprofile', 'english');

		} else {

			$this->lang->load('myprofile', 'indonesian');

		}







		//get SEO

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

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

		$this->data_header['browser_title'] =  ucwords($website_name->website_name) . ' - My Account';

		$this->data_header['meta_description'] = ucwords($website_name->website_name) . ' - My Account';

		$this->data_header['meta_keywords'] = $website_name->meta_keywords;



		$this->load->view("themes/$this->theme_no/header", $this->data_header);

		$this->load->view('account/affiliator', $data);

		$this->load->view("themes/$this->theme_no/footer", $this->data_footer);

	}



	// Controller method untuk mengupdate informasi bank via Ajax



	public function update_bank_information()

	{

		if ($this->input->method() !== 'post') {

			return $this->output

				->set_content_type('application/json')

				->set_status_header(401)

				->set_output(json_encode([

					'status' => 'error',

					'message' => 'Please login first'

				]));

		}



		$id_customer = (int) $this->session->userdata('customer')['customer_id'];



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

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

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



		// Validasi data input

		if (empty($bank_name) || empty($account_name) || empty($account_number)) {

			return $this->output

				->set_content_type('application/json')

				->set_status_header(400)

				->set_output(json_encode([

					'status' => 'error',

					'message' => 'All fields are required'

				]));

		}



		$data_bank = [

			'account_type' => $bank_name,

			'account_name' => $account_name,

			'account_number' => $account_number,

		];



		// Update data menggunakan query builder

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

		$update_data_bank = $this->db->update('affiliator_register', $data_bank);



		if ($update_data_bank) {

			return $this->output

				->set_content_type('application/json')

				->set_status_header(200)

				->set_output(json_encode([

					'status' => 'success',

					'message' => 'Bank Information Successfully Updated'

				]));

		}



		return $this->output

			->set_content_type('application/json')

			->set_status_header(500)

			->set_output(json_encode([

				'status' => 'error',

				'message' => 'Bank Information Update Failed'

			]));

	}





	public function update_bank_info()

	{

		if ($this->input->method() !== 'post') {

			show_404();

		}

		log_message('debug', 'Reached update_bank_info method.');





		$id_customer = (int) $this->session->userdata('customer')['customer_id'];



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

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

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

		$dataBank = [

			'account_name' => $accountHolder,

			'account_number' => $accountNumber,

			'account_type' => $bankName

		];



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

		$update = $this->db->update('affiliator_register', $dataBank);



		if ($update) {

			$response = ['message' => 'Informasi bank berhasil diupdate.'];

		} else {

			$response = ['message' => 'Gagal menyimpan data.'];

		}



		echo json_encode($response);

	}





	public function submitmissionreport()

	{



		$data = array(

			'id_customer' => $this->input->post('customer_id'),

			'id_mission' => $this->input->post('mission_id'),

			'name_mission' => $this->input->post('mission_name'),

			'link' => $this->input->post('link'),

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

		);

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



		redirect('account/affiliator');

	}





	public function register_affiliator()

	{

		// Mendapatkan ID pelanggan dari session

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];



		// Menentukan bahasa

		$lang = $this->session->userdata('site_lang') === 'english' ? 'english' : 'indonesian';



		// Mengambil data input

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

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

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

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

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



		// Membuat referral dan voucher

		$prefix = strtoupper(substr($nama, 0, 3));

		$referral = "LACI{$prefix}";

		$voucher = "LACI{$prefix}";



		// Data untuk tabel affiliator_register

		$register_data = [

			'id_customer' => $id_customer,

			'nama' => $nama,

			'no_telpon' => $no_hp,

			'email' => $email,

			'sosial_media' => $link_sosmed,

			'ktp' => 0,

			'referral' => $referral,

			'voucher' => $voucher,

			'status' => 'waiting',

			'kategori' => $kategori,

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

		];



		// Insert data ke tabel affiliator_register

		if ($this->db->insert('affiliator_register', $register_data)) {

			// Data untuk tabel customers

			$customer_data = [

				'affiliate' => 'waiting',

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

			];



			// Update tabel customers

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

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



			// Response sukses

			$response = [

				'status' => 'success',

				'message' => 'Registration successful.',

				'data' => $register_data

			];

		} else {

			// Response gagal

			$response = [

				'status' => 'error',

				'message' => 'Registration failed. Please try again.'

			];

		}



		// Mengembalikan respons dalam bentuk JSON

		echo json_encode($response);

	}

	function invite_friend_delete($id)

	{



		$data = array(

			'id_invite_friend' => $id

		);



		$this->db->delete('invite_friend', $data);



		$this->session->set_flashdata('success', '<br>

			<p style="background:green; color:white; padding:5px; font-weight:bold;">Delete Email Success.</p>');

		redirect('account/invite_friend');

	}



	// New update profile

	public function update_profile()

	{

		// Check if it's not a POST request or missing update_profile flag

		if (!$this->input->method() === 'post' || !$this->input->post('update_profile')) {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'Invalid request method'

				]));

		}



		// Get reseller ID

		$reseller_id = $this->db->select('reseller_id')

			->from('customers')

			->where('id_customers', $this->session->userdata('customer')['customer_id'])

			->get()

			->row()

			->reseller_id;



		// Set validation rules based on reseller_id

		$rules = $this->get_validation_rules($reseller_id);

		$this->form_validation->set_rules($rules);



		// Run validation

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

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'Please check the form for errors',

					'errors' => $this->form_validation->error_array(),

				]));

		}



		// Process the data

		try {

			$data = $this->prepare_profile_data($reseller_id);

			$id_customer = (int) $this->session->userdata('customer')['customer_id'];



			// Update profile

			$this->customer_m->update_profile($id_customer, $data);



			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => true,

					'message' => 'Profile updated successfully',

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

				]));

		} catch (Exception $e) {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'An error occurred while updating profile',

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

				]));

		}

	}



	private function get_validation_rules($reseller_id)

	{

		$rules = [

			'name' => [

				'field' => 'name',

				'label' => 'Name',

				'rules' => 'trim|required'

			],

			'phone' => [

				'field' => 'phone',

				'label' => 'Phone',

				'rules' => 'trim|required|numeric'

			],

			'email' => [

				'field' => 'email',

				'label' => 'Email',

				'rules' => 'trim|required'

			]

		];



		if ($reseller_id == 8) {

			$rules['alt_email'] = [

				'field' => 'alt_email',

				'label' => 'Alt Email',

				'rules' => 'trim|required'

			];

		}



		return $rules;

	}



	private function prepare_profile_data($reseller_id)

	{

		$data = [

			'name' => $this->security->xss_clean($this->input->post('name')),

			'recipient_name' => $this->security->xss_clean($this->input->post('name')),

			'shipping_name' => $this->security->xss_clean($this->input->post('name')),

			'sex_type' => $this->security->xss_clean($this->input->post('gender')),

			'phone' => $this->security->xss_clean($this->input->post('phone')),

			'shipping_phone' => $this->security->xss_clean($this->input->post('phone')),

			'email' => $this->security->xss_clean($this->input->post('email')),

			'newsletter' => 'yes'

		];



		if ($reseller_id == 8) {

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

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

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

			$data['birthday'] = $day . '-' . $month . '-' . $year;

			$data['email_alt'] = $this->security->xss_clean($this->input->post('alt_email'));

		} else {

			$data['birthday'] = $this->security->xss_clean($this->input->post('birthday'));

		}



		return $data;

	}



	//callback function validation register new handphone

	function _cek_phone($str)

	{



		$num_rows = $this->customer_m->cek_existing_phone($str, (int) $this->session->userdata('customer')['customer_id']);



		if ($num_rows != 0) {

			$this->form_validation->set_message('_cek_phone', 'Nomor Handphone sudah terdaftar !');

			return FALSE;

		} else {

			return TRUE;

		}

	}



	//callback function validation register new email

	function _cek_email($str)

	{



		$num_rows = $this->customer_m->cek_existing_email($str, (int) $this->session->userdata('customer')['customer_id']);



		if ($num_rows != 0) {

			$this->form_validation->set_message('_cek_email', 'Email sudah terdaftar !');

			return FALSE;

		} else {

			return TRUE;

		}

	}



	// Shipping page

	function shipping()

	{

		$data['content_view'] = 'account/shipping_new';

		$customerId = (int) $this->session->userdata('customer')['customer_id'];

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

		$data['reseller_id'] = $data['customer']->reseller_id;

		// $data['shipping_data'] = $this->getShippingData($customerId);

		$data['addresses'] = $this->customer_m->get_customer_addresses($customerId);

		$this->handleSummaryPageRedirect();



		$this->visitortracking->trackVisitor();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Safe & hassle-free shipping! Check your address and delivery details to make sure everything’s perfect—so your pleasure arrives without any drama!"

			: "Pengiriman aman & tanpa ribet! Cek detail alamat dan info pengiriman piranti asmara-mu. Pastikan semuanya benar biar pesanan sampai tanpa drama!";





		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Shipping',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

		];

		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	private function handleSummaryPageRedirect()

	{

		if ($this->input->post('shipping_summarypage')) {

			$this->session->set_userdata('shipping_summarypage', TRUE);

		}

	}



	private function getShippingData($customerId)

	{

		$shipping = $this->customer_m->get_shipping($customerId);



		// Get billing districts and subdistricts if reseller

		$billingDistricts = [];

		$billingSubdistricts = [];

		if ($shipping && $shipping->reseller_id) {

			$billingDistricts = $this->getDistrictsByProvince($shipping->id_province);

			$billingSubdistricts = $this->getSubdistrictsByDistrict($shipping->id_district);

		}



		// Get shipping districts and subdistricts

		$shippingDistricts = $shipping ? $this->getDistrictsByProvince($shipping->shipping_id_province) : [];

		$shippingSubdistricts = $shipping ? $this->getSubdistrictsByDistrict($shipping->shipping_id_district) : [];



		return [

			'shipping' => $shipping,

			'provinces' => $this->getProvinces(),

			'districts' => $shippingDistricts,

			'subdistricts' => $shippingSubdistricts,

			'billing_districts' => $billingDistricts,

			'billing_subdistricts' => $billingSubdistricts

		];

	}



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

	}



	private function getProvinces()

	{

		return $this->db->select('rajaongkir_province_id as id, province as name')

			->from('indonesia_provinces')

			->order_by('province', 'ASC')

			->get()

			->result();

	}



	// AJAX For Frontend

	public function getDistricts()

	{

		$this->output->set_content_type('application/json');



		$provinceId = $this->input->post('province_id');



		if (!$provinceId) {

			$response = [

				'status' => 'error',

				'message' => 'Province ID is required',

				'data' => [],

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

			];

			$this->output->set_output(json_encode($response));

			return;

		}



		$districts = $this->getDistrictsByProvince($provinceId);



		$response = [

			'status' => 'success',

			'message' => 'Districts retrieved successfully',

			'data' => $districts,

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

		];



		$this->output->set_output(json_encode($response));

	}



	public function getSubdistricts()

	{

		$this->output->set_content_type('application/json');



		$districtId = $this->input->post('district_id');

		if (!$districtId) {

			$response = [

				'status' => 'error',

				'message' => 'District ID is required',

				'data' => [],

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

			];

			$this->output->set_output(json_encode($response));

			return;

		}



		$subdistricts = $this->getSubdistrictsByDistrict($districtId);



		$response = [

			'status' => 'success',

			'message' => 'Subdistricts retrieved successfully',

			'data' => $subdistricts,

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

		];



		$this->output->set_output(json_encode($response));

	}



	// Update shipping data

	function update_shipping()

	{

		// Cek apakah request adalah POST dan update_shipping flag ada

		if ($this->input->method() !== 'post' || !$this->input->post('update_shipping')) {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'Invalid request method'

				]));

		}



		// Ambil reseller_id

		$reseller_id = $this->db->select('reseller_id')

			->from('customers')

			->where('id_customers', $this->session->userdata('customer')['customer_id'])

			->get()

			->row()

			->reseller_id;



		$is_reseller = !empty($reseller_id);



		// Atur validasi

		$rules = [

			['field' => 'shipping_name', 'label' => 'Nama Penerima', 'rules' => 'required|trim'],

			['field' => 'shipping_province', 'label' => 'Provinsi', 'rules' => 'required|trim'],

			['field' => 'shipping_district', 'label' => 'Kota/Kabupaten', 'rules' => 'required|trim'],

			['field' => 'shipping_subdistrict', 'label' => 'Kecamatan', 'rules' => 'required|trim'],

			['field' => 'shipping_address', 'label' => 'Alamat Lengkap', 'rules' => 'required|trim'],

			['field' => 'shipping_poscode', 'label' => 'Kode Pos', 'rules' => 'required|trim|exact_length[5]|numeric'],

		];



		if ($is_reseller) {

			$rules = array_merge($rules, [

				['field' => 'billing_name', 'label' => 'Nama Penerima', 'rules' => 'required|trim'],

				['field' => 'billing_province', 'label' => 'Provinsi', 'rules' => 'required|trim'],

				['field' => 'billing_district', 'label' => 'Kota/Kabupaten', 'rules' => 'required|trim'],

				['field' => 'billing_subdistrict', 'label' => 'Kecamatan', 'rules' => 'required|trim'],

				['field' => 'billing_address', 'label' => 'Alamat Lengkap', 'rules' => 'required|trim'],

				['field' => 'billing_poscode', 'label' => 'Kode Pos', 'rules' => 'required|trim|exact_length[5]|numeric'],

			]);

		}

		$this->form_validation->set_rules($rules);



		// Validasi gagal

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

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'Please check the form for errors',

					'errors' => $this->form_validation->error_array(),

				]));

		}



		// Siapkan data

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

		$data = [

			'shipping_name' => $this->security->xss_clean($input['shipping_name']),

			'shipping_postcode' => $this->security->xss_clean($input['shipping_poscode']),

			'shipping_address' => $this->security->xss_clean($input['shipping_address']),

			'shipping_id_country' => '0',

			'shipping_country' => 'Indonesia',

			'id_country' => '0',

			'country' => 'Indonesia',

		];



		if ($is_reseller) {

			$data = array_merge($data, [

				'recipient_name' => $this->security->xss_clean($input['billing_name']),

				'postcode' => $this->security->xss_clean($input['billing_poscode']),

				'address' => $this->security->xss_clean($input['billing_address']),

				'id_province' => (int) $input['billing_province'],

				'id_district' => (int) $input['billing_district'],

				'id_subdistrict' => (int) $input['billing_subdistrict'],

			]);



			$data['shipping_id_province'] = (int) $input['shipping_province'];

			$data['shipping_id_district'] = (int) $input['shipping_district'];

			$data['shipping_id_subdistrict'] = (int) $input['shipping_subdistrict'];

		} else {

			$data['shipping_id_province'] = (int) $input['shipping_province'];

			$data['shipping_id_district'] = (int) $input['shipping_district'];

			$data['shipping_id_subdistrict'] = (int) $input['shipping_subdistrict'];

		}





		// Ambil nama wilayah

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

			->from('indonesia_provinces')

			->where('rajaongkir_province_id', $data['id_province'])

			->get()

			->row()

			->province;



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

			->from('indonesia_districts')

			->where('rajaongkir_id_district', $data['id_district'])

			->get()

			->row()

			->district;



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

			->from('indonesia_subdistricts')

			->where('rajaongkir_id_subdistrict', $data['id_subdistrict'])

			->get()

			->row()

			->subdistrict;



		$data['shipping_province'] = $this->db->select('province')

			->from('indonesia_provinces')

			->where('rajaongkir_province_id', $data['shipping_id_province'])

			->get()

			->row()

			->province;



		$data['shipping_district'] = $this->db->select('district')

			->from('indonesia_districts')

			->where('rajaongkir_id_district', $data['shipping_id_district'])

			->get()

			->row()

			->district;



		$data['shipping_subdistrict'] = $this->db->select('subdistrict')

			->from('indonesia_subdistricts')

			->where('rajaongkir_id_subdistrict', $data['shipping_id_subdistrict'])

			->get()

			->row()

			->subdistrict;



		// Simpan ke database

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

		try {

			$this->customer_m->update_shipping($id_customer, $data);



			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => true,

					'message' => 'Shipping address updated successfully',

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

				]));

		} catch (Exception $e) {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'success' => false,

					'message' => 'An error occurred while updating the shipping address',

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

				]));

		}

	}



	public function save_address()

	{

		// Set response header untuk JSON

		$this->output->set_content_type('application/json');



		// Validasi request method

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

			$response = array(

				'success' => false,

				'message' => 'Method not allowed'

			);

			$this->output->set_output(json_encode($response));

			return;

		}



		// Validasi user login

		if (!$this->session->userdata('customer')) {

			$response = array(

				'success' => false,

				'message' => 'User not authenticated'

			);

			$this->output->set_output(json_encode($response));

			return;

		}



		// Ambil data dari POST

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

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

		$recipient_name = $this->input->post('receiverName');

		$phone = $this->input->post('receiverPhone');

		$address = $this->input->post('fullAddress');

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

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

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

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

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

		$district_name = $this->input->post('district');

		$subdistrict_name = $this->input->post('subdistrict');

		$postal_code = $this->input->post('postalCode');

		$is_main_address = $this->input->post('isMainAddress') === 'true' ? 1 : 0;



		// Validasi required fields

		if (

			empty($label) || empty($recipient_name) || empty($phone) || empty($address) ||

			empty($city) || empty($district_name) || empty($subdistrict_name) || empty($postal_code)

		) {

			$response = array(

				'success' => false,

				'message' => 'Semua field wajib harus diisi'

			);

			$this->output->set_output(json_encode($response));

			return;

		}



		// Start transaction

		$this->db->trans_start();



		// Jika ini adalah alamat utama, set alamat lain menjadi tidak utama

		if ($is_main_address) {

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

				->update('customer_addresses', array('is_default' => 0));

		}



		$lat_value = null;

		$lng_value = null;



		if (!empty($latitude) && is_numeric($latitude) && $latitude != '0') {

			$lat_value = (float) $latitude;

		}



		if (!empty($longitude) && is_numeric($longitude) && $longitude != '0') {

			$lng_value = (float) $longitude;

		}



		// Prepare data untuk insert

		$address_data = array(

			'customer_id' => $customer_id,

			'label' => $label,

			'recipient_name' => $recipient_name,

			'phone' => $phone,

			'address' => $address,

			'notes' => $notes,

			'latitude' => $lat_value,

			'longitude' => $lng_value,

			'province' => $province,

			'city' => $city,

			'district' => $district_name,

			'rajaongkir_district_id' => NULL,

			'subdistrict' => $subdistrict_name,

			'rajaongkir_subdistrict_id' => NULL,

			'postal_code' => $postal_code,

			'is_default' => $is_main_address,

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

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

		);



		// Insert data alamat

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



		// Complete transaction

		$this->db->trans_complete();



		// Check transaction status

		if ($this->db->trans_status() === FALSE || !$insert_result) {

			$response = array(

				'success' => false,

				'message' => 'Gagal menyimpan alamat. Silakan coba lagi.'

			);

		} else {

			$response = array(

				'success' => true,

				'message' => 'Alamat berhasil disimpan!',

				'address_id' => $this->db->insert_id()

			);

		}



		$this->output->set_output(json_encode($response));

	}

	public function set_default_address($id)

	{

		if (!$this->session->userdata('customer')['customer_id']) {

			echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);

			return;

		}



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



		// Unset semua alamat default

		$this->customer_m->unset_default($customer_id);



		// Set alamat ini sebagai default

		$result = $this->customer_m->set_default($id, $customer_id);



		if ($result) {

			echo json_encode([

				'status' => 'success',

				'message' => 'Alamat berhasil dipilih'

			]);

		} else {

			echo json_encode([

				'status' => 'error',

				'message' => 'Gagal memilih alamat'

			]);

		}

	}



	private function normalize_region_name($name)

	{

		$name = strtolower(trim($name));



		$name = preg_replace('/^kota\s+/i', '', $name);

		$name = preg_replace('/^kabupaten\s+/i', '', $name);

		$name = preg_replace('/^kec(?:amatan)?\s+/i', '', $name);



		$name = preg_replace('/[^a-zA-Z0-9\s]/', '', $name);

		$name = preg_replace('/\s+/', ' ', $name);



		return trim($name);

	}



	private function generate_search_variations($name)

	{

		$normalized = $this->normalize_region_name($name);

		$variations = array();



		$variations[] = $normalized;



		$variations[] = str_replace(' ', '', $normalized);



		$variations[] = str_replace(' ', '_', $normalized);



		$original_clean = strtolower(trim($name));

		$variations[] = $original_clean;



		$variations = array_unique(array_filter($variations));



		return $variations;

	}



	private function find_district($district_name)

	{

		$variations = $this->generate_search_variations($district_name);



		foreach ($variations as $variation) {

			$safe_variation = $this->db->escape_str($variation);



			$district = $this->db

				->where('LOWER(district)', $safe_variation)

				->get('indonesia_districts')

				->row();



			if ($district) {

				return $district;

			}

		}



		foreach ($variations as $variation) {

			$safe_variation = $this->db->escape_str($variation);



			$this->db->where("LOWER(district) LIKE '%" . $safe_variation . "%'");

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



			if ($district) {

				return $district;

			}



			$this->db->reset_query();

		}



		return null;

	}



	private function find_subdistrict($subdistrict_name)

	{

		$variations = $this->generate_search_variations($subdistrict_name);



		foreach ($variations as $variation) {

			$safe_variation = $this->db->escape_str($variation);



			$subdistrict = $this->db

				->where('LOWER(subdistrict)', $safe_variation)

				->get('indonesia_subdistricts')

				->row();



			if ($subdistrict) {

				return $subdistrict;

			}

		}



		foreach ($variations as $variation) {

			$safe_variation = $this->db->escape_str($variation);



			$this->db->where("LOWER(subdistrict) LIKE '%" . $safe_variation . "%'");

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



			if ($subdistrict) {

				return $subdistrict;

			}



			$this->db->reset_query();

		}



		return null;

	}



	function wishlist()

	{

		$this->load->model(['order_m', 'customer_m', 'Top_banner_m']);

		$data['content_view'] = 'account/wishlist';

		$customerId = (int) $this->session->userdata('customer')['customer_id'];

		// $customer = $this->customer_m->get_customer($customerId);



		$user_wishlist = $this->get_wishlist_with_product_details($customerId);

		$data['wishlists'] = $user_wishlist;



		$banners = $this->Top_banner_m->get_active_banners();

		$websiteData = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();

		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Pleasure at your fingertips! Your wishlist is ready to bring unexpected fun, only at Laci Asmara!"

			: "Kenikmatan dalam genggaman! Wishlist mu siap memberi kesenangan tak terduga, hanya di Laci Asmara!";

		// Prepare header data

		$this->data_header = [

			'website_icon' => $websiteData->website_icon,

			'browser_title' => ucwords($websiteData->browser_title) . ' - Wishlists',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];





		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();

		// Load views

		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	private function get_wishlist_with_product_details($customerId)

	{

		$this->db->select('w.id_wishlists, w.product_id, w.created_at, w.variant, w.product_detail_id, p.alias, p.title AS product_title, pi.image AS product_image')

			->from('wishlists w')

			->join('products p', 'p.id_products = w.product_id')

			->join('product_images pi', 'pi.product_details_id = w.product_detail_id AND pi.product_id = w.product_id', 'left')

			->where('w.customer_id', $customerId)

			->where('pi.status', 1)

			->where('pi.priority', 1)

			->order_by('w.created_at', 'DESC');



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



		return $wishlist_details;

	}



	private function get_user_wishlist($customerId)

	{

		$wishlist = $this->db->select('*')

			->from('wishlists')

			->where('customer_id', $customerId)

			->get()

			->result();



		return $wishlist;

	}







	function claim()

	{

		$this->load->model(['order_m', 'customer_m', 'Top_banner_m']);

		$data['content_view'] = 'account/warranty_claim_new';



		$customerId = (int) $this->session->userdata('customer')['customer_id'];

		$customer = $this->customer_m->get_customer($customerId);

		$resellerId = $customer->reseller_id ?? null;



		$payment_status = empty($resellerId) ? [5] : [5, 8]; // 5 for 'Terkirim', 8 for 'Selesai'



		// Get orders and claims

		$orders = $this->get_orders($customerId, $payment_status, $resellerId);

		$data['orders_list'] = $orders;

		$claims = $this->get_claims($customerId);



		foreach ($claims as &$claim) {

			$claim->status_text = $this->mapClaimStatus($claim->status); // Status name (e.g., Proses Analisa)

			$claim->status_class = $this->getClaimStatusClass($claim->status); // CSS class for status

		}



		$data['claim_history_list'] = $claims;



		// Load language files

		$this->load_language_files();



		// Get banners and website configuration data

		$banners = $this->Top_banner_m->get_active_banners();

		$websiteData = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Trouble with your pleasure device? Claim your warranty easily—no hassle! Fast process, guaranteed safe, and your satisfaction stays top priority!"

			: "Piranti asmara bermasalah? Klaim garansI dengan mudah & tanpa ribet. Proses cepat, dijamin aman, dan kepuasanmu tetap terjaga!";



		// Prepare header data

		$this->data_header = [

			'website_icon' => $websiteData->website_icon,

			'browser_title' => ucwords($websiteData->browser_title) . ' - Warranty Claim',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		// Load views

		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	public function get_order_details_list()

	{

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



		$orderDetails = $this->db->select('*')

			->from('orders_detail')

			->where('orders_id', $orderId)

			->get()

			->result();



		echo json_encode($orderDetails);

	}



	private function get_orders($customerId, $payment_status, $resellerId)

	{

		$this->db->distinct()

			->select('o.id_orders, o.order_date')

			->from('orders o')

			->join('orders_detail od', 'o.id_orders = od.orders_id')

			->join('claim_garansi cg', 'cg.no_order_detail_id = od.id_orders_detail', 'left')

			->where('o.customer_id', $customerId);



		if (is_array($payment_status)) {

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

		} else {

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

		}



		// Jika resellerId kosong/null, terapkan batasan tanggal

		if (empty($resellerId)) {

			$this->db->group_start()

				->where('od.is_sale', 'no')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)', NULL, FALSE)

				->or_where('od.is_sale', 'yes')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', NULL, FALSE)

				->group_end();

		}

		// Jika resellerId ada/tidak null, tidak ada batasan tanggal (tidak perlu kondisi tambahan)



		if (empty($resellerId)) {

			$this->db->where('cg.id_claim IS NULL', null, false);

		}



		return $this->db->get()->result();

	}



	private function get_claims($customerId)

	{

		return $this->db->select('claim_garansi.id_claim, claim_garansi.payment_confirm, claim_garansi.keterangan, orders.order_date, orders_detail.item_name, claim_garansi.reason_claim, claim_garansi.link_bukti, claim_garansi.status, claim_garansi.payment_confirm, claim_garansi.payment_confirm_detail')

			->from('claim_garansi')

			->join('orders', 'orders.id_orders = claim_garansi.no_order_id')

			->join('orders_detail', 'orders_detail.id_orders_detail = claim_garansi.no_order_detail_id')

			->where('claim_garansi.customer_id', $customerId)

			->order_by('claim_garansi.id_claim', 'DESC')

			->get()

			->result();

	}



	private function mapClaimStatus($status)

	{

		$statusMap = [

			1 => 'Proses Analisa',

			2 => 'Disetujui',

			3 => 'Ditolak',

			4 => 'Terkirim Produk',

			5 => 'Terkirim Voucher/Credit',

			6 => 'Disetujui Voucher/Credit',

		];

		return $statusMap[$status] ?? 'Unknown';

	}



	private function getClaimStatusClass($status)

	{

		$classMap = [

			1 => 'proses-analisa',

			2 => 'disetujui',

			3 => 'ditolak',

			4 => 'terkirim-produk',

			5 => 'terkirim-voucher',

			6 => 'disetujui-voucher',

		];

		return $classMap[$status] ?? 'unknown';

	}





	private function load_language_files()

	{

		$lang = $this->session->userdata('site_lang') == 'english' ? 'english' : 'indonesian';

		$this->lang->load('mainpage', $lang);

		$this->lang->load('payment_confirmation', $lang);

		$this->lang->load('claim_lang', $lang);

	}



	// Untuk insert claim garanasi

	public function claim_warranty()

	{

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



		// Validasi form

		$this->form_validation->set_rules('order_id', 'Order ID', 'required');

		$this->form_validation->set_rules('product_select', 'Product', 'required');

		$this->form_validation->set_rules('claim_reasons', 'Alasan Claim', 'required');

		$this->form_validation->set_rules('claim_proof_video', 'Bukti Video', 'required|valid_url');



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

			// Jika validasi gagal, kembalikan pesan error

			$response = [

				'status' => 'error',

				'message' => validation_errors()

			];

			return $this->output

				->set_content_type('application/json')

				->set_status_header(400)

				->set_output(json_encode($response));

		} else {

			$id_customer = (int) $this->session->userdata('customer')['customer_id'];



			$data = [

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

				'no_order_detail_id' => $this->input->post('product_select'),

				'reason_claim' => $this->input->post('claim_reasons'),

				'link_bukti' => $this->input->post('claim_proof_video'),

				'customer_id' => $id_customer,

				'order_date' => $this->input->post('order_date'),

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

				'keterangan' => $this->input->post('item_name'),

				'status' => '1',

				'lang' => $this->session->userdata('site_lang') == 'english' ? 'english' : 'indonesian'

			];



			// Insert ke database

			if ($this->db->insert('claim_garansi', $data)) {

				$response = [

					'status' => 'success',

					'message' => 'Claim submitted successfully.'

				];

				return $this->output

					->set_content_type('application/json')

					->set_status_header(200)

					->set_output(json_encode($response));

			} else {

				$response = [

					'status' => 'error',

					'message' => 'Failed to submit the claim. Please try again.'

				];

				return $this->output

					->set_content_type('application/json')

					->set_status_header(500)

					->set_output(json_encode($response));

			}

		}

	}



	public function generate_invoice($id)

	{

		if ($id == NULL) {

			redirect('account/order_history');

		}



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

		if ($count_order < 1) {

			redirect('account/order_history');

		}



		//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('account/order_history');

		}

	}



	public function generate_commision_report($id)

	{

		if ($id == NULL) {

			redirect('account/affiliator');

		}



		$count_order = $this->db->select('id_daftar')->from('affiliator_register')->where('id_daftar', $id)->get()->num_rows();

		if ($count_order < 1) {

			redirect('account/affiliator');

		}



		//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'] = 'Report No: ' . $id;



		//get affiliator register

		$this->db->select('*')->from('affiliator_register')->where('id_daftar', $id);

		$pdf_data['affiliator'] = $this->db->get()->row();



		if ($count_order > 0) {

			//get customer detail

			$pdf_data['customer'] = $this->db->select('*')->from('customers')->where('id_customers', $pdf_data['affiliator']->id_customer)->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/commision_report_affiliator', $pdf_data, true);

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

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

			$this->dompdf->render();

			$this->dompdf->stream('commision_report.pdf', array("Attachment" => 0));

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

			$file_to_save = 'uploads/pdf/commision_report.pdf';

			file_put_contents($file_to_save, $output);

		} else {

			redirect('account/affiliator');

		}

	}



	public function get_order_details($id_orders)

	{

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

		$reseller_id = $this->db->select('reseller_id')->from('customers')->where('id_customers', $id_customer)->get()->row()->reseller_id;

		if ($reseller_id == NULL) {

			$this->db->select('od.id_orders_detail, od.attributes, od.item_name, od.orders_id, o.order_date')

				->from('orders_detail od')

				->join('claim_garansi cg', 'cg.no_order_detail_id = od.id_orders_detail', 'left')

				->join('orders o', 'o.id_orders = od.orders_id')

				->where('cg.id_claim IS NULL', null, false)

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

				->group_start()

				->where('od.is_sale', 'no')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)', NULL, FALSE)

				->or_group_start()

				->where('od.is_sale', 'yes')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', NULL, FALSE)

				->group_end()

				->group_end();

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

			echo json_encode($query);

		} else {

			$this->db->select('od.id_orders_detail, od.attributes, od.item_name, od.orders_id, o.order_date')

				->from('orders_detail od')

				->join('claim_garansi cg', 'cg.no_order_detail_id = od.id_orders_detail', 'left')

				->join('orders o', 'o.id_orders = od.orders_id')

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

				->group_start()

				->where('od.is_sale', 'no')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR)', NULL, FALSE)

				->or_group_start()

				->where('od.is_sale', 'yes')

				->where('o.order_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', NULL, FALSE)

				->group_end()

				->group_end();

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

			echo json_encode($query);

		}

	}







	public function claim_pengajuan()

	{

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];



		$data = array(

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

			'no_order_detail_id' => $this->input->post('order_detail_id'),

			'reason_claim' => $this->input->post('reason_pengajuan'),

			'link_bukti' => $this->input->post('link_video'),

			'customer_id' => $id_customer,

			'order_date' => $this->input->post('order_date'),

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

			'keterangan' => $this->input->post('item_name'),

			'status' => '1',

		);

		if ($this->session->userdata('site_lang') == 'english') {

			$data['lang'] = 'english';

		} else {

			$data['lang'] = 'indonesian';

		}

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

		redirect('account/claim');

	}



	// Change Password

	function change_password()

	{



		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

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

		$data['is_password_set'] = !empty($data['customer']->password);

		$data['is_oauth_user'] = $data['customer']->oauth_provider === 'google';

		$data['content_view'] = 'account/change_password_new';

		$this->visitortracking->trackVisitor();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Keep your account safe! Change your password easily,, so you can explore freely without worrying about security risks."

			: "Jaga keamanan akunmu! Ganti password akun dengan mudah & cepat, biar eksplorasi tetap seru tanpa khawatir risiko keamanan.";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Password Update',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();

		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	// Change password new

	public function update_change_password()

	{

		// Cek apakah request menggunakan metode POST

		if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode(['status' => false, 'message' => lang('invalid_request')]));

		}



		// Load bahasa

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

		$this->lang->load('myprofile', $site_lang == 'english' ? 'english' : 'indonesian');



		// Dapatkan ID customer dari session

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

		$customer = $this->customer_m->get_customer($id_customer);



		// Aturan validasi dasar

		$base_rules = [

			[

				'field' => 'new_password',

				'label' => ucwords(lang('password')),

				'rules' => 'trim|required|min_length[8]'

			],

			[

				'field' => 'confirm_password',

				'label' => ucwords(lang('confirm_password')),

				'rules' => 'trim|required|matches[new_password]'

			]

		];



		// Tambahkan validasi old_password jika bukan user OAuth baru

		if ($customer->oauth_provider != 'google' || !empty($customer->password)) {

			$base_rules[] = [

				'field' => 'old_password',

				'label' => ucwords(lang('old_password')),

				'rules' => 'trim|required'

			];

		}



		$this->form_validation->set_rules($base_rules);



		// Cek validasi form

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

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'status' => false,

					'message' => lang('validation_error'),

					'errors' => $this->form_validation->error_array(),

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

				]));

		}



		// Validasi password lama jika diperlukan

		if (($customer->oauth_provider != 'google' || !empty($customer->password))) {

			// Skip validasi untuk user OAuth yang belum set password

			if (!($customer->oauth_provider == 'google' && empty($customer->password))) {

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

				$old_password_hash = $this->customer_m->hash($old_password);



				// Cek apakah password lama sesuai

				$password_match = $this->db->where('id_customers', $id_customer)

					->where('password', $old_password_hash)

					->count_all_results('customers');



				if ($password_match === 0) {

					return $this->output

						->set_content_type('application/json')

						->set_output(json_encode([

							'status' => false,

							'message' => lang('validation_error'),

							'errors' => ['old_password' => ucwords(lang('password_not_match'))],

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

						]));

				}

			}

		}



		// Proses update password

		try {

			$data = ['password' => password_hash($this->input->post('new_password'), PASSWORD_DEFAULT)];



			if ($customer->oauth_provider == 'google' && empty($customer->password)) {

				$data['oauth_provider'] = 'google';

			}



			$this->customer_m->update_profile($id_customer, $data);



			$message = ($customer->oauth_provider == 'google' && empty($customer->password))

				? ucwords(lang('password_created'))

				: ucwords(lang('password_changed'));



			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'status' => true,

					'message' => $message,

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

				]));

		} catch (Exception $e) {

			return $this->output

				->set_content_type('application/json')

				->set_output(json_encode([

					'status' => false,

					'message' => lang('password_error'),

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

				]));

		}

	}



	function _cek_oldpassword($str)

	{

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('myprofile', 'english');

		} else {

			$this->lang->load('myprofile', 'indonesian');

		}

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

		$customer = $this->db->select('password, oauth_provider')

			->from('customers')

			->where('id_customers', $id_customer)

			->get()

			->row();



		if ($customer->oauth_provider == 'google' && empty($customer->password)) {

			return TRUE;

		}



		$inputted_password = $this->customer_m->hash($str);



		$count_password = $this->db->select('id_customers')

			->from('customers')

			->where('password', $inputted_password)

			->where('id_customers', $id_customer)

			->get()

			->num_rows();



		if ($count_password == 0) {

			$this->form_validation->set_message('_cek_oldpassword', ucwords(lang('password_not_match')));

			return FALSE;

		}

		return TRUE;

	}





	function order_history()

	{

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



		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

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

		$data['api_key'] = '3151faf0c9775f624d2ebb885cfbed8589ad7e8fd04278c1ac42ea0ea37dc2a6';

		$data['courier'] = 'jne';



		$orders = $this->order_m->get_order_history($id_customer);



		// Detail items

		$data['orders'] = array_map(function ($order) {

			return [

				'id' => $order->id_orders,

				'date' => date('d M Y', strtotime($order->order_date)),

				'payment_confirm' => $order->payment_confirm,

				'no_resi' => $order->no_resi ?? '',

				'phone' => $order->phone ?? '',

				'status' => $this->mapOrderStatus($order->payment_status, $order->no_resi),

				'status_class' => $this->getStatusClass($order->payment_status, $order->no_resi),

				'items' => $this->getOrderItems($order->id_orders, $order->customer_id, $order->payment_status),

				'subtotal' => $order->total_amount,

				'total' => $order->grand_total_amount,

				'claim_credit' => $this->getClaimCredit($order->id_orders),

				'shipping_fee' => $order->shipping_fee,

				'redeemed_voucher_amount' => $order->redeemed_voucher_amount,

				'redeemed_voucher_code' => $order->redeemed_voucher_code,

				'minus_reward_amount' => $order->minus_reward_amount,

				'minus_reward' => $order->minus_reward,

				'plus_reward' => $order->plus_reward,

				'insurance_cost' => $order->insurance_cost,

				'insurance_status' => $order->insurance_status,

			];

		}, $orders);



		// 'can_review' => $this->canReview($order),

		$data['content_view'] = 'account/order_history_new';

		$this->visitortracking->trackVisitor();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

			$this->lang->load('order_history', 'english');

			$this->lang->load('payment_confirmation', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

			$this->lang->load('order_history', 'indonesian');

			$this->lang->load('payment_confirmation', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Check your order status easily! View your order history to track purchases, shipping updates & details—all in just one page!"

			: "Cek status pesanan dengan mudah! Lihat riwayat transaksi di Laci Asmara untuk tracking pesanan, detail pembelian & update pengiriman dalam sekali klik.";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Transaction History',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];



		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	private function getClaimCredit($id_order)

	{

		$claim_credit = $this->db->select('creditclaimamount')

			->from('orders')

			->where('id_orders', $id_order)

			->get()

			->row();

		return $claim_credit->creditclaimamount;

	}



	private function mapOrderStatus($status, $no_resi = null)

	{

		// Cek terlebih dahulu jika status adalah 4 dan ada resi

		if ($status == 4 && !empty($no_resi)) {

			return 'Dikirim';

		}



		$statusMap = [

			0 => 'Pending',

			1 => 'Belum Dibayar',

			2 => 'Batal',

			3 => 'Sudah Dibayar',

			4 => 'Diproses',

			5 => 'Selesai',

			6 => 'Bayar Sebagian',

			8 => 'Selesai',

			9 => 'Komplain'

		];

		return $statusMap[$status] ?? 'Unknown';

	}



	private function getStatusClass($status, $no_resi = null)

	{

		// Cek terlebih dahulu jika status adalah 4 dan ada resi

		if ($status == 4 && !empty($no_resi)) {

			return 'sent';

		}



		$classMap = [

			0 => 'pending',

			1 => 'unpaid',

			2 => 'batal',

			3 => 'paid',

			4 => 'processed',

			5 => 'selesai',

			6 => 'halfpaid',

			8 => 'selesai',

			9 => 'complain'

		];

		return $classMap[$status] ?? 'berlangsung';

	}



	private function getOrderItems($orderId, $customerId = null, $paymentStatus = null)

	{

		$items = $this->db->select('

				od.item_name, 

				od.quantity, 

				od.item_price, 

				od.item_id,

				od.product_id,

				od.id_orders_detail,

				p.alias,

				pi.image

			')

			->from('orders_detail od')

			->join(

				'product_images pi',

				'od.item_id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1',

				'left'

			)

			->join(

				'products p',

				'od.product_id = p.id_products',

				'left'

			)

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

			->get()

			->result();



		// Tambahkan can_review untuk setiap item jika parameter tersedia

		if ($customerId !== null && $paymentStatus !== null) {

			foreach ($items as $item) {

				$item->can_review = $this->canReviewItem($item->product_id, $customerId, $paymentStatus);

			}

		}



		return $items;

	}



	// For Frontend

	public function getOrderItemsJSON($orderId)

	{

		// Ambil data order untuk mendapatkan payment_status

		$order = $this->db->select('payment_status')

			->from('orders')

			->where('id_orders', $orderId)

			->get()

			->row();



		if (!$order) {

			echo json_encode(['error' => 'Order not found']);

			return;

		}



		// Ambil customer_id dari session

		$customerId = $this->session->userdata('customer')['customer_id'];



		// Panggil getOrderItems dengan parameter lengkap

		$items = $this->getOrderItems($orderId, $customerId, $order->payment_status);



		echo json_encode($items);

	}





	private function canReviewItem($productId, $customerId, $paymentStatus)

	{

		if (!in_array($paymentStatus, [5, 8])) {

			return false;

		}



		// Jika product_id atau customer_id kosong, return false

		if (empty($productId) || empty($customerId)) {

			return false;

		}



		// Cast ke integer

		$productId = (int) $productId;

		$customerId = (int) $customerId;



		// Hanya cek review yang approved

		$approvedReview = $this->db->select('id')

			->from('product_review')

			->where('product_id', $productId)

			->where('customer_id', $customerId)

			->where('status', 'approved')

			->get()

			->row();



		return !$approvedReview;

	}



	public function komplain_pesanan()

	{

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

		$newStatus = $this->input->post('new_status');

		$linkClaim = $this->input->post('linkclaim');



		$this->db->select('od.id_orders_detail, od.quantity, od.item_price');

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

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

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

		$orders_detail = $query->result();



		$totalClaimAmount = 0;



		foreach ($orders_detail as $order_detail) {

			$inputQuantity = $this->input->post('quantity')[$order_detail->id_orders_detail] ?? 0;

			if ($inputQuantity > $order_detail->quantity) {

				echo json_encode([

					'status' => 'error',

					'message' => 'Quantity exceeds available stock for one or more items.',

				]);

				return;

			}

			$totalClaimAmount += ($inputQuantity * $order_detail->item_price);

		}



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

		$update_data = [

			'payment_status' => $newStatus,

			'creditclaimamount' => $totalClaimAmount,

			'linkclaim' => $linkClaim,

		];



		if ($this->db->update('orders', $update_data)) {

			echo json_encode([

				'status' => 'success',

				'message' => 'Complaint processed successfully.',

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

			]);

		} else {

			echo json_encode([

				'status' => 'error',

				'message' => 'Failed to process complaint.',

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

			]);

		}

	}



	public function ubah_status_pesanan()

	{

		// Dapatkan data dari POST request

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

		$newStatus = $this->input->post('new_status');



		// Validasi dan sanitasi data jika diperlukan

		if (!$orderID || !$newStatus) {

			echo json_encode([

				'status' => 'error',

				'message' => 'Order ID atau status baru tidak ditemukan.',

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

			]);

			return;

		}



		// Update status pesanan di database

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

		$update_data = [

			'payment_status' => $newStatus

		];



		if ($this->db->update('orders', $update_data)) {

			echo json_encode([

				'status' => 'success',

				'message' => 'Status pesanan berhasil diubah.',

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

			]);

		} else {

			echo json_encode([

				'status' => 'error',

				'message' => 'Terjadi kesalahan saat mengubah status pesanan.',

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

			]);

		}

	}



	public function point_rewards()

	{

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

		$id_customer = (int) $this->session->userdata('customer')['customer_id'];

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

		$data['reseller'] = $this->get_reseller($id_customer);

		$data['content_view'] = 'account/point_rewards_new';



		$orders = $this->order_m->get_order_history($id_customer);



		// Detail items

		$data['orders'] = array_map(function ($order) {

			return [

				'id' => $order->id_orders,

				'date' => date('d M Y', strtotime($order->order_date)),

				'plus_reward' => $order->plus_reward,

				'minus_reward' => $order->minus_reward,

				'redeemed_voucher_code' => $order->redeemed_voucher_code,

			];

		}, $orders);



		$customer_data = $this->db->select('current_pointreward')

			->from('customers')

			->where('id_customers', $id_customer)

			->get()

			->row();

		// Dari customers (point customer saat ini)

		$data['current_point'] = $customer_data->current_pointreward;

		$data['credit'] = $customer_data->current_pointreward;



		$this->visitortracking->trackVisitor();

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('mainpage', 'english');

			$this->lang->load('pointrewards', 'english');

		} else {

			$this->lang->load('mainpage', 'indonesian');

			$this->lang->load('pointrewards', 'indonesian');

		}



		$banners = $this->Top_banner_m->get_active_banners();

		$website_data = $this->db->select('website_icon, browser_title, meta_description')

			->from('configuration')

			->where('id_configuration', 1)

			->get()

			->row();



		$meta_description = ($this->session->userdata('site_lang') == 'english')

			? "Your points, your pleasure! Check your Laci Asmara rewards and trade them in for your favorite pleasure gear—don’t let them go to waste!"

			: "Jangan biarkan poinmu sia-sia! Cek saldo point & rewards dari Laci Asmara dan tukarkan dengan piranti kesayangan.";



		$this->data_header = [

			'website_icon' => $website_data->website_icon,

			'browser_title' => ucwords($website_data->browser_title) . ' - Points',

			'meta_description' => $meta_description,

			'banners' => $banners,

			'logo_path' => 'https://storage.googleapis.com/laciasmara-photos/laciaasmara_assets/laciasmara_landing_page/laciasmara_landing_page_logo.webp',

			'footer_categories' => $this->Footer_m->get_all_categories(),

			'footer_social_media' => $this->Footer_m->get_social_media(),

			'footer_payment_methods' => $this->Footer_m->get_payment_methods(),

			'footer_asmaradoor' => $this->Footer_m->get_asmaradoor(),

			'footer_bottom' => $this->Footer_m->get_footer_bottom()

		];

		$this->data_footer['popular_categories'] = $this->Category_m->get_footer_popular_categories();

		$this->data_footer['trending_searches'] = $this->Statistic_m->get_trending_searches();



		$this->load->view("themes/3/header_new", $this->data_header);

		$this->load->view('account/index', $data);

		$this->load->view("themes/3/footer_new", $this->data_footer);

	}



	private function get_reseller($id_customer)

	{

		$customer_data = $this->db->select('reseller_id')

			->from('customers')

			->where('id_customers', $id_customer)

			->get()

			->row();

		return $customer_data->reseller_id;

	}



	public function claimvoucher_finish() {}

	public function claim_payment_confirmation()

	{



		if (!isset($_POST['claim_confirm_payment'])) {

			redirect('account/claim');

		}



		$data['id_claim'] = (int) $this->input->post('id_claim');



		$query = $this->db->select('*')

			->from('claim_garansi')

			->where('id_claim', $data['id_claim'])

			->get()

			->row();

		$data['data_claim'] = $query;



		$this->data_header['page_title'] = 'Claim Payment Confirmation';



		//LOAD LANGUAGE FILES 

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('payment_confirmation', 'english');

		} else {

			$this->lang->load('payment_confirmation', 'indonesian');

		}



		//get SEO

		$this->data_header['browser_title'] =  ucwords($this->data_header['website_name']) . ' - Claim Payment Confirmation';

		$this->data_header['meta_description'] = ucwords($this->data_header['website_name']) . ' - Claim Payment Confirmation';



		$this->load->view("themes/$this->theme_no/header", $this->data_header);

		$this->load->view('account/claim_payment_confirmation', $data);

		$this->load->view("themes/$this->theme_no/footer", $this->data_footer);

	}



	public function payment_confirmation()

	{



		if (!isset($_POST['confirm_payment'])) {

			redirect('account/order_history');

		}



		$data['order_id'] = (int) $this->input->post('order_id');



		$query = $this->db->select('*')

			->from('orders')

			->where('id_orders', $data['order_id'])

			->get()

			->row();

		$data['data_order'] = $query;



		$this->data_header['page_title'] = 'Payment Confirmation';



		//LOAD LANGUAGE FILES 

		if ($this->session->userdata('site_lang') == 'english') {

			$this->lang->load('payment_confirmation', 'english');

		} else {

			$this->lang->load('payment_confirmation', 'indonesian');

		}



		//get SEO

		$this->data_header['browser_title'] =  ucwords($this->data_header['website_name']) . ' - Payment Confirmation';

		$this->data_header['meta_description'] = ucwords($this->data_header['website_name']) . ' - Payment Confirmation';



		$this->load->view("themes/$this->theme_no/header", $this->data_header);

		$this->load->view('account/payment_confirmation', $data);

		$this->load->view("themes/$this->theme_no/footer", $this->data_footer);

	}



	// New

	public function update_claimpaymentconfirmation()

	{

		$image_name = null;

		if ($_FILES['receipt_file']['size'] !== 0) {

			$config['upload_path'] = './uploads/receipt_file/';

			$config['allowed_types'] = 'jpeg|jpg|png|pdf';

			$config['max_size'] = '5000';

			$this->load->library('upload', $config);

			if (!$this->upload->do_upload('receipt_file')) {

				echo json_encode(['status' => 'error', 'message' => 'Image upload error: ' . $this->upload->display_errors()]);

				return;

			} else {

				$image = $this->upload->data();

				$image_name = $image['file_name'];

			}

		}



		$payment_date = explode('-', $this->input->post('payment_date'));

		$new_payment_date = $payment_date[2] . '-' . $payment_date[1] . '-' . $payment_date[0];

		$total_amount = (int) $this->input->post('total_amount');

		$to_bank = ucwords($this->input->post('to_bank'));

		$from_bank = ucwords($this->input->post('from_bank'));

		$account_name = $this->security->xss_clean(ucwords($this->input->post('account_name')));

		$account_number = $this->security->xss_clean(ucwords($this->input->post('account_number')));



		$payment_confirm_details_json = [

			'payment_date' => $new_payment_date,

			'total_amount' => $total_amount,

			'to_bank' => $to_bank,

			'from_bank' => $from_bank,

			'account_name' => $account_name,

			'account_number' => $account_number,

			'receipt_file' => $image_name ? base_url('uploads/receipt_file/') . $image_name : null

		];



		$payment_confirm_details =

			'<p>Payment Date: ' . $new_payment_date . '</p>' .

			'<p>Payment Amount: Rp ' . number_format($total_amount) . '</p>' .

			'<p>To Bank: ' . $to_bank . '</p>' .

			'<p>From Bank: ' . $from_bank . '</p>' .

			'<p>From Acc Name: ' . $account_name . '</p>' .

			'<p>From Acc No: ' . $account_number . '</p>' .

			'<p>Receipt file: <a href="' . base_url('uploads/receipt_file/') . $image_name . '">' . $image_name . '</a></p>';



		$data = [

			'payment_confirm' => 1,

			'payment_confirm_detail' => $payment_confirm_details

		];



		$claim_id = (int) $this->input->post('claim_id');

		$this->db->where('id_claim', $claim_id);

		$update_status = $this->db->update('claim_garansi', $data);



		if ($update_status) {

			echo json_encode(['status' => 'success', 'message' => 'Payment confirmation updated successfully.']);

		} else {

			echo json_encode(['status' => 'error', 'message' => 'Failed to update payment confirmation.']);

		}

	}



	// New update payment confirmation

	public function update_paymentconfirmation()

	{



		// Handle file upload if present

		$image_name = null;

		if ($_FILES['receipt_file']['size'] !== 0) {

			$config['upload_path'] = './uploads/receipt_file/';

			$config['allowed_types'] = 'jpeg|jpg|png|pdf';

			$config['max_size'] = '5000';

			$this->load->library('upload', $config);

			if (!$this->upload->do_upload('receipt_file')) {

				echo json_encode(['status' => 'error', 'message' => 'Image upload error: ' . $this->upload->display_errors()]);

				return;

			} else {

				$image = $this->upload->data();

				$image_name = $image['file_name'];

			}

		}



		// Process payment details

		$payment_date = explode('-', $this->input->post('payment_date'));

		$new_payment_date = $payment_date[2] . '-' . $payment_date[1] . '-' . $payment_date[0];

		$total_amount = (int) $this->input->post('total_amount');

		$to_bank = ucwords($this->input->post('to_bank'));

		$from_bank = ucwords($this->input->post('from_bank'));

		$account_name = $this->security->xss_clean(ucwords($this->input->post('account_name')));

		$account_number = $this->security->xss_clean(ucwords($this->input->post('account_number')));



		$payment_confirm_details_json = [

			'payment_date' => $new_payment_date,

			'total_amount' => $total_amount,

			'to_bank' => $to_bank,

			'from_bank' => $from_bank,

			'account_name' => $account_name,

			'account_number' => $account_number,

			'receipt_file' => $image_name ? base_url('uploads/receipt_file/') . $image_name : null

		];



		$payment_confirm_details =

			'<p>Payment Date: ' . $new_payment_date . '</p>' .

			'<p>Payment Amount: Rp ' . number_format($total_amount) . '</p>' .

			'<p>To Bank: ' . $to_bank . '</p>' .

			'<p>From Bank: ' . $from_bank . '</p>' .

			'<p>From Acc Name: ' . $account_name . '</p>' .

			'<p>From Acc No: ' . $account_number . '</p>' .

			'<p>Receipt file: <a href="' . base_url('uploads/receipt_file/') . $image_name . '">' . $image_name . '</a></p>';





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

		$case_payment = 'ke-1';



		// Prepare the data to update based on case_payment

		$data = [

			'payment_status' => 1,

			'payment_confirm' => 1,

			'payment_confirm_details' => $payment_confirm_details

		];



		if ($case_payment == 'ke-2') {

			$data = [

				'payment_status' => 1,

				'payment_confirm_remaining' => 1,

				'payment_confirm_details_remaining' => $payment_confirm_details

			];

		}



		// Update order in database

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

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

		$update_status = $this->db->update('orders', $data);



		if ($update_status) {

			// Send email notification

			$this->send_payment_confirmation_email($order_id, json_encode($payment_confirm_details_json), $case_payment);

			echo json_encode(['status' => 'success', 'message' => 'Payment confirmation updated successfully.']);

		} else {

			echo json_encode(['status' => 'error', 'message' => 'Failed to update payment confirmation.']);

		}

	}



	private function send_payment_confirmation_email($order_id, $payment_confirm_details, $case_payment)

	{

		// Load the email library  

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



		// Get customer name  

		$customer_id = (int) $this->session->userdata('customer')['customer_id'];

		$this->db->select('name')->from('customers')->where('id_customers', $customer_id);

		$customer_name = $this->db->get()->row()->name;



		// Get website data  

		$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)->get()->row();

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

		$emails = $this->configuration_m->get_emails();

		$bank = $this->configuration_m->get_bank();



		// Construct email message  

		$myMessage = '<html><body>';

		$myMessage .= '<table style="border-color: #666;" cellpadding="10">';

		$myMessage .= "<tr><td><strong>Order No:</strong> </td><td>" . $order_id . "</td></tr>";

		$myMessage .= "<tr><td><strong>Payment Date:</strong> </td><td>" . $this->input->post('payment_date') . "</td></tr>";

		$myMessage .= "<tr><td><strong>Amount: Rp </strong> </td><td>" . number_format($payment_confirm_details['total_amount']) . "</td></tr>";

		$myMessage .= "<tr><td><strong>To Bank:</strong> </td><td>" . $payment_confirm_details['to_bank'] . "</td></tr>";

		$myMessage .= "<tr><td><strong>From bank:</strong> </td><td>" . $payment_confirm_details['from_bank'] . "</td></tr>";

		$myMessage .= "<tr><td><strong>Account Name:</strong> </td><td>" . $payment_confirm_details['account_name'] . "</td></tr>";

		$myMessage .= "<tr><td><strong>Account Number:</strong> </td><td>" . $payment_confirm_details['account_number'] . "</td></tr>";

		$myMessage .= "</table>";

		$myMessage .= "<p>Please verify the payment, and confirm the payment to us.</p>";

		$myMessage .= "</body></html>";



		// Email configuration  

		$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   



		// Initialize email configuration  

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



		// Set email parameters  

		$this->email->from($website_data->email_smtp, $website_data->website_name);

		$this->email->to($emails->from_email);

		$this->email->subject($case_payment == 'ke-2' ? 'Customer Payment Confirmation 2' : 'Customer Payment Confirmation');

		$this->email->message($myMessage);



		// Send email and return the status  

		return $this->email->send();

	}



	public function add_to_wishlist()

	{

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

		if (empty($customer)) {

			return $this->output

				->set_content_type('application/json')

				->set_status_header(401)

				->set_output(json_encode([

					'status' => 'error',

					'message' => 'Please login first'

				]));

		}



		$data = [

			'customer_id' => $this->session->userdata('customer')['customer_id'],

			'product_id' => $this->input->post('product_id'),

			'product_detail_id' => $this->input->post('product_detail_id'),

			'variant' => $this->input->post('variant'),

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

		];





		// Cek apakah produk sudah ada di wishlist

		$existing_wishlist = $this->db->get_where('wishlists', [

			'customer_id' => $data['customer_id'],

			'product_id' => $data['product_id'],

			'product_detail_id' => $data['product_detail_id']

		])->row();



		if ($existing_wishlist) {

			// Jika sudah ada, hapus dari wishlist

			$result = $this->db->delete('wishlists', [

				'customer_id' => $data['customer_id'],

				'product_id' => $data['product_id'],

				'product_detail_id' => $data['product_detail_id']

			]);

			$wishlist_count = $this->db->where('customer_id', $data['customer_id'])->count_all_results('wishlists');





			return $this->output

				->set_content_type('application/json')

				->set_status_header(200)

				->set_output(json_encode([

					'status' => 'success',

					'message' => 'Successfully removed from wishlist',

					'is_wishlisted' => false,

					'wishlist_count' => $wishlist_count

				]));

		} else {

			// Jika belum ada, tambahkan ke wishlist

			if ($this->_process_add_to_wishlist($data)) {

				$wishlist_count = $this->db->where('customer_id', $data['customer_id'])->count_all_results('wishlists');



				return $this->output

					->set_content_type('application/json')

					->set_status_header(200)

					->set_output(json_encode([

						'status' => 'success',

						'message' => 'Successfully added to wishlist',

						'is_wishlisted' => true,

						'wishlist_count' => $wishlist_count

					]));

			}

		}



		return $this->output

			->set_content_type('application/json')

			->set_status_header(500)

			->set_output(json_encode([

				'status' => 'error',

				'message' => 'Failed to process wishlist',

				'is_wishlisted' => null

			]));

	}



	private function _process_add_to_wishlist($data)

	{

		return $this->db->insert('wishlists', [

			'customer_id' => $data['customer_id'],

			'product_id' => $data['product_id'],

			'product_detail_id' => $data['product_detail_id'],

			'variant' => $data['variant'],

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

		]);

	}



	public function remove_from_wishlist()

	{

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

		if (!$customer) {

			return $this->_send_json_response('error', 'Please login first', 401);

		}



		$data = [

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

			'product_id' => $this->input->post('product_id'),

			'product_detail_id' => $this->input->post('product_detail_id')

		];



		// Validasi input

		if (!$data['product_id'] || !$data['product_detail_id']) {

			return $this->_send_json_response('error', 'Invalid product data', 400);

		}



		if ($this->_process_remove_from_wishlist($data)) {

			return $this->_send_json_response('success', 'Successfully removed from wishlist', 200);

		}



		return $this->_send_json_response('error', 'Failed to remove from wishlist', 500);

	}



	private function _process_remove_from_wishlist($data)

	{

		$this->db->trans_start();

		$result = $this->db->where($data)->delete('wishlists');

		$this->db->trans_complete();



		return $this->db->trans_status() && $result;

	}



	private function _send_json_response($status, $message, $http_code = 200)

	{

		return $this->output

			->set_content_type('application/json')

			->set_status_header($http_code)

			->set_output(json_encode([

				'status' => $status,

				'message' => $message

			]));

	}



	public function onboarding()

	{

		// Check if user is logged in

		if (!$this->session->userdata('customer') || !$this->session->userdata('customer')['customer_loggedin']) {

			redirect('login');

		}



		// Get customer data from session

		$customer_data = $this->session->userdata('customer');



		// Load customer data from database to ensure we have the latest

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



		// Check if onboarding is actually needed

		if (!empty($customer->sex_type) && !empty($customer->birthday)) {

			// If already has required info, redirect to appropriate page

			$this->_redirect_after_onboarding();

			return;

		}



		// Process form submission

		if ($this->input->post()) {

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



			// Set validation rules

			$this->form_validation->set_rules('birthday', 'Tanggal Lahir');

			$this->form_validation->set_rules('sex_type', 'Jenis Kelamin', 'in_list[male,female,others]');



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

				// Calculate age from birthday

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

				$today = new DateTime();

				$birthdate = new DateTime($birthday);

				$age = $birthdate->diff($today)->y;



				// Update customer data

				$update_data = [

					'birthday' => $birthday,

					'sex_type' => $this->input->post('sex_type')

				];



				$this->db->update('customers', $update_data, ['id_customers' => $customer_data['customer_id']]);



				// Remove the needs_onboarding flag from session

				$customer_data['needs_onboarding'] = false;

				$this->session->set_userdata('customer', $customer_data);



				// Redirect to appropriate page

				$this->session->set_flashdata('success', 'Terima kasih telah melengkapi profil Anda!');

				$this->_redirect_after_onboarding();

				return;

			}

		}



		// Set view data

		$data = [

			'customer' => $customer,

			'title' => 'Lengkapi Profil Anda',

			'description' => 'Sebelum melanjutkan, kami perlu beberapa informasi tambahan.',

			'error' => ''

		];



		// Load view

		$this->load->view('account/onboarding', $data);

	}



	// Helper method to redirect after onboarding

	private function _redirect_after_onboarding()

	{

		$redirect_to = $this->session->userdata('after_onboarding_redirect');

		$this->session->unset_userdata('after_onboarding_redirect');



		if (!empty($redirect_to)) {

			redirect($redirect_to);

		} else {

			redirect(base_url());

		}

	}

}


https://t.me/RX1948 - 2025