|
Server : Apache/2.4.18 (Ubuntu) System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64 User : oppastar ( 1041) PHP Version : 7.0.33-0ubuntu0.16.04.15 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority, Directory : /var/www/laciasmara.com/public_html/shop/application/controllers/ |
Upload File : |
<?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();
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['browser_title'] .= ' - Account';
$this->data_header['meta_description'] = $meta_description;
$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');
}
$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['browser_title'] .= ' - Profile';
$this->data_header['meta_description'] = $meta_description;
$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);
}
// Affiliate Page
function affiliate()
{
$id_customer = (int) $this->session->userdata('customer')['customer_id'];
$referral_code = null;
// Cek status affiliate
$affiliate_status = $this->_check_customer_affiliate_status($id_customer);
if ($affiliate_status == 'approve') {
$referral_code = $this->_get_referral_code($id_customer);
$data['referral_code'] = $referral_code;
}
// Data to pass
$data['customer'] = $this->customer_m->get_customer_by_id($id_customer);
$data['affiliate_status'] = $affiliate_status;
$data['content_view'] = 'account/affiliate';
// Get affiliate data
$affiliate_data = $this->_get_affiliate_data($id_customer);
if ($affiliate_data) {
$affiliator_id = $affiliate_data['id'];
// Commission Summary
$commission_summary = $this->_get_commission_summary($affiliator_id, $referral_code);
$data['commission_summary'] = $commission_summary;
// Orders/Transactions
$transactions = $this->_get_transactions_by_referral_code($referral_code);
$data['transactions'] = $transactions;
$data['total_transactions'] = count($transactions['orders']);
// Withdrawal History
$withdrawals_history = $this->_get_withdrawals_history($affiliator_id);
$data['withdrawals_history'] = $withdrawals_history;
// Links with Statistics
$affiliate_links = $this->_get_affiliate_links_with_statistics($affiliator_id);
$data['affiliate_links'] = $affiliate_links;
// Referred Customers
$data['total_referred_customers'] = $this->_get_total_referred_customers($referral_code);
$data['referred_customers'] = $this->_get_referred_customers_data($referral_code);
$data['affiliate_data'] = $affiliate_data;
}
$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');
}
$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['browser_title'] .= ' - Affiliate Program';
$this->data_header['meta_description'] = $meta_description;
// echo "<pre>";
// print_r($data);
// echo "</pre>";
$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);
}
// ==================== COMMISSION FUNCTIONS ====================
/**
* Get comprehensive commission summary for an affiliator
* Includes: order commissions, click commissions, and withdrawal info
*
* @param int $affiliator_id
* @param string $referral_code
* @return array Commission summary with all calculations
*/
private function _get_commission_summary($affiliator_id, $referral_code)
{
// 1. Get Order-based Commissions from affiliator_commissions table
$order_commissions = $this->_get_order_commissions_breakdown($affiliator_id);
// 2. Get Click-based Commission (50 rupiah per unique IP)
$click_commission = $this->_get_click_commission($referral_code);
// 3. Get Total Withdrawals
$total_withdrawn = $this->_get_total_withdrawn_amount($affiliator_id);
// 4. Calculate totals
$total_order_commission = $order_commissions['total'];
$total_commission = $total_order_commission + $click_commission['total_amount'];
$available_balance = $total_commission - $total_withdrawn;
return [
// Order Commissions Breakdown
'order_commission' => [
'pending' => $order_commissions['pending'],
'approved' => $order_commissions['approved'],
'paid' => $order_commissions['paid'],
'cancelled' => $order_commissions['cancelled'],
'total' => $order_commissions['total'],
'total_orders' => $order_commissions['total_orders']
],
// Click Commission
'click_commission' => [
'unique_clicks' => $click_commission['unique_clicks'],
'rate_per_click' => $click_commission['rate_per_click'],
'total_amount' => $click_commission['total_amount']
],
// Grand Totals
'total_commission_earned' => $total_commission,
'total_withdrawn' => $total_withdrawn,
'available_balance' => $available_balance,
// Additional Stats
'total_conversions' => $order_commissions['total_orders'],
'conversion_rate' => $click_commission['unique_clicks'] > 0
? round(($order_commissions['total_orders'] / $click_commission['unique_clicks']) * 100, 2)
: 0
];
}
/**
* Get order commissions breakdown by status
*
* @param int $affiliator_id
* @return array Commissions grouped by status
*/
private function _get_order_commissions_breakdown($affiliator_id)
{
$result = $this->db->select('
COUNT(*) as total_orders,
SUM(commission_amount) as total_commission,
SUM(CASE WHEN status = "pending" THEN commission_amount ELSE 0 END) as pending,
SUM(CASE WHEN status = "approved" THEN commission_amount ELSE 0 END) as approved,
SUM(CASE WHEN status = "paid" THEN commission_amount ELSE 0 END) as paid,
SUM(CASE WHEN status = "cancelled" THEN commission_amount ELSE 0 END) as cancelled
')
->from('affiliator_commissions')
->where('affiliator_id', $affiliator_id)
->get()
->row();
return [
'total_orders' => $result ? (int) $result->total_orders : 0,
'total' => $result ? (float) $result->total_commission : 0.00,
'pending' => $result ? (float) $result->pending : 0.00,
'approved' => $result ? (float) $result->approved : 0.00,
'paid' => $result ? (float) $result->paid : 0.00,
'cancelled' => $result ? (float) $result->cancelled : 0.00
];
}
/**
* Calculate click commission (50 rupiah per unique IP address)
*
* @param string $referral_code
* @return array Click statistics and commission amount
*/
private function _get_click_commission($referral_code)
{
$rate_per_click = 50; // 50 rupiah per unique click
$result = $this->db->select('COUNT(DISTINCT ip_address) as unique_clicks')
->from('visits')
->where('referral_code', $referral_code)
->where('is_affiliate_visit', 1)
->get()
->row();
$unique_clicks = $result ? (int) $result->unique_clicks : 0;
$total_amount = $unique_clicks * $rate_per_click;
return [
'unique_clicks' => $unique_clicks,
'rate_per_click' => $rate_per_click,
'total_amount' => $total_amount
];
}
/**
* Get total amount that has been withdrawn
*
* @param int $affiliator_id
* @return float Total withdrawn amount
*/
private function _get_total_withdrawn_amount($affiliator_id)
{
$result = $this->db->select('SUM(amount) as total_withdrawn')
->from('affiliator_withdrawals')
->where('affiliator_id', $affiliator_id)
->where('status', 'completed')
->get()
->row();
return $result && $result->total_withdrawn ? (float) $result->total_withdrawn : 0.00;
}
// ==================== AFFILIATE DATA FUNCTIONS ====================
/**
* Get affiliate/affiliator data by customer ID
*
* @param int $customer_id
* @return array|null Affiliate data
*/
private function _get_affiliate_data($customer_id)
{
$affiliate = $this->db->select('*')
->from('affiliators')
->where('customer_id', $customer_id)
->get()
->row_array();
return $affiliate ? $affiliate : null;
}
/**
* Get referral code for a customer
*
* @param int $customer_id
* @return string|null Referral code
*/
private function _get_referral_code($customer_id)
{
$result = $this->db->select('referral_code')
->from('affiliators')
->where('customer_id', $customer_id)
->get()
->row();
return $result ? $result->referral_code : null;
}
/**
* Check customer affiliate status
*
* @param int $customer_id
* @return string|null Status: 'approve', 'pending', 'rejected', etc
*/
private function _check_customer_affiliate_status($customer_id)
{
$result = $this->db->select('affiliate')
->from('customers')
->where('id_customers', $customer_id)
->get()
->row();
return $result ? $result->affiliate : null;
}
// ==================== TRANSACTION FUNCTIONS ====================
/**
* Get all transactions/orders made using this referral code
* WITH commission calculation based on commission rules
*
* @param string $referral_code
* @param string|null $affiliator_type Optional: asmaradoor|asmarasana (for calculation)
* @return array Orders with details and calculated commission
*/
private function _get_transactions_by_referral_code($referral_code, $affiliator_type = null)
{
// Get affiliator info if type not provided
if (!$affiliator_type) {
$affiliator = $this->_get_affiliator_by_referral_code($referral_code);
$affiliator_type = $affiliator ? $affiliator['type'] : null;
}
// Get orders
$orders = $this->db->select('
o.id_orders,
o.customer_id,
o.order_date,
o.grand_total_amount,
o.payment_status,
o.tracking_affiliator_id,
c.name AS customer_name
')
->from('orders o')
->join('customers c', 'c.id_customers = o.customer_id', 'left')
->group_start()
->where('o.redeemed_voucher_code', $referral_code)
->or_where('o.referral', $referral_code)
->group_end()
->where('o.payment_status', 5) // Only completed orders
->order_by('o.order_date', 'DESC')
->get()
->result_array();
if (empty($orders)) {
return [];
}
$total_orders_commission = 0;
$total_orders_amount = 0;
foreach ($orders as &$order) {
// Get order items with full details
$order_items = $this->_get_order_items_with_details($order['id_orders']);
$order_commission = 0;
$items_with_commission = [];
// Calculate commission per item using rules system
foreach ($order_items as $item) {
$rate_info = $this->_get_commission_rate_for_item(
$affiliator_type,
$item->product_id,
$item->brand_id,
$item->category_ids
);
$item_subtotal = (float) $item->subtotal;
$item_commission = ($item_subtotal * $rate_info['rate']) / 100;
$order_commission += $item_commission;
// Format item data for display
$items_with_commission[] = [
'item_name' => $item->item_name,
'quantity' => $item->quantity,
'subtotal' => $item_subtotal,
'commission_rate' => $rate_info['rate'],
'commission_amount' => round($item_commission, 2),
'rule_applied' => $rate_info['rule_type'],
'brand_name' => $item->brand_name ?? '-',
'categories' => implode(', ', $item->category_names)
];
}
// Calculate weighted average commission rate for this order
$order_amount = (float) $order['grand_total_amount'];
$weighted_rate = $order_amount > 0
? ($order_commission / $order_amount) * 100
: 0;
// Add commission data to order
$order['items'] = $items_with_commission;
$order['commission_amount'] = round($order_commission, 2);
$order['commission_rate'] = round($weighted_rate, 2);
$order['total_items'] = count($items_with_commission);
// Check if commission record exists in database
$existing_commission = $this->db
->select('id, status, commission_amount')
->from('affiliator_commissions')
->where('order_id', $order['id_orders'])
->get()
->row();
if ($existing_commission) {
$order['commission_status'] = $existing_commission->status;
$order['commission_id'] = $existing_commission->id;
$order['commission_recorded'] = (float) $existing_commission->commission_amount;
} else {
$order['commission_status'] = 'not_created';
$order['commission_id'] = null;
$order['commission_recorded'] = 0;
}
// Accumulate totals
$total_orders_commission += $order_commission;
$total_orders_amount += $order_amount;
}
// Add summary data
$result = [
'orders' => $orders,
'summary' => [
'total_orders' => count($orders),
'total_amount' => $total_orders_amount,
'total_commission' => round($total_orders_commission, 2),
'average_commission_rate' => $total_orders_amount > 0
? round(($total_orders_commission / $total_orders_amount) * 100, 2)
: 0,
'referral_code' => $referral_code,
'affiliator_type' => $affiliator_type
]
];
return $result;
}
/**
* Get affiliator by referral code
* EXISTING METHOD - Keep for backward compatibility
*
* @param string $referral_code
* @return array|null
*/
private function _get_affiliator_by_referral_code($referral_code)
{
$this->db->select('id, referral_code, type, commission_rate, customer_discount_rate, status');
$this->db->from('affiliators');
$this->db->where('UPPER(referral_code)', strtoupper($referral_code));
$result = $this->db->get()->row_array();
return $result ?: null;
}
/**
* Get commission rate for specific item based on rules
* Priority: product_specific (30) > brand (20) > category (10) > default (0)
*
* @param string $affiliator_type (asmaradoor|asmarasana)
* @param int $product_id
* @param int|null $brand_id
* @param array $category_ids Multiple categories
* @return array ['rate' => float, 'rule_type' => string, 'target_info' => string]
*/
private function _get_commission_rate_for_item($affiliator_type, $product_id, $brand_id, $category_ids = [])
{
// ========================================================================
// PRIORITY 1: Product-specific rule (highest priority = 30)
// ========================================================================
$product_rule = $this->db
->select('commission_rate, id')
->from('affiliator_commission_rules')
->where('affiliator_type', $affiliator_type)
->where('rule_type', 'product')
->where('target_id', $product_id)
->where('status', 'active')
->order_by('priority', 'DESC')
->limit(1)
->get()
->row();
if ($product_rule) {
return [
'rate' => (float) $product_rule->commission_rate,
'rule_type' => 'product',
'target_info' => "Product ID: {$product_id}",
'rule_id' => $product_rule->id
];
}
// ========================================================================
// PRIORITY 2: Brand-specific rule (priority = 20)
// ========================================================================
if ($brand_id) {
$brand_rule = $this->db
->select('commission_rate, id')
->from('affiliator_commission_rules')
->where('affiliator_type', $affiliator_type)
->where('rule_type', 'brand')
->where('target_id', $brand_id)
->where('status', 'active')
->order_by('priority', 'DESC')
->limit(1)
->get()
->row();
if ($brand_rule) {
return [
'rate' => (float) $brand_rule->commission_rate,
'rule_type' => 'brand',
'target_info' => "Brand ID: {$brand_id}",
'rule_id' => $brand_rule->id
];
}
}
// ========================================================================
// PRIORITY 3: Category rule (priority = 10)
// Check all categories, return first match with highest priority
// ========================================================================
if (!empty($category_ids)) {
$category_rule = $this->db
->select('commission_rate, target_id, id')
->from('affiliator_commission_rules')
->where('affiliator_type', $affiliator_type)
->where('rule_type', 'category')
->where_in('target_id', $category_ids)
->where('status', 'active')
->order_by('priority', 'DESC')
->limit(1)
->get()
->row();
if ($category_rule) {
return [
'rate' => (float) $category_rule->commission_rate,
'rule_type' => 'category',
'target_info' => "Category ID: {$category_rule->target_id}",
'rule_id' => $category_rule->id
];
}
}
// ========================================================================
// PRIORITY 4: Default rule (lowest priority = 0)
// ========================================================================
$default_rule = $this->db
->select('commission_rate, id')
->from('affiliator_commission_rules')
->where('affiliator_type', $affiliator_type)
->where('rule_type', 'default')
->where('target_id IS NULL')
->where('status', 'active')
->order_by('priority', 'DESC')
->limit(1)
->get()
->row();
if ($default_rule) {
return [
'rate' => (float) $default_rule->commission_rate,
'rule_type' => 'default',
'target_info' => 'Default rate',
'rule_id' => $default_rule->id
];
}
// ========================================================================
// FALLBACK: No rule found (should not happen if properly configured)
// ========================================================================
log_message('warning', sprintf(
"No commission rule found for %s, product %d, brand %d, categories [%s]",
$affiliator_type,
$product_id,
$brand_id,
implode(',', $category_ids)
));
return [
'rate' => 0,
'rule_type' => 'none',
'target_info' => 'No rule configured',
'rule_id' => null
];
}
/**
* Get order items with complete details (brand, categories)
*
* @param int $order_id
* @return array Order items with brand and category information
*/
private function _get_order_items_with_details($order_id)
{
// Get base order items
$this->db->select('
od.id_orders_detail,
od.product_id,
od.item_name,
od.item_price,
od.quantity,
od.subtotal,
p.brand_id,
b.brand as brand_name
');
$this->db->from('orders_detail od');
$this->db->join('products p', 'p.id_products = od.product_id', 'left');
$this->db->join('brands b', 'b.id_brands = p.brand_id', 'left');
$this->db->where('od.orders_id', $order_id);
$items = $this->db->get()->result();
// Enrich dengan category data untuk setiap item
foreach ($items as $item) {
// Get all categories untuk produk ini
$categories = $this->db
->select('cp.id_category, c.category')
->from('category_product cp')
->join('categories c', 'c.id_categories = cp.id_category', 'left')
->where('cp.id_product', $item->product_id)
->get()
->result();
// Extract category IDs dan names
$item->category_ids = [];
$item->category_names = [];
foreach ($categories as $cat) {
if ($cat->id_category) {
$item->category_ids[] = (int) $cat->id_category;
$item->category_names[] = $cat->category;
}
}
}
return $items;
}
// ==================== WITHDRAWAL FUNCTIONS ====================
/**
* Get withdrawal history for an affiliator
*
* @param int $affiliator_id
* @return array Withdrawal records
*/
private function _get_withdrawals_history($affiliator_id)
{
$withdrawals = $this->db->select('*')
->from('affiliator_withdrawals')
->where('affiliator_id', $affiliator_id)
->order_by('created_at', 'DESC')
->get()
->result_array();
return $withdrawals;
}
// ==================== LINK STATISTICS FUNCTIONS ====================
/**
* Get all active affiliate links with their statistics
*
* @param int $affiliator_id
* @return array Array of affiliate links with statistics
*/
private function _get_affiliate_links_with_statistics($affiliator_id)
{
$links = $this->db->select('
al.id,
al.link_code,
al.link_type,
al.product_id,
al.title,
al.description,
al.intended_platform,
al.campaign_name,
al.short_url,
al.full_url,
al.status,
al.total_clicks,
al.unique_clicks,
al.total_conversions,
al.total_revenue,
al.last_clicked_at,
al.created_at,
al.expires_at
')
->from('affiliator_links al')
->where('al.affiliator_id', $affiliator_id)
->where('al.status', 'active')
->order_by('al.created_at', 'DESC')
->get()
->result_array();
foreach ($links as &$link) {
$link['click_stats'] = $this->_get_link_click_statistics($link['id']);
$link['conversion_stats'] = $this->_get_link_conversion_statistics($link['id']);
}
return $links;
}
/**
* Get click statistics for a specific affiliate link
*
* @param int $link_id
* @return array Click statistics
*/
private function _get_link_click_statistics($link_id)
{
$stats = $this->db->select('
COUNT(*) as total_clicks,
COUNT(DISTINCT ip_address) as unique_clicks_by_ip,
COUNT(DISTINCT session_id) as unique_visitors_by_session
')
->from('visits')
->where('link_id', $link_id)
->where('is_affiliate_visit', 1)
->get()
->row();
return [
'total_clicks' => $stats ? (int) $stats->total_clicks : 0,
'unique_clicks' => $stats ? (int) $stats->unique_clicks_by_ip : 0,
'unique_visitors' => $stats ? (int) $stats->unique_visitors_by_session : 0
];
}
/**
* Get conversion statistics for a specific affiliate link
*
* @param int $link_id
* @return array Conversion statistics
*/
private function _get_link_conversion_statistics($link_id)
{
$stats = $this->db->select('
COUNT(*) as total_conversions,
SUM(commission_amount) as total_commission,
SUM(CASE WHEN status = "approved" OR status = "paid" THEN commission_amount ELSE 0 END) as approved_commission,
SUM(CASE WHEN status = "pending" THEN commission_amount ELSE 0 END) as pending_commission,
SUM(order_amount) as total_order_value
')
->from('affiliator_commissions')
->where('link_id', $link_id)
->get()
->row();
return [
'total_conversions' => $stats ? (int) $stats->total_conversions : 0,
'total_commission' => $stats ? (float) $stats->total_commission : 0.00,
'approved_commission' => $stats ? (float) $stats->approved_commission : 0.00,
'pending_commission' => $stats ? (float) $stats->pending_commission : 0.00,
'total_order_value' => $stats ? (float) $stats->total_order_value : 0.00
];
}
// ==================== CUSTOMER REFERRAL FUNCTIONS ====================
/**
* Get total number of customers referred by this referral code
*
* @param string $referral_code
* @return int Total referred customers
*/
private function _get_total_referred_customers($referral_code)
{
$result = $this->db->select('COUNT(*) as total')
->from('customers')
->where('refferal', $referral_code)
->get()
->row();
return $result ? (int) $result->total : 0;
}
/**
* Get list of customers who used this referral code
*
* @param string $referral_code
* @return array Customer data
*/
private function _get_referred_customers_data($referral_code)
{
$customers = $this->db->select('name, phone, email, join_date')
->from('customers')
->where('refferal', $referral_code)
->order_by('join_date', 'DESC')
->get()
->result_array();
return $customers;
}
// ==================== AJAX/API FUNCTIONS ====================
/**
* Get daily clicks data for chart (AJAX endpoint)
*
* @return void Outputs JSON
*/
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->db->select('DATE(created_at) AS date, COUNT(DISTINCT ip_address) AS unique_visits')
->from('visits')
->where('referral_code', $referral_code)
->where('is_affiliate_visit', 1)
->where('DATE(created_at) >=', $start_date)
->where('DATE(created_at) <=', $end_date)
->group_by('DATE(created_at)')
->order_by('date', 'ASC')
->get()
->result_array();
echo json_encode($daily_clicks);
}
// 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 = [
'bank_name' => $bank_name,
'bank_account_name' => $account_name,
'bank_account_number' => $account_number,
];
// Update data menggunakan query builder
$this->db->where('id_customer', $id_customer);
$update_data_bank = $this->db->update('affiliators', $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 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');
$link_sosmed = $this->input->post('link_sosmed');
$kategori = $this->input->post('kategori');
$commission_rate = 0;
$customer_discount_rate = 0;
if ($kategori == 'asmaradoor') {
$commission_rate = 10.00;
$customer_discount_rate = 10.00;
} else if ($kategori == 'amarasana') {
$commission_rate = 20.00;
}
// Membuat referral dan voucher
$prefix = strtoupper(substr($nama, 0, 3));
$referral = "LACI{$prefix}";
// Data untuk tabel
$register_data = [
'customer_id' => $id_customer,
'social_media' => $link_sosmed,
'referral_code' => $referral,
'customer_discount_rate' => $customer_discount_rate,
'commission_rate' => $commission_rate,
'status' => 'pending',
'type' => $kategori,
];
// Insert data ke tabel
if ($this->db->insert('affiliators', $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);
}
// 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');
}
$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['browser_title'] .= ' - Shipping Address';
$this->data_header['meta_description'] = $meta_description;
$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)
) {
$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;
$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['browser_title'] .= ' - Wishlist';
$this->data_header['meta_description'] = $meta_description;
// 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();
$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!";
$this->data_header['browser_title'] .= ' - Claim Warranty';
$this->data_header['meta_description'] = $meta_description;
// 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 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');
}
$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['browser_title'] .= ' - Password Change';
$this->data_header['meta_description'] = $meta_description;
$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');
}
$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['browser_title'] .= ' - Transaction History';
$this->data_header['meta_description'] = $meta_description;
$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');
}
$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['browser_title'] .= ' - Point Rewards';
$this->data_header['meta_description'] = $meta_description;
$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());
}
}
}