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

class Checkout extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Payment_model');
        if ($this->cart->total_items() == 0) {
            redirect(base_url());
        }
    }

    public function index()
    {
        $data['title'] = 'Checkout - ' . $this->Settings_model->general()["app_name"];
        $data['css'] = 'checkout';
        $data['responsive'] = '';
        $data['city'] = $this->Payment_model->getCity();
        $this->db->select("*, rekening.id as rekeningId, bank.name AS bankName");
        $this->db->join("bank", "bank.id=rekening.rekening");
        $data['payment'] = $this->db->get('rekening');
        $data['logo_pay'] = $this->db->get('logo_payment')->row_array();
        $data['flat_ongkir'] = $this->db->get('flat_ongkir');
        $this->load->view('templates/header', $data);
        $this->load->view('page/checkout');
        $this->load->view('templates/footer_mintmpl');
        $this->load->view('templates/footer_real');
    }

    public function checkoutCoupon()
    {
        $coupon = $this->input->post('coupon');
        $check = $this->db->get_where('coupon', ['code' => $coupon])->row_array();
        if ($check) {
            if ($check['dated'] >= date('Y-m-d')) {
                if ($this->cart->total() >= $check['min']) {
                    if ($check['type'] == 1) {
                        $diskonnya = ($this->cart->total() * $check['discount']) / 100;
                        $price = $this->cart->total() - $diskonnya;
                        echo json_encode(["success" => true, "discount" => $diskonnya]);
                    } else {
                        echo json_encode(["success" => true, "discount" => $check['discount']]);
                    }
                } else {
                    $priceHarusnya = number_format($check['min'], 0, ",", ".");
                    echo json_encode(["success" => false, "msg" => "Belanja minimal Rp.$priceHarusnya untuk menggunakan kupon ini"]);
                }
            } else {
                echo json_encode(["success" => false, "msg" => "Kode kupon yang dimasukkan sudah habis masa berlaku"]);
            }
        } else {
            echo json_encode(["success" => false, "msg" => "Kode kupon yang dimasukan tidak tersedia"]);
        }
    }

    public function go()
    {
        $invoice = time();
        $name = $this->input->post('name');
        $wa = $this->input->post('wa');
        $address = $this->input->post('address');
        $district = $this->input->post('district');
        $subdistrict = $this->input->post('subdistrict');
        $courier = $this->input->post('courier');
        $ongkir = $this->input->post('ongkir');
        $random = $this->input->post('random');
        $potongan = $this->input->post('potongan');
        $payment = $this->input->post('payment');
        $service1 = explode("-", $courier);
        $service2 = $service1[2];
        $ongkir = $service1[0];
        $kurir = $service1[1];
        if ($payment == "13") {
            $feeCODdb = $this->Settings_model->general()['fee_cod'];
            $random = (intval($this->cart->total()) + intval($ongkir)) * intval($feeCODdb) / 100;
        } else {
            $random = $this->input->post('random');
        }
        function whichOnePrice($payment, $price)
        {
            $convertion = 14397;
            if ($payment == 8) {
                return 'USD ' . number_format($price / $convertion, 2);
            } else {
                return 'Rp ' . number_format($price, 0, ",", ".");
            }
        }
        $addressBySubdistrict = $this->Settings_model->getSubdistrictByIdAndCity($subdistrict, $district);
        if ($this->Settings_model->getSetting()['shipping_feature'] == 1) {
            if ($payment == 8) {
                $totalall = intval($this->cart->total()) + intval($ongkir) - intval($potongan);
            } else {
                $totalall = intval($this->cart->total()) + intval($ongkir) + intval($random) - intval($potongan);
            }
            if ($name != "" && $wa != "" && $address != "" && $district != "" && $subdistrict != "" && $courier != "" && $ongkir != "") {
                $dataIns = [
                    'invoice_code' => $invoice,
                    'name' => $name,
                    'telp' => $wa,
                    'regency' => $district,
                    'district' => $subdistrict,

                    'address' => $address,
                    'courier' => $service2,
                    'courier_service' => $kurir,
                    'ongkir' => $ongkir,
                    'total_price' => $this->cart->total(),
                    'uniq_number' => $random,
                    'total_all' => $totalall,
                    'potongan' => $potongan,
                    'date_input' => date('Y-m-d H:i:s'),
                    'dated' => date('Y-m-d'),
                    'payment' => $payment
                ];
                $this->db->insert('invoice', $dataIns);
                foreach ($this->cart->contents() as $c) {
                    $data = [
                        'id_invoice' => $invoice,
                        'product_name' => $c['name'],
                        'price' => $c['price'],
                        'qty' => $c['qty'],
                        'slug' => $c['slug'],
                        'size' => $c['option']['Variant'],
                        'color' => $c['option']['Color']
                    ];
                    $this->db->insert('transaction', $data);
                }
                $list = '';
                $nom = 1;
                foreach ($this->cart->contents() as $c) {
                    $list .= '*' . $nom . '. ' . $c['name'] . '*%0A';
                    $list .= 'Jumlah: ' . $c['qty'] . '%0A';
                    if ($c['option']['Color'] != "" || $c['option']['Variant'] != "") {
                        $list .= 'Varian: ' . $c['option']['Color'] . ' ' . $c['option']['Variant'] . '%0A';
                    }
                    $list .= 'Harga Satuan: ' . whichOnePrice($payment, $c['price']) . '%0A';
                    $list .= 'Harga Total: ' . whichOnePrice($payment, $c['subtotal']) . '%0A%0A';
                    $nom++;
                }
                $list .= 'Subtotal: *' . whichOnePrice($payment, $this->cart->total()) . '*%0A';
                $list .= 'Ongkir: *' . whichOnePrice($payment, $ongkir) . '*%0A';
                if ($payment == 8) {
                    $list .= 'Kode Unik: *USD 0.00*%0A';
                } else {
                    if ($payment != "13") {
                        $list .= 'Kode Unik: *Rp ' . $random . '*%0A';
                    } else {
                        $list .= 'Biaya COD ' . $this->Settings_model->general()['fee_cod'] . '%: *Rp ' . number_format($random, 0, ",", ".") . '*%0A';
                    }
                }
                if ($potongan != "0") {
                    $list .= 'Potongan: *' . whichOnePrice($payment, $potongan) . '*%0A';
                }
                $list .= 'Total: *' . whichOnePrice($payment, $totalall) . '*%0A';
                $list .= '-----------------------%0A';
                $list .= '*Nama:*%0A';
                $list .= $name . ' (' . $wa . ')%0A%0A';
                $list .= '*Alamat:*%0A';
                $list .= $address . ' Kec. ' . $addressBySubdistrict['subdistrict_name'] . ' ' . $addressBySubdistrict['type'] . ' ' . $addressBySubdistrict['city']  . '%0A%0A';
                if ($this->input->post('payment') != "0") {
                    $rekening = $this->db->get_where('rekening', ['rekening' => $this->input->post('payment')])->row_array();
                    $bank = $this->db->get_where('bank', ['id' => $rekening['rekening']])->row_array();
                    if ($payment != "13") {
                        $list .= '*Pembayaran:*%0A';
                        $list .= $bank['name'] . '%0A';
                        $list .= $rekening['number'] . ' an ' . $rekening['name'];
                    }
                }
                if ($payment == "13") {
                    $list .= '*Pembayaran:*%0A';
                    $list .= 'Cash On Delivery (COD)';
                }
                $this->cart->destroy();
                $waadmin = $this->Settings_model->getSetting()['wa_admin'];
                redirect("https://wa.me/$waadmin?text=Hi kak, saya mau order. %0A%0A" . $list);
            } else {
                redirect(base_url() . 'checkout');
            }
        } else {
            if ($payment == 8) {
                $totalall = intval($this->cart->total()) - intval($potongan);
            } else {
                $totalall = intval($this->cart->total()) + intval($random) - intval($potongan);
            }
            if ($name != "" && $wa != "" && $address != "") {
                $location = $this->input->post('location');
                $idflatongkir = explode("**", $location)[0];
                $flat_ongkir = $this->db->get_where('flat_ongkir', ['id' => $idflatongkir])->row_array();
                $dataIns = [
                    'invoice_code' => $invoice,
                    'name' => $name,
                    'telp' => $wa,
                    'address' => $address,
                    'location' => $flat_ongkir ? $flat_ongkir['location'] : "",
                    'total_price' => $this->cart->total(),
                    'ongkir' => $flat_ongkir ? $flat_ongkir['fee'] : 0,
                    'uniq_number' => $random,
                    'total_all' => $flat_ongkir ? $totalall + $flat_ongkir['fee'] : $totalall,
                    'potongan' => $potongan,
                    'date_input' => date('Y-m-d H:i:s'),
                    'dated' => date('Y-m-d'),
                    'payment' => $payment
                ];
                $this->db->insert('invoice', $dataIns);
                foreach ($this->cart->contents() as $c) {
                    $data = [
                        'id_invoice' => $invoice,
                        'product_name' => $c['name'],
                        'price' => $c['price'],
                        'qty' => $c['qty'],
                        'slug' => $c['slug'],
                        'size' => $c['option']['Variant'],
                        'color' => $c['option']['Color']
                    ];
                    $this->db->insert('transaction', $data);
                }
                $list = '';
                $nom = 1;
                foreach ($this->cart->contents() as $c) {
                    $list .= '*' . $nom . '. ' . $c['name'] . '*%0A';
                    $list .= 'Jumlah: ' . $c['qty'] . '%0A';
                    if ($c['option']['Color'] != "" || $c['option']['Variant'] != "") {
                        $list .= 'Varian: ' . $c['option']['Color'] . ' ' . $c['option']['Variant'] . '%0A';
                    }
                    $list .= 'Harga Satuan: ' . whichOnePrice($payment, $c['price']) . '%0A';
                    $list .= 'Harga Total: ' . whichOnePrice($payment, $c['subtotal']) . '%0A%0A';
                    $nom++;
                }
                $list .= 'Subtotal: *' . whichOnePrice($payment, $this->cart->total()) . '*%0A';
                if ($flat_ongkir) {
                    $list .= 'Ongkir: *' . number_format($flat_ongkir['fee'], 0, ",", ".") . '*%0A';
                }
                if ($payment == 8) {
                    $list .= 'Kode Unik: *USD 0.00*%0A';
                } else {
                    if ($payment != "13") {
                        $list .= 'Kode Unik: *Rp ' . $random . '*%0A';
                    } else {
                        $list .= 'Biaya COD ' . $this->Settings_model->general()['fee_cod'] . '%: *Rp ' . number_format($random, 0, ",", ".") . '*%0A';
                    }
                }
                if ($potongan != "0") {
                    $list .= 'Potongan: *' . whichOnePrice($payment, $potongan) . '*%0A';
                }
                $list .= 'Total: *' . whichOnePrice($payment, $totalall) . '*%0A';
                $list .= '-----------------------%0A';
                $list .= '*Nama:*%0A';
                $list .= $name . ' (' . $wa . ')%0A%0A';
                $list .= '*Alamat:*%0A';
                $list .= $address . '%0A%0A';
                if($flat_ongkir){
                    $list .= '*Lokasi:*%0A';
                    $list .= $flat_ongkir['location'] . '%0A%0A';
                }
                if ($this->input->post('payment') != "0") {
                    $rekening = $this->db->get_where('rekening', ['rekening' => $this->input->post('payment')])->row_array();
                    $bank = $this->db->get_where('bank', ['id' => $rekening['rekening']])->row_array();
                    if ($payment != "13") {
                        $list .= '*Pembayaran:*%0A';
                        $list .= $bank['name'] . '%0A';
                        $list .= $rekening['number'] . ' an ' . $rekening['name'];
                    }
                }
                if ($payment == "13") {
                    $list .= '*Pembayaran:*%0A';
                    $list .= 'Cash On Delivery (COD)';
                }
                $this->cart->destroy();
                $waadmin = $this->Settings_model->getSetting()['wa_admin'];
                redirect("https://wa.me/$waadmin?text=Hi kak, saya mau order. %0A%0A" . $list);
            } else {
                redirect(base_url() . 'checkout');
            }
        }
    }
}
