https://t.me/RX1948
Server : Apache/2.4.18 (Ubuntu)
System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64
User : oppastar ( 1041)
PHP Version : 7.0.33-0ubuntu0.16.04.15
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Directory :  /var/www/laciasmara.com/public_html/shop/application/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/laciasmara.com/public_html/shop/application/controllers/Payment.php
<?php if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Payment extends Customer_Controller
{
  private $order_id = null;

  function __construct()
  {
    parent::__construct();
    $this->load->model('order_m');
    $this->load->model('order_detail_m');
    $this->load->model('product_m');
    $this->load->model('configuration_m');
    $this->load->library('cart');
    $this->load->library('paypal_lib');
    $this->load->library('encryption');
    $this->load->library('GoogleClient');
    $this->load->library('VisitorTracking');
    $this->load->model('Top_banner_m');
    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('mainpage', 'english');
    } else {
      $this->lang->load('mainpage', 'indonesian');
    }
    $loginUrl = $this->googleclient->getLoginUrl();

    $this->data_footer['googleUrl'] = $loginUrl;
  }

  public function process()
  {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'failed',
          'message' => 'Invalid request method'
        ]));
      return;
    }

    $payment_data = $this->input->post();
    // Validasi data yang diperlukan
    if (!isset($payment_data['orderId']) && !isset($payment_data['paymentType'])) {
      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'failed',
          'message' => 'Order ID or Payment Type is missing'
        ]));
      return;
    }

    $orderId = $payment_data['orderId'];
    $paymentType = $payment_data['paymentType'];
    $paymentTypeSlug = [
      'bank transfer BCA' => 'bca',
      'bank transfer MANDIRI' => 'mandiri',
      'DOKU' => 'doku',
      'Paypal' => 'paypal'
    ];

    $orderData = $this->getOrderDataById($orderId);
    if (!$orderData) {
      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'failed',
          'message' => 'Order data not found'
        ]));
      return;
    }


    // Doku data
    $orderDetails = $this->getOrderDetailByOrderId($orderId);
    $basket = [];
    foreach ($orderDetails as $item) {
      $basket[] = sprintf(
        '%s,%s,%s,%s',
        $item['item_name'],   // Nama produk
        number_format($item['item_price'], 2, '.', ''),  // Harga dengan format 2 desimal
        $item['quantity'],    // Jumlah produk
        number_format($item['subtotal'], 2, '.', '')     // Subtotal dengan format 2 desimal
      );
    }

    $basket = implode(';', $basket);

    if (strtolower($paymentType) === 'doku') {
      // Doku payment process
      $dokuEndpoint = 'https://pay.doku.com/Suite/Receive';
      $mallID = '10746346';
      $sharedKey = 'W4p2h2N3L4X8';
      $transIdMerchant = $orderId;
      $totalAmount = $orderData['grand_total_amount'];
      $msg =  number_format($totalAmount, 2, '.', '') . $mallID . $sharedKey . $transIdMerchant;
      $words = sha1($msg);

      $requestData = [
        'BASKET' => $basket,
        'MALLID' => '10746346',
        'CHAINMERCHANT' => 'NA',
        'CURRENCY' => 360,
        'PURCHASECURRENCY' => 360,
        'AMOUNT' => number_format($totalAmount, 2, '.', ''),
        'PURCHASEAMOUNT' => number_format($totalAmount, 2, '.', ''),
        'TRANSIDMERCHANT' => $transIdMerchant,
        'WORDS' => $words,
        'REQUESTDATETIME' => date('YmdHis'),
        'SESSIONID' => session_id(),
        'PAYMENTCHANNEL' => '',
        'EMAIL' => $orderData['customer_email'],
        'NAME' => $orderData['name'],
        'ADDRESS' => $orderData['shipping_address'],
        'COUNTRY' => 360,
        'STATE' => $orderData['shipping_district'],
        'CITY' => $orderData['shipping_district'],
        'PROVINCE' => $orderData['shipping_province'],
        'ZIPCODE' => $orderData['shipping_postcode'],
        'HOMEPHONE' => $orderData['shipping_phone'],
        'MOBILEPHONE' => $orderData['shipping_phone'],
        'WORKPHONE' => $orderData['shipping_phone'],
        'BIRTHDATE' => $orderData['birthday'],
      ];

      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'success',
          'message' => 'Redirecting to DOKU payment page.',
          'response' => $requestData,
          'redirect_url' => $dokuEndpoint,
          'payment_type' => $paymentType,
        ]));
      return;
    }
    if (strtolower($paymentType) == 'paypal') {
      $paypalEndpoint = base_url() . 'payment/paypal_payment/' . $orderId;
      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'success',
          'message' => 'Redirecting to Paypal payment page.',
          'redirect_url' => $paypalEndpoint,
          'payment_type' => $paymentType,
        ]));
      return;
    } else {
      // Metode pembayaran lain (BCA, Mandiri)
      $confirmationUrl = base_url("payment/confirmation?orderid={$orderId}&payment={$paymentTypeSlug[$paymentType]}");

      $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode([
          'status' => 'success',
          'message' => 'Redirecting to confirmation page.',
          'redirect_url' => $confirmationUrl,
          'payment_type' => $paymentType,
        ]));
    }

    // $confirmationUrl = base_url("payment/confirmation?orderid={$orderId}&payment={$paymentTypeSlug[$paymentType]}");

    // $this->output
    //   ->set_content_type('application/json')
    //   ->set_output(json_encode([
    //     'status' => 'success',
    //     'message' => 'Redirecting to confirmation page.',
    //     'redirect_url' => $confirmationUrl,
    //     'payment_type' => $paymentType,
    //   ]));
  }

  private function getOrderDataById($order_id)
  {
    $this->db->select('orders.*, customers.email AS customer_email, customers.birthday, customers.reseller_id, customers.name, customers.shipping_name, customers.shipping_address, customers.shipping_province, customers.shipping_district, customers.shipping_subdistrict, customers.shipping_postcode, customers.shipping_phone, customers.phone, customers.type');
    $this->db->from('orders');
    $this->db->join('customers', 'customers.id_customers = orders.customer_id', 'left');
    $this->db->where('orders.id_orders', $order_id);

    $query = $this->db->get();
    return $query->row_array();
  }


  private function getOrderDetailByOrderId($order_id)
  {
    $this->db->select('orders_detail.*, product_images.image AS item_image');
    $this->db->from('orders_detail');
    $this->db->join('product_images', 'orders_detail.item_id = product_images.product_details_id');
    $this->db->where('orders_detail.orders_id', $order_id);
    $this->db->where('product_images.status', 1);
    $this->db->where('product_images.priority', 1);
    $query = $this->db->get();
    return $query->result_array();
  }


  public function confirmation()
  {
    $this->visitortracking->trackVisitor();
    $orderId = $this->input->get('orderid');
    $paymentType = $this->input->get('payment');
    $website_data = $this->db->select('website_icon, browser_title, meta_description')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();

    // Handle language
    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('mainpage', 'english');
    } else {
      $this->lang->load('mainpage', 'indonesian');
    }

    $orderData = $this->getOrderDataById($orderId);
    $orderDetails = $this->getOrderDetailByOrderId($orderId);
    $bankData = $this->getBankData($paymentType);

    $meta_description = ($this->session->userdata('site_lang') == 'english')
      ? "Payment’s received! Now just sit back, relax, and let us handle the rest. Check your order history & get ready for the pleasure to roll in!"
      : "Mantap, pembayaran berhasil! Sekarang tinggal duduk manis, pesananmu segera diproses. Cek riwayat transaksi & tunggu kenikmatan dari Laci Asmara!";

    $data_view = [
      'orderData' => $orderData,
      'orderDetails' => $orderDetails,
      'paymentType' => $paymentType,
      'bankData' => $bankData,
      'website_icon' => $website_data->website_icon,
      'browser_title' => ucwords($website_data->browser_title) . ' - Payment Confirmation',
      'meta_description' => $meta_description,
    ];

    // Update payment status
    try {
      if (!empty($orderData['reseller_id'])) {
        $data = [
          'payment_status' => 0,
        ];
      } else {
        $data = [
          'payment_status' => 1,
        ];
      }

      $this->db->where('id_orders', $orderId);
      $this->db->update('orders', $data);

      // Commit transaction if no errors
      $this->db->trans_complete();

      if ($this->db->trans_status() === FALSE) {
        throw new Exception('Error updating payment status.');
      }
    } catch (Exception $e) {
      $this->db->trans_rollback();
      log_message('error', $e->getMessage());
      show_error('An error occurred while processing the payment status.');
    }

    try {
      // Coba kirim email konfirmasi
      $this->send_confirmation_email($paymentType, $orderData, $orderDetails, $bankData);
    } catch (Exception $e) {
      // Log error jika email gagal dikirim
      log_message('error', 'Gagal mengirim email konfirmasi: ' . $e->getMessage());
    }

    $this->cart->destroy();
    $this->destroy_session_data();
    $this->load->view('payment/order-confirmation', $data_view);
  }

  private function getBankData($paymentType)
  {
    $this->db->select('payment_type, bank_name, account_number, account_holder');
    $this->db->from('bank_accounts');
    $this->db->where('payment_type', $paymentType);
    $query = $this->db->get();
    return $query->row_array();
  }


  function post_payment()
  {
    // echo '<pre>';
    // echo $this->session->userdata('shipping_cart');
    // echo '</pre>';
    // exit();
    if (!$this->session->userdata('shipping_cart')) {
      redirect('cart');
    }

    if (!isset($_POST['lanjutPembayaran'])) {
      redirect('shipping');
    }

    //check if user not register yet
    if (
      !$this->session->userdata('customer') ||
      $this->session->userdata('customer')['customer_id'] == null ||
      $this->session->userdata('customer')['customer_type'] == 'guest'
    ) {
      //register new guest and return the id
      //from guest checkout shipping
      //check if email already exist, and check customer type..
      $count_customer = $this->db
        ->select('id_customers')
        ->from('customers')
        ->where(
          'email',
          $this->security->xss_clean($this->input->post('email'))
        )
        ->get()
        ->num_rows();

      if ($count_customer > 0) {
        //customer already exist
        //check customer type. if customer type is regular, then update shipping information only..
        $guest_data = [
          'shipping_name' => $this->security->xss_clean(
            $this->input->post('name')
          ),
          'shipping_phone' => $this->security->xss_clean(
            $this->input->post('phone')
          ),
          'shipping_id_province' => $this->input->post('shipping_province'),
          'shipping_id_district' => $this->input->post('shipping_district'),
          'shipping_id_subdistrict' => $this->input->post(
            'shipping_subdistrict'
          ),
          'address' => $this->security->xss_clean(
            $this->input->post('address')
          ),
          'shipping_address' => $this->security->xss_clean(
            $this->input->post('address')
          ),
          'postcode' => $this->security->xss_clean(
            $this->input->post('postcode')
          ),
          'shipping_postcode' => $this->security->xss_clean(
            $this->input->post('postcode')
          ),
          'birthday' => $this->security->xss_clean(
            $this->input->post('birthday')
          ),
          'sex_type' => $this->security->xss_clean(
            $this->input->post('sex_type')
          ),
        ];
        $this->db->where(
          'email',
          $this->security->xss_clean($this->input->post('email'))
        );
        $this->db->update('customers', $guest_data);

        //get customer id
        $this->db
          ->select('id_customers, name')
          ->from('customers')
          ->where(
            'email',
            $this->security->xss_clean($this->input->post('email'))
          );
        $customer_data = $this->db->get()->row();
        $customer_name = $customer_data->name;
        $customer_id = $customer_data->id_customers;

        $guest_data = [
          'customer_name' => ucwords($customer_name),
          'customer_email' => $this->session->userdata('guest_details')['email'],
          'customer_id' => $customer_id,
          'customer_loggedin' => true,
          'customer_type' => 'guest',
        ];
        $this->session->set_userdata('customer', $guest_data);
      } else {
        //customer not yet exist
        //insert new customer
        $guest_data = [
          'name' => $this->security->xss_clean($this->input->post('name')),
          'recipient_name' => $this->security->xss_clean(
            $this->input->post('name')
          ),
          'shipping_name' => $this->security->xss_clean(
            $this->input->post('name')
          ),
          'email' => $this->security->xss_clean($this->input->post('email')),
          'phone' => $this->security->xss_clean($this->input->post('phone')),
          'shipping_phone' => $this->security->xss_clean(
            $this->input->post('phone')
          ),
          'shipping_id_province' => $this->input->post('shipping_province'),
          'shipping_id_district' => $this->input->post('shipping_district'),
          'shipping_id_subdistrict' => $this->input->post(
            'shipping_subdistrict'
          ),
          'address' => $this->security->xss_clean(
            $this->input->post('address')
          ),
          'shipping_address' => $this->security->xss_clean(
            $this->input->post('address')
          ),
          'postcode' => $this->security->xss_clean(
            $this->input->post('postcode')
          ),
          'shipping_postcode' => $this->security->xss_clean(
            $this->input->post('postcode')
          ),
          'birthday' => $this->security->xss_clean(
            $this->input->post('birthday')
          ),
          'sex_type' => $this->security->xss_clean(
            $this->input->post('sex_type')
          ),
          'type' => 'guest',
        ];
        $this->db->insert('customers', $guest_data);
        $customer_id = $this->db->insert_id();

        $customer_data = [
          'customer_name' => 'Guest',
          'customer_email' => $this->session->userdata('guest_details')['email'],
          'customer_id' => $customer_id,
          'customer_loggedin' => true,
          'customer_type' => 'guest',
        ];
        $this->session->set_userdata('customer', $customer_data);
      }
    } elseif (
      $this->session->userdata('customer')['customer_id'] != null &&
      $this->session->userdata('customer')['customer_type'] == 'regular'
    ) {
      //customer is logged in..
      //update detail
      $id = $this->session->userdata('customer')['customer_id'];
      $temp_is_first =  $this->db->select('is_first')->from('customers')->where('id_customers', $id)->get()->row()->is_first;

      $customer_data = [
        'shipping_id_province' => $this->input->post('shipping_province'),
        'shipping_id_district' => $this->input->post('shipping_district'),
        'is_first' => $temp_is_first + 1,
        'shipping_id_subdistrict' => $this->input->post('shipping_subdistrict'),
        'shipping_address' => $this->security->xss_clean(
          $this->input->post('address')
        ),
        'shipping_postcode' => $this->security->xss_clean(
          $this->input->post('postcode')
        ),
      ];

      //check if shipping_name & shipping_phone empty
      $customer = $this->db
        ->select('name, phone, shipping_name, shipping_phone')
        ->from('customers')
        ->where(
          'id_customers',
          $this->session->userdata('customer')['customer_id']
        )
        ->get()
        ->row();

      if (empty($customer->shipping_name)) {
        $customer_data['shipping_name'] = $customer->name;
      }

      if (empty($customer->shipping_phone)) {
        $customer_data['shipping_phone'] = $customer->phone;
      }
      $this->db->where(
        'id_customers',
        $this->session->userdata('customer')['customer_id']
      );
      $this->db->update('customers', $customer_data);
    }

    //set customer_note into session
    $this->session->set_userdata(
      'customer_note',
      $this->security->xss_clean($this->input->post('customer_note'))
    );
    $this->session->set_userdata(
      'receiver_name',
      $this->security->xss_clean($this->input->post('receiver_name'))
    );
    $this->session->set_userdata(
      'receiver_phone',
      $this->security->xss_clean($this->input->post('receiver_phone'))
    );
    $this->session->set_userdata(
      'insurance_cost',
      $this->security->xss_clean($this->input->post('insurance_cost'))
    );
    $this->session->set_userdata(
      'insurance_status',
      $this->security->xss_clean($this->input->post('insurance_status'))
    );

    redirect('payment');
  }

  function index()
  {
    if (!$this->session->userdata('shipping_cart')) {
      redirect('cart');
    }

    if (!$this->session->userdata('shipping_to_payment')) {
      redirect('shipping');
    }

    //check shipping_cart if the stock is available for each warehouse
    $have_stock = true;

    foreach ($this->session->userdata('shipping_cart') as $rowid => $item) {
      //get product name
      $product_name = $this->db
        ->select('title')
        ->from('products')
        ->where('id_products', $item['product_id'])
        ->get()
        ->row()->title;

      //get total stok from warehouse
      $current_stock = $this->db
        ->select('stock')
        ->from('stock')
        ->where('id_product', $item['product_id'])
        ->where('id_product_detail', $item['id'])
        ->where('warehouse_id', $item['warehouse_id'])
        ->get()
        ->row()->stock;

      if ($current_stock < $item['qty']) {
        if ($item['is_backorder'] == 'no') {
          $this->session->set_flashdata(
            'no_stock' . $rowid,
            'Not Enough Stock'
          );
          $have_stock = false;
        }
      }
    }

    if ($have_stock == false) {
      redirect('shipping/no_stock');
    }

    //INSERT NEW ORDERS
    $grand_total = 0;
    foreach ($this->session->userdata('shipping_cart') as $rowid => $item) {
      $grand_total = $grand_total + $item['subtotal'];
    }

    //GET THE VALUE OF INDENT (only for indent item)
    $indent_remaining = 0;
    foreach (
      $this->session->userdata('shipping_cart')
      as $rowid => $shipping_cart_item
    ) {
      if ($shipping_cart_item['is_backorder'] == 'yes') {
        $indent_remaining =
          $indent_remaining +
          ($shipping_cart_item['price'] - $shipping_cart_item['dp_price']) *
          $shipping_cart_item['qty'];
      }
    }

    //GET THE VALUE OF INDENT SHIPPING FEE (only for indent item)
    $indent_shipping_fee = 0;
    foreach (
      $this->session->userdata('shipping_cart')
      as $rowid => $shipping_cart_item
    ) {
      if ($shipping_cart_item['is_backorder'] == 'yes') {
        $indent_shipping_fee =
          $indent_shipping_fee + $shipping_cart_item['shipping_fee'];
      }
    }

    //get shipping address, province, district and subdistrict
    $customer_data = $this->db
      ->select(
        'email, shipping_name, shipping_address, shipping_id_province, shipping_id_district, shipping_id_subdistrict, shipping_postcode, shipping_phone, shipping_country,current_pointreward,is_first, refferal'
      )
      ->from('customers')
      ->where(
        'id_customers',
        $this->session->userdata('customer')['customer_id']
      )
      ->get()
      ->row();

    //get subdistrict, distirct and province name
    $subdistrict = $this->db
      ->select('subdistrict')
      ->from('indonesia_subdistricts')
      ->where(
        'rajaongkir_id_subdistrict',
        $customer_data->shipping_id_subdistrict
      )
      ->get()
      ->row()->subdistrict;

    //get district
    $district = $this->db
      ->select('district')
      ->from('indonesia_districts')
      ->where('rajaongkir_id_district', $customer_data->shipping_id_district)
      ->get()
      ->row()->district;

    //get province
    $province = $this->db
      ->select('province')
      ->from('indonesia_provinces')
      ->where('rajaongkir_province_id', $customer_data->shipping_id_province)
      ->get()
      ->row()->province;

    $get_grand_total = 0;
    foreach ($this->session->userdata('shipping_cart') as $item) {
      $get_grand_total += $item['subtotal'];
    }

    $q_config_cond = $this->db
      ->select(
        'type_cond_prov_free_shipping, cond_more_prov_free_shipping, cond_less_prov_free_shipping'
      )
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();

    $reseller_tier_config = $this->db
      ->select(
        'minimum_order'
      )
      ->from('resellers')
      ->get()
      ->row();

    $free_shipping_type = $this->db
      ->select('free_shipping_type')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row()->free_shipping_type;

    $condition_freeshipping = false;

    $reseller_id = $this->db->select('reseller_id')->from('customers')->where('id_customers', $this->session->userdata('customer')['customer_id'])->get()->row()->reseller_id;
    if ($reseller_id == null) {
      if ($free_shipping_type == 'region') {
        if ($this->session->userdata('cart_has_discounted_items') == 'no') {
          $selected_region_province = $this->db
            ->select('*')
            ->from('free_shipping_region')
            ->where('configuration_id', 1)
            ->where('province_id', $customer_data->shipping_id_province)
            ->get();

          if ($selected_region_province->num_rows() > 0) {
            switch ($q_config_cond->type_cond_prov_free_shipping) {
              case 'more_than':
                if (
                  // Kalau grand totalnya lebih besar dari 1.500.000
                  $get_grand_total >= $q_config_cond->cond_more_prov_free_shipping
                ) {
                  $condition_freeshipping = true;
                } else {
                  $condition_freeshipping = false;
                }
                break;
              case 'less_than':
                if (
                  $get_grand_total <= $q_config_cond->cond_less_prov_free_shipping
                ) {
                  $condition_freeshipping = true;
                } else {
                  $condition_freeshipping = false;
                }
                break;

              default:
                $condition_freeshipping = true;
                break;
            }
          }
        }
      }

      if ($free_shipping_type == 'region') {
        if ($this->session->userdata('cart_has_discounted_items') == 'yes') {
          $selected_region_province = $this->db
            ->select('*')
            ->from('free_shipping_region')
            ->where('configuration_id', 1)
            ->where('province_id', $customer_data->shipping_id_province)
            ->get();

          if ($selected_region_province->num_rows() > 0) {
            switch ($q_config_cond->type_cond_prov_free_shipping) {
              case 'more_than':
                if (
                  $get_grand_total >= $q_config_cond->cond_more_prov_free_shipping
                ) {
                  $condition_freeshipping = true;
                } else {
                  $condition_freeshipping = false;
                }
                break;
              case 'less_than':
                if (
                  $get_grand_total <= $q_config_cond->cond_less_prov_free_shipping
                ) {
                  $condition_freeshipping = true;
                } else {
                  $condition_freeshipping = false;
                }
                break;

              default:
                $condition_freeshipping = true;
                break;
            }
          }
        }
      }
    } else {
      $condition_freeshipping = false;
    }
    if ($this->session->userdata('cart_has_discounted_items') == 'no') {
      $isfirst = $customer_data->is_first;
    } else {
      $isfirst = 2;
    }
    //insert new order to orders table
    $data = [
      'customer_id' => (int) $this->session->userdata('customer')['customer_id'],
      'total_amount' => $grand_total,
      'order_date' => date('Y-m-d H:i:s'),
      'recipient_name' => $customer_data->shipping_name,
      'address' => $customer_data->shipping_address,
      'subdistrict' => $subdistrict,
      'district' => $district,
      'province' => $province,
      'postcode' => $customer_data->shipping_postcode,
      'phone' => $customer_data->shipping_phone,
      'email' => $customer_data->email,
      'first' => $isfirst,
      'country' => $customer_data->shipping_country,
      'shipping_fee' => $this->session->userdata('total_shipping_fee'),
      'free_shipping_fee' => $this->session->userdata('free_shipping'),
      'created_by' => 'system',
      'indent_remaining' => $indent_remaining,
      'indent_shipping_fee' => $indent_shipping_fee,
      'customer_note' => $this->session->userdata('customer_note'),
      'gift_receiver_name' => $this->session->userdata('receiver_name'),
      'gift_receiver_phone' => $this->session->userdata('receiver_phone'),
      'insurance_status' => $this->session->userdata('insurance_status'),
      'insurance_cost' => $this->session->userdata('insurance_cost'),
      'referral' => !empty($this->session->userdata('referral')) ? $this->session->userdata('referral') : $customer_data->refferal,
      'special_event' => $this->session->userdata('gimmickeligible'),
      'source' => $this->session->userdata('visitor_tracking')['source'],
      'medium' => $this->session->userdata('visitor_tracking')['medium'],
      'campaign' => $this->session->userdata('visitor_tracking')['campaign'],
    ];

    // $customer_data->refferal
    if ($this->session->userdata('site_lang') == 'english') {
      $data['order_language'] = 'english';
    } else {
      $data['order_language'] = 'indonesian';
    }

    //add voucher
    if ($this->session->userdata('chosen_voucher_code')) {
      $data['redeemed_voucher_code'] = $this->session->userdata(
        'chosen_voucher_code'
      );
      $data['redeemed_voucher_type'] = $this->session->userdata(
        'chosen_voucher_type'
      );
      $data['redeemed_voucher_value'] = $this->session->userdata(
        'chosen_voucher_discount'
      );
      $data['redeemed_voucher_amount'] = $this->session->userdata(
        'redeemed_voucher_amount'
      );
    }

    //add tax
    if ($this->session->userdata('tax')) {
      $data['ppn'] = $this->session->userdata('tax');
    }

    //add point rewards
    $pointrewards = $this->db
      ->select('*')
      ->from('point_rewards')
      ->where('id_point_rewards', 1)
      ->get()
      ->row();

    if ($this->session->userdata('customer')['customer_type'] != 'guest') {
      if ($pointrewards->active == 'yes') {

        $reseller_id = $this->db->select('reseller_id')->from('customers')->where('id_customers', $this->session->userdata('customer')['customer_id'])->get()->row()->reseller_id;
        if ($reseller_id == NULL) {
          $data['plus_reward'] = ceil($grand_total / $pointrewards->ratio);
        } else {
          $data['plus_reward'] = 0;
        }
      }
    }

    //minus point rewards
    if ($this->session->userdata('chosen_point')) {
      $data['current_reward'] = $customer_data->current_pointreward;
      $data['sisa_reward'] =
        $customer_data->current_pointreward -
        $this->session->userdata('chosen_point');
      $data['minus_reward'] = $this->session->userdata('chosen_point');
      $data['minus_reward_amount'] = $this->session->userdata(
        'chosen_point_discount'
      );
    }

    //GRAND FINAL TOTAL AMOUNT CALCULATION
    $finalshippingfee = 0;

    $calculate_finalshippingfee =
      $this->session->userdata('total_shipping_fee') -
      $this->session->userdata('free_shipping');

    if ($calculate_finalshippingfee > 0) {
      $finalshippingfee = $calculate_finalshippingfee;
    }
    if ($this->session->userdata('insurance_status') == 'Yes') {
      $insurance = $this->session->userdata('insurance_cost');
    } else {
      $insurance = 0;
    }
    $data['grand_total_amount'] =
      $grand_total -
      $this->session->userdata('redeemed_voucher_amount') -
      $this->session->userdata('chosen_point_discount') +
      $finalshippingfee + $insurance;

    if ($data['grand_total_amount'] <= 0) {
      if ($finalshippingfee > 0) {
        $data['grand_total_amount'] = $finalshippingfee;
      }
    }

    //get total downpayment
    $data['total_downpayment'] =
      $data['grand_total_amount'] - $indent_remaining - $indent_shipping_fee;

    if ($condition_freeshipping == true) {
      $data['grand_total_amount'] =
        $data['grand_total_amount'] -
        $data['shipping_fee'] -
        $data['indent_shipping_fee'];

      $data['total_downpayment'] =
        $data['total_downpayment'] -
        $data['shipping_fee'] -
        $data['indent_shipping_fee'];

      $data['shipping_fee'] = 0;
    }

    $this->db->insert('orders', $data);
    $order_id = $this->db->insert_id();

    /*insert shipping session to shipping table*/
    if ($this->session->userdata('shipping_session') != null) {
      foreach (
        $this->session->userdata('shipping_session')
        as $shipping_session
      ) {
        $insert_shipping_session = [
          'order_id' => $order_id,
          'warehouse_id' => $shipping_session['warehouse_id'],
          'shipping_fee' => $shipping_session['shipping_fee'],
          'is_indent' => $shipping_session['is_indent'],
        ];
        $this->db->insert('shipping', $insert_shipping_session);
      }
    }

    if ($this->session->userdata('chosen_point')) {
      //deduct minus_rewards to customer current point rewards..
      //get customer current point reward
      $current_point_reward = $this->db
        ->select('current_pointreward')
        ->from('customers')
        ->where(
          'id_customers',
          (int) $this->session->userdata('customer')['customer_id']
        )
        ->get()
        ->row()->current_pointreward;
      $new_point_reward = $current_point_reward - (int) $data['minus_reward'];

      //add new point back to customers table
      $data = [
        'current_pointreward' => $new_point_reward,
      ];
      $this->db->where(
        'id_customers',
        (int) $this->session->userdata('customer')['customer_id']
      );
      $this->db->update('customers', $data);
    }
    //insert new order details to order details table
    foreach ($this->session->userdata('shipping_cart') as $item) {
      $item_data = [
        'orders_id' => $order_id,
        'item_id' => (int) $item['id'],
        'product_id' => (int) $item['product_id'],
        'item_name' => $item['name'],
        'item_price' => (int) $item['price'],
        'quantity' => (int) $item['qty'],
        'subtotal' => (int) $item['subtotal'],
        'warehouse_id' => $item['warehouse_id'],
        'chosen_shipping_id' => $item['chosen_shipping_id'],
        'shipping_fee' => $item['shipping_fee'],
        'is_backorder' => $item['is_backorder'],
        'dp_percentage' => $item['dp_percentage'],
        'indent_message' => $item['indent_message'],
        'is_flashsale' => $item['is_flashsale'],
        'attribute_detail_ids' => serialize($item['attribute_detail_ids']),
      ];

      //get SKU
      $item_data['sku'] = $this->db
        ->select('sku')
        ->from('product_details')
        ->where('id', $item['id'])
        ->get()
        ->row()->sku;

      //get Atribute details
      $item_data['attributes'] = '';
      $count = 1;
      foreach ($item['attribute_detail_ids'] as $detail_id) {
        if ($this->session->userdata('site_lang') == 'english') {
          $detail_name = $this->db
            ->select('attribute_detail_en')
            ->from('product_attributes_detail')
            ->where('id', $detail_id)
            ->get()
            ->row()->attribute_detail_en;
        } else {
          $detail_name = $this->db
            ->select('attribute_detail')
            ->from('product_attributes_detail')
            ->where('id', $detail_id)
            ->get()
            ->row()->attribute_detail;
        }

        if ($count == 1) {
          $item_data['attributes'] = $detail_name;
        } else {
          $item_data['attributes'] =
            $item_data['attributes'] . ', ' . $detail_name;
        }
        $count++;
      }

      if ($item['is_sale'] == true) {
        $item_data['is_sale'] = 'yes';
      } else {
        $item_data['is_sale'] = 'no';
      }
      $this->order_detail_m->save($item_data, $id = null);

      //ONLY FOR FLASHSALE ITEM
      //check if an item is currently in flashsale
      $count_product = $this->db
        ->select('product_id')
        ->from('flashsale_products')
        ->where('flashsale_id', $this->session->userdata('flashsale_id_active'))
        ->where('product_id', $item['product_id'])
        ->get()
        ->num_rows();

      if ($count_product > 0) {
        //this product is part of flashsale
        $counter_data = $this->db
          ->select('counter, terjual')
          ->from('flashsale_products')
          ->where(
            'flashsale_id',
            $this->session->userdata('flashsale_id_active')
          )
          ->where('product_id', $item['product_id'])
          ->get()
          ->row();
        $current_counter = $counter_data->counter;
        $current_terjual = $current_counter->terjual;

        $data = [
          'counter' => $current_counter - $item['qty'],
          'terjual' => $current_terjual + $item['qty'],
        ];
        $this->db->where(
          'flashsale_id',
          $this->session->userdata('flashsale_id_active')
        );
        $this->db->where('product_id', $item['product_id']);
        $this->db->update('flashsale_products', $data);

        //update also flashsale customer
        $data = [
          'customer_id' => $this->session->userdata('customer')['customer_id'],
          'flashsale_id' => $this->session->userdata('flashsale_id_active'),
          'flashsale_product_id' => $item['product_id'],
          'purchase_qty' => $item['qty'],
        ];
        $this->db->insert('flashsale_customer', $data);
      }

      //DEDUCT VOUCHERS FROM VOUCHER TABLE
      if ($this->session->userdata('chosen_voucher_code')) {
        $qty_ready = $this->db
          ->select('qty_ready')
          ->from('vouchers')
          ->where(
            'voucher_code',
            $this->session->userdata('chosen_voucher_code')
          )
          ->get()
          ->row()->qty_ready;

        if ($qty_ready != null) {
          $new_qty_ready = $qty_ready - 1;
          $data = [
            'qty_ready' => $new_qty_ready,
          ];
          $this->db->where(
            'voucher_code',
            $this->session->userdata('chosen_voucher_code')
          );
          $this->db->update('vouchers', $data);
        }
      }

      //UPDATE VOUCHER USER TABLE
      //get voucher id
      if ($this->session->userdata('chosen_voucher_code')) {
        $voucher_id = $this->db
          ->select('id_vouchers')
          ->from('vouchers')
          ->where(
            'voucher_code',
            $this->session->userdata('chosen_voucher_code')
          )
          ->get()
          ->row()->id_vouchers;

        //check if this voucher already been used before in voucher user table
        $count_voucher = $this->db
          ->select('id_voucher_users')
          ->from('voucher_users')
          ->where('voucher_id', $voucher_id)
          ->where(
            'customer_id',
            (int) $this->session->userdata('customer')['customer_id']
          )
          ->get()
          ->num_rows();

        if ($count_voucher == 0) {
          //voucher not exist yet, insert new voucher
          $data = [
            'voucher_id' => $voucher_id,
            'customer_id' => (int) $this->session->userdata('customer')['customer_id'],
            'voucher_used' => 1,
          ];
          $this->db->insert('voucher_users', $data);
        } else {
          //voucher already exist
          //get current used voucher quantity, and add 1
          $voucher_user = $this->db
            ->select('id_voucher_users, voucher_used')
            ->from('voucher_users')
            ->where('voucher_id', (int) $voucher_id)
            ->where(
              'customer_id',
              (int) $this->session->userdata('customer')['customer_id']
            )
            ->get()
            ->row();
          $new_voucher_used = $voucher_user->voucher_used + 1;

          $data = [
            'voucher_used' => (int) $new_voucher_used,
          ];
          $this->db->where('id_voucher_users', $voucher_user->id_voucher_users);
          $this->db->update('voucher_users', $data);
        }
      }
    }

    //DEDUCT CURRENT STOCK WITH PURCHASE QUANTITY
    foreach ($this->session->userdata('shipping_cart') as $rowid => $item) {
      if ($item['is_backorder'] == 'no') {
        //get current stock from stock table
        $current_stock = $this->db
          ->select('id, stock')
          ->from('stock')
          ->where('id_product', (int) $item['product_id'])
          ->where('id_product_detail', (int) $item['id'])
          ->where('warehouse_id', (int) $item['warehouse_id'])
          ->get()
          ->row();
        $new_item_stock = $current_stock->stock - (int) $item['qty'];
        $stock_data = [
          'stock' => $new_item_stock,
        ];
        //update the product item stock in database
        $this->db->where('id_product', (int) $item['product_id']);
        $this->db->where('id_product_detail', (int) $item['id']);
        $this->db->where('warehouse_id', (int) $item['warehouse_id']);
        $this->db->update('stock', $stock_data);

        //get $stock_id
        $stock_id = $current_stock->id;

        //update stock_movement_table
        $movement_data = [
          'stock_id' => $stock_id,
          'type' => '-',
          'stock_change' => (int) $item['qty'],
          'remark' => 'Sales Order No: ' . $order_id,
          'total' => (int) $new_item_stock,
          'name' => 'System'
        ];
        $this->db->insert('stock_movement', $movement_data);
      }
    }

    $order = $this->db
      ->select('*')
      ->from('orders')
      ->where('id_orders', $order_id)
      ->get()
      ->row();

    $grand_final_total =
      $order->grand_total_amount -
      $order->indent_remaining -
      $order->indent_shipping_fee;

    $finalshippingfee = 0;

    $calculate_finalshippingfee =
      $order->shipping_fee -
      $order->free_shipping_fee -
      $order->indent_shipping_fee;

    if ($calculate_finalshippingfee > 0) {
      $finalshippingfee = $calculate_finalshippingfee;
    }

    $total_non_shipping =
      $order->total_amount -
      $order->redeemed_voucher_amount -
      $order->minus_reward_amount;

    if ($grand_final_total <= 0) {
      if ($finalshippingfee <= 0) {
        $this->session->set_userdata('free_order_id', $order_id);

        $update_payment_status = [
          'payment_type' => 'free order',
          'payment_status' => 3,
          'sisa_kembali' => $grand_final_total,
        ];
        $this->db->where('id_orders', $order_id);
        $this->db->update('orders', $update_payment_status);

        redirect('payment/free_order');
      }
    }

    //LOAD MIDTRANS PAYMENTS IF ACTIVE
    // $midtrans_active = $this->db->select('midtrans')->from('configuration')->where('id_configuration', 1)->get()->row()->midtrans;
    // if($midtrans_active == 1) {
    // 	//load midtrans payment function
    // 	$data = $this->midtrans_processing($order, $order_id, $total_non_shipping, $finalshippingfee, $customer_data, $subdistrict, $district, $province);
    // }

    //LOAD DOKU PAYMENTS ID ACTIVE
    $data['doku_payment'] = $this->doku_processing(
      $order,
      $order_id,
      $total_non_shipping,
      $finalshippingfee,
      $customer_data,
      $subdistrict,
      $district,
      $province
    );

    //LOAD BANK TRANSFER MANUAL IF ACTIVE
    $bank_active = $this->db
      ->select('bank_transfer, bank_transfer1')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();

    $data['bca_is_active'] = $bank_active->bank_transfer;
    $data['mandiri_is_active'] = $bank_active->bank_transfer1;
    $data['order_id'] = $order_id;

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('payment', 'english');
    } else {
      $this->lang->load('payment', 'indonesian');
    }
    //load payment view
    $website_name = $this->db
      ->select('website_name')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row()->website_name;
    $this->data_header['browser_title'] = ucwords($website_name) . ' - Payment';
    $this->data_header['meta_description'] =
      ucwords($website_name) . ' - Payment';

    $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('payment', $data);
    $this->load->view("themes/$this->theme_no/footer", $this->data_footer);

    $this->session->unset_userdata('shipping_to_payment');
  }

  public function paypal_payment($id)
  {
    $key = 'sb-hws8i3184847';

    $data_payment = [
      'payment_type' => 'Paypal',
    ];
    $this->db->where('id_orders', $id);
    $this->db->update('orders', $data_payment);

    $method = 'aes-256-cbc';
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
    $encryptedId = openssl_encrypt($id, $method, $key, 0, $iv);
    $encryptedId = base64_encode($iv . $encryptedId);
    $encryptedId = strtr($encryptedId, '+/=', '._-');

    // Set variables for PayPal form
    $returnURL = base_url('payment/paypal_success/') . $encryptedId; // Payment success URL
    $cancelURL = base_url('payment/paypal_cancel/') . $encryptedId; // Payment cancel URL
    $notifyURL = base_url('payment/paypal_ipn/') . $encryptedId; // IPN URL

    // Get particular product data
    $order = $this->db->select('*')
      ->from('orders')
      ->where('id_orders', $id)
      ->get()
      ->row();
    $userID = $order->customer_id; // Current user ID
    $logo = base_url() . 'Your_logo_url';
    $amount = $order->grand_total_amount / 14000;

    // PayPal fields
    $this->paypal_lib->add_field('return', $returnURL);
    $this->paypal_lib->add_field('cancel_return', $cancelURL);
    $this->paypal_lib->add_field('notify_url', $notifyURL);
    $this->paypal_lib->add_field('item_name', 'Order Laciasmara :' . $id);
    $this->paypal_lib->add_field('custom', $userID);
    $this->paypal_lib->add_field('item_number', $id);
    $this->paypal_lib->add_field('amount', $amount);
    $this->paypal_lib->image($logo);

    $this->paypal_lib->paypal_auto_form();
  }

  public function preview_paypal_success()
  {
    $this->load->view('paypal_success');
  }

  public function preview_paypal_fail()
  {
    $this->load->view('paypal_fail');
  }


  public function paypal_success($encryptedId)
  {
    $key = 'sb-hws8i3184847';

    $encryptedId = strtr($encryptedId, '._-', '+/=');
    $decodedData = base64_decode($encryptedId);
    $method = 'aes-256-cbc';
    $ivLength = openssl_cipher_iv_length($method);
    $iv = substr($decodedData, 0, $ivLength);
    $encryptedId = substr($decodedData, $ivLength);
    $id = openssl_decrypt($encryptedId, $method, $key, 0, $iv);

    if ($id === false) {
      redirect(base_url());
    }

    $order = $this->db->select('*')
      ->from('orders')
      ->where('id_orders', $id)
      ->get()
      ->row();

    if (!$order) {
      redirect(base_url());
    }

    $paypalInfo = $this->input->get();

    // Transaction data
    $data['item_number'] = $paypalInfo['item_number'];
    $data['txn_id'] = $paypalInfo["tx"];
    $data['payment_amt'] = $paypalInfo["amt"];
    $data['currency_code'] = $paypalInfo["cc"];
    $data['status'] = $paypalInfo["st"];

    // Update order status
    $order = [
      'payment_status' => 3,
    ];

    $this->db->where('id_orders', $id);
    $this->db->update('orders', $order);

    $this->destroy_session_data();

    // $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('paypal_success', $data);
    // $this->load->view("themes/$this->theme_no/footer", $this->data_footer);
  }


  function paypal_cancel($encryptedId)
  {
    //if transaction cancelled
    // $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('paypal_fail');
    // $this->load->view("themes/$this->theme_no/footer", $this->data_footer);
  }

  function paypal_ipn()
  {
    //paypal return transaction details array
    $paypalInfo    = $this->input->post();
    $data['user_id'] = $paypalInfo['custom'];
    $data['product_id']    = $paypalInfo["item_number"];
    $data['txn_id']    = $paypalInfo["txn_id"];
    $data['payment_gross'] = $paypalInfo["mc_gross"];
    $data['currency_code'] = $paypalInfo["mc_currency"];
    $data['payer_email'] = $paypalInfo["payer_email"];
    $data['payment_status']    = $paypalInfo["payment_status"];
    $paypalURL = $this->paypal_lib->paypal_url;
    $result    = $this->paypal_lib->curlPost($paypalURL, $paypalInfo);

    //check whether the payment is verified
    if (preg_match("/VERIFIED/i", $result)) {
      //insert the transaction data into the database
      $this->product->storeTransaction($data);
    }
  }

  private function doku_processing(
    $order,
    $order_id,
    $total_non_shipping,
    $finalshippingfee,
    $customer_data,
    $subdistrict,
    $district,
    $province
  ) {
    //Process DOKU script
    $doku_data['transidmerchant'] = $order_id;
    // $doku_data['payment_type'] =  $this->session->userdata('chosen_payment_type');
    $doku_data['payment_type'] = 'doku_creditcard';
    $doku_data['basket'] = $this->session->userdata('shipping_cart');
    $doku_data['amount'] = $total_non_shipping;
    $doku_data['cname'] = $customer_data->shipping_name;
    $doku_data['cemail'] = $customer_data->email;
    $doku_data['cwphone'] = $customer_data->shipping_phone;
    $doku_data['cmphone'] = $customer_data->shipping_phone;
    $doku_data['caddress'] = $customer_data->shipping_address;
    $doku_data['czipcode'] = $customer_data->shipping_postcode;
    $doku_data['birthday'] = $customer_data->birthday;
    $doku_data['ccity'] =  $district;
    $doku_data['cstate'] = $province;
    $doku_data['ccountry'] = 'Indonesia';
    $doku_data['saddress'] = $customer_data->shipping_address;
    $doku_data['szipcode'] = $customer_data->shipping_postcode;
    $doku_data['scity'] = $subdistrict;
    $doku_data['sstate'] = $province;
    $doku_data['scountry'] = 'Indonesia';
    $doku_data['carrier_name'] = $this->session->userdata('carrier_name');
    $doku_data['total_shipping_fee'] = $finalshippingfee;

    if ($this->session->userdata('cart_has_discounted_items') == 'no') {
      $disc_first = 0;
      $referral = !empty($order->referral) ? $order->referral : $order->redeemed_voucher_code;

      $affiliator = $this->db->select('kategori')
        ->from('affiliator_register')
        ->where('referral', $referral)
        ->get()
        ->row();

      if ($customer_data->first == 1) { // Jika ini adalah pembelian pertama
        if ($order->order_date >= '2024-08-01') {
          if (!empty($affiliator)) {
            if ($affiliator->kategori == 'asmarasana' || $referral == 'laciput') {
              $disc_first = $order->total_amount * 0.05;
            } elseif ($affiliator->kategori == 'asmaradoor') {
              $disc_first = $order->total_amount * 0.10;
            }
          } else {
            $disc_first = $order->total_amount * 0.05;
          }
        } else {
          $disc_first = $order->total_amount * 0.05;
        }
        $firstpurchase = ($total_non_shipping) * $disc_first;
      } else {
        $firstpurchase = 0;
      }
    }
    $doku_data['total_amount'] = number_format(
      (float) ($total_non_shipping + $finalshippingfee - $firstpurchase),
      2,
      '.',
      ''
    );

    if ($this->session->userdata('tax')) {
      $doku_data['tax'] = $this->session->userdata('tax');
    }

    return $doku_data;
  }

  private function midtrans_processing(
    $order,
    $order_id,
    $total_non_shipping,
    $finalshippingfee,
    $customer_data,
    $subdistrict,
    $district,
    $province
  ) {
    require_once APPPATH . 'third_party/Veritrans.php';

    //get key
    $midtrans = $this->db
      ->select(
        'veritrans_server_key, veritrans_sandbox_server_key, veritrans_client_key, veritrans_sandbox_client_key, veritrans_production_mode, credit_card, gopay, permata_va, bni_va, mandiri_bill, akulaku'
      )
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();
    $production_mode = $midtrans->veritrans_production_mode;

    //Set erver key
    if ($production_mode == 'true') {
      Veritrans_Config::$isProduction = true;
      Veritrans_Config::$serverKey = $midtrans->veritrans_server_key;
      $data['client_key'] = $midtrans->veritrans_client_key;
      $data['snap_url'] = 'https://app.midtrans.com/snap/snap.js';
    } else {
      Veritrans_Config::$isProduction = false;
      Veritrans_Config::$serverKey = $midtrans->veritrans_sandbox_server_key;
      $data['client_key'] = $midtrans->veritrans_sandbox_client_key;
      $data['snap_url'] = 'https://app.sandbox.midtrans.com/snap/snap.js';
    }

    // Enable sanitization
    Veritrans_Config::$isSanitized = true;

    // Enable 3D-Secure
    Veritrans_Config::$is3ds = true;

    if ($total_non_shipping <= 0) {
      if ($finalshippingfee > 0) {
        //disable midtrans non product transaction items to avoid negative grand total
        $midtrans_disable_non_product_items = true;
      }
    }

    // Populate items
    // define a two-dimensional array
    //get order detail
    $order_details = $this->db
      ->select('*')
      ->from('orders_detail')
      ->where('orders_id', $order_id)
      ->get()
      ->result();

    $total_item_price = 0;

    foreach ($order_details as $item) {
      //get dp price for indent porduct
      if ($item->is_backorder == 'yes') {
        $price = ($item->item_price * $item->dp_percentage) / 100;
        $name = strip_tags(substr($item->item_name, 0, 48)) . '..Downpayment';
      } else {
        $price = $item->item_price;
        $name = strip_tags(substr($item->item_name, 0, 48)) . '..';
      }

      $items[] = [
        'id' => $item->product_id,
        'price' => (int) $price,
        'quantity' => $item->quantity,
        'name' => $name,
      ];

      $total_item_price = $total_item_price + $price * $item->quantity;
    }

    if (!isset($midtrans_disable_non_product_items)) {
      //add voucher discount into the item
      if ($order->redeemed_voucher_amount != null) {
        if ($order->redeemed_voucher_type == 'amount') {
          //by amount
          //deduct voucher into item, so gross == total items
          $items[] = [
            'id' => 'voucher',
            'price' => -$order->redeemed_voucher_amount,
            'quantity' => 1,
            'name' => 'Voucher: ' . $order->redeemed_voucher_code,
          ];
        } else {
          //by percentage
          //deduct voucher into item, so gross == total items
          $items[] = [
            'id' => 'voucher',
            'price' => -$order->redeemed_voucher_amount,
            'quantity' => 1,
            'name' => 'Voucher: ' . $order->redeemed_voucher_code,
          ];
        }
      }

      //add point rewards discount
      if ($order->minus_reward_amount != null) {
        $items[] = [
          'id' => 'pointrewards',
          'price' => -$order->minus_reward_amount,
          'quantity' => 1,
          'name' => 'Point Rewards',
        ];
      }

      if ($finalshippingfee > 0) {
        //add shipping fee into the item
        $set_shipping_fee = 0;
        foreach ($order_details as $key) {
          if ($key->is_backorder == 'yes') {
            $set_shipping_fee += $key->shipping_fee;
          } else {
            $set_shipping_fee += 0;
          }
        }
        $items[] = [
          'id' => 'shipping',
          'price' => $set_shipping_fee,
          'quantity' => 1,
          'name' => 'Shipping Fee',
        ];

        //add free shipping
        if ($order->free_shipping_fee != null) {
          $items[] = [
            'id' => 'freeshipping',
            'price' => -$order->free_shipping_fee,
            'quantity' => 1,
            'name' => 'Free Shipping',
          ];
        }
      }

      //add creditcard total fee (transaction fee + admin fee)
      if ($this->session->userdata('chosen_payment_type') == 'veritrans') {
        $items[] = [
          'id' => 'veritrans_fee',
          'price' => (int) $this->session->userdata('veritrans_total_fee'),
          'quantity' => 1,
          'name' => 'Credit Card Admin',
        ];
      }

      //add virtualaccount total fee (admin fee)
      if ($this->session->userdata('chosen_payment_type') == 'virtualaccount') {
        $items[] = [
          'id' => 'virtualaccount_fee',
          'price' => (int) $this->session->userdata('virtualaccount_total_fee'),
          'quantity' => 1,
          'name' => 'Virtual Account Admin',
        ];
      }

      //add tax
      if ($this->session->userdata('tax')) {
        $items[] = [
          'id' => 'tax',
          'price' => (int) $this->session->userdata('tax'),
          'quantity' => 1,
          'name' => 'Tax',
        ];
      }
    } else {
      $items[] = [
        'id' => 'discount',
        'price' => -$total_item_price,
        'quantity' => 1,
        'name' => 'Discount',
      ];

      if ($finalshippingfee > 0) {
        //add shipping fee into the item
        $items[] = [
          'id' => 'shipping',
          'price' => $order->shipping_fee,
          'quantity' => 1,
          'name' => 'Shipping Fee',
        ];

        //add free shipping
        if ($order->free_shipping_fee != null) {
          $items[] = [
            'id' => 'freeshipping',
            'price' => -$order->free_shipping_fee,
            'quantity' => 1,
            'name' => 'Free Shipping',
          ];
        }
      }
    }

    // echo '<pre>';
    // print_r($items);
    // echo '</pre>';
    // exit();

    // Populate customer's billing address
    $billing_address = [
      'first_name' => $customer_data->shipping_name,
      'last_name' => '',
      'address' => $customer_data->shipping_address,
      'city' => $subdistrict . '. ' . $district . '. ' . $province,
      'postal_code' => $customer_data->shipping_postcode,
      'phone' => $customer_data->shipping_phone,
      'country_code' => 'IDN',
    ];

    // Populate customer's shipping address
    $shipping_address = [
      'first_name' => $customer_data->shipping_name,
      'last_name' => '',
      'address' => $customer_data->shipping_address,
      'city' => $subdistrict . '. ' . $district . '. ' . $province,
      'postal_code' => $customer_data->shipping_postcode,
      'phone' => $customer_data->shipping_phone,
      'country_code' => 'IDN',
    ];

    // Populate customer's Info
    $customer_details = [
      'first_name' => $customer_data->shipping_name,
      'last_name' => '',
      'email' => $customer_data->email,
      'phone' => $customer_data->shipping_phone,
      'billing_address' => $billing_address,
      'shipping_address' => $shipping_address,
    ];

    if ($midtrans->credit_card == 1) {
      //MIDTRANS CREDIT CARD
      $transaction_details_cc = [
        'order_id' => $order_id . '-cc',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_creditcard = [
        'enabled_payments' => ['credit_card'],
        'transaction_details' => $transaction_details_cc,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_cc'] = Veritrans_Snap::getSnapToken(
        $transaction_creditcard
      );
    }

    if ($midtrans->gopay == 1) {
      //MIDTRANS GOPAY
      $transaction_details_gopay = [
        'order_id' => $order_id . '-gopay',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_gopay = [
        'enabled_payments' => ['gopay'],
        'transaction_details' => $transaction_details_gopay,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_gopay'] = Veritrans_Snap::getSnapToken(
        $transaction_gopay
      );
    }

    if ($midtrans->akulaku == 1) {
      //MIDTRANS AKULAKU
      $transaction_details_akulaku = [
        'order_id' => $order_id . '-akulaku',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_akulaku = [
        'enabled_payments' => ['akulaku'],
        'transaction_details' => $transaction_details_akulaku,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_akulaku'] = Veritrans_Snap::getSnapToken(
        $transaction_akulaku
      );
    }

    if ($midtrans->permata_va == 1) {
      //MIDTRANS PERMATA VA
      $transaction_details_permatava = [
        'order_id' => $order_id . '-permatava',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_permatava = [
        'enabled_payments' => ['permata_va'],
        'transaction_details' => $transaction_details_permatava,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_permatava'] = Veritrans_Snap::getSnapToken(
        $transaction_permatava
      );
    }

    if ($midtrans->bni_va == 1) {
      //MIDTRANS BNI VA
      $transaction_details_bniva = [
        'order_id' => $order_id . '-bniva',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_bniva = [
        'enabled_payments' => ['bni_va'],
        'transaction_details' => $transaction_details_bniva,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_bniva'] = Veritrans_Snap::getSnapToken(
        $transaction_bniva
      );
    }

    if ($midtrans->mandiri_bill == 1) {
      //MIDTRANS MANDIRI BILL PAYMENT
      $transaction_details_echannel = [
        'order_id' => $order_id . '-echannel',
        'gross_amount' => (int) $grand_final_total,
      ];

      $transaction_echannel = [
        'enabled_payments' => ['echannel'],
        'transaction_details' => $transaction_details_echannel,
        'customer_details' => $customer_details,
        'item_details' => $items,
      ];

      $data['snapToken_echannel'] = Veritrans_Snap::getSnapToken(
        $transaction_echannel
      );
    }

    $data['order_id'] = $order_id;

    //create midtrans order_id session to be used by response success midtrans page
    $this->session->set_userdata('midtrans_order_id', $order_id);

    return $data;
  }

  public function bank_transfer_processing($bank_name = null, $order_id = null)
  {
    if ($bank_name == null && $order_id == null) {
      redirect('shipping');
    }

    $this->order_id = $order_id;

    $order = $this->db
      ->select('*')
      ->from('orders')
      ->where('id_orders', $order_id)
      ->get()
      ->row();

    //get order detail
    $order_details = $this->db
      ->select('*')
      ->from('orders_detail')
      ->where('orders_id', $order_id)
      ->get()
      ->result();

    //get customer district / city name
    $customer_data = $this->db
      ->select(
        'name, email, phone, shipping_address, shipping_id_district, shipping_id_subdistrict, shipping_id_province'
      )
      ->from('customers')
      ->where(
        'id_customers',
        (int) $this->session->userdata('customer')['customer_id']
      )
      ->get()
      ->row();

    //get subdistrict, distirct and province name
    $subdistrict = $this->db
      ->select('subdistrict')
      ->from('indonesia_subdistricts')
      ->where(
        'rajaongkir_id_subdistrict',
        $customer_data->shipping_id_subdistrict
      )
      ->get()
      ->row()->subdistrict;

    //get district
    $district = $this->db
      ->select('district')
      ->from('indonesia_districts')
      ->where('rajaongkir_id_district', $customer_data->shipping_id_district)
      ->get()
      ->row()->district;

    //get province
    $province = $this->db
      ->select('province')
      ->from('indonesia_provinces')
      ->where('rajaongkir_province_id', $customer_data->shipping_id_province)
      ->get()
      ->row()->province;

    //BCA manual bank transfer
    if ($bank_name == 'bca') {
      $payment_type = 'bank transfer BCA';

      $reseller_id = $this->db->select('reseller_id')->from('customers')->where('id_customers', $this->session->userdata('customer')['customer_id'])->get()->row()->reseller_id;

      if ($reseller_id == NULL) {
        //update payment status to become 1 // not paid
        $data = [
          'payment_status' => 1,
          'payment_type' => $payment_type,

        ];
        $this->db->where('id_orders', $order_id);
        $this->db->update('orders', $data);

        //Send email
        $this->process_send_email($payment_type);
      } else {

        $data = [
          'payment_status' => 0,
          'payment_type' => $payment_type,
        ];

        $this->db->where('id_orders', $order_id);
        $this->db->update('orders', $data);
      }
      //LOAD PAYMENT RETURN PAGE
      $data['bank'] = $this->configuration_m->get_bank();
      $data['email'] = $customer_data->email;
      $data['order_id'] = $order_id;

      $data['order_info'] = $this->db
        ->select(
          'insurance_status, insurance_cost, redeemed_voucher_type, minus_reward_amount, grand_total_amount, total_amount, indent_remaining, indent_shipping_fee, id_orders, order_date,payment_status, payment_confirm, recipient_name, address, district, subdistrict, province, postcode, shipping_fee, free_shipping_fee, minus_reward, redeemed_voucher_code, redeemed_voucher_amount, redeemed_voucher_value, first, referral'
        )
        ->from('orders')
        ->where('id_orders', $order_id)
        ->get()
        ->row();

      $this->destroy_session_data();

      if ($this->session->userdata('site_lang') == 'english') {
        $this->lang->load('order_history', 'english');
      } else {
        $this->lang->load('order_history', 'indonesian');
      }

      //create new session to display on thank you page
      $bca_data = [
        'grand_total' =>
        $data['order_info']->grand_total_amount -
          $data['order_info']->indent_remaining -
          $data['order_info']->indent_shipping_fee,
        'order_info' => $data['order_info'],
        'bank' => $data['bank'],
        'email' => $data['email'],
        'order_id' => $data['order_id'],
      ];
      $this->session->set_userdata('bca_data', $bca_data);

      if ($reseller_id == NULL) {
        redirect('payment/process_payment');
      } else {
        redirect('payment/retailer_approval_process');
      }
    }

    //MANDIRI manual bank transfer
    if ($bank_name == 'mandiri') {
      $payment_type = 'bank transfer MANDIRI';

      $reseller_id = $this->db->select('reseller_id')->from('customers')->where('id_customers', $this->session->userdata('customer')['customer_id'])->get()->row()->reseller_id;

      if ($reseller_id == NULL) {
        //update payment status to become 1 // not paid
        $data = [
          'payment_status' => 1,
          'payment_type' => $payment_type,

        ];
        $this->db->where('id_orders', $order_id);
        $this->db->update('orders', $data);

        //Send email
        $this->process_send_email($payment_type);
      } else {

        $data = [
          'payment_status' => 0,
          'payment_type' => $payment_type,
        ];

        $this->db->where('id_orders', $order_id);
        $this->db->update('orders', $data);
      }



      //LOAD PAYMENT RETURN PAGE
      $data['bank'] = $this->configuration_m->get_bank1();
      $data['email'] = $customer_data->email;
      $data['order_id'] = $order_id;

      $data['order_info'] = $this->db
        ->select(
          'insurance_status, insurance_cost, redeemed_voucher_type, minus_reward_amount, grand_total_amount, total_amount, indent_remaining, indent_shipping_fee, id_orders, order_date,payment_status, payment_confirm, recipient_name, address, district, subdistrict, province, postcode, shipping_fee, free_shipping_fee, minus_reward, redeemed_voucher_code, redeemed_voucher_amount, redeemed_voucher_value, first, referral'
        )
        ->from('orders')
        ->where('id_orders', $order_id)
        ->get()
        ->row();

      $this->destroy_session_data();

      if ($this->session->userdata('site_lang') == 'english') {
        $this->lang->load('order_history', 'english');
      } else {
        $this->lang->load('order_history', 'indonesian');
      }

      //create new session to display on thank you page
      $mandiri_data = [
        'grand_total' =>
        $data['order_info']->grand_total_amount -
          $data['order_info']->indent_remaining -
          $data['order_info']->indent_shipping_fee,
        'order_info' => $data['order_info'],
        'bank' => $data['bank'],
        'email' => $data['email'],
        'order_id' => $data['order_id'],
      ];
      $this->session->set_userdata('mandiri_data', $mandiri_data);

      if ($reseller_id == NULL) {
        redirect('payment/process_payment');
      } else {
        redirect('payment/retailer_approval_process');
      }
    }
  }

  public function retailer_approval_process()
  {
    if (
      !$this->session->userdata('bca_data') &&
      !$this->session->userdata('mandiri_data')
    ) {
      redirect(base_url());
    }

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('order_history', 'english');
    } else {
      $this->lang->load('order_history', 'indonesian');
    }

    $this->data_header['datalayer'] = [
      'ecomm_pagetype' => 'purchase',
    ];

    if ($this->session->userdata('bca_data')) {
      //get SEO
      $this->db
        ->select('website_name')
        ->from('configuration')
        ->where('id_configuration', 1);
      $website_name = $this->db->get()->row();
      $this->data_header['browser_title'] =
        ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';
      $this->data_header['meta_description'] =
        ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';

      $data = $this->session->userdata('bca_data');
    }

    if ($this->session->userdata('mandiri_data')) {
      //get SEO
      $this->db
        ->select('website_name')
        ->from('configuration')
        ->where('id_configuration', 1);
      $website_name = $this->db->get()->row();
      $this->data_header['browser_title'] =
        ucwords($website_name->website_name) .
        ' - MANDIRI Manual Bank Transfer';
      $this->data_header['meta_description'] =
        ucwords($website_name->website_name) .
        ' - MANDIRI Manual Bank Transfer';

      $data = $this->session->userdata('mandiri_data');
    }

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('payment', 'english');
    } else {
      $this->lang->load('payment', 'indonesian');
    }

    $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('retailerapproval', $data);
    $this->load->view("themes/$this->theme_no/footer", $this->data_footer);

    //destroy bank data
    $this->session->unset_userdata('bca_data');
    $this->session->unset_userdata('mandiri_data');
  }

  public function process_payment()
  {
    if (
      !$this->session->userdata('bca_data') &&
      !$this->session->userdata('mandiri_data')
    ) {
      redirect(base_url());
    }

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('order_history', 'english');
    } else {
      $this->lang->load('order_history', 'indonesian');
    }

    $this->data_header['datalayer'] = [
      'ecomm_pagetype' => 'purchase',
    ];

    if ($this->session->userdata('bca_data')) {
      //get SEO
      $this->db
        ->select('website_name')
        ->from('configuration')
        ->where('id_configuration', 1);
      $website_name = $this->db->get()->row();
      $this->data_header['browser_title'] =
        ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';
      $this->data_header['meta_description'] =
        ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';

      $data = $this->session->userdata('bca_data');
    }

    if ($this->session->userdata('mandiri_data')) {
      //get SEO
      $this->db
        ->select('website_name')
        ->from('configuration')
        ->where('id_configuration', 1);
      $website_name = $this->db->get()->row();
      $this->data_header['browser_title'] =
        ucwords($website_name->website_name) .
        ' - MANDIRI Manual Bank Transfer';
      $this->data_header['meta_description'] =
        ucwords($website_name->website_name) .
        ' - MANDIRI Manual Bank Transfer';

      $data = $this->session->userdata('mandiri_data');
    }

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('payment', 'english');
    } else {
      $this->lang->load('payment', 'indonesian');
    }

    $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('banktransfer', $data);
    $this->load->view("themes/$this->theme_no/footer", $this->data_footer);

    //destroy bank data
    $this->session->unset_userdata('bca_data');
    $this->session->unset_userdata('mandiri_data');
  }

  public function free_order()
  {
    $order_id = $this->session->userdata('free_order_id');
    $this->session->unset_userdata('free_order_id');

    if ($order_id == null) {
      redirect('welcome');
    }

    //get customer district / city name
    $customer_data = $this->db
      ->select(
        'name, email, phone, shipping_address, shipping_id_district, shipping_id_subdistrict, shipping_id_province'
      )
      ->from('customers')
      ->where(
        'id_customers',
        (int) $this->session->userdata('customer')['customer_id']
      )
      ->get()
      ->row();

    //LOAD PAYMENT RETURN PAGE
    $data['email'] = $customer_data->email;
    $data['order_id'] = $order_id;

    $data['order_info'] = $this->db
      ->select(
        'insurance_status, insurance_cost, id_orders,order_date,payment_status,payment_confirm,recipient_name,address,district,subdistrict,province,postcode'
      )
      ->from('orders')
      ->where('id_orders', $order_id)
      ->get()
      ->row();
    $data['grand_total'] = '0';

    $this->destroy_session_data();

    if ($this->session->userdata('site_lang') == 'english') {
      $this->lang->load('order_history', 'english');
    } else {
      $this->lang->load('order_history', 'indonesian');
    }

    //get SEO
    $website_name = $this->db
      ->select('website_name')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();
    $this->data_header['browser_title'] =
      ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';
    $this->data_header['meta_description'] =
      ucwords($website_name->website_name) . ' - BCA Manual Bank Transfer';

    $this->load->view("themes/$this->theme_no/header", $this->data_header);
    $this->load->view('free_order', $data);
    $this->load->view("themes/$this->theme_no/footer", $this->data_footer);
  }

  private function send_confirmation_email($paymentType, $orderData, $orderDetails, $bankData)
  {
    $email_data['email'] = $orderData['email'];
    $email_data['name'] = $orderData['name'];
    $email_data['phone'] = $orderData['phone'];
    $email_data['type'] = $orderData['type'];

    $email_data['emails'] = $this->configuration_m->get_emails();
    $email_data['bank'] = $bankData;
    if ($this->session->userdata('site_lang') == 'english') {
      $email_data['subject'] = 'Order Confirmation';
    } else {
      $email_data['subject'] = 'Konfirmasi Pesanan';
    }
    $email_data['order'] = $orderData;
    $email_data['order_details'] = $orderDetails;


    switch ($paymentType) {
      case 'bca':
        if ($this->session->userdata('site_lang') == 'english') {
          $view_file = 'email/english/bank_transfer_english';
        } else {
          $view_file = 'email/indonesian/bank_transfer_indo';
        }
        break;
      case 'mandiri':
        if ($this->session->userdata('site_lang') == 'english') {
          $view_file = 'email/english/bank_transfer_english';
        } else {
          $view_file = 'email/indonesian/bank_transfer_indo';
        }
        break;
    }

    $data_log = [
      'recipient_name' => $orderData['name'],  // Alamat email penerima
      'recipient_email' => $orderData['email'],  // Alamat email penerima
      'recipient_phone' => $orderData['phone'],  // no telp penerima
      'recipient_type' => $orderData['type'],  // Alamat email penerima
      'subject' => $email_data['subject'],        // Subjek email
      'email_body' => $this->load->view($view_file, $email_data, TRUE),  // Isi email
    ];

    // Loggin berhasil
    $this->db->insert('email_payment_log', $data_log);
    $this->send_email($view_file, $email_data);
  }
  private function process_send_email($payment_type)
  {
    //----SEND EMAIL TO CUSTOMER
    //get customer name
    if ($this->session->userdata('customer')['customer_id'] != null) {
      $customer_id = (int) $this->session->userdata('customer')['customer_id'];
    } else {
      $customer_id = $this->db
        ->select('customer_id')
        ->from('orders')
        ->where('id_orders', $this->order_id)
        ->get()
        ->row()->customer_id;
    }
    $this->db
      ->select('name,phone,type,email')
      ->from('customers')
      ->where('id_customers', $customer_id);
    $email_data['customer'] = $this->db->get()->row();
    $email_data['email'] = $email_data['customer']->email;
    $email_data['name'] = $email_data['customer']->name;
    $email_data['phone'] = $email_data['customer']->phone;
    $email_data['type'] = $email_data['customer']->type;

    $email_data['emails'] = $this->configuration_m->get_emails();

    if ($payment_type == 'bank transfer BCA') {
      $email_data['bank'] = $this->db
        ->select('bank')
        ->from('configuration')
        ->where('id_configuration', 1)
        ->get()
        ->row()->bank;
    } elseif ($payment_type == 'bank transfer MANDIRI') {
      $email_data['bank'] = $this->db
        ->select('bank1')
        ->from('configuration')
        ->where('id_configuration', 1)
        ->get()
        ->row()->bank1;
    }

    if ($this->session->userdata('site_lang') == 'english') {
      $email_data['subject'] = 'Order Confirmation';
    } else {
      $email_data['subject'] = 'Konfirmasi Pesanan';
    }

    //get order detail and customer detail
    $email_data['order'] = $this->order_m->get_order($this->order_id);
    $email_data['order_details'] = $this->order_detail_m->get_orders_detail(
      $this->order_id
    );

    //get vouchers detail
    if ($this->session->userdata('chosen_voucher_code')) {
      $email_data['chosen_voucher_code'] = $this->session->userdata(
        'chosen_voucher_code'
      );
      $email_data['chosen_voucher_type'] = $this->session->userdata(
        'chosen_voucher_type'
      );
      $email_data['chosen_voucher_discount'] = $this->session->userdata(
        'chosen_voucher_discount'
      );
      $email_data['redeemed_voucher_amount'] = $this->session->userdata(
        'redeemed_voucher_amount'
      );
    }

    //get shipping fee total
    $email_data['carrier_name'] = $this->session->userdata('carrier_name');
    $email_data['total_shipping_fee'] = $this->session->userdata(
      'total_shipping_fee'
    );

    //add tax to email, if exist..
    if ($this->session->userdata('tax')) {
      $email_data['tax'] = $this->session->userdata('tax');
    }

    //add point reward to email, if exist..
    if ($this->session->userdata('chosen_point')) {
      $email_data['chosen_point'] = $this->session->userdata('chosen_point');
      $email_data['chosen_point_discount'] = $this->session->userdata(
        'chosen_point_discount'
      );
    }

    switch ($payment_type) {
      case 'bank transfer BCA':
        if ($this->session->userdata('site_lang') == 'english') {
          $view_file = 'email/english/bank_transfer_english';
        } else {
          $view_file = 'email/indonesian/bank_transfer_indo';
        }
        break;
      case 'bank transfer MANDIRI':
        if ($this->session->userdata('site_lang') == 'english') {
          $view_file = 'email/english/bank_transfer_english';
        } else {
          $view_file = 'email/indonesian/bank_transfer_indo';
        }
        break;
      case 'cod':
        if ($this->session->userdata('site_lang') == 'english') {
          $view_file = 'email/english/cod';
        } else {
          $view_file = 'email/indonesian/cod';
        }
        break;
      case 'midtrans':
        if ($this->session->userdata('site_lang') == 'english') {
          /*$email = $this->load->view('email/english/bank_transfer', $data, TRUE);   */
          $view_file = 'email/english/bank_transfer_english';
        } else {
          $view_file = 'email/indonesian/bank_transfer_indo';
        }
        break;
    }
    $data_log = [
      'recipient_name' => $email_data['name'],  // Alamat email penerima
      'recipient_email' => $email_data['email'],  // Alamat email penerima
      'recipient_phone' => $email_data['phone'],  // no telp penerima
      'recipient_type' => $email_data['type'],  // Alamat email penerima
      'subject' => $email_data['subject'],        // Subjek email
      'email_body' => $this->load->view($view_file, $email_data, TRUE),  // Isi email
    ];

    $this->db->insert('email_payment_log', $data_log);


    $this->send_email($view_file, $email_data); //function in My_Controller
  }

  private function destroy_session_data()
  {
    if ($this->session->userdata('customer')['customer_type'] == 'guest') {
      $this->session->unset_userdata('customer');
    }

    //DESTROY CART AND UNSET SOME SESSION, BUT NOT CUSTOMER SESSION
    $this->cart->destroy();
    $this->session->unset_userdata('grand_total');
    $this->session->unset_userdata('recipient_name');
    $this->session->unset_userdata('address');
    $this->session->unset_userdata('id_district');
    $this->session->unset_userdata('id_subdistrict');
    $this->session->unset_userdata('id_province');
    $this->session->unset_userdata('district');
    $this->session->unset_userdata('subdistrict');
    $this->session->unset_userdata('province');
    $this->session->unset_userdata('country');
    $this->session->unset_userdata('postcode');
    $this->session->unset_userdata('phone');
    $this->session->unset_userdata('order_id');
    $this->session->unset_userdata('is_from_cart');
    $this->session->unset_userdata('chosen_voucher_type');
    $this->session->unset_userdata('chosen_voucher_discount');
    $this->session->unset_userdata('chosen_voucher_code');
    $this->session->unset_userdata('total_categoryproduct_promo');
    $this->session->unset_userdata('redeemed_voucher_amount');
    $this->session->unset_userdata('total_shipping_fee');
    $this->session->unset_userdata('referral');
    $this->session->unset_userdata('gimmickeligible');
    $this->session->unset_userdata('carrier');
    $this->session->unset_userdata('carrier_name');
    $this->session->unset_userdata('summary_message');
    $this->session->unset_userdata('add_point_reward');
    $this->session->unset_userdata('minus_point_reward');
    $this->session->unset_userdata('chosen_point');
    $this->session->unset_userdata('chosen_point_discount');
    $this->session->unset_userdata('chosen_payment_type');
    $this->session->unset_userdata('tax');
    $this->session->unset_userdata('productpage_to_cart');
    $this->session->unset_userdata('choose_dropship_status');
    $this->session->unset_userdata('destination_latitude');
    $this->session->unset_userdata('destination_longitude');
    $this->session->unset_userdata('current_viewed_category_id');
    $this->session->unset_userdata('shipping_cart');
    $this->session->unset_userdata('prescription_uniqid');
    $this->session->unset_userdata('guest_details');
    $this->session->unset_userdata('guest_shipping_id');
    $this->session->unset_userdata('customer_note');
    $this->session->unset_userdata('referral'); //unset user referral data after payment successful
    $this->session->unset_userdata('visitor_tracking');
    $this->session->unset_userdata('initial_visitor_tracking');
    $this->session->unset_userdata('current_page_tracked');
  }

  public function send_email_view()
  {
    $orderId = 194196;
    $paymentType = "bca";
    $orderData = $this->getOrderDataById($orderId);
    $orderDetails = $this->getOrderDetailByOrderId($orderId);
    $bankData = $this->getBankData($paymentType);
    $website_data = $this->db->select('website_icon, browser_title, meta_description')
      ->from('configuration')
      ->where('id_configuration', 1)
      ->get()
      ->row();

    $data_view = [
      'orderData' => $orderData,
      'orderDetails' => $orderDetails,
      'paymentType' => $paymentType,
      'bankData' => $bankData,
      'website_icon' => $website_data->website_icon,
      'browser_title' => ucwords($website_data->browser_title) . ' - Payment Confirmation',
      'meta_description' => $website_data->meta_description,
    ];
    $this->load->view('email/indonesian/bank_transfer_indo', $data_view);
  }
}

https://t.me/RX1948 - 2025