<?php
# application/middleware/TestMiddleware.php

class Otentikasi_login implements Luthier\MiddlewareInterface{

    public function run($args = []){
        if(ci()->session->userdata('id_karyawan') === null){
            redirect(route('login') . '?ref=' . urlencode(current_url()));
        }else{
          if($this->wizard()) {
            return;
          }
        }

    }

    /*fungsi untuk memanggil wizard*/
    function wizard() {
      if($this->cek_level_admin_atau_admin_finance()) {
        if($this->cek_punya_wizard()) {
          if($this->redirect_wizard()) {
            return true;
          }
        } else {
          return true;
        }
      } else {
        return true;
      }
    }

    /*pengecekan apakah level admin atau finance*/
    function cek_level_admin_atau_admin_finance() {
      $level_user = ci()->session->userdata('level_user');
      if($level_user == 1 or $level_user == 6) {
        return true;
      } else {
        return false;
      }
    }

    /*pengecekan apakah terdapat wizard pada tabel db*/
    function cek_punya_wizard() {
      $id_company = ci()->session->userdata('id_company');
      $wizard = ci()->db->where('id_company', $id_company)->get('wizard');
      if($wizard) {
        return true;
      } else {
        return false;
      }
    }

    /*redirect yang dijalankan sesuai kondisi wizard sudah sampai mana pada tabel wizard db*/
    function redirect_wizard() {
      $id_company = ci()->session->userdata('id_company');
      $wizard = ci()->db->where('id_company', $id_company)->get('wizard')->row();
      if($wizard->data_lokasi == '0') {
        redirect('wizard/lokasi');
      } elseif($wizard->data_lokasi == '1') {
        if($wizard->akun_kedep == '0') {
          redirect(route('wizard.akun.kepala_departemen.home'));
        } elseif($wizard->akun_kedep == '1') {
          if($wizard->akun_staff == '0') {
            redirect(route('wizard.akun.staff.home'));
          } elseif($wizard->akun_staff == '1') {
            if($wizard->tambah_akun == '0') {
              redirect(route('wizard.akun.tambah'));
            } elseif($wizard->tambah_akun == '1') {
              if($wizard->selesai == '0') {
                redirect(route('wizard.berhasil'));
              } elseif($wizard->selesai == '1') {
                return true;
              }
            }
          }
        }
      }
    }
}
