|
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 if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Cart extends Public_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('cart_model');
$this->load->model('product_m');
$this->load->model('customer_m');
$this->load->model('Footer_m');
$this->load->model('Category_m');
$this->load->model('Statistic_m');
$this->load->library('VisitorTracking');
$this->load->library('form_validation');
$this->load->library('cart');
}
public function index()
{
$this->load->library('GoogleClient');
$this->load->model('Top_banner_m');
$this->visitortracking->trackVisitor();
$loginUrl = $this->googleclient->getLoginUrl();
$this->data_footer['googleUrl'] = $loginUrl;
$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');
}
$this->visitortracking->trackVisitor();
if ($this->session->userdata('customer')) {
$id_customer = (int) $this->session->userdata('customer')['customer_id'];
$this->data['customer'] = $this->customer_m->get_customer($id_customer);
}
$meta_description = ($this->session->userdata('site_lang') == 'english')
? "Pleasure is waiting in your cart. Checkout and try your instruments of love today!"
: "Sensasi nikmat sudah menunggu di keranjang. Checkout dan cobain piranti asmara hari ini!";
$this->data_header['browser_title'] .= ' - Cart';
$this->data_header['meta_description'] = $meta_description;
$this->session->set_userdata('is_from_cart', 'yes');
$this->load->view("themes/3/header_new", $this->data_header);
$this->load->view('cart_new');
$this->load->view("themes/3/footer_new", $this->data_footer);
}
public function cart_new()
{
$this->visitortracking->trackVisitor();
$this->load->library('GoogleClient');
$this->load->model('Top_banner_m');
$loginUrl = $this->googleclient->getLoginUrl();
$this->data_footer['googleUrl'] = $loginUrl;
if ($this->session->userdata('site_lang') == 'english') {
$this->lang->load('mainpage', 'english');
} else {
$this->lang->load('mainpage', 'indonesian');
}
$this->visitortracking->trackVisitor();
if ($this->session->userdata('customer')) {
$id_customer = (int) $this->session->userdata('customer')['customer_id'];
$this->data['customer'] = $this->customer_m->get_customer($id_customer);
}
$this->data_header['browser_title'] .= ' - Cart';
// Load views
$this->load->view("themes/3/header_new", $this->data_header);
$this->load->view('cart_new');
$this->load->view("themes/3/footer_new", $this->data_footer);
}
public function add()
{
//check if there is post request, if not, reject & redirect
if (empty($_POST)) {
redirect('cart');
}
$data['id'] = (int) $this->input->post('product_id');
$data['name'] = ucwords($this->input->post('product_name'));
$data['qty'] = (int) $this->input->post('qty');
$data['price'] = (int) $this->input->post('price');
$data['options']['warehouse_name'] = '';
$data['options']['warehouse_id'] = null;
//check if this item has discount
$discount_price = $this->db
->select('discounted_price')
->from('product_details')
->where('id', (int) $this->input->post('product_id'))
->get()
->row()->discounted_price;
if ($discount_price > 0) {
$data['options']['has_discount'] = 'yes';
} else {
$data['options']['has_discount'] = 'no';
}
$this->cart->product_name_rules = '[:print:]'; //this is to eliminate cart product name restriction on special characters
$this->cart->insert($data);
redirect('cart');
}
public function add_to_cart()
{
$this->load->library('session');
$this->load->library('user_agent');
$this->load->model('Cart_model');
if ($this->input->server('REQUEST_METHOD') !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
return;
}
$id_customer = $this->session->userdata('customer')['customer_id'] ?? null;
$cart_items = $this->session->userdata('temp_cart') ?? [];
// Kirim data POST ke model untuk validasi & mendapatkan detail produk
$post_data = $this->input->post();
$product_data = $this->Cart_model->get_product_data($post_data);
if ($product_data['status'] === 'error') {
echo json_encode($product_data);
return;
}
// Jika user belum login, simpan ke session sementara
if (!$id_customer) {
$cart_items[] = $product_data['data'];
$this->session->set_userdata('temp_cart', $cart_items);
echo json_encode([
'status' => 'error',
'message' => 'Redirect to login'
]);
return;
}
// Jika user sudah login, tambahkan ke keranjang
$result = $this->Cart_model->add_to_cart($product_data['data'], $id_customer);
echo json_encode($result);
}
public function get_cart_items()
{
$cart_items = $this->cart->contents();
$items = [];
foreach ($cart_items as $item) {
$items[] = [
'rowid' => $item['rowid'],
'id' => $item['id'],
'detail_id' => $item['detail_id'],
'variant' => $item['variant'],
'name' => $item['name'],
'stock' => $item['options']['stock'],
'qty' => $item['qty'],
'price' => $item['price'],
'image' => $item['options']['image'],
'discount_status' => $this->session->userdata('cart_has_discounted_items'),
'subtotal' => $item['qty'] * $item['price']
];
}
echo json_encode([
'status' => 'success',
'items' => $items,
'total_items' => $this->cart->total_items(),
]);
}
public function update_quantity()
{
$rowid = $this->input->post('rowid');
$action = $this->input->post('action');
if (!$rowid || !$action) {
echo json_encode(['status' => 'error', 'message' => 'Ada yang aneh nih, coba refresh halaman dulu ya']);
return;
}
$cart_item = $this->cart->get_item($rowid);
if (empty($cart_item) || !isset($cart_item['options']['stock'])) {
echo json_encode(['status' => 'error', 'message' => 'Itemnya hilang dari keranjang kamu, coba refresh halaman ini ya']);
return;
}
$current_stock = (int) $cart_item['options']['stock'];
$stock_keep = (int) $cart_item['options']['stock_keep'];
$available_stock = $current_stock - $stock_keep;
$new_qty = $cart_item['qty'];
if ($action === 'increase') {
if ($new_qty < $available_stock) {
$new_qty++;
} else {
echo json_encode(['status' => 'error', 'message' => "Yaah engga bisa ditambahin lagi, stoknya udah mentok nih."]);
return;
}
} elseif ($action === 'decrease') {
if ($new_qty > 1) {
$new_qty--;
} else {
echo json_encode(['status' => 'error', 'message' => 'Jumlah minimal beli 1 ye, kalau mau hapus item, klik tombol hapus']);
return;
}
}
if (isset($this->session->userdata('customer')['customer_id'])) {
// Ambil reseller_id dari session customer
$reseller_id = $this->db->select('reseller_id')
->from('customers')
->where('id_customers', $this->session->userdata('customer')['customer_id'])
->get()
->row()
->reseller_id;
if ($reseller_id) {
// Cek apakah harga reseller dan min_quantity ada
$this->db->select('price, min_quantity')
->from('resellers_price')
->where('reseller_id', $reseller_id)
->where('product_detail_id', $cart_item['id']);
$reseller_price_data = $this->db->get()->row();
if ($reseller_price_data) {
// Jika harga reseller tersedia, gunakan harga reseller
$cart_item['price'] = $reseller_price_data->price;
// Pastikan kuantitas tidak kurang dari min_quantity
if ($new_qty < $reseller_price_data->min_quantity) {
echo json_encode([
'status' => 'error',
'message' => "Sorry, minimum quantity for reseller is {$reseller_price_data->min_quantity} pcs. Please choose higher quantity."
]);
return;
}
} else {
// Jika harga reseller tidak ada, gunakan harga biasa
$cart_item['price'] = $cart_item['price'];
}
}
}
$data = [
'rowid' => $rowid,
'qty' => $new_qty,
'price' => $cart_item['price']
];
if ($this->cart->update($data)) {
echo json_encode(['status' => 'success']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui kuantitas']);
}
}
public function remove($rowid)
{
$data = [
'rowid' => $rowid,
'qty' => 0,
];
$this->cart->update($data);
redirect('cart');
}
public function removes($rowid)
{
if ($rowid == "all") {
$this->cart->destroy();
} else {
$data = [
'rowid' => $rowid,
'qty' => 0,
];
$this->cart->update($data);
}
redirect('category/all-categories', 'refresh');
}
// public function remove_item()
// {
// $rowid = $this->input->post('rowid');
// $detail_id = $this->input->post('detail_id');
// $csrf = $this->security->get_csrf_hash(); // Generate CSRF hash baru
// if ($rowid) {
// $data = [
// 'rowid' => $rowid,
// 'qty' => 0,
// ];
// $this->cart->update($data);
// echo json_encode([
// 'status' => 'success',
// 'total_items' => $this->cart->total_items(), // Kirim total items baru
// 'subtotal' => $this->cart->total(), // Kirim subtotal baru
// 'csrf' => $csrf // Kirim CSRF hash baru
// ]);
// } else {
// echo json_encode([
// 'status' => 'error',
// 'message' => 'Item tidak ditemukan.',
// 'csrf' => $csrf
// ]);
// }
// }
public function remove_item()
{
$this->load->library('cart');
$this->load->library('session');
$rowid = $this->input->post('rowid');
$detail_id = $this->input->post('detail_id');
$csrf = $this->security->get_csrf_hash(); // Generate CSRF hash baru
if ($rowid) {
// Hapus item dari keranjang
$data = [
'rowid' => $rowid,
'qty' => 0,
];
$this->cart->update($data);
// Periksa apakah masih ada produk dengan diskon di keranjang
$cart_items = $this->cart->contents();
$has_discounted_items = false;
foreach ($cart_items as $item) {
// Query database untuk memeriksa apakah produk memiliki harga diskon
$product = $this->db->select('discounted_price')
->where('id', $item['id'])
->get('product_details')
->row();
if ($product && $product->discounted_price > 0) {
$has_discounted_items = true;
break;
}
}
if ($has_discounted_items) {
$this->session->set_userdata('cart_has_discounted_items', 'yes');
} else {
$this->session->unset_userdata('cart_has_discounted_items');
}
// Kirim respons dengan data terbaru
echo json_encode([
'status' => 'success',
'total_items' => $this->cart->total_items(), // Kirim total items baru
'subtotal' => $this->cart->total(), // Kirim subtotal baru
'csrf' => $csrf // Kirim CSRF hash baru
]);
} else {
// Jika rowid tidak ditemukan
echo json_encode([
'status' => 'error',
'message' => 'Item tidak ditemukan.',
'csrf' => $csrf
]);
}
}
public function get_suggested_products($product_id)
{
$product = $this->db->get_where('products', ['id_products' => $product_id])->row();
$suggested_products = [];
if ($product) {
$product_suggest = $product->product_suggest;
if (!empty($product_suggest)) {
$suggested_ids = explode(',', $product_suggest);
$suggested_products = $this->db->select('
p.id_products,
p.title,
p.alias,
p.brand_id,
pd.id AS id_detail,
pd.price,
pd.discounted_price,
COALESCE(variants.variants, "No variants available") AS variants,
pi.image,
pi_secondary.image AS image_secondary,
s.stock,
s.stock_keep,
(COALESCE(s.stock, 0) - COALESCE(s.stock_keep, 0)) AS stock_sell,
IF(s.stock IS NULL OR s.stock_keep IS NULL OR (s.stock - s.stock_keep) <= 0, 1, 0) as sort_order,
total_sales.total_sales,
total_reviews.total_reviews,
rp.price AS reseller_price,
rp.min_quantity AS reseller_min_quantity
')
->from('products p')
->join('product_details pd', 'p.id_products = pd.product_id', 'left')
->join('product_images pi', 'pd.id = pi.product_details_id AND pi.priority = 1 AND pi.status = 1', 'left')
->join('product_images pi_secondary', 'pd.id = pi_secondary.product_details_id AND pi_secondary.priority = 2 AND pi.status = 1', 'left')
->join('stock s', 'pd.id = s.id_product_detail', 'left')
->join('(SELECT item_id, SUM(quantity) AS total_sales FROM orders_detail WHERE warehouse_id = 1 GROUP BY item_id) total_sales', 'pd.id = total_sales.item_id', 'left')
->join('(SELECT product_id, COUNT(id) AS total_reviews FROM product_review GROUP BY product_id) total_reviews', 'p.id_products = total_reviews.product_id', 'left')
->join('(SELECT pc.product_details_id, GROUP_CONCAT(DISTINCT CONCAT_WS(": ", pa.product_attribute, pad.attribute_detail) SEPARATOR "; ") AS variants
FROM product_combination pc
JOIN product_attributes pa ON pc.attribute_id = pa.id
JOIN product_attributes_detail pad ON pc.attribute_detail_id = pad.id
GROUP BY pc.product_details_id) variants', 'pd.id = variants.product_details_id', 'left')
->join('category_product cp', 'p.id_products = cp.id_product', 'inner')
->join('resellers_price rp', 'pd.id = rp.product_detail_id', 'left')
->where_in('p.id_products', $suggested_ids)
->where('p.product_status', '1')
->where('p.deleted_at', null)
->having('(COALESCE(s.stock, 0) - COALESCE(s.stock_keep, 0)) > 0')
->group_by('p.id_products')
->order_by('sort_order', 'ASC')
->order_by('pd.id', 'ASC')
->limit(2)
->get()
->result_array();
$suggested_products = $this->prepare_all_products($suggested_products);
}
}
header('Content-Type: application/json');
echo json_encode([
'status' => 'success',
'data' => $suggested_products
]);
}
private function prepare_all_products($products)
{
$customer = $this->session->userdata('customer');
$is_reseller = false;
$reseller_price_map = []; // Map produk -> reseller price
if (!empty($customer['customer_id'])) {
$customer_id = $customer['customer_id'];
$customer_data = $this->db->where('id_customers', $customer_id)->get('customers')->row_array();
if (!empty($customer_data['reseller_id'])) {
// Cek apakah reseller valid
$reseller = $this->db->where('id_resellers', $customer_data['reseller_id'])->get('resellers')->row_array();
if ($reseller) {
$is_reseller = true;
// Ambil semua harga reseller untuk produk
$reseller_prices = $this->db->where('reseller_id', $reseller['id_resellers'])->get('resellers_price')->result_array();
foreach ($reseller_prices as $price) {
$reseller_price_map[$price['product_detail_id']] = $price['price'];
}
}
}
}
$this->load->model('Review_m');
// Format data produk
$formatted_products = [];
foreach ($products as $product) {
$is_discounted = $product['discounted_price'] > 0;
$default_price = $product['price']; // Harga normal di tabel product_details
$discounted_price = $product['discounted_price'];
$current_price = $is_discounted ? $discounted_price : $default_price;
// Jika reseller, gantikan harga dan tambahkan MSRP
$msrp_price = null;
if ($is_reseller && isset($reseller_price_map[$product['id_detail']])) {
$msrp_price = $current_price; // Harga normal jadi MSRP
$current_price = $reseller_price_map[$product['id_detail']]; // Ganti dengan reseller price
}
$review_data = $this->Review_m->get_product_reviews($product['id_products']);
$average_rating = isset($review_data['average_rating']) ? round($review_data['average_rating'], 1) : 0;
$total_reviews = isset($review_data['total_reviews']) ? $review_data['total_reviews'] : 0;
$variants = !empty($product['variants']) ? explode('; ', $product['variants']) : [];
$formatted_products[] = [
'id' => $product['id_products'],
'title' => $product['title'],
'id_detail' => $product['id_detail'],
'alias' => $product['alias'],
'current_price' => $current_price,
'original_price' => $is_discounted ? $default_price : null, // Hanya untuk customer biasa
'msrp_price' => $msrp_price, // Hanya untuk reseller
'image' => $product['image'],
'image_secondary' => $product['image_secondary'],
'stock' => $product['stock'],
'stock_sell' => $product['stock_sell'],
'average_rating' => $average_rating,
'total_reviews' => $total_reviews,
'variants' => $variants,
'is_wishlisted' => $this->_check_wishlist_status($product['id_products'], $this->session->userdata('customer')['customer_id'])
];
}
return $formatted_products;
}
private function _check_wishlist_status($product_id, $customer_id)
{
if (!$customer_id) return false;
$exists = $this->db->where([
'customer_id' => $customer_id,
'product_id' => $product_id
])->get('wishlists')->num_rows();
return $exists > 0;
}
public function update_cart()
{
//check if there is post request, if not, reject & redirect
if (!isset($_POST['update_cart'])) {
redirect('cart');
}
// Recieve post values,calcute them and update
$cart_info = $_POST['cart_array'];
/* echo '<pre>';
print_r($cart_info);
echo '</pre>';
exit(); */
foreach ($cart_info as $sku => $cart) {
//get product detail id
$this->db
->select('id_product_details')
->from('product_details')
->where('sku', $sku);
$id_product_detail = $this->db->get()->row()->id_product_details;
//check the minimum purchase qty required
if (isset($this->session->userdata('customer')['customer_id'])) {
//customer is logged in
//check if customer is a reseller. if reseller use reseller min quantity
$this->db
->select('reseller_id')
->from('customers')
->where(
'id_customers',
$this->session->userdata('customer')['customer_id']
);
$reseller_id = $this->db->get()->row()->reseller_id;
//check if reseller price already available (already input by admin)
$this->db
->select('price')
->from('resellers_price')
->where('reseller_id', $reseller_id)
->where('product_detail_id', $id_product_detail);
$count_reseller = $this->db->get()->num_rows();
if ($reseller_id != null && $count_reseller > 0) {
//customer is reseller, and data already inputtedby admin. so use reseller min quantity
$this->db
->select('min_quantity')
->from('resellers_price')
->where('reseller_id', $reseller_id)
->where('product_detail_id', $id_product_detail);
$min_quantity = $this->db->get()->row()->min_quantity;
} elseif ($reseller_id == null) {
$min_quantity = 1;
} elseif ($reseller_id != null && $count_reseller == 0) {
//customer is a reseller, but data not input yet, or customer choose empty option..
//then give default reseller min quantity
//get reseller min quantity
$this->db
->select('min_quantity')
->from('resellers_price')
->where('reseller_id', $reseller_id)
->where('product_detail_id', $id_product_detail);
$min_quantity = $this->db->get()->row()->min_quantity;
}
if ($cart['qty'] < $min_quantity) {
//cart quantity is less than minimum quantity
$this->session->set_flashdata(
'no_stock',
"<br>
<p style='background:grey; color:white; padding:5px; font-weight:bold;'>Sorry minimum quantity is {$min_quantity} pcs. Please choose higher quantity.</p>"
);
redirect('cart');
}
}
//check the available stock for current SKU
$this->db
->select('stock')
->from('product_details')
->where('sku', $sku);
$available_stock = (int) $this->db->get()->row()->stock;
if ($cart['qty'] > $available_stock) {
//stocks are not enough
$this->session->set_flashdata(
'no_stock',
'<br>
<p style="background:grey; color:white; padding:5px; font-weight:bold;">Sorry not enough stock for chosen quantity. Please choose smaller quantity.</p>'
);
redirect('cart');
} else {
//stocks are enough
$rowid = $cart['rowid'];
$price = $cart['price'];
$qty = $cart['qty'];
$amount = $price * $cart['qty'];
$data = [
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty,
];
$this->cart->update($data);
}
}
redirect('cart');
}
//callback function validation cek stock available when add to cart
public function cek_stock()
{
$id_product_details = $this->input->post('product_size');
$chosen_quantity = (int) $this->input->post('qty');
//get current stock froms product_details table
$this->db->select('stock');
$this->db->from('product_details');
$this->db->where('id_product_details', $id_product_details);
$query = $this->db->get();
$current_stock = (int) $query->row()->stock;
//check if quantity is less or equal to current stock
if ($chosen_quantity > $current_stock) {
return false;
} else {
return true;
}
}
/*email to user if product is available*/
public function customer_notification()
{
$data = [
'id_products' => (int) $this->input->post('product_id'),
'email' => $this->security->xss_clean(
$this->input->post('emailMeAvailable')
),
];
$this->db->select('*');
$this->db->from('customers_notification');
$this->db->where('id_products', $data['id_products']);
$this->db->where('email', $data['email']);
$query1 = $this->db->get();
$cek = $query1->row();
if ($cek != null) {
$this->session->set_flashdata(
'email_sended1',
'<br>
<p style="background:green; color:white; padding:5px; font-weight:bold;">
Anda sudah mengirim e-mail untuk mengetahui informasi produk ini.<br>
Kami akan segera memberi tahu anda apabila stok tersedia.
</p>'
);
} else {
$this->db->insert('customers_notification', $data);
$this->session->set_flashdata(
'email_sended',
'<br>
<p style="background:green; color:white; padding:5px; font-weight:bold;">
Alamat E-mail diterima.<br>
Kami akan segera memberi tahu anda apabila stok tersedia.
</p>'
);
}
redirect($this->input->post('page_url'));
}
public function customer_notifications()
{
$data = [
'id_products' => (int) $this->input->post('product_id'),
'email' => $this->security->xss_clean(
$this->input->post('emailMeAvailable')
),
];
$this->db->select('*');
$this->db->from('customers_notification');
$this->db->where('id_products', $data['id_products']);
$this->db->where('email', $data['email']);
$query1 = $this->db->get();
$cek = $query1->row();
if ($cek != null) {
$this->session->set_flashdata(
'email_sended1',
'<br>
<p style="background:green; color:white; padding:5px; font-weight:bold;">
Anda sudah mengirim e-mail untuk mengetahui informasi produk ini.<br>
Kami akan segera memberi tahu anda apabila stok tersedia.
</p>'
);
} else {
$this->db->insert('customers_notification', $data);
$this->session->set_flashdata(
'email_sended',
'<br>
<p style="background:green; color:white; padding:5px; font-weight:bold;">
Alamat E-mail diterima.<br>
Kami akan segera memberi tahu anda apabila stok tersedia.
</p>'
);
}
redirect($this->input->post('page_url') . '#' . $data['id_products']);
}
}