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

class Administrator extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('cookie');
		$this->load->library('form_validation');
		$this->load->model('Categories_model');
		$this->load->model('Products_model');
		$this->load->model('Settings_model');
		$this->load->model('Promo_model');
		$this->load->model('Order_model');

		if (!$this->session->userdata('admin')) {
			$cookie = get_cookie('djehbicd');
			if ($cookie == NULL) {
				redirect(base_url());
			} else {
				$getCookie = $this->db->get_where('admin', ['cookie' => $cookie])->row_array();
				if ($getCookie) {
					$dataCookie = $getCookie;
					$dataSession = [
						'id' => $dataCookie['id']
					];
					$this->session->set_userdata('admin', true);
					$this->session->set_userdata($dataSession);
				} else {
					redirect(base_url());
				}
			}
		}

		get_system_auth();
	}

	// dashboard
	public function index()
	{
		$filter = $_GET['filter'];
		$data['title'] = 'Dashboard - Admin Panel';
		$data['getInvoiceonoff'] = $this->Settings_model->getInvoiceonoffday();
		$data['lead'] = $this->Settings_model->getLeadInvoice($filter);
		$data['order'] = $this->Settings_model->getOrderInvoice($filter);
		$data['omset'] = $this->Settings_model->getOmsetInvoice($filter);
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/index', $data);
		$this->load->view('templates/footer_admin');
	}

	// orders
	public function orders()
	{
		$filter = $_GET['filter'];
		if ($filter == NULL) {
			$filter = "";
		}
		$data['title'] = 'Pesanan - Admin Panel';
		$config['base_url'] = base_url() . 'administrator/orders/';
		$config['total_rows'] = $this->Order_model->getOrders($filter, "", "")->num_rows();
		$config['per_page'] = 10;
		$config['first_link']       = 'First';
		$config['last_link']        = 'Last';
		$config['next_link']        = 'Next';
		$config['prev_link']        = 'Prev';
		$config['full_tag_open']    = '<div class="pagging text-center"><nav><ul class="pagination justify-content-center">';
		$config['full_tag_close']   = '</ul></nav></div>';
		$config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
		$config['num_tag_close']    = '</span></li>';
		$config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
		$config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
		$config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['next_tagl_close']  = '<span aria-hidden="true">&raquo;</span></span></li>';
		$config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['prev_tagl_close']  = '</span>Next</li>';
		$config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['first_tagl_close'] = '</span></li>';
		$config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['last_tagl_close']  = '</span></li>';
		$from = $this->uri->segment(3);
		$this->pagination->initialize($config);
		$data['orders'] = $this->Order_model->getOrders($filter, $config['per_page'], $from);
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/orders', $data);
		$this->load->view('templates/footer_admin');
	}

	public function search_orders()
	{
		$key = $_GET['q'];
		$data['title'] = 'Pesanan - Admin Panel';
		$config['base_url'] = base_url() . 'administrator/orders/';
		$config['total_rows'] = $this->Order_model->getSearchOrders($key, "", "")->num_rows();
		$config['per_page'] = 10;
		$config['first_link']       = 'First';
		$config['last_link']        = 'Last';
		$config['next_link']        = 'Next';
		$config['prev_link']        = 'Prev';
		$config['full_tag_open']    = '<div class="pagging text-center"><nav><ul class="pagination justify-content-center">';
		$config['full_tag_close']   = '</ul></nav></div>';
		$config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
		$config['num_tag_close']    = '</span></li>';
		$config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
		$config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
		$config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['next_tagl_close']  = '<span aria-hidden="true">&raquo;</span></span></li>';
		$config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['prev_tagl_close']  = '</span>Next</li>';
		$config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['first_tagl_close'] = '</span></li>';
		$config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['last_tagl_close']  = '</span></li>';
		$from = $this->uri->segment(3);
		$this->pagination->initialize($config);
		$data['orders'] = $this->Order_model->getSearchOrders($key, $config['per_page'], $from);
		$data['search'] = $key;
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/orders', $data);
		$this->load->view('templates/footer_admin');
	}

	public function orders_set_status_action()
	{
		$id_order = $this->input->post('id');
		$status = $this->input->post('status');
		foreach ($id_order as $id) {
			if ($status == 5) {
				$this->db->where('id', $id);
				$this->db->delete('invoice');
			} else {
				$this->db->set('status', $status);
				$this->db->where('id', $id);
				$this->db->update('invoice');
			}
			if ($status == 3) {
				$order = $this->db->get_where('invoice', ['id' => $id])->row_array();
				$transaction = $this->db->get_where('transaction', ['id_invoice' => $order['invoice_code']]);
				foreach ($transaction->result_array() as $t) {
					$this->db->set('transaction', 'transaction+' . $t['qty'] . '', FALSE);
					$this->db->set('stock', 'stock-' . $t['qty'] . '', FALSE);
					$this->db->where('slug', $t['slug']);
					$this->db->update('products');
				}
			}
		}
	}

	public function detail_order($id)
	{
		if ($this->Order_model->getDataInvoice($id)) {
			$data['title'] = 'Detail Pesanan - Admin Panel';
			$data['orders'] = $this->Order_model->getOrderByInvoice($id);
			$data['invoice'] = $this->Order_model->getDataInvoice($id);
			$data['loc'] = $this->Settings_model->getSubdistrictByIdAndCity($data['invoice']['district'], $data['invoice']['regency']);
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/detail_order', $data);
			$this->load->view('templates/footer_admin');
		} else {
			redirect(base_url() . 'administrator/orders');
		}
	}

	public function print_invoice_order($id)
	{
		if ($this->Order_model->getDataInvoice($id)) {
			$data['title'] = 'Detail Pesanan - Admin Panel';
			$data['orders'] = $this->Order_model->getOrderByInvoice($id);
			$data['invoice'] = $this->Order_model->getDataInvoice($id);
			$data['loc'] = $this->Settings_model->getSubdistrictByIdAndCity($data['invoice']['district'], $data['invoice']['regency']);
			$this->load->view('administrator/print_order_invoice', $data);
		} else {
			redirect(base_url() . 'administrator/orders');
		}
	}

	public function print_label_order($id)
	{
		if ($this->Order_model->getDataInvoice($id)) {
			$data['title'] = 'Detail Pesanan - Admin Panel';
			$data['orders'] = $this->Order_model->getOrderByInvoice($id);
			$data['invoice'] = $this->Order_model->getDataInvoice($id);
			$data['loc'] = $this->Settings_model->getSubdistrictByIdAndCity($data['invoice']['district'], $data['invoice']['regency']);
			$this->load->view('administrator/print_label_invoice', $data);
		} else {
			redirect(base_url() . 'administrator/orders');
		}
	}

	public function see_invoice_detail_order($id)
	{
		if ($this->Order_model->getDataInvoice($id)) {
			$data['title'] = 'Detail Pesanan - Admin Panel';
			$data['orders'] = $this->Order_model->getOrderByInvoice($id);
			$data['invoice'] = $this->Order_model->getDataInvoice($id);
			$data['loc'] = $this->Settings_model->getSubdistrictByIdAndCity($data['invoice']['district'], $data['invoice']['regency']);
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/see_invoice_detail_order', $data);
			$this->load->view('templates/footer_admin');
		} else {
			redirect(base_url() . 'administrator/orders');
		}
	}

	public function process_order($id)
	{
		$this->db->set('status', 1);
		$this->db->where('invoice_code', $id);
		$this->db->update('invoice');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Pesanan terkonfirmasi',
            icon: 'success'
            });
        </script>");
		redirect(base_url() . 'administrator/order/' . $id);
	}

	public function finish_orderan($id)
	{
		$this->db->set('process', 1);
		$this->db->set('send', 1);
		$this->db->where('invoice_code', $id);
		$this->db->update('invoice');
		$transaction = $this->db->get_where('transaction', ['id_invoice' => $id]);
		foreach ($transaction->result_array() as $t) {
			$this->db->set('transaction', 'transaction+' . $t['qty'] . '', FALSE);
			$this->db->set('stock', 'stock-' . $t['qty'] . '', FALSE);
			$this->db->where('slug', $t['slug']);
			$this->db->update('products');
		}
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Selesai',
            icon: 'success'
            });
        </script>");
		redirect(base_url() . 'administrator/order/' . $id);
	}

	public function sending_order($id)
	{
		$resi = $this->input->post('resi', true);
		if ($resi == NULL) {
			redirect(base_url() . 'administrator/orders');
		}
		$buyer = $this->db->get_where('invoice', ['invoice_code' => $id])->row_array();
		$this->db->set('status', 2);
		$this->db->set('resi', $resi);
		$this->db->where('invoice_code', $id);
		$this->db->update('invoice');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Pesanan sedang dikirim',
            icon: 'success'
            });
        </script>");
		redirect(base_url() . 'administrator/order/' . $id);
	}

	public function ratings()
	{
		$data['title'] = 'Konfirmasi Rating - Admin Panel';
		$this->db->select("*, rating.id AS ratingId");
		$this->db->from("rating");
		$this->db->join("products", "rating.product=products.id");
		$this->db->order_by('rating.id', 'desc');
		$this->db->where('rating.active', 0);
		$data['rating'] = $this->db->get();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/ratings', $data);
		$this->load->view('templates/footer_admin');
	}

	public function ratings_product($id)
	{
		$product = $this->db->get_where('products', ['id' => $id])->row_array();
		$data['title'] = 'Rating ' . $product['title'] . ' - Admin Panel';
		$this->db->order_by('id', 'desc');
		$this->db->where('product', $id);
		$data['rating'] = $this->db->get('rating');
		$data['product'] = $product;
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/ratings_product', $data);
		$this->load->view('templates/footer_admin');
	}

	public function confirm_rating($id)
	{
		$this->db->set("active", 1);
		$this->db->where('id', $id);
		$this->db->update('rating');
		$this->session->set_flashdata('upload', "<script>
			swal({
			text: 'Rating berhasil ditampilkan',
			icon: 'success'
			});
			</script>");
		redirect(base_url() . 'administrator/' . $_GET['redirect']);
	}

	public function delete_rating($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('rating');
		$this->session->set_flashdata('upload', "<script>
			swal({
			text: 'Rating berhasil dihapus',
			icon: 'success'
			});
			</script>");
		redirect(base_url() . 'administrator/' .  $_GET['redirect']);
	}

	// categories
	public function categories()
	{
		$this->form_validation->set_rules('name', 'Name', 'required', ['required' => 'Nama kategori wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Kategori - Admin Panel';
			$data['getCategories'] = $this->Categories_model->getCategories();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/categories', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = array();
			$upload = $this->Categories_model->uploadIcon();

			if ($upload['result'] == 'success') {
				$this->Categories_model->insertCategory($upload);
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Kategori berhasil ditambahkan',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/categories');
			} else {
				$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                Gagal menambah kategori, pastikan icon berukuran maksimal 2mb dan berformat png, jpg, jpeg. Silakan ulangi lagi.
              </div>");
				redirect(base_url() . 'administrator/categories');
			}
		}
	}

	public function category($id)
	{
		$this->form_validation->set_rules('name', 'Name', 'required', ['required' => 'Nama kategori wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Edit Kategori - Admin Panel';
			$data['category'] = $this->Categories_model->getCategoryById($id);
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/edit_category', $data);
			$this->load->view('templates/footer_admin');
		} else {
			if ($_FILES['icon']['name'] != "") {
				$data = array();
				$upload = $this->Categories_model->uploadIcon();
				if ($upload['result'] == 'success') {
					$this->Categories_model->updateCategory($upload['file']['file_name'], $id);
					$this->session->set_flashdata('upload', "<script>
                        swal({
                        text: 'Kategori berhasil diubah',
                        icon: 'success'
                        });
                        </script>");
					redirect(base_url() . 'administrator/categories');
				} else {
					$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                    Gagal mengubah kategori, pastikan icon berukuran maksimal 2mb dan berformat png, jpg, jpeg. Silakan ulangi lagi.
                  </div>");
					redirect(base_url() . 'administrator/category/' . $id);
				}
			} else {
				$oldIcon = $this->input->post('oldIcon');
				$this->Categories_model->updateCategory($oldIcon, $id);
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Kategori berhasil diubah',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/categories');
			}
		}
	}

	public function deleteCategory($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('categories');
		$this->db->where('category', $id);
		$this->db->delete('products');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Kategori berhasil dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/categories');
	}

	// products
	public function products()
	{
		$data['title'] = 'Produk - Admin Panel';
		$config['base_url'] = base_url() . 'administrator/products/';
		$config['total_rows'] = $this->Products_model->getProducts("", "")->num_rows();
		$config['per_page'] = 10;
		$config['first_link']       = 'First';
		$config['last_link']        = 'Last';
		$config['next_link']        = 'Next';
		$config['prev_link']        = 'Prev';
		$config['full_tag_open']    = '<div class="pagging text-center"><nav><ul class="pagination justify-content-center">';
		$config['full_tag_close']   = '</ul></nav></div>';
		$config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
		$config['num_tag_close']    = '</span></li>';
		$config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
		$config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
		$config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['next_tagl_close']  = '<span aria-hidden="true">&raquo;</span></span></li>';
		$config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['prev_tagl_close']  = '</span>Next</li>';
		$config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['first_tagl_close'] = '</span></li>';
		$config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['last_tagl_close']  = '</span></li>';
		$from = $this->uri->segment(3);
		$this->pagination->initialize($config);
		$data['getProducts'] = $this->Products_model->getProducts($config['per_page'], $from);
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/products', $data);
		$this->load->view('templates/footer_admin');
	}

	public function search_products()
	{
		$key = $_GET['q'];
		$data['title'] = 'Produk: ' . $key . ' - Admin Panel';
		$config['base_url'] = base_url() . 'administrator/products/';
		$config['total_rows'] = $this->Products_model->getSearchProducts($key, "", "")->num_rows();
		$config['per_page'] = 10;
		$config['first_link']       = 'First';
		$config['last_link']        = 'Last';
		$config['next_link']        = 'Next';
		$config['prev_link']        = 'Prev';
		$config['full_tag_open']    = '<div class="pagging text-center"><nav><ul class="pagination justify-content-center">';
		$config['full_tag_close']   = '</ul></nav></div>';
		$config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
		$config['num_tag_close']    = '</span></li>';
		$config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
		$config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';
		$config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['next_tagl_close']  = '<span aria-hidden="true">&raquo;</span></span></li>';
		$config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['prev_tagl_close']  = '</span>Next</li>';
		$config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
		$config['first_tagl_close'] = '</span></li>';
		$config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
		$config['last_tagl_close']  = '</span></li>';
		$from = $this->uri->segment(3);
		$this->pagination->initialize($config);
		$data['getProducts'] = $this->Products_model->getSearchProducts($key, $config['per_page'], $from);
		$data['search'] = $key;
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/products', $data);
		$this->load->view('templates/footer_admin');
	}

	public function products_set_status_action()
	{
		$id_order = $this->input->post('id');
		$status = $this->input->post('status');
		foreach ($id_order as $id) {
			if ($status == 3) {
				$this->db->where('id', $id);
				$this->db->delete('products');
			} else {
				$this->db->set('publish', $status);
				$this->db->where('id', $id);
				$this->db->update('products');
			}
		}
	}

	public function import_massal_products()
	{
		include APPPATH . 'third_party/PHPExcel/PHPExcel.php';

		$config['upload_path'] = realpath('assets/admin/xls/');
		$config['allowed_types'] = 'xlsx|xls|csv';
		$config['max_size'] = '10000';
		$config['encrypt_name'] = true;

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload()) {

			$this->session->set_flashdata('failed', '<div class="alert alert-danger"><b>PROSES IMPORT GAGAL!</b> ' . $this->upload->display_errors() . '</div>');
			redirect(base_url() . 'administrator/products');
		} else {

			$data_upload = $this->upload->data();

			$excelreader     = new PHPExcel_Reader_Excel2007();
			$loadexcel         = $excelreader->load('assets/admin/xls/' . $data_upload['file_name']);
			$sheet             = $loadexcel->getActiveSheet()->toArray(null, true, true, true);

			$data = array();
			$colorData = array();
			$variantData = array();
			$galleryData = array();

			$numrow = 1;
			$idproduct = $this->db->query('SELECT * FROM products ORDER BY id DESC LIMIT 1')->row_array()['id'] + 1;
			foreach ($sheet as $row) {
				if ($numrow > 1) {
					if ($row['A'] == "") {
						$variant = $row['I'];
						$dataVariant = explode(",", $variant);
						array_push($variantData, array(
							'product' => $idproduct - 1,
							'type' => $dataVariant[0],
							'price' => $dataVariant[1],
						));
					} else {
						array_push($data, array(
							'id' => $idproduct,
							'title' => $row['A'],
							'category' => $row['B'],
							'stock' => $row['C'],
							'weight' => $row['D'],
							'price' => $row['E'],
							'discount' => $row['F'],
							'description' => $row['G'],
							'publish' => 1,
							'img' => $row['J'],
							'ex_img' => 1,
							'date_submit' => date("Y-m-d H:i:s"),
							'slug' => $this->textToSlug($row['A']),
							'variant_name' => $row['I'],
						));

						$color = $row['H'];
						$dataColor = explode(",", $color);
						foreach ($dataColor as $key => $value) {
							if ($dataColor[$key] != "") {
								array_push($colorData, array(
									'product' => $idproduct,
									'color' => $dataColor[$key]
								));
							}
						}

						if ($row['K'] != "") {
							array_push($galleryData, array(
								'id_product' => $idproduct,
								'img' => $row['K'],
								'ex_img' => 1,
								'sort' => 1
							));
						}
						if ($row['L'] != "") {
							array_push($galleryData, array(
								'id_product' => $idproduct,
								'img' => $row['L'],
								'ex_img' => 1,
								'sort' => 2
							));
						}
						if ($row['M'] != "") {
							array_push($galleryData, array(
								'id_product' => $idproduct,
								'img' => $row['M'],
								'ex_img' => 1,
								'sort' => 3
							));
						}
						if ($row['N'] != "") {
							array_push($galleryData, array(
								'id_product' => $idproduct,
								'img' => $row['N'],
								'ex_img' => 1,
								'sort' => 4
							));
						}
						$idproduct++;
					}
				}
				$numrow++;
			}
			$this->db->insert_batch('products', $data);
			$this->db->insert_batch('img_product', $galleryData);
			$this->db->insert_batch('color_product', $colorData);
			$this->db->insert_batch('variant', $variantData);
			unlink(realpath('assets/admin/xls/' . $data_upload['file_name']));

			$this->session->set_flashdata('upload', "<script>
				swal({
				text: 'Produk berhasil di import',
				icon: 'success'
				});
			</script>");
			redirect(base_url() . 'administrator/products');
		}
	}

	function textToSlug($text = '')
	{
		$text = trim($text);
		if (empty($text)) return '';
		$text = preg_replace("/[^a-zA-Z0-9\-\s]+/", "", $text);
		$text = strtolower(trim($text));
		$text = str_replace(' ', '-', $text);
		$text = $text_ori = preg_replace('/\-{2,}/', '-', $text);
		return $text;
	}

	public function add_product()
	{
		$this->form_validation->set_rules('title', 'title', 'required', ['required' => 'Judul wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Tambah Produk - Admin Panel';
			$data['categories'] = $this->Categories_model->getCategories();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/add_product', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = array();
			$upload = $this->Products_model->uploadImg();

			if ($upload['result'] == 'success') {
				$this->Products_model->insertProduct($upload);
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Produk berhasil ditambahkan',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/products');
			} else {
				$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                Gagal menambah produk, pastikan foto produk utama berukuran maksimal 2mb dan berformat png, jpg, jpeg. Silakan ulangi lagi.
              </div>");
				redirect(base_url() . 'administrator/product/add');
			}
		}
	}

	public function edit_product($id)
	{
		$this->form_validation->set_rules('title', 'title', 'required', ['required' => 'Judul wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Edit Produk - Admin Panel';
			$data['categories'] = $this->Categories_model->getCategories();
			$data['product'] = $this->Products_model->getProductById($id);
			$getColor = $this->db->get_where('color_product', ['product' => $id]);
			$data['color'] = "";
			foreach ($getColor->result_array() as $c) {
				$data['color'] .= $c['color'] . ",";
			}
			$data['variant'] = $this->db->get_where('variant', ['product' => $id]);
			$data['gallery1'] = $this->db->get_where('img_product', ['id_product' => $id, 'sort' => 1])->row_array();
			$data['gallery2'] = $this->db->get_where('img_product', ['id_product' => $id, 'sort' => 2])->row_array();
			$data['gallery3'] = $this->db->get_where('img_product', ['id_product' => $id, 'sort' => 3])->row_array();
			$data['gallery4'] = $this->db->get_where('img_product', ['id_product' => $id, 'sort' => 4])->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/edit_product', $data);
			$this->load->view('templates/footer_admin');
		} else {
			if ($_FILES['img']['name'] != "") {
				$data = array();
				$upload = $this->Products_model->uploadImg();

				if ($upload['result'] == 'success') {
					$this->Products_model->updateProduct($upload, $id);
					$this->session->set_flashdata('upload', "<script>
                        swal({
                        text: 'Produk berhasil disimpan',
                        icon: 'success'
                        });
                        </script>");
					redirect(base_url() . 'administrator/product/' . $id . '/edit');
				} else {
					$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                        Gagal menyimpan produk, pastikan foto produk utama berukuran maksimal 2mb dan berformat png, jpg, jpeg. Silakan ulangi lagi.
                    </div>");
					redirect(base_url() . 'administrator/product/' . $id . '/edit');
				}
			} else {
				$upload = "";
				$this->Products_model->updateProduct($upload, $id);
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Produk berhasil disimpan',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/product/' . $id . '/edit');
			}
		}
	}

	public function delete_product($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('products');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Produk berhasil dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/products');
	}

	// coupon
	public function coupon()
	{
		$data['title'] = 'Kupon - Admin Panel';
		$this->db->order_by('id', 'desc');
		$data['coupon'] = $this->db->get('coupon');
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/coupon', $data);
		$this->load->view('templates/footer_admin');
	}

	public function add_coupon()
	{
		$this->form_validation->set_rules('name', 'name', 'required', ['required' => 'Nama wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Tambah Kupon - Admin Panel';
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/add_coupon', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->insertCoupon();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Kupon berhasil disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/coupon');
		}
	}

	public function edit_coupon($id)
	{
		$this->form_validation->set_rules('name', 'name', 'required', ['required' => 'Nama wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Edit Kupon - Admin Panel';
			$data['coupon'] = $this->db->get_where('coupon', ['id' => $id])->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/edit_coupon', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->editCoupon($id);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Kupon berhasil disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/coupon');
		}
	}

	public function delete_coupon($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('coupon');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Kupon berhasil dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/coupon/');
	}

	// pages
	public function pages()
	{
		$data['title'] = 'Halaman - Admin Panel';
		$data['pages'] = $this->Settings_model->getPages();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/pages', $data);
		$this->load->view('templates/footer_admin');
	}

	public function add_page()
	{
		$this->form_validation->set_rules('title', 'Judul', 'required', ['required' => 'Judul wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Tambah Halaman - Admin Panel';
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/add_page', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->insertPage();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Halaman berhasil ditambahkan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/pages');
		}
	}

	public function edit_page($id)
	{
		$this->form_validation->set_rules('title', 'Judul', 'required', ['required' => 'Judul wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Edit Halaman - Admin Panel';
			$data['page'] = $this->Settings_model->getPageById($id);
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/edit_page', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->updatePage($id);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Halaman berhasil diubah',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/pages');
		}
	}

	public function delete_page($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('pages');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Halaman Berhasil Dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/pages');
	}

	public function report()
	{
		$date1 = $_GET['date1'];
		$date2 = $_GET['date2'];
		if ($date1 != "" && $date2 != "") {
			$this->db->where('status !=', 0);
			$this->db->where('dated >=', $date1);
			$this->db->where('dated <=', $date2);
			$this->db->order_by('id', 'desc');
			$data['report'] = $this->db->get("invoice");
			$data['date'] = date('d-m-Y', strtotime($date1)) . " sampai " . date('d-m-Y', strtotime($date2));
		} else {
			$data['report'] = $this->db->get_where('invoice', ['dated' => date('Y-m-d'), 'status !=' => 0]);
			$data['date'] = date('d-m-Y');
		}
		$data['title'] = 'Laporan - Admin Panel';
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/report', $data);
		$this->load->view('templates/footer_admin');
	}

	public function banner_popup()
	{
		$data['title'] = 'Banner Pop up - Admin Panel';
		$data['banner'] = $this->db->get('banner_popup');
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/banner_popup', $data);
		$this->load->view('templates/footer_admin');
	}

	public function add_banner_popup()
	{
		$this->form_validation->set_rules('delay', 'Delay', 'required', ['required' => 'Delay wajib diisi']);
		$this->form_validation->set_rules('url', 'URL', 'required', ['required' => 'URL wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Buat Banner - Admin Panel';
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/add_banner_popup', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$upload = $this->Settings_model->uploadImg();
			if ($upload['result'] == 'success') {
				$this->Settings_model->insertBannerPopup($upload);
				$this->session->set_flashdata('upload', "<script>
					swal({
					text: 'Banner Pop up berhasil ditambahkan',
					icon: 'success'
					});
					</script>");
				redirect(base_url() . 'administrator/banner-popup');
			} else {
				$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
				Gagal menambah banner, pastikan banner berukuran maksimal 2mb dan berformat png, jpg atau jpeg.
				</div>");
				redirect(base_url() . 'administrator/banner-popup/add');
			}
		}
	}

	public function delete_banner_popup($id)
	{
		$banner = $this->db->get_where('banner_popup', ['id' => $id])->row_array()['img'];
		unlink("./assets/images/banner/$banner");
		$this->db->where('id', $id);
		$this->db->delete('banner_popup');
		$this->session->set_flashdata('upload', "<script>
			swal({
			text: 'Banner popup Berhasil Dihapus',
			icon: 'success'
			});
			</script>");
		redirect(base_url() . 'administrator/banner-popup');
	}

	// design
	public function design_header()
	{
		$this->form_validation->set_rules('name', 'Nama', 'required', ['required' => 'Nama wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Tampilan - Admin Panel';
			$data['general'] = $this->Settings_model->general();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_header', $data);
			$this->load->view('templates/footer_admin');
		} else {
			if ($_FILES['logo']['name'] != "" || $_FILES['logo-dark']['name'] != "" || $_FILES['favicon']['name'] != "") {
				$data = array();

				if ($_FILES['logo']['name'] != "") {
					$uploadLogo = $this->Settings_model->uploadlogo();
					$successLogo = $uploadLogo['result'];
					$sendLogo = $uploadLogo['file']['file_name'];
				} else {
					$uploadLogo = "";
					$successLogo = 'success';
				}

				if ($_FILES['logo-dark']['name'] != "") {
					$uploadLogoDark = $this->Settings_model->uploadlogodark();
					$successLogoDark = $uploadLogoDark['result'];
					$sendLogoDark = $uploadLogoDark['file']['file_name'];
				} else {
					$uploadLogoDark = "";
					$successLogoDark = 'success';
				}

				if ($_FILES['favicon']['name'] != "") {
					$uploadFavicon = $this->Settings_model->uploadFavicon();
					$successFavicon = $uploadFavicon['result'];
					$sendFavicon = $uploadFavicon['file']['file_name'];
				} else {
					$uploadFavicon = "";
					$successFavicon = 'success';
				}


				if ($successLogo == 'success' && $successLogoDark == 'success' && $successFavicon == 'success') {
					$this->Settings_model->updateGeneral($sendLogo, $sendLogoDark, $sendFavicon);
					$this->session->set_flashdata('upload', "<script>
                        swal({
                        text: 'Pengaturan berhasil disimpan',
                        icon: 'success'
                        });
                        </script>");
					redirect(base_url() . 'administrator/design/header');
				} else {
					$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                        Gagal menyimpan, pastikan logo atau favicon berukuran maksimal 2mb dan berformat png, jpg, jpeg. Silakan ulangi lagi.
                    </div>");
					redirect(base_url() . 'administrator/design/header');
				}
			} else {
				$this->Settings_model->updateGeneral("", "", "");
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Pengaturan berhasil disimpan',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/design/header');
			}
		}
	}

	public function design_menu()
	{
		$this->form_validation->set_rules('page', 'page', 'required', ['required' => 'page wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$this->db->select("*, menu.id AS menuid");
			$this->db->join('pages', 'menu.page=pages.id');
			$data['menu'] = $this->db->get('menu');
			$data['pages'] = $this->Settings_model->getPages();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_menu', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->addMenu();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Berhasil menambah footer',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/design/menu');
		}
	}

	public function delete_menu($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('menu');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Berhasil menghapus menu',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/design/menu');
	}

	public function design_banner()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['banner'] = $this->Settings_model->getBanner();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/design_banner', $data);
		$this->load->view('templates/footer_admin');
	}

	public function design_add_banner()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/design_add_banner', $data);
		$this->load->view('templates/footer_admin');
	}

	public function add_banner_setting_post()
	{
		$data = array();
		$upload = $this->Settings_model->uploadImg();
		if ($upload['result'] == 'success') {
			$insert = $this->Settings_model->insertBanner($upload);
			if ($insert) {
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Banner berhasil ditambahkan',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/design/banner');
			} else {
				$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
                Gagal menambah banner, gambar yang kamu upload tidak berukuran 1600x400px.
                </div>");
				redirect(base_url() . 'administrator/design/banner/add');
			}
		} else {
			$this->session->set_flashdata('failed', "<div class='alert alert-danger' role='alert'>
            Gagal menambah banner, pastikan banner berukuran maksimal 2mb, berformat png, jpg, jpeg. Dan berukuran 1600x400px.
            </div>");
			redirect(base_url() . 'administrator/setting/banner/add');
		}
	}

	public function delete_banner($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('banner');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Banner Berhasil Dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/design/banner');
	}

	public function design_chat_help()
	{
		$this->form_validation->set_rules('message', 'Pesan', 'required', ['required' => 'Pesan wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->Settings_model->getSetting();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_chat_help', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = [
				'message_chat_help' => $this->input->post('message'),
				'color_chat_help' => $this->input->post('color'),
			];
			$this->db->update('settings', $data);
			$this->session->set_flashdata('upload', "<script>
                swal({
                    text: 'Berhasil menyimpan pengaturan',
                    icon: 'success'
                    });
                    </script>");
			redirect(base_url() . 'administrator/design/chat-help');
		}
	}

	public function design_social_proof()
	{
		$this->form_validation->set_rules('pause', 'Jeda', 'required', ['required' => 'Jeda antar notifikasi harus diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['general'] = $this->Settings_model->general();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_social_proof', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = [
				'pause_social_proof' => $this->input->post('pause'),
				'time_social_proof' => $this->input->post('time'),
			];
			$this->db->update('general', $data);
			$this->session->set_flashdata('upload', "<script>
                swal({
                    text: 'Berhasil menyimpan pengaturan',
                    icon: 'success'
                    });
                    </script>");
			redirect(base_url() . 'administrator/design/social-prof');
		}
	}

	public function design_footer_about()
	{
		$this->form_validation->set_rules('about', 'about', 'required', ['required' => 'Tentang kami wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->Settings_model->getSetting();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_footer_about', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->db->set('short_desc', $this->input->post('about'));
			$this->db->update('settings');
			$this->session->set_flashdata('upload', "<script>
                swal({
                    text: 'Berhasil menyimpan pengaturan',
                    icon: 'success'
                    });
                    </script>");
			redirect(base_url() . 'administrator/design/footer');
		}
	}

	public function design_footer_sosmed()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['sosmed'] = $this->Settings_model->getSosmed();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/design_footer_sosmed', $data);
		$this->load->view('templates/footer_admin');
	}

	public function design_footer_add_sosmed()
	{
		$this->form_validation->set_rules('name', 'name', 'required', ['required' => 'name wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_footer_add_sosmed', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->addSosmed();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Sosial Media Berhasil Disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/design/footer/sosmed');
		}
	}

	public function design_footer_edit_sosmed($id)
	{
		$this->form_validation->set_rules('name', 'name', 'required', ['required' => 'name wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['sosmed'] = $this->Settings_model->getSosmedById($id);
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_footer_edit_sosmed', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->editSosmed($id);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Sosial Media Berhasil Disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/design/footer/sosmed');
		}
	}

	public function delete_sosmed($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('sosmed');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Sosmed Berhasil Dihapus',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/design/footer/sosmed');
	}

	public function design_footer_payment()
	{
		$this->form_validation->set_rules('bank', 'bank', 'required', ['required' => 'bank wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['logo'] = $this->db->get('logo_payment')->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_footer_payment', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = [
				'bca' => $this->input->post('bca') == 'on' ? 1 : 0,
				'mandiri' => $this->input->post('mandiri') == 'on' ? 1 : 0,
				'bri' => $this->input->post('bri') == 'on' ? 1 : 0,
				'bni' => $this->input->post('bni') == 'on' ? 1 : 0,
				'bcas' => $this->input->post('bcas') == 'on' ? 1 : 0,
				'bsi' => $this->input->post('bsi') == 'on' ? 1 : 0,
				'atmbersama' => $this->input->post('atmbersama') == 'on' ? 1 : 0,
				'paypal' => $this->input->post('paypal') == 'on' ? 1 : 0,
				'jenius' => $this->input->post('jenius') == 'on' ? 1 : 0,
				'ovo' => $this->input->post('ovo') == 'on' ? 1 : 0,
				'dana' => $this->input->post('dana') == 'on' ? 1 : 0,
				'gopay' => $this->input->post('gopay') == 'on' ? 1 : 0,
				'jago' => $this->input->post('jago') == 'on' ? 1 : 0,
			];
			$this->db->update('logo_payment', $data);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Logo pembayaran berhasi disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/design/footer/payment');
		}
	}

	public function design_footer_help()
	{
		$this->form_validation->set_rules('page', 'page', 'required', ['required' => 'page wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$this->db->select("*, footer.id AS footerid");
			$this->db->join('pages', 'footer.page=pages.id');
			$data['footer'] = $this->db->get('footer');
			$data['pages'] = $this->Settings_model->getPages();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/design_footer_help', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->addFooter();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Berhasil menambah footer',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/design/footer/help');
		}
	}

	public function delete_footer($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('footer');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Berhasil menghapus footer',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/design/footer/help');
	}

	// settings
	public function setting_account()
	{
		$this->form_validation->set_rules('wa', 'wa', 'required', ['required' => 'Wa wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->db->get('settings')->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/setting_account', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$wa = $this->input->post('wa');
			$data = [
				'wa_admin' => $wa
			];
			$this->db->update('settings', $data);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Berhasil menyimpan pengaturan akun',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/setting/account');
		}
	}

	public function setting_payment()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['bank'] = $this->db->get('bank');
		$data['setting'] = $this->db->get('settings')->row_array();
		$data['general'] = $this->Settings_model->general();
		$this->db->select("*, bank.id AS bankId, rekening.id AS rekeningId, bank.name AS bankName, rekening.name AS rekeningName");
		$this->db->join('bank', 'rekening.rekening=bank.id');
		$data['rekening'] = $this->db->get('rekening');
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_payment', $data);
		$this->load->view('templates/footer_admin');
	}

	public function save_setting_payment()
	{
		$rekening = $this->input->post('rekening');
		$name = $this->input->post('name');
		$number = $this->input->post('number');
		$rekeningId = $this->input->post('rekeningId');
		foreach ($rekening as $key => $value) {
			if ($_POST['rekening'][$key] != "0") {
				if ($_POST['rekeningId'][$key] == "0") {
					$result = [
						'rekening' => $_POST['rekening'][$key],
						'name' => $_POST['name'][$key],
						'number' => $_POST['number'][$key],
					];
					$this->db->insert('rekening', $result);
				} else {
					$result = [
						'rekening' => $_POST['rekening'][$key],
						'name' => $_POST['name'][$key],
						'number' => $_POST['number'][$key],
					];
					$this->db->where('id', $_POST['rekeningId'][$key]);
					$this->db->update('rekening', $result);
				}
			}
		}
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Pengaturan Pembayaran berhasil disimpan',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/setting/payment');
	}

	public function save_setting_flat_ongkir()
	{
		$location = $this->input->post('location');
		foreach ($location as $key => $value) {
			if ($_POST['location'][$key] != "") {
				if ($_POST['shippingId'][$key] == "0") {
					$result = [
						'location' => $_POST['location'][$key],
						'fee' => $_POST['fee'][$key],
					];
					$this->db->insert('flat_ongkir', $result);
				} else {
					$result = [
						'location' => $_POST['location'][$key],
						'fee' => $_POST['fee'][$key],
					];
					$this->db->where('id', $_POST['shippingId'][$key]);
					$this->db->update('flat_ongkir', $result);
				}
			}
		}
		$this->session->set_flashdata('upload', "<script>
			swal({
			text: 'Berhasil menyimpan flat ongkir',
			icon: 'success'
			});
			</script>");
		redirect(base_url() . 'administrator/setting/shipping?flat=true');
	}

	public function save_setting_payment_cod_feature()
	{
		$fee_cod = $this->input->post('fee_cod');
		$minimal_fee_cod = $this->input->post('minimal_fee_cod');
		$maximal_fee_cod = $this->input->post('maximal_fee_cod');
		$data = [
			'fee_cod' => $fee_cod,
			'minimal_fee_cod' => $minimal_fee_cod,
			'maximal_fee_cod' => $maximal_fee_cod
		];
		$this->db->update('general', $data);
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Pengaturan Pembayaran COD berhasil disimpan',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/setting/payment');
	}

	public function setting_shipping()
	{
		$this->form_validation->set_rules('api_rajaongkir', 'Rajaongkir', 'required', ['required' => 'Rajaongkir wajib diisi']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->db->get('settings')->row_array();
			$data['flat_ongkir'] = $this->db->get('flat_ongkir');
			$data['general'] = $this->Settings_model->general();
			$data['regency'] = $this->Settings_model->getRegency();
			$data['selectRegency'] = $this->Settings_model->getSubdistrictById();
			$data['courier'] = $this->db->get('courier')->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/setting_shipping', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$this->Settings_model->updateShipping();
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Pengaturan pengiriman berhasil disimpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/setting/shipping');
		}
	}

	public function setting_notification()
	{
		redirect(base_url() . 'administrator/setting/notification/follow-up');
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_notification_followup()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification_followup', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_notification_confirmation()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification_confirmation', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_notification_delivery()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification_delivery', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_notification_finish()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification_finish', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_notification_cancel()
	{
		$data['title'] = 'Pengaturan - Admin Panel';
		$data['notification'] = $this->db->get('notification')->row_array();
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/setting_notification_cancel', $data);
		$this->load->view('templates/footer_admin');
	}

	public function setting_pixel()
	{
		$this->form_validation->set_rules('helper', 'helper', 'required', ['required' => 'hanya helper']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->db->get('settings')->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/setting_pixel', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$dbpixel = $this->input->post('idPixel');
			$this->db->set('id_pixel', $dbpixel);
			$this->db->update('settings');
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'ID Pixel berhasil simpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/setting/pixel');
		}
	}

	public function setting_seo()
	{
		$this->form_validation->set_rules('helper', 'helper', 'required', ['required' => 'hanya helper']);
		if ($this->form_validation->run() == false) {
			$data['title'] = 'Pengaturan - Admin Panel';
			$data['setting'] = $this->db->get('settings')->row_array();
			$this->load->view('templates/header_admin', $data);
			$this->load->view('administrator/setting_seo', $data);
			$this->load->view('templates/footer_admin');
		} else {
			$data = [
				'ga_id' => $this->input->post('gaID'),
				'gs_console' => $this->input->post('gsConsole', true),
			];
			$this->db->update('settings', $data);
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Pengaturan SEO berhasil simpan',
                icon: 'success'
                });
                </script>");
			redirect(base_url() . 'administrator/setting/seo');
		}
	}

	public function getSelectSubdistrictById()
	{
		$id = $this->input->post('id');
		$subdistrict = $this->Settings_model->getSubdistrictByCity($id);
		$list = "<option>Pilih Kecamatan</option>";
		foreach ($subdistrict as $d) {
			$list .= "<option value='" . $d['subdistrict_id'] . "'>Kecamatan " . $d['subdistrict_name'] . "";
		}
		echo json_encode($list);
	}

	// ajax
	public function getFullAddressRO()
	{
		$subdistrict = $_GET['subdistrict'];
		$city = $_GET['city'];
		$getData = $this->Settings_model->getSubdistrictByIdAndCity($subdistrict, $city);
		$list = 'Kec. ' . $getData['subdistrict_name'] . ' ' . $getData['type'] . ' ' . $getData['city'];
		echo $list;
	}

	public function ajax_get_product_by_id($id)
	{
		$return = $this->Products_model->getProductById($id);
		echo json_encode($return);
	}

	public function chat_help_status_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['chat_help'] == 1) {
			$this->db->set('chat_help', 0);
			$this->db->update('settings');
		} else {
			$this->db->set('chat_help', 1);
			$this->db->update('settings');
		}
	}

	public function social_proof_status_change()
	{
		$db = $this->db->get('general')->row_array();
		if ($db['social_proof_status'] == 1) {
			$this->db->set('social_proof_status', 0);
			$this->db->update('general');
		} else {
			$this->db->set('social_proof_status', 1);
			$this->db->update('general');
		}
	}

	public function payment_feature_setting_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['payment_feature'] == 1) {
			$this->db->set('payment_feature', 0);
			$this->db->update('settings');
		} else {
			$this->db->set('payment_feature', 1);
			$this->db->update('settings');
		}
	}

	public function coupon_status_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['potongan_feature'] == 1) {
			$this->db->set('potongan_feature', 0);
			$this->db->update('settings');
		} else {
			$this->db->set('potongan_feature', 1);
			$this->db->update('settings');
		}
	}

	public function uniq_code_feature_setting_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['uniq_code_feature'] == 1) {
			$this->db->set('uniq_code_feature', 0);
			$this->db->update('settings');
		} else {
			$this->db->set('uniq_code_feature', 1);
			$this->db->update('settings');
		}
	}

	public function payment_cod_feature_setting_change()
	{
		$db = $this->db->get('general')->row_array();
		if ($db['payment_cod_status'] == 1) {
			$this->db->set('payment_cod_status', 0);
			$this->db->update('general');
		} else {
			$this->db->set('payment_cod_status', 1);
			$this->db->update('general');
		}
		echo $db['payment_cod_status'];
	}

	public function shipping_feature_setting_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['shipping_feature'] == 1) {
			$this->db->set('shipping_feature', 0);
			$this->db->update('settings');
			echo "0";
		} else {
			$this->db->set('shipping_feature', 1);
			$this->db->set('flatshipping_feature', 0);
			$this->db->update('settings');
			echo "1";
		}
	}

	public function flatshipping_feature_setting_change()
	{
		$db = $this->db->get('settings')->row_array();
		if ($db['flatshipping_feature'] == 1) {
			$this->db->set('flatshipping_feature', 0);
			$this->db->update('settings');
			echo "0";
		} else {
			$this->db->set('flatshipping_feature', 1);
			$this->db->set('shipping_feature', 0);
			$this->db->update('settings');
			echo "1";
		}
	}

	public function delete_rekening_from_database()
	{
		$id = $this->input->post('id');
		$this->db->where('id', $id);
		$this->db->delete('rekening');
	}

	public function delete_flat_ongkir_from_database()
	{
		$id = $this->input->post('id');
		$this->db->where('id', $id);
		$this->db->delete('flat_ongkir');
	}

	public function insertNotificationSetting()
	{
		$type = $_GET['type'];
		$content = $this->input->post('content');
		if ($type == "1") {
			$this->db->set('new_order', $content);
		} else if ($type == "2") {
			$content2 = $this->input->post('content2');
			$content3 = $this->input->post('content3');
			$this->db->set('follow_up_1', $content);
			$this->db->set('follow_up_2', $content2);
			$this->db->set('follow_up_3', $content3);
		} else if ($type == "3") {
			$this->db->set('confirmation', $content);
		} else if ($type == "4") {
			$this->db->set('delivery', $content);
		} else if ($type == "5") {
			$this->db->set('finish', $content);
		} else if ($type == "6") {
			$this->db->set('cancel', $content);
		}
		$this->db->update('notification');
	}

	public function getNotificationTable()
	{
		$id = $_GET['id'];
		$get = $this->db->get('notification')->row_array();
		$data = "";
		if ($id == 1) {
			$data = $get['follow_up_1'];
		} else if ($id == 2) {
			$data = $get['follow_up_2'];
		} else if ($id == 3) {
			$data = $get['follow_up_3'];
		} else if ($id == 4) {
			$data = $get['confirmation'];
		} else if ($id == 5) {
			$data = $get['delivery'];
		} else if ($id == 6) {
			$data = $get['finish'];
		} else if ($id == 7) {
			$data = $get['cancel'];
		}
		echo $data;
	}

	public function getOrderDetailAjax($id)
	{
		$get = $this->db->get_where('invoice', ['id' => $id])->row_array();
		echo json_encode($get);
	}

	public function delete_variant_from_database($id)
	{
		$this->db->where('id', $id);
		$this->db->delete('variant');
		echo true;
	}

	public function delete_gallery_img_from_database()
	{
		$id = $_GET['id'];
		$sort = $_GET['sort'];
		$this->db->where('id_product', $id);
		$this->db->where('sort', $sort);
		$this->db->delete('img_product');
		echo true;
	}

	// edit
	public function edit()
	{
		$data['title'] = 'Edit Profil Admin - Admin Panel';
		$admin = $this->db->get('admin')->row_array();
		$data['admin'] = $admin;
		$this->load->view('templates/header_admin', $data);
		$this->load->view('administrator/edit', $data);
		$this->load->view('templates/footer_admin');
	}

	public function edit_username()
	{
		$this->db->set('username', $this->input->post('username'));
		$this->db->update('admin');
		$this->session->set_flashdata('upload', "<script>
            swal({
            text: 'Username berhasil diubah',
            icon: 'success'
            });
            </script>");
		redirect(base_url() . 'administrator/edit');
	}

	public function edit_pass()
	{
		$admin = $this->db->get('admin')->row_array();
		if (password_verify($this->input->post('oldPassword'), $admin['password'])) {
			if ($this->input->post('newPassword') ==  $this->input->post('confirmPassword')) {
				$pass = password_hash($this->input->post('newPassword'), PASSWORD_DEFAULT);
				$this->db->set('password', $pass);
				$this->db->update('admin');
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Password berhasil diubah',
                    icon: 'success'
                    });
                    </script>");
				redirect(base_url() . 'administrator/edit');
			} else {
				$this->session->set_flashdata('upload', "<script>
                    swal({
                    text: 'Konfirmasi password tidak sama. Silakan coba lagi',
                    icon: 'error'
                    });
                    </script>");
				redirect(base_url() . 'administrator/edit');
			}
		} else {
			$this->session->set_flashdata('upload', "<script>
                swal({
                text: 'Password lama salah. Silakan coba lagi',
                icon: 'error'
                });
                </script>");
			redirect(base_url() . 'administrator/edit');
		}
	}

	public function logout()
	{
		session_unset();
		session_destroy();
		delete_cookie('djehbicd');
		redirect(base_url() . 'login/admin');
	}
}
