|
Server : Apache/2.4.18 (Ubuntu) System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64 User : oppastar ( 1041) PHP Version : 7.0.33-0ubuntu0.16.04.15 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority, Directory : /var/www/laciasmara.com/public_html/shop/application/controllers/admin/ |
Upload File : |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Brands extends Admin_Controller
{
//this property is used for validating existing brand title on call back edit brand
private $brand_current_id = NULL;
function __construct()
{
parent::__construct();
$this->load->model('brand_m');
$this->load->model('product_m');
}
public function manage()
{
$data['userdata'] = $this->session->userdata();
$data['title'] = 'Pengaturan Merk | Laciasmara';
$data['total_brands'] = $this->brand_m->count_brands();
$data['active_brands'] = $this->brand_m->count_brands(1);
$data['inactive_brands'] = $this->brand_m->count_brands(0);
$this->load->view('admin_new/layouts/header', $data);
$this->load->view('admin_new/brands/manage_brands.php');
$this->load->view('admin_new/layouts/footer');
}
public function add_brand()
{
$data['userdata'] = $this->session->userdata();
$data['title'] = 'Tambah Merk | Laciasmara';
$this->load->view('admin_new/layouts/header', $data);
$this->load->view('admin_new/brands/add_brand');
$this->load->view('admin_new/layouts/footer');
}
function edit_brand($id_brand = NULL)
{
if (!$id_brand) {
redirect('admin/products/manage-brand');
}
$data['userdata'] = $this->session->userdata();
$data['title'] = 'Ubah Merk | Laciasmara';
$data['brand'] = $this->brand_m->fetch_brand_by_id($id_brand);
$this->load->view('admin_new/layouts/header', $data);
$this->load->view('admin_new/brands/edit_brand');
$this->load->view('admin_new/layouts/footer');
}
function brand_product($id_brand = NULL)
{
if (!$id_brand) {
redirect('admin/products/manage-brand');
}
$data['userdata'] = $this->session->userdata();
$data['title'] = 'Produk Merk | Laciasmara';
$data['brand'] = $this->brand_m->fetch_brand_by_id($id_brand);
$this->load->view('admin_new/layouts/header', $data);
$this->load->view('admin_new/brands/brand_product');
$this->load->view('admin_new/layouts/footer');
}
public function get_brands()
{
$tab = $this->input->get('tab', true);
$sort = $this->input->get('sort', true);
$this->db->select('
b.*,
(SELECT COALESCE(COUNT(p.id_products), 0)
FROM products p
WHERE p.brand_id = b.id_brands) AS total_products,
(SELECT COALESCE(SUM(s.stock), 0)
FROM stock s
JOIN product_details pd ON s.id_product_detail = pd.id
JOIN products p ON pd.product_id = p.id_products
WHERE p.brand_id = b.id_brands) AS total_stock,
(SELECT COALESCE(MIN(pd.price), 0)
FROM product_details pd
JOIN products p ON pd.product_id = p.id_products
WHERE p.brand_id = b.id_brands) AS min_price,
(SELECT COALESCE(MAX(pd.price), 0)
FROM product_details pd
JOIN products p ON pd.product_id = p.id_products
WHERE p.brand_id = b.id_brands) AS max_price,
(SELECT COALESCE(SUM(od.quantity), 0)
FROM orders_detail od
JOIN product_details pd ON od.item_id = pd.id
JOIN products p ON pd.product_id = p.id_products
WHERE p.brand_id = b.id_brands) AS total_sold
');
$this->db->from('brands b');
if ($tab === 'active') {
$this->db->where('b.status', '1');
} elseif ($tab === 'inactive') {
$this->db->where('b.status', '0');
}
switch ($sort) {
case 'baru':
$this->db->order_by('created_at', 'DESC');
break;
case 'baru-diubah':
$this->db->order_by('updated_at', 'DESC');
break;
case 'terlaris':
$this->db->order_by('total_sold', 'DESC');
break;
case 'kurang-diminati':
$this->db->order_by('total_sold', 'ASC');
break;
case 'harga-tertinggi':
$this->db->order_by('max_price', 'DESC');
break;
case 'harga-terendah':
$this->db->order_by('min_price', 'ASC');
break;
case 'nama-az':
$this->db->order_by('b.brand', 'ASC');
break;
case 'nama-za':
$this->db->order_by('b.brand', 'DESC');
break;
case 'stok-terbanyak':
$this->db->order_by('total_stock', 'DESC');
break;
case 'stok-tersedikit':
$this->db->order_by('total_stock', 'ASC');
break;
default:
$this->db->order_by('b.priority', 'ASC');
break;
}
$this->db->cache_on();
$query = $this->db->get();
$this->db->cache_off();
$all_brands = $query->result();
echo json_encode($all_brands);
}
public function get_brand_products()
{
$brandId = $this->input->get('id', true);
$isEmptyStockOnly = filter_var($this->input->get('isEmptyStockOnly', true), FILTER_VALIDATE_BOOLEAN);
$isLowStock = filter_var($this->input->get('isLowStock', true), FILTER_VALIDATE_BOOLEAN);
$isNewProduct = filter_var($this->input->get('isNewProduct', true), FILTER_VALIDATE_BOOLEAN);
$isDiscounted = filter_var($this->input->get('isDiscounted', true), FILTER_VALIDATE_BOOLEAN);
$isBestSelling = filter_var($this->input->get('isBestSelling', true), FILTER_VALIDATE_BOOLEAN);
$sort = $this->input->get('sort', true);
// Tambahkan parameter filter tanggal
$dateFilter = $this->input->get('date_filter', true);
$startDate = $this->input->get('start_date', true);
$endDate = $this->input->get('end_date', true);
log_message('debug', 'Date Filter: ' . $dateFilter);
// Query utama untuk mendapatkan produk
$this->db->select('
p.title,
p.alias,
p.product_status,
p.id_products,
p.created_at,
p.updated_at,
pd.id as product_detail_id,
MIN(pd.price) as min_price,
MAX(pd.price) as max_price,
CASE
WHEN COUNT(pd.id) > 1 THEN "-"
ELSE MAX(pd.sku)
END as sku,
pi.image as image,
s.stock as total_stock,
b.brand as brand_title,
COALESCE(od_count.total_sold, 0) as total_sold
');
$this->db->from('products p');
$this->db->join('product_details pd', 'pd.product_id = p.id_products', 'left');
$this->db->join('stock s', 'pd.id = s.id_product_detail AND s.warehouse_id = 1', 'left');
$this->db->join('brands b', 'p.brand_id = b.id_brands', 'left');
$this->db->join('product_images pi', 'pi.product_details_id = pd.id AND pi.priority = 1 AND pi.status = 1', 'left');
$this->db->join('category_product cp', 'cp.id_product = p.id_products', 'left');
// Subquery untuk mendapatkan total_sold dengan filter payment_status = 5
// dan filter tanggal sesuai parameter
$od_subquery = "SELECT od.product_id, COUNT(*) as total_sold
FROM orders_detail od
JOIN orders o ON od.orders_id = o.id_orders
WHERE o.payment_status = 5";
// Tambahkan filter tanggal ke subquery
if ($dateFilter) {
switch ($dateFilter) {
case 'today':
$od_subquery .= " AND DATE(o.order_date) = CURDATE()";
break;
case 'yesterday':
$od_subquery .= " AND DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
break;
case 'last7days':
$od_subquery .= " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
break;
case 'last30days':
$od_subquery .= " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
break;
case 'thisMonth':
$od_subquery .= " AND YEAR(o.order_date) = YEAR(CURDATE()) AND MONTH(o.order_date) = MONTH(CURDATE())";
break;
case 'thisYear':
$od_subquery .= " AND YEAR(o.order_date) = YEAR(CURDATE())";
break;
case 'custom':
if ($startDate && $endDate) {
$od_subquery .= " AND DATE(o.order_date) BETWEEN '$startDate' AND '$endDate'";
}
break;
}
}
$od_subquery .= " GROUP BY od.product_id";
$this->db->join("($od_subquery) as od_count", 'p.id_products = od_count.product_id', 'left');
$this->db->where('p.brand_id', $brandId);
// Filter sebelumnya tetap dipertahankan
if ($isEmptyStockOnly) {
$this->db->having('total_stock = 0');
}
if ($isLowStock) {
$this->db->having('total_stock > 0 AND total_stock < 5');
}
if ($isNewProduct) {
$this->db->where("p.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
}
if ($isDiscounted) {
$this->db->where("p.id_products IN (
SELECT pd.product_id FROM product_details pd
WHERE pd.discounted_price > 0
)");
}
if ($isBestSelling) {
// Perlu memodifikasi filter best selling juga untuk menyesuaikan dengan tanggal
$bestselling_subquery = "SELECT od.product_id
FROM orders_detail od
JOIN orders o ON od.orders_id = o.id_orders
WHERE o.payment_status = 5";
// Tambahkan filter tanggal ke subquery best selling jika diperlukan
if ($dateFilter) {
switch ($dateFilter) {
case 'today':
$bestselling_subquery .= " AND DATE(o.order_date) = CURDATE()";
break;
case 'yesterday':
$bestselling_subquery .= " AND DATE(o.order_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
break;
case 'last7days':
$bestselling_subquery .= " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
break;
case 'last30days':
$bestselling_subquery .= " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
break;
case 'thisMonth':
$bestselling_subquery .= " AND YEAR(o.order_date) = YEAR(CURDATE()) AND MONTH(o.order_date) = MONTH(CURDATE())";
break;
case 'thisYear':
$bestselling_subquery .= " AND YEAR(o.order_date) = YEAR(CURDATE())";
break;
case 'custom':
if ($startDate && $endDate) {
$bestselling_subquery .= " AND DATE(o.order_date) BETWEEN '$startDate' AND '$endDate'";
}
break;
}
}
$bestselling_subquery .= " GROUP BY od.product_id ORDER BY COUNT(*) DESC LIMIT 10";
$this->db->join("($bestselling_subquery) AS best_selling", "p.id_products = best_selling.product_id");
}
// Sort
switch ($sort) {
case 'terlaris':
$this->db->order_by('total_sold', 'DESC');
break;
case 'kurang-diminati':
$this->db->order_by('total_sold', 'ASC');
break;
case 'harga-tertinggi':
$this->db->order_by('max_price', 'DESC');
break;
case 'harga-terendah':
$this->db->order_by('min_price', 'ASC');
break;
case 'nama-az':
$this->db->order_by('p.title', 'ASC');
break;
case 'nama-za':
$this->db->order_by('p.title', 'DESC');
break;
case 'stok-terbanyak':
$this->db->order_by('total_stock', 'DESC');
break;
case 'stok-tersedikit':
$this->db->order_by('total_stock', 'ASC');
break;
}
$this->db->group_by('p.id_products');
$query = $this->db->get();
$all_products = $query->result();
// Post-processing (tidak ada perubahan)
foreach ($all_products as $product) {
// Process price range
if (!empty($product->min_price) && !empty($product->max_price)) {
$product->price = ($product->min_price == $product->max_price) ? $product->min_price : $product->min_price . ' - ' . $product->max_price;
} else {
$product->price = 'N/A';
}
unset($product->min_price, $product->max_price);
// Ambil detail produk dengan variannya
$this->db->select('
pd.id as product_detail_id,
pd.sku,
pd.price,
COALESCE(s.stock, 0) as stock,
pd.discounted_price,
GROUP_CONCAT(
CONCAT_WS(": ", pa.product_attribute, pad.attribute_detail)
SEPARATOR ", "
) as variants,
pa.product_attribute as attribute,
pad.attribute_detail as attribute_detail
');
$this->db->from('product_details pd');
$this->db->join('product_combination pc', 'pc.product_details_id = pd.id', 'left');
$this->db->join('product_attributes pa', 'pc.attribute_id = pa.id', 'left');
$this->db->join('product_attributes_detail pad', 'pc.attribute_detail_id = pad.id', 'left');
$this->db->join('stock s', 'pd.id = s.id_product_detail', 'left');
$this->db->where('pd.product_id', $product->id_products);
$this->db->group_by('pd.id');
$this->db->order_by('pd.id', 'ASC');
$variants_query = $this->db->get();
$product->variants = $variants_query->result();
}
echo json_encode($all_products);
}
// Insert new brand
public function store()
{
// Set upload configuration
$config['upload_path'] = './uploads/brand/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 500; // 500KB
$config['encrypt_name'] = TRUE;
// Create directory if not exists
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
// Load upload library
$this->load->library('upload', $config);
// Ambil data dari POST
$data = $this->input->post();
// Buat alias untuk brand
$alias = strtolower(str_replace(' ', '-', preg_replace('/[^a-zA-Z0-9\s]/', '', trim($data['brandName']))));
// Ambil last priority
$this->db->select_max('priority');
$last_priority = $this->db->get('brands')->row()->priority ?? 0;
$priority = $last_priority + 1;
// Data yang akan disimpan ke dalam tabel categories
$brand_data = [
'brand' => htmlspecialchars($data['brandName']),
'alias' => $alias,
'status' => isset($data['status']) ? (string)$data['status'] : 'inactive',
'priority' => $priority,
'meta_title' => htmlspecialchars($data['seoTitle']),
'meta_description' => htmlspecialchars($data['seoMetaDescription']),
'description' => $data['short_desc_id'],
'description_en' => $data['short_desc_en'],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'updated_by' => $this->session->userdata('name') ?? 'System',
];
// Begin transaction
$this->db->trans_begin();
try {
// Upload banner image if exists
if (!empty($_FILES['bannerImage']['name'])) {
if ($this->upload->do_upload('bannerImage')) {
$upload_data = $this->upload->data();
// Validasi dimensi gambar
list($width, $height) = getimagesize($upload_data['full_path']);
if ($width > 1500 || $height > 500) {
// Hapus file yang sudah diupload
@unlink($upload_data['full_path']);
throw new Exception('Dimensi gambar terlalu besar. Maksimal 1500 x 500 pixel.');
}
$brand_data['image'] = $upload_data['file_name'];
} else {
throw new Exception($this->upload->display_errors('', ''));
}
}
if (!empty($_FILES['logoImage']['name'])) {
if ($this->upload->do_upload('logoImage')) {
$upload_data = $this->upload->data();
// Validasi dimensi gambar
list($width, $height) = getimagesize($upload_data['full_path']);
if ($width > 1500 || $height > 500) {
// Hapus file yang sudah diupload
@unlink($upload_data['full_path']);
throw new Exception('Dimensi gambar terlalu besar. Maksimal 1500 x 500 pixel.');
}
$brand_data['logo'] = $upload_data['file_name'];
} else {
throw new Exception($this->upload->display_errors('', ''));
}
}
// Insert kategori
$this->db->insert('brands', $brand_data);
// Commit transaksi jika sukses
if ($this->db->trans_status() === FALSE) {
throw new Exception('Transaction failed');
}
$this->db->trans_commit();
// Set pesan sukses
$this->session->set_flashdata('message', 'Merk berhasil ditambahkan');
$this->session->set_flashdata('message_type', 'success');
// Redirect ke halaman brand
redirect('admin/products/manage-brand');
} catch (Exception $e) {
// Rollback transaksi jika terjadi kesalahan
$this->db->trans_rollback();
// Set pesan error
$this->session->set_flashdata('message', 'Gagal menambahkan brand: ' . $e->getMessage());
$this->session->set_flashdata('message_type', 'error');
// Redirect ke halaman tambah brand
redirect('admin/brands/add-brand');
}
}
// Update from edit_brand
public function update($id_brand)
{
// Set upload configuration
$config['upload_path'] = './uploads/brand/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 500; // 500KB
$config['encrypt_name'] = TRUE;
// Create directory if not exists
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
// Load upload library
$this->load->library('upload', $config);
// Ambil data dari POST
$data = $this->input->post();
// Ambil data brand saat ini dari database
$current_brand = $this->db->get_where('brands', ['id_brands' => $id_brand])->row();
// Buat alias untuk brand
$alias = strtolower(str_replace(' ', '-', preg_replace('/[^a-zA-Z0-9\s]/', '', trim($data['brandName']))));
// Data yang akan diperbarui dalam tabel categories
$brand_data = [
'brand' => htmlspecialchars($data['brandName']),
'alias' => $alias,
'status' => isset($data['status']) ? (string)$data['status'] : 'inactive',
'meta_title' => htmlspecialchars($data['seoTitle']),
'meta_description' => htmlspecialchars($data['seoMetaDescription']),
'description' => $data['short_desc_id'],
'description_en' => $data['short_desc_en'],
'updated_at' => date('Y-m-d H:i:s'),
'updated_by' => $this->session->userdata('name') ?? 'System',
];
// Begin transaction
$this->db->trans_begin();
try {
// Cek apakah ada gambar yang diupload
if (!empty($_FILES['bannerImage']['name'])) {
if ($this->upload->do_upload('bannerImage')) {
$upload_data = $this->upload->data();
// Validasi dimensi gambar
list($width, $height) = getimagesize($upload_data['full_path']);
if ($width > 1500 || $height > 500) {
// Hapus file yang sudah diupload
@unlink($upload_data['full_path']);
throw new Exception('Dimensi gambar terlalu besar. Maksimal 1500 x 500 pixel.');
}
// Hapus gambar lama jika ada
if (!empty($current_brand->image) && file_exists('./uploads/brand/' . $current_brand->image)) {
@unlink('./uploads/brand/' . $current_brand->image);
}
// Simpan gambar baru
$brand_data['image'] = $upload_data['file_name'];
} else {
throw new Exception($this->upload->display_errors('', ''));
}
} elseif (isset($data['removeImage']) && $data['removeImage'] == '1') {
// Jika user memilih untuk menghapus gambar tanpa upload baru
if (!empty($current_brand->image) && file_exists('./uploads/brand/' . $current_brand->image)) {
@unlink('./uploads/brand/' . $current_brand->image);
}
$brand_data['image'] = ''; // Kosongkan field image
}
// Logo Upload
// Cek apakah ada gambar yang diupload
if (!empty($_FILES['logoImage']['name'])) {
if ($this->upload->do_upload('logoImage')) {
$upload_data = $this->upload->data();
// Validasi dimensi gambar
list($width, $height) = getimagesize($upload_data['full_path']);
if ($width > 1500 || $height > 500) {
// Hapus file yang sudah diupload
@unlink($upload_data['full_path']);
throw new Exception('Dimensi gambar terlalu besar. Maksimal 1500 x 500 pixel.');
}
// Hapus gambar lama jika ada
if (!empty($current_brand->logo) && file_exists('./uploads/brand/' . $current_brand->logo)) {
@unlink('./uploads/brand/' . $current_brand->logo);
}
// Simpan gambar baru
$brand_data['logo'] = $upload_data['file_name'];
} else {
throw new Exception($this->upload->display_errors('', ''));
}
} elseif (isset($data['removeLogo']) && $data['removeLogo'] == '1') {
// Jika user memilih untuk menghapus gambar tanpa upload baru
if (!empty($current_brand->logo) && file_exists('./uploads/brand/' . $current_brand->logo)) {
@unlink('./uploads/brand/' . $current_brand->logo);
}
$brand_data['logo'] = ''; // Kosongkan field logo
}
// Update brand
$this->db->where('id_brands', $id_brand);
$this->db->update('brands', $brand_data);
// Commit transaksi jika sukses
if ($this->db->trans_status() === FALSE) {
throw new Exception('Transaction failed');
}
$this->db->trans_commit();
// Set pesan sukses
$this->session->set_flashdata('message', 'Merk berhasil diperbarui');
$this->session->set_flashdata('message_type', 'success');
// Redirect ke halaman brand
redirect('admin/products/manage-brand');
} catch (Exception $e) {
// Rollback transaksi jika terjadi kesalahan
$this->db->trans_rollback();
// Set pesan error
$this->session->set_flashdata('message', 'Gagal memperbarui merk: ' . $e->getMessage());
$this->session->set_flashdata('message_type', 'error');
// Redirect ke halaman edit brand
redirect('admin/brands/edit-brand/' . $id_brand);
}
}
public function updateBrand()
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$id_brands = $this->input->post('id_brands');
$field = $this->input->post('field');
$value = trim($this->input->post('value'));
// Validasi input
if (empty($id_brands) || empty($field) || empty($value)) {
echo json_encode(['success' => false, 'message' => 'Data tidak valid']);
return;
}
// Buat alias dari value yang dikirim
$alias = preg_replace('/[^a-zA-Z0-9\s]/', '', $value); // Hapus karakter spesial
$alias = preg_replace('/\s+/', ' ', $alias); // Ganti banyak spasi dengan satu spasi
$alias = str_replace(' ', '-', $alias); // Ganti spasi dengan tanda "-"
$alias = strtolower($alias); // Ubah ke huruf kecil
// Tentukan field alias yang akan diperbarui
$aliasField = 'alias';
// Update data di database
$this->db->where('id_brands', $id_brands);
$update = $this->db->update('brands', [
$field => $value,
$aliasField => $alias
]);
if ($update) {
echo json_encode([
'success' => true,
'message' => 'Merk berhasil diperbarui',
'csrf_hash' => $this->security->get_csrf_hash() // Perbarui CSRF jika diperlukan
]);
} else {
echo json_encode(['success' => false, 'message' => 'Gagal memperbarui merk']);
}
}
// Delete brand
public function delete_brand($id)
{
// Validasi ID merk
if (!$id || !is_numeric($id)) {
echo json_encode(["success" => false, "message" => "ID merk tidak valid."]);
return;
}
// Memastikan merk yang akan dihapus ada
$this->db->where('id_brands', $id);
$product = $this->db->get('brands')->row();
if (!$product) {
echo json_encode(["success" => false, "message" => "Merk tidak ditemukan."]);
return;
}
// Menghapus produk
$this->db->where('id_brands', $id);
$deleteSuccess = $this->db->delete('brands');
if ($deleteSuccess) {
echo json_encode(["success" => true, "message" => "Merk berhasil dihapus."]);
} else {
echo json_encode(["success" => false, "message" => "Gagal menghapus merk, coba lagi nanti."]);
}
}
public function updateStatus()
{
if (!$this->input->is_ajax_request()) {
show_error('No direct script access allowed', 403);
return;
}
// Ambil data dari POST
$id_brands = $this->input->post('id_brands');
$new_status = $this->input->post('new_status');
// Update harga produk
$this->db->where('id_brands', $id_brands);
$update = $this->db->update('brands', ['status' => $new_status]);
echo json_encode(["success" => $update]);
}
//this is to list all brands
public function index()
{
//Add pagination
$this->load->helper('pagination_helper');
add_pagination(base_url() . 'admin/brands/index', $this->brand_m->record_count(), 6, 4);
//get all brands
$this->data['brands'] = $this->brand_m->get_all_brands();
//load view
$this->data['subview'] = 'admin/brands/index';
$this->load->view('admin/templates/header', $this->data_header);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/templates/footer');
}
//to add & edit brand in admin
public function edit($id = NULL)
{
$this_case = $this->input->post('this_case');
if (isset($this_case)) {
if ($this_case == 'addmerk_in_product') {
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$config = $this->brand_m->rules;
// array_push($config,array(
// 'field' => 'description_en',
// 'label' => 'Description English',
// 'rules' => 'trim'
// ),array(
// 'field' => 'description',
// 'label' => 'Description Indonesia',
// 'rules' => 'trim'
// ));
$this->form_validation->set_rules($config);
if ($this->form_validation->run($this) == FALSE) {
echo json_encode(array('sukses' => validation_errors()));
}
if ($this->form_validation->run($this) == TRUE) {
$image_filename = $this->image_processing($_FILES['userfile'], 'banner');
$logo_filename = $this->image_processing($_FILES['userfile2'], 'logo');
$data = $this->table_data_processing($image_filename, $logo_filename, $this_case);
$this->brand_m->add_brand($data);
$user_id = $this->session->userdata('admin')['id'];
$activity = 'User menambah brand(' . $data['brand'] . ')';
log_activity($user_id, $activity);
$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Merek berhasil dibuat</p>');
$get_all_brands = $this->brand_m->get_brands();
// $output_opt = '<option value="" disabled selected>Pilih Merek...</option>';
$get_all_brands = $this->brand_m->get_brands();
// foreach ($get_all_brands as $key) {
// $output_opt .= '<option value="'.$key->id_brands.'">'.$key->brand.'</option>';
// }
echo json_encode(array(
// 'config'=>$config,
'sukses' => 'sukses',
'get_all_brands' => $get_all_brands,
));
}
}
} else {
if ($id == NULL) {
//create new brand
$this->data['brands'] = $this->brand_m->get_new();
//get ordering number and display at add form
$this->db->select_max('priority')->from('brands');
$current_priority = $this->db->get()->row()->priority;
if ($current_priority == NULL) {
$this->data['brands']->priority = 1;
} else {
$this->data['brands']->priority = $current_priority + 1;
}
} else {
//check if id exist. If not exist, redirect to add new
$count = $this->brand_m->count_exist($id);
if ($count == 0) {
redirect(base_url('admin/brands/edit'));
}
$this->data['brands'] = $this->brand_m->get($id);
$this->brand_current_id = (int) $id;
}
//validation check
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); //add class to form validation error, to be styled
$config = $this->brand_m->rules;
$this->form_validation->set_rules($config);
if ($this->form_validation->run($this) == TRUE) {
$image_filename = $this->image_processing($_FILES['userfile'], 'banner');
$logo_filename = $this->image_processing($_FILES['userfile2'], 'logo');
$data = $this->table_data_processing($image_filename, $logo_filename);
if ($this->brand_current_id == NULL) {
$this->brand_m->add_brand($data);
$user_id = $this->session->userdata('admin')['id'];
$activity = 'User menambah brand(' . $data['brand'] . ')';
log_activity($user_id, $activity);
$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Merek berhasil dibuat</p>');
redirect('admin/brands');
} else {
$this->brand_m->edit_brand($id, $data);
$user_id = $this->session->userdata('admin')['id'];
$activity = 'User mengedit brand(' . $data['brand'] . ')';
log_activity($user_id, $activity);
$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Merek berhasil diedit</p>');
redirect('admin/brands/edit/' . $id);
}
}
$this->data['subview'] = 'admin/brands/edit';
$this->load->view('admin/templates/header', $this->data_header);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/templates/footer');
}
}
//to delete a brand
public function delete($id = NULL)
{
if ($id == NULL) redirect(base_url('admin/brands'));
//check if id exist.
$count = $this->brand_m->count_exist($id);
if ($count == 0) {
redirect(base_url('admin/brands'));
}
//delete image from server
//check if there is an existing image
$this->db->select('image, logo')->from('brands')->where('id_brands', (int) $id);
$image = $this->db->get()->row();
$banner = $image->image;
$logo = $image->logo;
if ($banner != '' && $banner != NULL) {
if (file_exists(FCPATH . '/uploads/brand/' . $banner)) {
//Delete the actual image file from server. FCPATH is codeigniter base path
unlink(FCPATH . '/uploads/brand/' . $banner);
}
}
if ($logo != '' && $logo != NULL) {
if (file_exists(FCPATH . '/uploads/brand/' . $logo)) {
//Delete the actual image file from server. FCPATH is codeigniter base path
unlink(FCPATH . '/uploads/brand/' . $logo);
}
}
//logging
$user_id = $this->session->userdata('admin')['id'];
$this->db->select('brand');
$this->db->from('brands');
$this->db->where('id_brands', $id);
$query = $this->db->get();
$data = $query->row();
// Buat string "title/SKU"
if ($data) {
$activity = 'User menghapus brand (' . $data->brand . ')';
} else {
// Handle jika data produk atau detail produk tidak ditemukan
$activity = 'User menghapus brand (' . $id . ')';
}
log_activity($user_id, $activity);
//delete brand
$this->brand_m->delete($id);
$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Brand berhasil dihapus</p>');
redirect('admin/brands');
}
//image upload processing
private function image_processing($image_file, $image_type = null)
{
if ($image_type == 'banner') {
$banner_input_name = 'userfile';
$max_size = '500';
//get max image width and height from configuration table
$this->db->select('brand_image_width, brand_image_height')->from('configuration')->where('id_configuration', 1);
$image_dimension = $this->db->get()->row();
$max_width = $image_dimension->brand_image_width;
$max_height = $image_dimension->brand_image_height;
} elseif ($image_type == 'logo') {
$banner_input_name = 'userfile2';
$max_size = '200';
//get max logo width and height from configuration table
$this->db->select('brand_logo_width, brand_logo_height')->from('configuration')->where('id_configuration', 1);
$image_dimension = $this->db->get()->row();
$max_width = $image_dimension->brand_logo_width;
$max_height = $image_dimension->brand_logo_height;
}
//check & processing image banner upload files
if ($image_file['size'] > 0) {
$config['upload_path'] = './uploads/brand/';
$config['allowed_types'] = 'png|jpg|jpeg|gif';
$config['max_size'] = $max_size;
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($banner_input_name)) {
$error = array('error' => $this->upload->display_errors());
$error_message = $error['error'];
$this->session->set_flashdata('success', "<div style='background:red; color:white; padding:5px; font-weight:bold;'>$error_message</div>");
if ($this->brand_current_id != NULL) {
redirect('admin/brands/edit/' . $this->brand_current_id);
} elseif ($this->brand_current_id == NULL) {
redirect('admin/brands/edit');
}
} else {
$image = $this->upload->data();
return $image['file_name'];
}
}
}
private function table_data_processing($image_filename, $logo_filename, $this_case = false)
{
$data = array(
'brand' => $this->security->xss_clean($this->input->post('brand_name')),
'alias' => url_title($this->security->xss_clean($this->input->post('brand_name'))),
'status' => $this->input->post('status'),
'priority' => $this->input->post('priority'),
'meta_description' => $this->security->xss_clean($this->input->post('meta_description')),
'meta_title' => $this->security->xss_clean($this->input->post('meta_title')),
'banner_link' => $this->security->xss_clean($this->input->post('banner_link')),
'updated_by' => $this->session->userdata('admin')['name'],
);
$data['description'] = $this->security->xss_clean($this->input->post('description'));
$data['description_en'] = $this->security->xss_clean($this->input->post('description_en'));
if ($this_case == 'addmerk_in_product' && $this_case != false) {
$data['description'] = $this->security->xss_clean($this->input->post('description_merk'));
$data['description_en'] = $this->security->xss_clean($this->input->post('description_en_merk'));
}
//image upload
if (isset($image_filename)) {
$data['image'] = $image_filename;
}
//logo upload
if (isset($logo_filename)) {
$data['logo'] = $logo_filename;
}
return $data;
}
//To delete brand banner image file from server, and from database
public function delete_image($id = NULL, $image_type = NULL)
{
$count = $this->brand_m->count_exist($id);
if ($id == NULL || $count == 0) {
redirect('admin/brands');
}
if ($image_type == 'banner') {
//if image type is banner
//get image file name for deletion
$this->db->select('image')->from('brands')->where('id_brands', (int) $id);
$image = $this->db->get()->row();
if (file_exists(FCPATH . '/uploads/brand/' . $image->image)) {
//Delete the actual image file from server. FCPATH is codeigniter base path
unlink(FCPATH . '/uploads/brand/' . $image->image);
}
//Delete image field from database
$data = array(
'image' => ''
);
$this->db->where('id_brands', (int) $id);
$this->db->update('brands', $data);
} else {
//if image type is logo
//get image file name for deletion
$this->db->select('logo')->from('brands')->where('id_brands', (int) $id);
$image = $this->db->get()->row();
if (file_exists(FCPATH . '/uploads/brand/' . $image->logo)) {
//Delete the actual image file from server. FCPATH is codeigniter base path
unlink(FCPATH . '/uploads/brand/' . $image->logo);
}
//Delete logo field from database
$data = array(
'logo' => ''
);
$this->db->where('id_brands', (int) $id);
$this->db->update('brands', $data);
}
$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Gambar berhasil dihapus</p>');
redirect('admin/brands/edit/' . $id);
}
//callback function validation add new brand
//make it private by adding _
public function _cek_existing_brand_title($str)
{
$num_rows = $this->brand_m->cek_existing_brand_title($str, $this->brand_current_id);
if ($num_rows != 0) {
$this->form_validation->set_message('_cek_existing_brand_title', 'Nama Brand sudah terdaftar');
return FALSE;
} else {
return TRUE;
}
}
public function view($id)
{
$ar_id_product = $this->brand_m->getProductBrand($id);
$this->data['vendors'] = $this->brand_m->getDetailVendors($ar_id_product);
$this->data['subview'] = 'admin/brands/view';
$this->load->view('admin/templates/header', $this->data_header);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/templates/footer');
}
}