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

class Settings_model extends CI_Model
{

  public function getSetting()
  {
    return $this->db->get('settings')->row_array();
  }

  public function general()
  {
    return $this->db->get('general')->row_array();
  }

  public function getRekening()
  {
    return $this->db->get('rekening');
  }

  public function getRekeningById($id)
  {
    return $this->db->get_where('rekening', ['id' => $id])->row_array();
  }

  public function getLeadInvoice($filter)
  {
    if ($filter == "all") {
      return $this->db->query('SELECT * FROM invoice');
    } else if ($filter == "yesterday") {
      $day = date('Y-m-d', time() - (60 * 60 * 24));
      $this->db->where('dated', $day);
      return $this->db->get("invoice");
    } else if ($filter == "last-week") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 7));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      return $this->db->get("invoice");
    } else if ($filter == "last-month") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 30));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      return $this->db->get("invoice");
    } else if ($filter == "month") {
      return $this->db->query('SELECT * FROM invoice WHERE MONTH(date_input) = ' . date('m') . '');
    } else {
      return $this->db->query('SELECT * FROM invoice WHERE YEAR(date_input) = ' . date('Y') . ' AND MONTH(date_input) = ' . date('m') . ' AND DAY(date_input) = ' . date('d') . '');
    }
  }

  public function getOrderInvoice($filter)
  {
    if ($filter == "all") {
      return $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3)');
    } else if ($filter == "yesterday") {
      $day = date('Y-m-d', time() - (60 * 60 * 24));
      $this->db->where('dated', $day);
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      return $this->db->get("invoice");
    } else if ($filter == "last-week") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 7));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      return $this->db->get("invoice");
    } else if ($filter == "last-month") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 30));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      return $this->db->get("invoice");
    } else if ($filter == "month") {
      return $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3) AND MONTH(date_input) = ' . date('m') . '');
    } else {
      return $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3) AND YEAR(date_input) = ' . date('Y') . ' AND MONTH(date_input) = ' . date('m') . ' AND DAY(date_input) = ' . date('d') . '');
    }
  }

  public function getOmsetInvoice($filter)
  {
    if ($filter == "all") {
      $db = $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3)');
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    } else if ($filter == "yesterday") {
      $day = date('Y-m-d', time() - (60 * 60 * 24));
      $this->db->where('dated', $day);
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      $db = $this->db->get("invoice");
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    } else if ($filter == "last-week") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 7));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      $db = $this->db->get("invoice");
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    } else if ($filter == "last-month") {
      $day = date('Y-m-d', time() - (60 * 60 * 24 * 30));
      $this->db->where('dated >=', $day);
      $this->db->where('dated <=', date('Y-m-d'));
      $this->db->where('status', 1);
      $this->db->or_where('status', 2);
      $this->db->or_where('status', 3);
      $db = $this->db->get("invoice");
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    } else if ($filter == "month") {
      $db = $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3) AND MONTH(date_input) = ' . date('m') . '');
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    } else {
      $db = $this->db->query('SELECT * FROM invoice WHERE (status = 1 OR status = 2 OR status = 3) AND YEAR(date_input) = ' . date('Y') . ' AND MONTH(date_input) = ' . date('m') . ' AND DAY(date_input) = ' . date('d') . '');
      $omset = 0;
      foreach ($db->result_array() as $d) {
        $omset += $d['total_all'];
      }
      return $omset;
    }
  }

  public function getInvoiceonoffday()
  {
    $date = date('d') + 1;
    $data = array();
    for ($x = 1; $x < $date; $x++) {
      $query['statuson' . $x] = $this->db->query('select count(id) as id from invoice where (status = 1 OR status = 2 OR status = 3) and MONTH(date_input) = ' . date('m') . ' and DAY(date_input) = ' . $x . ' order by DAY(date_input) asc')->result();

      $query['statusoff' . $x] = $this->db->query('select count(id) as id from invoice where MONTH(date_input) = ' . date('m') . ' and DAY(date_input) = ' . $x . ' order by DAY(date_input) asc')->result();
      array_push($data, $query);
    }
    return $data[date('d') - 1];
  }

  public function getPages()
  {
    return $this->db->get('pages');
  }

  public function getSosmed()
  {
    return $this->db->get('sosmed');
  }

  public function getSosmedById($id)
  {
    return $this->db->get_where('sosmed', ['id' => $id])->row_array();
  }

  public function getFooterInfo()
  {
    $this->db->select("distinct(page), pages.title AS title, pages.slug AS slug");
    $this->db->from("footer");
    $this->db->join("pages", "footer.page=pages.id");
    $this->db->where('footer.type', 1);
    return $this->db->get();
  }

  public function getFooterHelp()
  {
    $this->db->join("pages", "footer.page=pages.id");
    return $this->db->get('footer');
  }

  public function getPageById($id)
  {
    return $this->db->get_where('pages', ['id' => $id])->row_array();
  }

  public function getBanner()
  {
    return $this->db->get('banner');
  }

  public function getRegency()
  {
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://pro.rajaongkir.com/api/city",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => FALSE,
      CURLOPT_SSL_VERIFYPEER => FALSE,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "key: " . $this->Settings_model->general()["api_rajaongkir"]
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response =  json_decode($response, true);
      return $response['rajaongkir']['results'];
    }
  }

  public function getSubdistrictByCity($id)
  {
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://pro.rajaongkir.com/api/subdistrict?city=$id",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => FALSE,
      CURLOPT_SSL_VERIFYPEER => FALSE,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "key: " . $this->Settings_model->general()["api_rajaongkir"]
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response =  json_decode($response, true);
      return $response['rajaongkir']['results'];
    }
  }

  public function getSubdistrictById()
  {
    $getDB = $this->db->get('settings')->row_array();
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://pro.rajaongkir.com/api/subdistrict?id=" . $getDB['regency_id'],
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => FALSE,
      CURLOPT_SSL_VERIFYPEER => FALSE,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "key: " . $this->Settings_model->general()["api_rajaongkir"]
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response =  json_decode($response, true);
      return $response['rajaongkir']['results'];
    }
  }

  public function getRegencyById()
  {
    $getDB = $this->db->get('settings')->row_array();
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.rajaongkir.com/starter/city?id=" . $getDB['regency_id'],
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => FALSE,
      CURLOPT_SSL_VERIFYPEER => FALSE,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "key: " . $this->Settings_model->general()["api_rajaongkir"]
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response =  json_decode($response, true);
      return $response['rajaongkir']['results'];
    }
  }

  public function getSubdistrictByIdAndCity($subdistrict, $city)
  {
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://pro.rajaongkir.com/api/subdistrict?city=$city&id=$subdistrict",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_SSL_VERIFYHOST => FALSE,
      CURLOPT_SSL_VERIFYPEER => FALSE,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "key: " . $this->Settings_model->general()["api_rajaongkir"]
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response =  json_decode($response, true);
      return $response['rajaongkir']['results'];
    }
  }

  public function updateShipping()
  {
    $data = [
      'regency_id' => $this->input->post('subdistrict'),
    ];
    $this->db->update('settings', $data);
    $data = [
      'api_rajaongkir' => $this->input->post('api_rajaongkir'),
    ];
    $this->db->update('general', $data);
    $data = [
      'pos' => $this->input->post('pos') == 'on' ? 1 : 0,
      'jne' => $this->input->post('jne') == 'on' ? 1 : 0,
      'lion' => $this->input->post('lion') == 'on' ? 1 : 0,
      'ninja' => $this->input->post('ninja') == 'on' ? 1 : 0,
      'ide' => $this->input->post('ide') == 'on' ? 1 : 0,
      'sicepat' => $this->input->post('sicepat') == 'on' ? 1 : 0,
      'sap' => $this->input->post('sap') == 'on' ? 1 : 0,
      'ncs' => $this->input->post('ncs') == 'on' ? 1 : 0,
      'anteraja' => $this->input->post('anteraja') == 'on' ? 1 : 0,
      'rex' => $this->input->post('rex') == 'on' ? 1 : 0,
      'sc' => $this->input->post('sc') == 'on' ? 1 : 0,
      'tiki' => $this->input->post('tiki') == 'on' ? 1 : 0,
      'rpx' => $this->input->post('rpx') == 'on' ? 1 : 0,
      'pandu' => $this->input->post('pandu') == 'on' ? 1 : 0,
      'wahana' => $this->input->post('wahana') == 'on' ? 1 : 0,
      'jnt' => $this->input->post('jnt') == 'on' ? 1 : 0,
      'pahala' => $this->input->post('pahala') == 'on' ? 1 : 0,
      'jet' => $this->input->post('jet') == 'on' ? 1 : 0,
      'slis' => $this->input->post('slis') == 'on' ? 1 : 0,
      'expedito' => $this->input->post('expedito') == 'on' ? 1 : 0,
      'dse' => $this->input->post('dse') == 'on' ? 1 : 0,
      'first' => $this->input->post('first') == 'on' ? 1 : 0,
      'star' => $this->input->post('star') == 'on' ? 1 : 0,
      'idl' => $this->input->post('idl') == 'on' ? 1 : 0,
    ];
    $this->db->update('courier', $data);
  }

  public function insertPage()
  {
    $title = $this->input->post('title');
    $content = $this->input->post('description');
    $slug = $this->input->post('slug');
    $data = [
      'title' => $title,
      'content' => $content,
      'slug' => $slug
    ];
    $this->db->insert('pages', $data);
  }

  public function updatePage($id)
  {
    $title = $this->input->post('title');
    $content = $this->input->post('description');
    $slug = $this->input->post('slug');
    $data = [
      'title' => $title,
      'content' => $content,
      'slug' => $slug
    ];
    $this->db->where('id', $id);
    $this->db->update('pages', $data);
  }

  public function getPageBySlug($slug)
  {
    return $this->db->get_where('pages', ['slug' => $slug])->row_array();
  }

  public function insertCoupon()
  {
    $name = $this->input->post('name');
    $code = $this->input->post('code');
    $dated = $this->input->post('dated');
    $min = $this->input->post('min');
    $type = $this->input->post('type');
    $discount = $this->input->post('discount');
    $data = [
      'name' => $name,
      'code' => $code,
      'dated' => $dated,
      'min' => $min,
      'type' => $type,
      'discount' => $discount
    ];
    $this->db->insert('coupon', $data);
  }

  public function editCoupon($id)
  {
    $name = $this->input->post('name');
    $code = $this->input->post('code');
    $dated = $this->input->post('dated');
    $min = $this->input->post('min');
    $type = $this->input->post('type');
    $discount = $this->input->post('discount');
    $data = [
      'name' => $name,
      'code' => $code,
      'dated' => $dated,
      'min' => $min,
      'type' => $type,
      'discount' => $discount
    ];
    $this->db->where('id', $id);
    $this->db->update('coupon', $data);
  }

  public function uploadlogo()
  {
    $config['upload_path'] = './assets/images/logo/';
    $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('logo')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function uploadlogodark()
  {
    $config['upload_path'] = './assets/images/logo/';
    $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('logo-dark')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function uploadFavicon()
  {
    $config['upload_path'] = './assets/images/logo/';
    $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('favicon')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function updateLogo($upload)
  {
    $db = $this->db->get('settings')->row_array();
    $logo = $db['logo'];
    unlink("./assets/images/logo/$logo");
    $img = $upload['file']['file_name'];
    $this->db->set('logo', $img);
    $this->db->update('settings');
  }

  public function updateGeneral($logo, $logodark, $favicon)
  {
    $app_name = $this->input->post('name');
    $contact = $this->input->post('contact');
    $navbar_color = $this->input->post('color');
    $btncolor = $this->input->post('btncolor');
    $db = $this->db->get('general')->row_array();

    if ($logo != "") {
      $getLogo = $db['logo'];
      unlink("./assets/images/logo/$getLogo");
      $newLogo = $logo;
    } else {
      $newLogo = $db['logo'];
    }
    if ($logodark != "") {
      $getLogoDark = $db['logo-dark'];
      unlink("./assets/images/logo/$getLogoDark");
      $newLogoDark = $logodark;
    } else {
      $newLogoDark = $db['logo-dark'];
    }
    if ($favicon != "") {
      $getFavicon = $db['favicon'];
      unlink("./assets/images/logo/$getFavicon");
      $newFavicon = $favicon;
    } else {
      $newFavicon = $db['favicon'];
    }

    $data = [
      'app_name' => $app_name,
      'navbar_color' => $navbar_color,
      'btncolor' => $btncolor,
      'contact' => $contact,
      'logo' => $newLogo,
      'logo-dark' => $newLogoDark,
      'favicon' => $newFavicon,
    ];
    $this->db->update('general', $data);
  }

  public function uploadBannerPackage()
  {
    $config['upload_path'] = './assets/images/banner/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('img')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function uploadBannerNews()
  {
    $config['upload_path'] = './assets/images/banner/';
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('img')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function uploadImg()
  {
    $config['upload_path'] = './assets/images/banner/';
    $config['allowed_types'] = 'jpg|png|jpeg|image/png|image/jpg|image/jpeg';
    $config['max_size'] = '2048';
    $config['file_name'] = round(microtime(true) * 1000);

    $this->load->library('upload', $config);
    if ($this->upload->do_upload('img')) {
      $return = array('result' => 'success', 'file' => $this->upload->data(), 'error' => '');
      return $return;
    } else {
      $return = array('result' => 'failed', 'file' => '', 'error' => $this->upload->display_errors());
      return $return;
    }
  }

  public function insertBanner($upload)
  {
    $img = $upload['file']['file_name'];
    $url = $this->input->post('url', true);
    $info = getimagesize(base_url() . 'assets/images/banner/' . $img);
    if ($info[0] != 1000 || $info[1] != 350) {
      unlink("./assets/images/banner/$img");
      return false;
    } else {
      if ($url == "") {
        $FixUrl = "#";
      } else {
        $FixUrl = $url;
      }
      $data = [
        'img' => $img,
        'url' => $FixUrl
      ];
      $this->db->insert('banner', $data);
      return true;
    }
  }

  public function insertBannerPopup($upload)
  {
    $img = $upload['file']['file_name'];
    $delay = $this->input->post('delay', true);
    $url = $this->input->post('url', true);
    $data = [
      'img' => $img,
      'delay' => $delay,
      'url' => $url
    ];
    $this->db->insert('banner_popup', $data);
  }

  public function editDescription()
  {
    $desc = $this->input->post('desc', true);
    $this->db->set('short_desc', $desc);
    $this->db->update('settings');
  }

  public function addRekening()
  {
    $bank = $this->input->post('rekening', true);
    $name = $this->input->post('name', true);
    $number = $this->input->post('number', true);
    $data = [
      'rekening' => $bank,
      'name' => $name,
      'number' => $number
    ];
    $this->db->insert('rekening', $data);
  }

  public function editRekening($id)
  {
    $bank = $this->input->post('rekening', true);
    $name = $this->input->post('name', true);
    $number = $this->input->post('number', true);
    $data = [
      'rekening' => $bank,
      'name' => $name,
      'number' => $number
    ];
    $this->db->where('id', $id);
    $this->db->update('rekening', $data);
  }

  public function addSosmed()
  {
    $name = $this->input->post('name', true);
    $icon = $this->input->post('icon', true);
    $link = $this->input->post('link', true);
    $data = [
      'name' => $name,
      'icon' => $icon,
      'link' => $link
    ];
    $this->db->insert('sosmed', $data);
  }

  public function editSosmed($id)
  {
    $name = $this->input->post('name', true);
    $icon = $this->input->post('icon', true);
    $link = $this->input->post('link', true);
    $data = [
      'name' => $name,
      'icon' => $icon,
      'link' => $link
    ];
    $this->db->where('id', $id);
    $this->db->update('sosmed', $data);
  }

  public function editAddress()
  {
    $address = $this->input->post('address', true);
    $regency = $this->input->post('settingSelectRegency', true);
    $data = [
      'address' => $address,
      'regency_id' => $regency
    ];
    $this->db->update('settings', $data);
  }

  public function addFooter()
  {
    $page = $this->input->post('page');
    $data = [
      'page' => intval($page)
    ];
    $this->db->insert('footer', $data);
  }

  public function addMenu()
  {
    $page = $this->input->post('page');
    $data = [
      'page' => intval($page)
    ];
    $this->db->insert('menu', $data);
  }
}
