Server : Apache/2.4.18 (Ubuntu) System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64 User : oppastar ( 1041) PHP Version : 7.0.33-0ubuntu0.16.04.15 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority, Directory : /proc/self/root/var/www/laciasmara.com/public_html/shop/application/controllers/admin/ |
Upload File : |
<?php if (!defined('BASEPATH')) { exit('No direct script access allowed'); } class Vouchers extends Admin_Controller { //this property is used for validating existing voucher title on call back edit voucher private $voucher_current_id = null; function __construct() { parent::__construct(); $this->load->model('voucher_m'); $this->load->model('customer_m'); $this->load->model('product_m'); $this->load->model('category_m'); $this->load->model('brand_m'); $this->load->helper('rajaongkir'); } public function index() { $data['userdata'] = $this->session->userdata(); $data['title'] = 'Voucher | Laciasmara'; $this->load->view('admin_new/layouts/header', $data); $this->load->view('admin_new/voucher/index'); $this->load->view('admin_new/layouts/footer'); } public function add() { $data['userdata'] = $this->session->userdata(); $data['title'] = 'Tambah Voucher | Laciasmara'; $data['provinces'] = $this->getProvinces(); $data['customers'] = $this->customer_m->fetch_all_customers(); $data['categories'] = $this->category_m->all_categories(); $data['brands'] = $this->brand_m->get_all_brands(); $data['products'] = $this->product_m->all_products(); $this->load->view('admin_new/layouts/header', $data); $this->load->view('admin_new/voucher/add_voucher'); $this->load->view('admin_new/layouts/footer'); } public function detail($id_voucher = null) { if (!$id_voucher) { redirect('admin/marketing/voucher'); } $data['userdata'] = $this->session->userdata(); $data['title'] = 'Detail Voucher | Laciasmara'; $data['provinces'] = $this->getProvinces(); $data['customers'] = $this->customer_m->fetch_all_customers(); $data['categories'] = $this->category_m->all_categories(); $data['brands'] = $this->brand_m->get_all_brands(); $data['products'] = $this->product_m->all_products(); $data['voucher'] = $this->getVoucherById($id_voucher); $this->load->view('admin_new/layouts/header', $data); $this->load->view('admin_new/voucher/detail_voucher'); $this->load->view('admin_new/layouts/footer'); } public function get_vouchers() { $sort = $this->input->get('sort', true); $dateFilter = $this->input->get('date_filter', true); $startDate = $this->input->get('start_date', true); $endDate = $this->input->get('end_date', true); $tab = $this->input->get('tab', true); // Filter berdasarkan jenis voucher $isNormalPromo = filter_var($this->input->get('isNormalPromo', true), FILTER_VALIDATE_BOOLEAN); $isBirthdayPromo = filter_var($this->input->get('isBirthdayPromo', true), FILTER_VALIDATE_BOOLEAN); $isGenderPromo = filter_var($this->input->get('isGenderPromo', true), FILTER_VALIDATE_BOOLEAN); $isTimePromo = filter_var($this->input->get('isTimePromo', true), FILTER_VALIDATE_BOOLEAN); $isCityPromo = filter_var($this->input->get('isCityPromo', true), FILTER_VALIDATE_BOOLEAN); $isQuantityPromo = filter_var($this->input->get('isQuantityPromo', true), FILTER_VALIDATE_BOOLEAN); $isProvincePromo = filter_var($this->input->get('isProvincePromo', true), FILTER_VALIDATE_BOOLEAN); $isCategoryPromo = filter_var($this->input->get('isCategoryPromo', true), FILTER_VALIDATE_BOOLEAN); $isBrandPromo = filter_var($this->input->get('isBrandPromo', true), FILTER_VALIDATE_BOOLEAN); $isProductPromo = filter_var($this->input->get('isProductPromo', true), FILTER_VALIDATE_BOOLEAN); $isCustomerPromo = filter_var($this->input->get('isCustomerPromo', true), FILTER_VALIDATE_BOOLEAN); $page = (int) ($this->input->get('page', true) ?? 1); $limit = (int) ($this->input->get('limit', true) ?? 10); $offset = ($page - 1) * $limit; $searchTerm = $this->input->get('search', true); // Build main query $this->db->select(' v.id_vouchers, v.voucher_code, v.voucher_name, v.voucher_type, v.qty_used, v.qty_ready, v.maxqty_per_person, v.min_order, v.discount_type, v.discount_value, v.created_date, v.expired_date, v.birthmonth, v.gender, v.promostart, v.promoend, v.provincepromo, v.quantitypromo, v.categorypromo, v.brandpromo, v.productpromo, v.customerpromo, COUNT(CASE WHEN o.redeemed_voucher_code = v.voucher_code THEN 1 ELSE NULL END) as actual_usage_count '); $this->db->from('vouchers v'); $this->db->join('orders o', 'o.redeemed_voucher_code = v.voucher_code', 'left'); // Filter status voucher berdasarkan tanggal kedaluwarsa if ($tab === 'active') { $this->db->where('(v.expired_date IS NULL OR v.expired_date >= CURDATE())'); } elseif ($tab === 'inactive') { $this->db->where('v.expired_date < CURDATE()'); } // Filter berdasarkan jenis voucher if ( $isNormalPromo || $isBirthdayPromo || $isGenderPromo || $isTimePromo || $isCityPromo || $isQuantityPromo || $isProvincePromo || $isCategoryPromo || $isBrandPromo || $isProductPromo || $isCustomerPromo ) { $voucherTypes = []; if ($isNormalPromo) $voucherTypes[] = 'normal promo'; if ($isBirthdayPromo) $voucherTypes[] = 'birthday promo'; if ($isGenderPromo) $voucherTypes[] = 'gender promo'; if ($isTimePromo) $voucherTypes[] = 'time promo'; if ($isCityPromo) $voucherTypes[] = 'city promo'; if ($isQuantityPromo) $voucherTypes[] = 'quantity promo'; if ($isProvincePromo) $voucherTypes[] = 'province promo'; if ($isCategoryPromo) $voucherTypes[] = 'category promo'; if ($isBrandPromo) $voucherTypes[] = 'brand promo'; if ($isProductPromo) $voucherTypes[] = 'product promo'; if ($isCustomerPromo) $voucherTypes[] = 'customer promo'; if (!empty($voucherTypes)) { $this->db->where_in('v.voucher_type', $voucherTypes); } } // Filter berdasarkan tanggal pembuatan voucher if ($dateFilter) { switch ($dateFilter) { case 'today': $this->db->where('DATE(v.created_date) = CURDATE()'); break; case 'yesterday': $this->db->where('DATE(v.created_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)'); break; case 'last7days': $this->db->where('v.created_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)'); break; case 'last30days': $this->db->where('v.created_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)'); break; case 'thisMonth': $this->db->where('MONTH(v.created_date) = MONTH(CURDATE()) AND YEAR(v.created_date) = YEAR(CURDATE())'); break; case 'thisYear': $this->db->where('YEAR(v.created_date) = YEAR(CURDATE())'); break; case 'custom': if ($startDate && $endDate) { $startDate = date('Y-m-d', strtotime($startDate)); $endDate = date('Y-m-d', strtotime($endDate)); if ($startDate && $endDate) { $this->db->where('DATE(v.created_date) >=', $startDate); $this->db->where('DATE(v.created_date) <=', $endDate); } } break; } } // Pencarian if (!empty($searchTerm)) { $this->db->group_start(); $this->db->like('v.voucher_code', $searchTerm); $this->db->or_like('v.voucher_name', $searchTerm); $this->db->or_like('v.voucher_type', $searchTerm); $this->db->or_like('v.birthmonth', $searchTerm); $this->db->or_like('v.gender', $searchTerm); $this->db->or_like('v.categorypromo', $searchTerm); $this->db->or_like('v.brandpromo', $searchTerm); $this->db->or_like('v.productpromo', $searchTerm); $this->db->or_like('v.customerpromo', $searchTerm); $this->db->group_end(); } // Group by untuk menghindari duplikasi voucher $this->db->group_by('v.id_vouchers'); // Apply sorting if ($sort) { switch ($sort) { case 'dipakai_banyak': $this->db->order_by('actual_usage_count', 'DESC'); break; case 'dipakai_dikit': $this->db->order_by('actual_usage_count', 'ASC'); break; default: // Default sort by newest created date $this->db->order_by('v.created_date', 'DESC'); } } else { // Default sort by newest created date $this->db->order_by('v.created_date', 'DESC'); } // Apply pagination $this->db->limit($limit, $offset); // Execute query $query = $this->db->get(); $all_vouchers = $query->result(); // Post-processing data foreach ($all_vouchers as $voucher) { // Format tanggal $voucher->created_date_formatted = date('d M Y H:i', strtotime($voucher->created_date)); $voucher->expired_date_formatted = !empty($voucher->expired_date) ? date('d M Y H:i', strtotime($voucher->expired_date)) : 'No Expiry'; // Format waktu promo jika ada if (!empty($voucher->promostart) && !empty($voucher->promoend)) { $voucher->promo_period = date('d M Y H:i', strtotime($voucher->promostart)) . ' - ' . date('d M Y H:i', strtotime($voucher->promoend)); } else { $voucher->promo_period = 'N/A'; } // Format tipe diskon if ($voucher->discount_type == 'percentage') { $voucher->discount_formatted = $voucher->discount_value . '%'; } else { $voucher->discount_formatted = 'Rp ' . number_format($voucher->discount_value, 0, ',', '.'); } // Format min order $voucher->min_order_formatted = 'Rp ' . number_format($voucher->min_order, 0, ',', '.'); // Format voucher type untuk tampilan $voucher->voucher_type_text = ucwords($voucher->voucher_type); // Set CSS class berdasarkan tipe voucher switch ($voucher->voucher_type) { case 'normal promo': $voucher->voucher_type_class = 'bg-blue-100 text-blue-700 px-2 py-1 rounded'; break; case 'birthday promo': $voucher->voucher_type_class = 'bg-pink-100 text-pink-700 px-2 py-1 rounded'; break; case 'gender promo': $voucher->voucher_type_class = 'bg-purple-100 text-purple-700 px-2 py-1 rounded'; break; case 'time promo': $voucher->voucher_type_class = 'bg-yellow-100 text-yellow-700 px-2 py-1 rounded'; break; case 'city promo': $voucher->voucher_type_class = 'bg-green-100 text-green-700 px-2 py-1 rounded'; break; case 'quantity promo': $voucher->voucher_type_class = 'bg-indigo-100 text-indigo-700 px-2 py-1 rounded'; break; case 'province promo': $voucher->voucher_type_class = 'bg-teal-100 text-teal-700 px-2 py-1 rounded'; break; case 'category promo': $voucher->voucher_type_class = 'bg-orange-100 text-orange-700 px-2 py-1 rounded'; break; case 'brand promo': $voucher->voucher_type_class = 'bg-red-100 text-red-700 px-2 py-1 rounded'; break; case 'product promo': $voucher->voucher_type_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded'; break; case 'customer promo': $voucher->voucher_type_class = 'bg-cyan-100 text-cyan-700 px-2 py-1 rounded'; break; default: $voucher->voucher_type_class = 'bg-gray-100 text-gray-700 px-2 py-1 rounded'; } // Status berdasarkan tanggal expired $now = new DateTime(); $expiry = !empty($voucher->expired_date) ? new DateTime($voucher->expired_date) : null; if ($expiry && $now > $expiry) { $voucher->status = 'Expired'; $voucher->status_class = 'bg-red-100 text-red-700 px-2 py-1 rounded'; } else { $voucher->status = 'Active'; $voucher->status_class = 'bg-green-100 text-green-700 px-2 py-1 rounded'; } // Usage status if ($voucher->actual_usage_count === null) { $voucher->actual_usage_count = 0; } // Format usage $voucher->usage_formatted = $voucher->actual_usage_count . ' / ' . $voucher->qty_ready; } // Get total number of vouchers (for pagination) $this->db->select('COUNT(DISTINCT v.id_vouchers) as total'); $this->db->from('vouchers v'); // Apply the same filters for counting if ( $isNormalPromo || $isBirthdayPromo || $isGenderPromo || $isTimePromo || $isCityPromo || $isQuantityPromo || $isProvincePromo || $isCategoryPromo || $isBrandPromo || $isProductPromo || $isCustomerPromo ) { $voucherTypes = []; if ($isNormalPromo) $voucherTypes[] = 'normal promo'; if ($isBirthdayPromo) $voucherTypes[] = 'birthday promo'; if ($isGenderPromo) $voucherTypes[] = 'gender promo'; if ($isTimePromo) $voucherTypes[] = 'time promo'; if ($isCityPromo) $voucherTypes[] = 'city promo'; if ($isQuantityPromo) $voucherTypes[] = 'quantity promo'; if ($isProvincePromo) $voucherTypes[] = 'province promo'; if ($isCategoryPromo) $voucherTypes[] = 'category promo'; if ($isBrandPromo) $voucherTypes[] = 'brand promo'; if ($isProductPromo) $voucherTypes[] = 'product promo'; if ($isCustomerPromo) $voucherTypes[] = 'customer promo'; if (!empty($voucherTypes)) { $this->db->where_in('v.voucher_type', $voucherTypes); } } // Filter berdasarkan tanggal untuk counting if ($dateFilter) { switch ($dateFilter) { case 'today': $this->db->where('DATE(v.created_date) = CURDATE()'); break; case 'yesterday': $this->db->where('DATE(v.created_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)'); break; case 'last7days': $this->db->where('v.created_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)'); break; case 'last30days': $this->db->where('v.created_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)'); break; case 'thisMonth': $this->db->where('MONTH(v.created_date) = MONTH(CURDATE()) AND YEAR(v.created_date) = YEAR(CURDATE())'); break; case 'thisYear': $this->db->where('YEAR(v.created_date) = YEAR(CURDATE())'); break; case 'custom': if ($startDate && $endDate) { $startDate = date('Y-m-d', strtotime($startDate)); $endDate = date('Y-m-d', strtotime($endDate)); if ($startDate && $endDate) { $this->db->where('DATE(v.created_date) >=', $startDate); $this->db->where('DATE(v.created_date) <=', $endDate); } } break; } } // Search filter untuk counting if (!empty($searchTerm)) { $this->db->group_start(); $this->db->like('v.voucher_code', $searchTerm); $this->db->or_like('v.voucher_name', $searchTerm); $this->db->or_like('v.voucher_type', $searchTerm); $this->db->or_like('v.birthmonth', $searchTerm); $this->db->or_like('v.gender', $searchTerm); $this->db->or_like('v.categorypromo', $searchTerm); $this->db->or_like('v.brandpromo', $searchTerm); $this->db->or_like('v.productpromo', $searchTerm); $this->db->or_like('v.customerpromo', $searchTerm); $this->db->group_end(); } $count_query = $this->db->get(); $count_result = $count_query->row(); $total_vouchers = $count_result->total; // Prepare pagination info $total_pages = ceil($total_vouchers / $limit); $pagination = [ 'current_page' => $page, 'total_pages' => $total_pages, 'total_records' => $total_vouchers, 'limit' => $limit ]; foreach ($all_vouchers as $voucher) { $voucher->_pagination = $pagination; } // Return JSON response echo json_encode($all_vouchers); } public function create_voucher() { // Verifikasi CSRF $this->load->library('form_validation'); $this->form_validation->set_rules('voucher_name', 'Nama Voucher', 'required'); $this->form_validation->set_rules('voucher_code', 'Kode Voucher', 'required|is_unique[vouchers.voucher_code]'); $this->form_validation->set_rules('voucher_type', 'Tipe Voucher', 'required'); if ($this->form_validation->run() == FALSE) { $this->session->set_flashdata('message', validation_errors()); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/add'); // Redirect kembali ke form return; } // Ambil data dari form $voucher_type_form = $this->input->post('voucher_type'); // Mengganti karakter "_" dengan spasi pada voucher_type $voucher_type_db = str_replace('_', ' ', $voucher_type_form); $voucher_data = array( 'voucher_code' => $this->input->post('voucher_code'), 'voucher_name' => $this->input->post('voucher_name'), 'voucher_type' => $voucher_type_db, // Menggunakan voucher_type dengan spasi 'qty_used' => $this->input->post('qty_voucher') ? $this->input->post('qty_voucher') : 0, 'qty_ready' => $this->input->post('qty_voucher') ? $this->input->post('qty_voucher') : NULL, 'maxqty_per_person' => $this->input->post('usage_limit_per_user') ? $this->input->post('usage_limit_per_user') : NULL, 'min_order' => $this->input->post('min_purchase') ? $this->input->post('min_purchase') : NULL, 'discount_type' => $this->input->post('discount_type'), 'discount_value' => $this->input->post('discount_type') == 'percentage' ? $this->input->post('discount_percentage') : $this->input->post('discount_amount'), 'created_date' => date('Y-m-d H:i:s'), 'expired_date' => $this->input->post('valid_until') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_until'))) : NULL ); // Set field sesuai tipe voucher yang dipilih (menggunakan voucher_type dari form yang masih mengandung "_") switch ($voucher_type_form) { case 'birthday_promo': $selected_birthmonths = $this->input->post('selected_birthday_months'); $voucher_data['birthmonth'] = is_array($selected_birthmonths) ? implode(', ', $selected_birthmonths) : $selected_birthmonths; break; case 'gender_promo': $selected_genders = $this->input->post('selected_genders'); $voucher_data['gender'] = is_array($selected_genders) ? implode(', ', $selected_genders) : $selected_genders; break; case 'time_promo': $valid_from = $this->input->post('valid_from'); $valid_until = $this->input->post('valid_until'); $time_start = $this->input->post('time_start'); $time_end = $this->input->post('time_end'); // Pastikan input tidak kosong if (!$valid_from || !$valid_until || !$time_start || !$time_end) { $this->session->set_flashdata('message', 'Tanggal dan waktu promo tidak boleh kosong.'); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/add'); return; } // Format ulang tanggal dan waktu $promostart = date('Y-m-d H:i:s', strtotime("$valid_from $time_start")); $promoend = date('Y-m-d H:i:s', strtotime("$valid_until $time_end")); // Validasi: promostart harus lebih awal dari promoend if ($promostart >= $promoend) { $this->session->set_flashdata('message', 'Waktu mulai promo harus lebih awal dari waktu akhir.'); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/add'); return; } $voucher_data['promostart'] = $promostart; $voucher_data['promoend'] = $promoend; break; case 'quantity_promo': $voucher_data['quantitypromo'] = $this->input->post('min_quantity'); break; case 'province_promo': $selected_province_ids = $this->input->post('selected_province_ids'); $voucher_data['provincepromo'] = is_array($selected_province_ids) ? implode(', ', $selected_province_ids) : $selected_province_ids; break; case 'category_promo': $selected_category_ids = $this->input->post('selected_category_ids'); $voucher_data['categorypromo'] = is_array($selected_category_ids) ? implode(', ', $selected_category_ids) : $selected_category_ids; break; case 'brand_promo': $selected_brand_ids = $this->input->post('selected_brand_ids'); $voucher_data['brandpromo'] = is_array($selected_brand_ids) ? implode(', ', $selected_brand_ids) : $selected_brand_ids; break; case 'product_promo': $selected_product_ids = $this->input->post('selected_product_ids'); $voucher_data['productpromo'] = is_array($selected_product_ids) ? implode(', ', $selected_product_ids) : $selected_product_ids; break; case 'customer_promo': $selected_customer_ids = $this->input->post('selected_customer_ids'); $voucher_data['customerpromo'] = is_array($selected_customer_ids) ? implode(', ', $selected_customer_ids) : $selected_customer_ids; break; } // Set periode promo hanya jika BUKAN time_promo if ($voucher_type_form !== 'time_promo') { $voucher_data['promostart'] = $this->input->post('valid_from') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_from'))) : NULL; $voucher_data['promoend'] = $this->input->post('valid_until') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_until'))) : NULL; } // Insert data voucher ke database $this->db->insert('vouchers', $voucher_data); $voucher_id = $this->db->insert_id(); if ($voucher_id) { $this->session->set_flashdata('message', 'Berhasil menambah voucher baru dengan kode : ' . $this->input->post('voucher_code')); $this->session->set_flashdata('message_type', 'success'); } else { $this->session->set_flashdata('message', 'Gagal menambah voucher baru'); $this->session->set_flashdata('message_type', 'error'); } // Redirect ke halaman daftar voucher redirect('admin/marketing/voucher'); } public function update_voucher($id_voucher = null) { if (!$id_voucher) { redirect('admin/marketing/voucher'); } // Verifikasi CSRF $this->load->library('form_validation'); $this->form_validation->set_rules('voucher_name', 'Nama Voucher', 'required'); // Cek kode voucher unik, kecuali jika kodenya sama dengan kode voucher yang sedang diedit $voucher = $this->db->get_where('vouchers', ['id_vouchers' => $id_voucher])->row(); if ($this->input->post('voucher_code') != $voucher->voucher_code) { $this->form_validation->set_rules('voucher_code', 'Kode Voucher', 'required|is_unique[vouchers.voucher_code]'); } else { $this->form_validation->set_rules('voucher_code', 'Kode Voucher', 'required'); } $this->form_validation->set_rules('voucher_type', 'Tipe Voucher', 'required'); if ($this->form_validation->run() == FALSE) { $this->session->set_flashdata('message', validation_errors()); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/detail/' . $id_voucher); // Redirect kembali ke form edit return; } // Ambil data dari form $voucher_type_form = $this->input->post('voucher_type'); // Mengganti karakter "_" dengan spasi pada voucher_type $voucher_type_db = str_replace('_', ' ', $voucher_type_form); $voucher_data = array( 'voucher_code' => $this->input->post('voucher_code'), 'voucher_name' => $this->input->post('voucher_name'), 'voucher_type' => $voucher_type_db, // Menggunakan voucher_type dengan spasi 'qty_used' => $this->input->post('qty_voucher') ? $this->input->post('qty_voucher') : 0, 'qty_ready' => $this->input->post('qty_voucher') ? $this->input->post('qty_voucher') : NULL, 'maxqty_per_person' => $this->input->post('usage_limit_per_user') ? $this->input->post('usage_limit_per_user') : NULL, 'min_order' => $this->input->post('min_purchase') ? $this->input->post('min_purchase') : NULL, 'discount_type' => $this->input->post('discount_type'), 'discount_value' => $this->input->post('discount_type') == 'percentage' ? $this->input->post('discount_percentage') : $this->input->post('discount_amount'), 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => $this->session->userdata('name'), 'expired_date' => $this->input->post('valid_until') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_until'))) : NULL ); // Reset semua field tipe voucher khusus $reset_fields = [ 'birthmonth', 'gender', 'promostart', 'promoend', 'quantitypromo', 'provincepromo', 'categorypromo', 'brandpromo', 'productpromo', 'customerpromo' ]; foreach ($reset_fields as $field) { $voucher_data[$field] = NULL; } // Set field sesuai tipe voucher yang dipilih (menggunakan voucher_type dari form yang masih mengandung "_") switch ($voucher_type_form) { case 'birthday_promo': $selected_birthmonths = $this->input->post('selected_birthday_months'); $voucher_data['birthmonth'] = is_array($selected_birthmonths) ? implode(', ', $selected_birthmonths) : $selected_birthmonths; break; case 'gender_promo': $selected_genders = $this->input->post('selected_genders'); $voucher_data['gender'] = is_array($selected_genders) ? implode(', ', $selected_genders) : $selected_genders; break; case 'time_promo': $valid_from = $this->input->post('valid_from'); $valid_until = $this->input->post('valid_until'); $time_start = $this->input->post('time_start'); $time_end = $this->input->post('time_end'); // Pastikan input tidak kosong if (!$valid_from || !$valid_until || !$time_start || !$time_end) { $this->session->set_flashdata('message', 'Tanggal dan waktu promo tidak boleh kosong.'); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/detail/' . $id_voucher); return; } // Format ulang tanggal dan waktu $promostart = date('Y-m-d H:i:s', strtotime("$valid_from $time_start")); $promoend = date('Y-m-d H:i:s', strtotime("$valid_until $time_end")); // Validasi: promostart harus lebih awal dari promoend if ($promostart >= $promoend) { $this->session->set_flashdata('message', 'Waktu mulai promo harus lebih awal dari waktu akhir.'); $this->session->set_flashdata('message_type', 'error'); redirect('admin/marketing/voucher/detail/' . $id_voucher); return; } $voucher_data['promostart'] = $promostart; $voucher_data['promoend'] = $promoend; break; case 'quantity_promo': $voucher_data['quantitypromo'] = $this->input->post('min_quantity'); break; case 'province_promo': $selected_province_ids = $this->input->post('selected_province_ids'); $voucher_data['provincepromo'] = is_array($selected_province_ids) ? implode(', ', $selected_province_ids) : $selected_province_ids; break; case 'category_promo': $selected_category_ids = $this->input->post('selected_category_ids'); $voucher_data['categorypromo'] = is_array($selected_category_ids) ? implode(', ', $selected_category_ids) : $selected_category_ids; break; case 'brand_promo': $selected_brand_ids = $this->input->post('selected_brand_ids'); $voucher_data['brandpromo'] = is_array($selected_brand_ids) ? implode(', ', $selected_brand_ids) : $selected_brand_ids; break; case 'product_promo': $selected_product_ids = $this->input->post('selected_product_ids'); $voucher_data['productpromo'] = is_array($selected_product_ids) ? implode(', ', $selected_product_ids) : $selected_product_ids; break; case 'customer_promo': $selected_customer_ids = $this->input->post('selected_customer_ids'); $voucher_data['customerpromo'] = is_array($selected_customer_ids) ? implode(', ', $selected_customer_ids) : $selected_customer_ids; break; } // Set periode promo jika ada // Set periode promo hanya jika BUKAN time_promo if ($voucher_type_form !== 'time_promo') { $voucher_data['promostart'] = $this->input->post('valid_from') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_from'))) : NULL; $voucher_data['promoend'] = $this->input->post('valid_until') ? date('Y-m-d H:i:s', strtotime($this->input->post('valid_until'))) : NULL; } // Update data voucher di database $this->db->where('id_vouchers', $id_voucher); $update_result = $this->db->update('vouchers', $voucher_data); if ($update_result) { $this->session->set_flashdata('message', 'Berhasil mengubah voucher dengan kode: ' . $this->input->post('voucher_code')); $this->session->set_flashdata('message_type', 'success'); } else { $this->session->set_flashdata('message', 'Gagal mengubah voucher'); $this->session->set_flashdata('message_type', 'error'); } // Redirect ke halaman daftar voucher redirect('admin/marketing/voucher'); } public function delete($id) { // Check if this is an AJAX request if ($this->input->is_ajax_request()) { // Process for AJAX request if ($this->db->delete('vouchers', ['id_vouchers' => $id])) { // Success response for AJAX $response = [ 'status' => true, 'message' => 'Berhasil menghapus voucher dengan ID: ' . $id ]; } else { // Error response for AJAX $response = [ 'status' => false, 'message' => 'Gagal menghapus voucher.' ]; } // Send JSON response $this->output ->set_content_type('application/json') ->set_output(json_encode($response)); } else { // Process for non-AJAX request (regular form submission) if ($this->db->delete('vouchers', ['id_vouchers' => $id])) { $this->session->set_flashdata('message', 'Berhasil menghapus voucher dengan ID: ' . $id); $this->session->set_flashdata('message_type', 'success'); } else { $this->session->set_flashdata('message', 'Gagal menghapus voucher.'); $this->session->set_flashdata('message_type', 'error'); } redirect('admin/marketing/voucher'); } } private function getProvinces() { return $this->db->select('rajaongkir_province_id as id, province as name') ->from('indonesia_provinces') ->order_by('province', 'ASC') ->get() ->result(); } public function get_province_name($id) { return $this->db->select('province') ->where('rajaongkir_province_id', $id) ->get('indonesia_provinces') ->row('province'); } private function getVoucherById($id_voucher) { return $this->db->select('*') ->from('vouchers') ->where('id_vouchers', $id_voucher) ->get() ->row(); } // //this is to list all vouchers // public function index() // { // /*----FILTER SEARCH VOUCHER--*/ // if (isset($_POST['search_voucher'])) { // //get product name from form // $this->data['keyword'] = $this->security->xss_clean( // $this->input->post('voucher') // ); // //get all customers // $this->db->select('*'); // $this->db->from('vouchers'); // $this->db->like('voucher_name', $this->data['keyword']); // $this->db->or_like('voucher_code', $this->data['keyword']); // $this->db->order_by('created_date', 'DESC'); // $this->data['vouchers'] = $this->db->get()->result(); // } else { // //pagination in action. 300 results per page // $this->load->library('pagination'); // $config['base_url'] = base_url() . 'admin/vouchers/index'; // $config['total_rows'] = $this->voucher_m->record_count(); // $config['per_page'] = 300; // $config["uri_segment"] = 4; // $config['num_tag_open'] = // '<span style="padding-left:10px; padding-right:10px">'; // $config['num_tag_close'] = '</span>'; // $this->pagination->initialize($config); // $this->data['vouchers'] = $this->voucher_m->get_all_vouchers( // $config["per_page"], // $this->uri->segment(4) // ); // $this->data['use_pagination'] = 'yes'; // } // //load view // $this->data['subview'] = 'admin/vouchers/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 a new voucher // public function add() // { // $this->data['products'] = $this->db // ->distinct() // ->select('title,id_products') // ->from('products') // ->where('product_status', 1) // ->order_by('title') // ->get() // ->result(); // $this->data['customers'] = $this->db // ->distinct() // ->select('id_customers,name,email') // ->from('customers') // ->where('status', 1) // ->order_by('name') // ->get() // ->result(); // $this->data['vouchers'] = $this->voucher_m->get_new(); // //get parent product categories // $this->load->model('category_m'); // $this->data['parent_categories'] = $this->category_m->get_parent_categories(); // //get brands // $this->db // ->select('id_brands, brand') // ->from('brands') // ->where('status', '1') // ->order_by('brand', 'ASC'); // $this->data['brands'] = $this->db->get()->result(); // //validation in action // //validation check in action // $config = $this->voucher_m->rules; // $this->form_validation->set_rules($config); // $this->form_validation->set_error_delimiters( // '<div class="error">', // '</div>' // ); // if ($this->form_validation->run($this) == true) { // $created_date = date('Y-m-d H:i:s'); // if ($this->input->post('expired_date')) { // $expired_date = explode('-', $this->input->post('expired_date')); // $new_expired_date = // $expired_date[2] . '-' . $expired_date[1] . '-' . $expired_date[0]; // } else { // $new_expired_date = null; // } // $data = $this->table_data_processing( // $this->input->post('voucher_name'), // $this->input->post('voucher_code'), // $this->input->post('qty_ready'), // $this->input->post('maxqty_per_person'), // $this->input->post('min_order'), // $this->input->post('discount_type'), // $this->input->post('discount_value'), // $created_date, // $new_expired_date, // $this->input->post('voucher_type'), // $this->input->post('birthmonth'), // $this->input->post('gender'), // $this->input->post('promostart'), // $this->input->post('promoend'), // $this->input->post('provincepromo'), // $this->input->post('quantitypromo') // ); // $this->input->post('voucher_type') == 'brand promo' // ? ($data['brandpromo'] = implode(',', $this->input->post('brand_id'))) // : ($data['brandpromo'] = null); // $this->input->post('voucher_type') == 'product promo' // ? ($data['productpromo'] = implode( // ',', // $this->input->post('product_id') // )) // : ($data['productpromo'] = null); // $this->input->post('voucher_type') == 'customer promo' // ? ($data['customerpromo'] = implode( // ',', // $this->input->post('customer_id') // )) // : ($data['customerpromo'] = null); // $this->voucher_m->add_voucher($data); // $voucher_name = $this->input->post('voucher_name'); // $user_id = $this->session->userdata('admin')['id']; // $activity = 'User menambah voucher (' . $voucher_name . ')'; // log_activity($user_id, $activity); // $this->session->set_flashdata( // 'success', // '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Voucher Add Successful</p>' // ); // redirect('admin/vouchers'); // } // //get all provinces data from provinces table // $this->db // ->select('rajaongkir_province_id, province') // ->from('indonesia_provinces') // ->order_by('rajaongkir_province_id', 'ASC'); // $this->data['provinces'] = $this->db->get()->result(); // //load view // $this->data['subview'] = 'admin/vouchers/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 edit voucher in admin public function edit($id = null) { //check if id exist. If not exist, show 404. $count = $this->voucher_m->count_exist($id); if ($count == 0) { //page not exist show_404(); } $this->load->model('category_m'); $this->data['parent_categories'] = $this->category_m->get_parent_categories(); //get brands $this->db ->select('id_brands, brand') ->from('brands') ->where('status', '1') ->order_by('brand', 'ASC'); $this->data['brands'] = $this->db->get()->result(); $this->data['products'] = $this->db ->distinct() ->select('title,id_products') ->from('products') ->where('product_status', 1) ->order_by('title') ->get() ->result(); $this->data['customers'] = $this->db ->distinct() ->select('id_customers,name,email') ->from('customers') ->where('status', 1) ->order_by('name') ->get() ->result(); $this->data['vouchers'] = $this->voucher_m->get($id); //get all chosen (active) categories $active_categories = $this->data['vouchers']->categorypromo; if ($active_categories != null) { $this->data['chosen_categories'] = array_filter( explode(',', $active_categories) ); //array_filter to remove empty array element } //get all chosen (active) brands $active_brands = $this->data['vouchers']->brandpromo; if ($active_brands != null) { $this->data['chosen_brands'] = array_filter(explode(',', $active_brands)); //array_filter to remove empty array element } //get all chosen (active) product $active_product = $this->data['vouchers']->productpromo; if ($active_product != null) { $this->data['chosen_products'] = array_filter( explode(',', $active_product) ); //array_filter to remove empty array element } //get all chosen (active) brands $active_customer = $this->data['vouchers']->customerpromo; if ($active_customer != null) { $this->data['chosen_customers'] = array_filter( explode(',', $active_customer) ); //array_filter to remove empty array element } $this->voucher_current_id = (int) $id; //validation check in action $config = $this->voucher_m->rules; $this->form_validation->set_rules($config); $this->form_validation->set_error_delimiters( '<div class="error">', '</div>' ); if ($this->form_validation->run($this) == true) { //get current created date from table $this->db ->select('created_date') ->from('vouchers') ->where('id_vouchers', (int) $id); $created_date = $this->db->get()->row()->created_date; if ($this->input->post('expired_date')) { $expired_date = explode('-', $this->input->post('expired_date')); $new_expired_date = $expired_date[2] . '-' . $expired_date[1] . '-' . $expired_date[0]; } else { $new_expired_date = null; } $data = $this->table_data_processing( $this->input->post('voucher_name'), $this->input->post('voucher_code'), $this->input->post('qty_ready'), $this->input->post('maxqty_per_person'), $this->input->post('min_order'), $this->input->post('discount_type'), $this->input->post('discount_value'), $created_date, $new_expired_date, $this->input->post('voucher_type'), $this->input->post('birthmonth'), $this->input->post('gender'), $this->input->post('promostart'), $this->input->post('promoend'), $this->input->post('provincepromo'), $this->input->post('quantitypromo') ); $this->input->post('voucher_type') == 'brand promo' ? ($data['brandpromo'] = implode(',', $this->input->post('brand_id'))) : ($data['brandpromo'] = null); $this->input->post('voucher_type') == 'product promo' ? ($data['productpromo'] = implode( ',', $this->input->post('product_id') )) : ($data['productpromo'] = null); $this->input->post('voucher_type') == 'customer promo' ? ($data['customerpromo'] = implode( ',', $this->input->post('customer_id') )) : ($data['customerpromo'] = null); $this->voucher_m->edit_voucher($id, $data); $voucher_name = $this->input->post('voucher_name'); $user_id = $this->session->userdata('admin')['id']; $activity = 'User mengedit voucher (' . $voucher_name . ')'; log_activity($user_id, $activity); $this->session->set_flashdata( 'success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Voucher Edit Successful</p>' ); redirect('admin/vouchers/edit/' . $id); } //get all provinces data from provinces table $this->db ->select('rajaongkir_province_id, province') ->from('indonesia_provinces') ->order_by('rajaongkir_province_id', 'ASC'); $this->data['provinces'] = $this->db->get()->result(); //load view $this->data['subview'] = 'admin/vouchers/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 voucher // public function delete($id) // { // //check if id exist. If not exist, show 404. // $count = $this->voucher_m->count_exist($id); // if ($count == 0) { // //page not exist // show_404(); // } // //logging // $user_id = $this->session->userdata('admin')['id']; // $this->db->select('voucher_name'); // $this->db->from('vouchers'); // $this->db->where('id_vouchers', $id); // $query = $this->db->get(); // $data = $query->row(); // if ($data) { // $activity = 'User menghapus voucher (' . $data->voucher_name . ')'; // } else { // $activity = 'User menghapus voucher (' . $id . ')'; // } // log_activity($user_id, $activity); // //delete voucher // $this->voucher_m->delete($id); // $this->session->set_flashdata( // 'success', // '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Voucher Delete Successful</p>' // ); // redirect('admin/vouchers'); // } private function table_data_processing( $voucher_name, $voucher_code, $qty_ready, $maxqty_per_person, $min_order, $discount_type, $discount_value, $created_date, $new_expired_date, $voucher_type, $birthmonth, $gender, $promostart, $promoend, $provincepromo, $quantitypromo ) { $data = [ 'voucher_name' => $this->security->xss_clean($voucher_name), 'voucher_code' => $this->security->xss_clean($voucher_code), 'discount_type' => $discount_type, 'discount_value' => (int) $this->security->xss_clean($discount_value), 'created_date' => $created_date, 'expired_date' => $new_expired_date, 'voucher_type' => $voucher_type, 'birthmonth' => $birthmonth, 'gender' => $gender, 'promostart' => $promostart, 'promoend' => $promoend, 'provincepromo' => $provincepromo, 'quantitypromo' => $quantitypromo, ]; if ($qty_ready == '') { $data['qty_ready'] = null; } else { $data['qty_ready'] = (int) $this->security->xss_clean($qty_ready); } if ($maxqty_per_person == '') { $data['maxqty_per_person'] = null; } else { $data['maxqty_per_person'] = (int) $this->security->xss_clean( $maxqty_per_person ); } if ($min_order == '') { $data['min_order'] = null; } else { $data['min_order'] = (int) $this->security->xss_clean($min_order); } //Promo by Product Category //get category_id from view, $categories_id = $this->input->post('category_id'); //check id there is content inside category array if (is_array($categories_id)) { $categories_id_count = count($categories_id); } else { $categories_id_count = 0; } if ($categories_id_count > 0) { $data['categorypromo'] = implode(',', $categories_id); } else { $data['categorypromo'] = null; } //Promo by Brand //get brand_id from view, $brands_id = $this->input->post('brand_id'); //check id there is content inside brand array if (is_array($brands_id)) { $brands_id_count = count($brands_id); } else { $brands_id_count = 0; } if ($brands_id_count > 0) { $data['brandpromo'] = implode(',', $brands_id); } else { $data['brandpromo'] = null; } return $data; } //callback function validation add new voucher //make it private by adding _ public function _cek_existing_voucher_code($str) { $num_rows = $this->voucher_m->cek_existing_voucher_code( $str, $this->voucher_current_id ); if ($num_rows != 0) { $this->form_validation->set_message( '_cek_existing_voucher_code', 'voucher code already exist !' ); return false; } else { return true; } } public function upload_vouchers() { //upload products data if (!isset($_POST['upload_csv'])) { show_404(); } //check if the uploaded file is csv format $mimes = ['application/vnd.ms-excel', 'text/plain', 'text/csv', 'text/tsv']; if (in_array($_FILES['userfile']['type'], $mimes)) { ini_set('auto_detect_line_endings', true); //to detect line ending //continue import operation //open the csv file and put into variable ($file = fopen($_FILES['userfile']['tmp_name'], 'r')) or die('cannot open file'); //initialize array $csv_data = []; //if not reach end of file... while (!feof($file)) { //put the csv into array.. $csv_data[] = fgetcsv($file, 10000, '~'); //file, length, separator.. } fclose($file); //close the file /* echo '<pre>'; print_r($csv_data); echo '</pre>'; exit(); */ $row_number = 0; foreach ($csv_data as $item) { $row_number = $row_number + 1; //skip the 1st row... if ($row_number != 1) { if (empty($item)) { continue; } //if array is empty, then continue to next iteration and bypass below script.. //check if product code already exist, if already exist, update the row, else, insert new $this->db ->select('voucher_code') ->from('vouchers') ->where('voucher_code', $item[0]); $count_code = $this->db->get()->num_rows(); if ($count_code > 0) { //voucher code already exist. update only.. } else { //insert new vouchers //add to vouchers table $data = [ 'voucher_code' => $item[0], 'voucher_name' => $item[1], 'voucher_type' => $item[2], 'discount_type' => $item[7], 'discount_value' => $item[8], ]; if (empty($item[6])) { $data['min_order'] = null; } else { $data['min_order'] = $item[6]; } if (empty($item[5])) { $data['maxqty_per_person'] = null; } else { $data['maxqty_per_person'] = $item[5]; } if (empty($item[4])) { $data['qty_ready'] = null; } else { $data['qty_ready'] = $item[4]; } if (empty($item[9])) { $data['expired_date'] = null; } else { $data['expired_date'] = $item[9]; } switch ($item[2]) { case 'normal promo': # code... break; case 'birthday promo': $data['birthmonth'] = $item[3]; break; case 'time promo': if (strpos($item[3], '|') !== false) { //must have | for start and end time $timepromo_array = explode('|', $item[3]); $data['promostart'] = trim($timepromo_array[0]); $data['promoend'] = trim($timepromo_array[1]); } break; case 'quantity promo': $data['quantitypromo'] = $item[3]; break; case 'province promo': $this->db ->select('rajaongkir_province_id') ->from('indonesia_provinces') ->where('province', $item[3]); $province_id = $this->db->get()->row(); if (count($province_id) > 0) { $data['provincepromo'] = $province_id->rajaongkir_province_id; } break; case 'category promo': if (strpos($item[3], '|') !== false) { //has more than 1 category $category_array = explode('|', $item[3]); $category_id_array = []; foreach ($category_array as $category_name) { //check if category exist $this->db ->select('id_categories') ->from('categories') ->where('category', trim($category_name)); $category_id = $this->db->get()->row(); if (count($category_id) > 0) { $category_id_array[] = $category_id->id_categories; } } $data['categorypromo'] = implode(',', $category_id_array); } else { //has only 1 category //check if category exist $this->db ->select('id_categories') ->from('categories') ->where('category', trim($item[3])); $category_id = $this->db->get()->row(); if (count($category_id) > 0) { $data['categorypromo'] = $category_id->id_categories; } } break; case 'brand promo': if (strpos($item[3], '|') !== false) { //has more than 1 brand $brand_array = explode('|', $item[3]); $brand_id_array = []; foreach ($brand_array as $brand_name) { //check if category exist $this->db ->select('id_brands') ->from('brands') ->where('brand', trim($brand_name)); $brand_id = $this->db->get()->row(); if (count($brand_id) > 0) { $brand_id_array[] = $brand_id->id_brands; } } $data['brandpromo'] = implode(',', $brand_id_array); } else { //has only 1 brand //check if brand exist $this->db ->select('id_brands') ->from('brands') ->where('brand', trim($item[3])); $brand_id = $this->db->get()->row(); if (count($brand_id) > 0) { $data['brandpromo'] = $brand_id->id_brands; } } break; } //insert into vouchers table $this->db->insert('vouchers', $data); } } /*---end if($row_number != 1) --*/ } /*---end foreach ($csv_data as $item) ---*/ $this->session->set_flashdata( 'success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Vouchers CSV Imported.</p>' ); redirect('admin/vouchers'); } else { //not a csv file. Not allowed. die('Sorry, file type not allowed. Please upload only CSV file.'); } } }