<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');

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

use chriskacerguis\RestServer\RestController;

class Api extends RestController
{
  function __construct()
  {
    parent::__construct();
    $this->load->model('model');
    // $this->db->query("SET sql_mode = '' ");
    date_default_timezone_set("Asia/Kuala_Lumpur");
  }

  public function index_get()
  {
    if ($this->session->userdata('level') == 'Admin' && $this->session->userdata('level') == 'Kepala Dinas') {
      $this->response(['message' => 'Halo Bosku'], 200);
    } else {
      $this->response(['message' => 'Halo gagal'], 400);
    }

    // redirect(base_url());

  }

  // -----------------------------------------------------------------------------------------------------------





  public function login_admin_get() // login admin
  {
    $username = $this->get('username');
    $password = $this->get('password');

    $cek_data = $this->model->tampil_data_where('tb_login_admin', ['username' => $username, 'password' => md5($password)])->result();

    if (count($cek_data) > 0) {
      $cek_data_admin = $this->model->tampil_data_where('tb_admin', ['nik' => $cek_data[0]->nik])->result()[0];
      $cek_data_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $cek_data_admin->id_dinas])->result()[0];
      $this->session->set_userdata(['nik' => $cek_data_admin->nik, "level" => $cek_data_admin->level, 'id_dinas' => $cek_data_dinas->id_dinas]);
      $level = $cek_data_admin->level == 'Admin' ? 1 : 2;
      $this->response(['message' => "Sukses Login", "status" => true, "level" => $level], 200);
    } else {
      $this->session->unset_userdata(array('nik', "level"));
      $this->response(['message' => "Gagal Login, Username dan Password salah", "status" => false], 400);
    }

    // $this->response(['res' => $username,'url' => $password], 200);

  }

  public function pengaturan_lokasi_put() // pengaturan titik kordinat dinas
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $lat = $this->put('lat');
    $lng = $this->put('lng');
    $id = $this->put('id');

    if ($lat == null || $lat == '' || $lng == null || $lng == '' || $id == null || $id == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }


    $cek_data = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id])->result();

    if (count($cek_data) > 0) {
      $this->model->update('tb_dinas', ['id_dinas' => $id], ['lat' => $lat, 'lng' => $lng]);
      $this->session->set_flashdata('info', 'Titik Kordinat Berhasil Diubah');
      $this->response(['message' => 'Sukses Tukar Kordinat ' . $cek_data[0]->dinas], 200);
    } else {
      $this->response(['message' => 'Data Tiada', 'stat' => false], 403);
    }

    // $this->response(['res' => 'ok','url' => $id], 200);

  }

  public function pengaturan_radius_put() // pengaturan titik kordinat dinas
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $radius = $this->put('radius');
    $id = $this->put('id');

    if ($radius == null || $radius == '' || $id == null || $id == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }


    $cek_data = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id])->result();

    if (count($cek_data) > 0) {
      $this->model->update('tb_dinas', ['id_dinas' => $id], ['radius' => $radius]);
      $this->session->set_flashdata('info', 'Radius Berhasil Diubah');
      $this->response(['message' => 'Sukses Ubah Radius ' . $cek_data[0]->dinas], 200);
    } else {
      $this->response(['message' => 'Data Tiada', 'stat' => false], 403);
    }

    // $this->response(['res' => 'ok','url' => $id], 200);

  }

  public function karyawan_post() // penambahan_karyawan
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->post('id_dinas');
    // $foto = $_FILES['foto'];
    $foto = $this->post('foto') == 'tiada' ? null : $_FILES['foto'];
    $nik = $this->post('nik');
    $nama = $this->post('nama');
    $no_telpon = $this->post('no_telpon');
    $jabatan = $this->post('jabatan');
    $alamat = $this->post('alamat');
    $status_form = $this->post('status_form');
    $status = $this->post('status');
    $pangkat = $this->post('pangkat');
    $status = $this->post('status');
    $tanggal_lahir = $this->post('tanggal_lahir');
    $tempat_lahir = $this->post('tempat_lahir');
    $jenis_kelamin = $this->post('jenis_kelamin');
    $keanggotaan = $this->post('keanggotaan');


    // $this->response(['message' => 'Data Karyawan Berhasil Diubah'], 200);

    if ($id_dinas == null || $id_dinas == '' || $nik == null || $nik == '' || $nama == null || $nama == '' || $no_telpon == null || $no_telpon == '' || $jabatan == null || $jabatan == '' || $alamat == null || $alamat == '' || $status_form == null || $status_form == '' || $pangkat == null || $pangkat == '' || $tanggal_lahir == null || $tanggal_lahir == '' || $tempat_lahir == null || $tempat_lahir == '' || $jenis_kelamin == null || $jenis_kelamin == '' || $keanggotaan == null || $keanggotaan == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }


    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    if ($status_form == 'tambah') {
      $cek_data = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik])->result();

      if (count($cek_data) > 0) {
        $this->response(['message' => 'Pegawai Dengan NIK ' . $nik . " telah terdaftar di sistem", 'stat' => false], 403);
      } else {
        $dir = "assets/images/foto_karyawan/$nik/";

        if (is_dir($dir) === false) {
          mkdir($dir);
        }

        $path = $dir . $foto['name'];
        move_uploaded_file($foto['tmp_name'], $path);
        $image_path = $path;

        $this->model->insert("tb_karyawan", ['nik' => $nik, 'nama' => $nama, 'no_telpon' => $no_telpon, 'jabatan' => $jabatan, 'alamat' => $alamat, "id_dinas" => $id_dinas, "image" => $image_path, "status" => $status, "pangkat" => $pangkat, "tanggal_lahir" => $tanggal_lahir, "tempat_lahir" => $tempat_lahir, "jenis_kelamin" => $jenis_kelamin, "keanggotaan" => $keanggotaan]);
        $this->model->insert("tb_login_user", ["username" => $nik, "password" => md5("12345678"), "nik" => $nik]);
        $this->response(['message' => 'Karyawan Dengan NIK ' . $nik . " berhasil didaftar di sistem\nUsername : " . $nik . "\nPassword : 12345678"], 201);
      }
    }

    if ($status_form == 'edit') {
      $cek_data = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik, "id_dinas" => $id_dinas])->result();


      if (count($cek_data) == 0) return $this->response(['message' => 'Pegawai Tidak Ditemukan', 'stat' => false], 401);

      if ($foto == null) {
        $this->model->update("tb_karyawan", ['nik' => $nik, "id_dinas" => $id_dinas], ["nama" => $nama, "no_telpon" => $no_telpon, "jabatan" => $jabatan, "alamat" => $alamat, "status" => $status, "pangkat" => $pangkat, "tanggal_lahir" => $tanggal_lahir, "tempat_lahir" => $tempat_lahir, "jenis_kelamin" => $jenis_kelamin, "keanggotaan" => $keanggotaan]);
      } else {
        $dir = "assets/images/foto_karyawan/$nik/";
        if (is_dir($dir) === false) {
          mkdir($dir);
        }

        $files = glob($dir . '*'); // get all file names
        foreach ($files as $file) { // iterate files
          if (is_file($file)) {
            unlink($file); // delete file
          }
        }


        $path = $dir . $foto['name'];
        move_uploaded_file($foto['tmp_name'], $path);
        $image_path = $path;

        $this->model->update("tb_karyawan", ['nik' => $nik, "id_dinas" => $id_dinas], ["nama" => $nama, "no_telpon" => $no_telpon, "jabatan" => $jabatan, "alamat" => $alamat,  "image" => $image_path, "status" => $status, "pangkat" => $pangkat, "tanggal_lahir" => $tanggal_lahir, "tempat_lahir" => $tempat_lahir, "jenis_kelamin" => $jenis_kelamin, "keanggotaan" => $keanggotaan]);
      }



      $this->response(['message' => 'Data Pegawai Berhasil Diubah'], 200);
    }



    // $this->response(['res' => 'ok', 'url' => $status], 200);
  }

  public function karyawanAll_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $check_data = $this->model->tampil_data_keseluruhan('tb_karyawan')->result();
    $this->response(['data' => $check_data], 200);
  }

  public function karyawan_get() // ambil data karyawan
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->get('id_dinas');
    $nik = $this->get('nik');


    if ($id_dinas == null || $id_dinas == '' || $nik == null || $nik == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    $cek_data = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik])->result();

    if (count($cek_data) == 0) return $this->response(['message' => 'Pegawai Tidak Ditemukan', 'stat' => false], 401);


    $this->response(['data' => $cek_data[0]], 200);
    // $this->response(['message' => 'Karyawan Tidak Ditemukan', 'stat' => false], 401);

  }

  public function karyawan_put() // edit data karyawan
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->put('id_dinas');
    $foto = $_FILES['foto'];
    $nik = $this->put('nik');
    $nama = $this->put('nama');
    $no_telpon = $this->put('no_telpon');
    $jabatan = $this->put('jabatan');
    $alamat = $this->put('alamat');

    // if ($id_dinas == null || $id_dinas == '' || $nik == null || $nik == '' || $nama == null || $nama == '' || $no_telpon == null || $no_telpon == '' || $jabatan == null || $jabatan == '' || $alamat == null || $alamat == '') {
    //   $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    // }

    // $cek_dinas = $this->model->tampil_data_where('tb_dinas',['id_dinas' => $id_dinas])->result();

    // if(count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    // $cek_data = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik, "id_dinas" => $id_dinas])->result();

    // if (count($cek_data) == 0) return $this->response(['message' => 'Karyawan Tidak Ditemukan', 'stat' => false], 401);

    // $this->model->update("tb_karyawan",['nik' => $nik, "id_dinas" => $id_dinas], ["nama" => $nama , "no_telpon" => $no_telpon , "jabatan" => $jabatan, "alamat" => $alamat]);

    // $this->response(['message' => '"Data Karyawan Berhasil Diubah'], 200);
    $this->response(['message' => $foto], 200);
  }

  public function karyawan_delete() // edit data karyawan
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->delete('id_dinas');
    $nik = $this->delete('nik');


    if ($id_dinas == null || $id_dinas == '' || $nik == null || $nik == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();



    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    $cek_data = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik, "id_dinas" => $id_dinas])->result();

    if (count($cek_data) == 0) return $this->response(['message' => 'Pegawai Tidak Ditemukan', 'stat' => false], 401);

    $dir = "assets/images/foto_karyawan/" . $nik;
    // delete all in $dir 
    array_map('unlink', glob("$dir/*.*"));
    // delete $dir
    rmdir($dir);


    $this->model->delete("tb_karyawan", ['nik' => $nik, "id_dinas" => $id_dinas]);


    $this->response(['message' => "Data Pegawai Berhasil Dihapus"], 200);
  }

  public function jam_kerja_post() // edit data karyawan
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->post('id_dinas');
    $hari = $this->post('hari');
    $jam_masuk = $this->post('jam_masuk');
    $jam_istirehat = $this->post('jam_istirehat');
    $jam_masuk_kembali = $this->post('jam_masuk_kembali');
    $jam_pulang = $this->post('jam_pulang');


    if ($id_dinas == null || $id_dinas == '' || $hari == null || $hari == '' || $jam_masuk == null || $jam_masuk == '' || $jam_istirehat == null || $jam_istirehat == '' || $jam_masuk_kembali == null || $jam_masuk_kembali == '' || $jam_pulang == null || $jam_pulang == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    $cek_data = $this->model->tampil_data_where('tb_pengaturan_jam_kerja_harian', ['hari' => $hari, "id_dinas" => $id_dinas])->result();

    if (count($cek_data) == 0) {
      $this->model->insert("tb_pengaturan_jam_kerja_harian", ['hari' => $hari, "id_dinas" => $id_dinas, "jam_masuk" => $jam_masuk,  "jam_istirehat" => $jam_istirehat, "jam_masuk_kembali" => $jam_masuk_kembali, "jam_pulang" => $jam_pulang]);
    } else {
      $this->model->update("tb_pengaturan_jam_kerja_harian", ['hari' => $hari, "id_dinas" => $id_dinas], ["jam_masuk" => $jam_masuk,  "jam_istirehat" => $jam_istirehat, "jam_masuk_kembali" => $jam_masuk_kembali, "jam_pulang" => $jam_pulang]);
    }
    // $this->model->delete("tb_karyawan",['nik' => $nik, "id_dinas" => $id_dinas]);
    // $this->session->set_flashdata('info',"Jam Kerja Hari ".ucfirst($hari)." Berhasil Diubah");
    $this->response(['message' => "Jam Kerja Hari " . ucfirst($hari), " Berhasil Diubah"], 200);
  }

  public function jam_kerja_get() // edit data karyawan
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->get('id_dinas');


    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    $cek_data = $this->model->tampil_data_where('tb_pengaturan_jam_kerja_harian', ["id_dinas" => $id_dinas])->result();


    $this->response(['data' => $cek_data], 200);
  }


  public function libur_post()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->post('id_dinas');
    $list_karyawan = $this->post('list_karyawan');
    $start_tanggal = $this->post('start_tanggal');
    $end_tanggal = $this->post('end_tanggal');
    $file = $_FILES['file'];
    $ket = $this->post('ket');

    if ($id_dinas == null || $id_dinas == '' || $list_karyawan == null || $list_karyawan == '' || $start_tanggal == null || $start_tanggal == '' || $end_tanggal == null || $end_tanggal == '' || $ket == null || $ket == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    if ($start_tanggal != $end_tanggal) {
      $period = new DatePeriod(
        new DateTime($start_tanggal),
        new DateInterval('P1D'),
        new DateTime($end_tanggal)
      );
    }

    $cek_last_ai = $this->model->cek_last_ai('tb_libur');
    $dir = "assets/libur/" . $cek_last_ai . "/";

    if (!is_dir($dir)) {
      mkdir($dir);
    }

    $path = $dir . $file['name'];
    move_uploaded_file($file['tmp_name'], $path);
    $file_path = $path;


    $this->model->insert('tb_libur', ['id_dinas' => $id_dinas, 'list_karyawan' => $list_karyawan, 'range_tanggal' => $start_tanggal . " - " . $end_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")", 'created_at' => date("Y-m-d H:i:s"), 'file' => $file_path]);
    $converted_list_karyawan = json_decode($list_karyawan);


    foreach ($converted_list_karyawan as $key1 => $value1) {
      if ($start_tanggal != $end_tanggal) {
        foreach ($period as $key => $value) {
          $this->model->insert('tb_informasi_libur', ['id_libur' => $cek_last_ai, 'nik' => $value1, "tanggal" => $value->format('Y-m-d'), 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
        }
      } else {
        $this->model->insert('tb_informasi_libur', ['id_libur' => $cek_last_ai, 'nik' => $value1, "tanggal" => $start_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
      }

      $this->model->insert('tb_informasi_libur', ['id_libur' => $cek_last_ai, 'nik' => $value1, "tanggal" => $end_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
    }
    $this->response(['message' => "Data Libur Berhasil Dimasukkan"], 200);
  }

  public function libur_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->get('id_dinas');
    $id_libur = $this->get('id_libur');


    if ($id_dinas == null || $id_dinas == '' || $id_libur == null || $id_libur == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $check_data = $this->model->tampil_data_where('tb_libur', ['id_libur' => $id_libur, "id_dinas" => $id_dinas])->result();

    if (count($check_data) == 0) return $this->response(['message' => 'Informasi Libur Tidak Ditemukan', 'stat' => false], 401);

    $data = array();

    $data['range_tanggal'] = $check_data[0]->range_tanggal;
    $data['ket'] = $check_data[0]->ket;
    $data['created_at'] = $check_data[0]->created_at;
    $data['file'] = $check_data[0]->file;

    $data['list_karyawan'] = '';

    $list_karyawan = json_decode($check_data[0]->list_karyawan);

    foreach ($list_karyawan as $key => $value) {
      $check_karyawan = $this->model->tampil_data_where('tb_karyawan', ['nik' => $value])->result();
      $data['list_karyawan']  .= " " . $check_karyawan[0]->nama . ' ,';
    }

    $data['list_karyawan']  = rtrim($data['list_karyawan'], ",");



    $this->response(['data' => $data], 200);
  }

  public function libur_delete()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->delete('id_dinas');
    $id_libur = $this->delete('id_libur');

    if ($id_dinas == null || $id_dinas == '' || $id_libur == null || $id_libur == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);


    $check_data = $this->model->tampil_data_where('tb_libur', ['id_libur' => $id_libur, "id_dinas" => $id_dinas])->result();

    if (count($check_data) == 0) return $this->response(['message' => 'Informasi Libur Tidak Ditemukan', 'stat' => false], 401);

    $dir = "assets/libur/" . $id_libur . "/";
    // remove all files in the directory
    array_map('unlink', glob("$dir/*.*"));
    // remove the directory itself
    rmdir($dir);

    $this->model->delete('tb_libur', ['id_libur' => $id_libur, "id_dinas" => $id_dinas]);

    $this->response(['message' => 'Data Libur Berhasil Dihapus'], 200);
  }

  public function perjalanan_dinas_post()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->post('id_dinas');
    $list_karyawan = $this->post('list_karyawan');
    $start_tanggal = $this->post('start_tanggal');
    $end_tanggal = $this->post('end_tanggal');
    $ket = $this->post('ket');
    $file = $_FILES['file'];

    if ($id_dinas == null || $id_dinas == '' || $list_karyawan == null || $list_karyawan == '' || $start_tanggal == null || $start_tanggal == '' || $end_tanggal == null || $end_tanggal == '' || $ket == null || $ket == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    if ($start_tanggal != $end_tanggal) {
      $period = new DatePeriod(
        new DateTime($start_tanggal),
        new DateInterval('P1D'),
        new DateTime($end_tanggal)
      );
    }


    $cek_last_ai = $this->model->cek_last_ai('tb_perjalanan_dinas');
    $dir = "assets/perjalanan_dinas/" . $cek_last_ai . "/";

    if (!is_dir($dir)) {
      mkdir($dir);
    }

    $path = $dir . $file['name'];
    move_uploaded_file($file['tmp_name'], $path);
    $file_path = $path;

    $this->model->insert('tb_perjalanan_dinas', ['id_dinas' => $id_dinas, 'list_karyawan' => $list_karyawan, 'range_tanggal' => $start_tanggal . " - " . $end_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")", 'created_at' => date("Y-m-d H:i:s"), 'sppd' => $file_path]);
    $converted_list_karyawan = json_decode($list_karyawan);


    foreach ($converted_list_karyawan as $key1 => $value1) {
      if ($start_tanggal != $end_tanggal) {
        foreach ($period as $key => $value) {
          $this->model->insert('tb_informasi_perjalanan_dinas', ['id_perjalanan_dinas' => $cek_last_ai, 'nik' => $value1, "tanggal" => $value->format('Y-m-d'), 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
        }
      } else {
        $this->model->insert('tb_informasi_perjalanan_dinas', ['id_perjalanan_dinas' => $cek_last_ai, 'nik' => $value1, "tanggal" => $start_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
      }

      $this->model->insert('tb_informasi_perjalanan_dinas', ['id_perjalanan_dinas' => $cek_last_ai, 'nik' => $value1, "tanggal" => $end_tanggal, 'ket' => $ket . " (" . $start_tanggal . " - " . $end_tanggal . ")"]);
    }
    $this->response(['message' => "Data Libur Berhasil Dimasukkan"], 200);
  }

  public function perjalanan_dinas_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->get('id_dinas');
    $id_perjalanan_dinas = $this->get('id_perjalanan_dinas');


    if ($id_dinas == null || $id_dinas == '' || $id_perjalanan_dinas == null || $id_perjalanan_dinas == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $check_data = $this->model->tampil_data_where('tb_perjalanan_dinas', ['id_perjalanan_dinas' => $id_perjalanan_dinas, "id_dinas" => $id_dinas])->result();

    if (count($check_data) == 0) return $this->response(['message' => 'Informasi Libur Tidak Ditemukan', 'stat' => false], 401);

    $data = array();

    $data['range_tanggal'] = $check_data[0]->range_tanggal;
    $data['ket'] = $check_data[0]->ket;
    $data['created_at'] = $check_data[0]->created_at;
    $data['sppd'] = $check_data[0]->sppd;

    $data['list_karyawan'] = '';

    $list_karyawan = json_decode($check_data[0]->list_karyawan);

    foreach ($list_karyawan as $key => $value) {
      $check_karyawan = $this->model->tampil_data_where('tb_karyawan', ['nik' => $value])->result();
      $data['list_karyawan']  .= " " . $check_karyawan[0]->nama . ' ,';
    }

    $data['list_karyawan']  = rtrim($data['list_karyawan'], ",");



    $this->response(['data' => $data], 200);
  }

  public function perjalanan_dinas_delete()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);
    $id_dinas = $this->delete('id_dinas');
    $id_perjalanan_dinas = $this->delete('id_perjalanan_dinas');

    if ($id_dinas == null || $id_dinas == '' || $id_perjalanan_dinas == null || $id_perjalanan_dinas == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $check_data = $this->model->tampil_data_where('tb_perjalanan_dinas', ['id_perjalanan_dinas' => $id_perjalanan_dinas, "id_dinas" => $id_dinas])->result();

    if (count($check_data) == 0) return $this->response(['message' => 'Informasi Libur Tidak Ditemukan', 'stat' => false], 401);

    $dir = 'assets/perjalanan_dinas/' . $id_perjalanan_dinas . '/';
    // remove all files in the directory
    array_map('unlink', glob("$dir/*.*"));
    // remove the directory itself
    rmdir($dir);

    $this->model->delete('tb_perjalanan_dinas', ['id_perjalanan_dinas' => $id_perjalanan_dinas, "id_dinas" => $id_dinas]);

    $this->response(['message' => 'Data Perjalanan Dinas Berhasil Dihapus'], 200);
  }

  public function get_today_absensi_get()
  {
    $id_dinas = $this->get('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Isi Semua Form', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $today = date("Y-m-d");

    $check_data = $this->model->tampil_data_where('tb_absensi_karyawan', ['id_dinas' => $id_dinas, 'tanggal' => $today])->result();
    $datanya = array();
    if (count($check_data) > 0) {

      foreach ($check_data as $key => $value) {
        $check_data_karyawan = $this->model->tampil_data_where('tb_karyawan', ['nik' => $value->nik])->result();
        $check_kordinat = $this->model->tampil_data_where('tb_kordinat_karyawan', ['nik' => $value->nik])->result();

        $status = "Sedang Bekerja";

        if ($check_data[$key]->jam_istirehat != null) {
          $status = "Sedang Istirehat";
        }
        if ($check_data[$key]->jam_masuk_kembali != null) {
          $status = "Sedang Bekerja";
        }
        if ($check_data[$key]->jam_pulang != null) {
          $status = "Pulang Kerja";
        }

        $datanya[$key]['nik'] = $value->nik;
        $datanya[$key]['nama'] = $check_data_karyawan[0]->nama;
        $datanya[$key]['lat'] = floatval($check_kordinat[0]->lat);
        $datanya[$key]['lng'] = floatval($check_kordinat[0]->lng);
        $datanya[$key]['last_updated'] = $check_kordinat[0]->updated_at;
        $datanya[$key]['status'] = $status;
      }
    }



    $this->response(['data' =>  $datanya], 200);
  }

  public function surat_masuk_post()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->post('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $asal_surat = $this->post('asal_surat');
    $no_surat = $this->post('no_surat');
    $tanggal_pengiriman = $this->post('tanggal_pengiriman');
    $tanggal_diterima = $this->post('tanggal_diterima');
    $no_agenda = $this->post('no_agenda');
    $sifat = $this->post('sifat') == '' ? null : $this->post('sifat');
    $perihal = $this->post('perihal') == '' ? null : $this->post('perihal');
    $diteruskan_kepada = $this->post('diteruskan_kepada') == '' ? null : $this->post('diteruskan_kepada');
    $respon = $this->post('respon') == '' ? null : $this->post('respon');
    $file_surat = $_FILES['file_surat'];
    $catatan = $this->post('catatan') == '' ? null : $this->post('catatan');

    $data = [
      'id_dinas' => $id_dinas,
      'asal_surat' => $asal_surat,
      'no_surat' => $no_surat,
      'tanggal_pengiriman' => $tanggal_pengiriman,
      'tanggal_diterima' => $tanggal_diterima,
      'no_agenda' => $no_agenda,
      'sifat' => $sifat,
      'perihal' => $perihal,
      'diteruskan_kepada' => $diteruskan_kepada,
      'respon' => $respon,
      'catatan' => $catatan,
      'file_surat' => $file_surat,
    ];

    $cek_data_surat = $this->model->tampil_data_where('tb_surat_masuk', ['id_dinas' => $id_dinas, 'no_surat' => $no_surat])->result();

    if (count($cek_data_surat) > 0) return $this->response(['message' => 'No Surat Sudah Ada Sebelumnya', 'stat' => false], 401);

    $cek_data_surat = $this->model->tampil_data_where('tb_surat_masuk', ['id_dinas' => $id_dinas, 'no_agenda' => $no_agenda])->result();

    if (count($cek_data_surat) > 0) return $this->response(['message' => 'No Agenda Sudah Ada Sebelumnya', 'stat' => false], 401);


    $dir = 'assets/surat_masuk/' . $id_dinas;

    if (!is_dir($dir)) {
      mkdir($dir);
    }

    $cek_last_increment = $this->model->cek_last_ai('tb_surat_masuk');
    $path = $dir . '/' . $cek_last_increment . '/';
    if (!is_dir($path)) {
      mkdir($path);
    }
    $path = $path . $file_surat['name'];
    move_uploaded_file($file_surat['tmp_name'], $path);
    $pdf_path = $path;

    // remove 'file_surat' from $data
    unset($data['file_surat']);
    $data['fail'] = $pdf_path;

    $this->model->insert('tb_surat_masuk', $data);


    $this->response(['data' =>  $data, 'message' => "No Surat " . $no_surat . "  Berhasil Ditambahkan", 'stat' => true], 200);
  }

  public function surat_masuk_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->get('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $id_surat = $this->get('id_surat');

    if ($id_surat == null || $id_surat == '') {
      $this->response(['message' => 'Surat Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_surat = $this->model->tampil_data_where('tb_surat_masuk', ['id_surat_masuk' => $id_surat, 'id_dinas' => $id_dinas])->result();

    if (count($cek_surat) == 0) return $this->response(['message' => 'Surat Tidak Ditemukan', 'stat' => false], 401);

    $this->response(['data' =>  $cek_surat[0], 'message' => "Surat Ditemukan", 'stat' => true], 200);
  }

  public function surat_masuk_put()
  {
    if ($this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->put('id_dinas');
    // $this->response(['data' =>  $id_dinas], 200);

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $id_surat_masuk = $this->put('id_surat_masuk');
    $no_surat = $this->put('no_surat');
    $sifat = $this->put('sifat') == '' ? null : $this->put('sifat');
    $diteruskan_kepada = $this->put('diteruskan_kepada') == '' ? null : $this->put('diteruskan_kepada');
    $respon = $this->put('respon') == '' ? null : $this->put('respon');
    $catatan = $this->put('catatan') == '' ? null : $this->put('catatan');
    
    // $this->response(['data' =>  $catatan], 200);

    if ($id_surat_masuk == null || $id_surat_masuk == '' || $no_surat == null || $no_surat == '' || $sifat == null || $sifat == '' || $diteruskan_kepada == null || $diteruskan_kepada == '' || $respon == null || $respon == '' || $catatan == null || $catatan == '') {
      $this->response(['message' => 'Data Tidak Lengkap', 'stat' => false], 401);
    }

    $data = [
      'sifat' => $sifat,
      'diteruskan_kepada' => $diteruskan_kepada,
      'respon' => $respon,
      'catatan' => $catatan,
      'updated_at' => date('Y-m-d H:i:s')
    ];

    $this->model->update('tb_surat_masuk', ['id_surat_masuk' => $id_surat_masuk, 'id_dinas' => $id_dinas], $data);

    $this->response(['data' =>  $data, 'message' => "Data No Surat " . $no_surat . "  Berhasil Diupdate", 'stat' => true], 200);
  }

  public function reset_id_put()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->put('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $nik = $this->put('nik');

    if ($nik == null || $nik == '') {
      $this->response(['message' => 'Nik Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_user = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik, 'id_dinas' => $id_dinas])->result();

    if (count($cek_user) == 0) return $this->response(['message' => 'User Tidak Ditemukan', 'stat' => false], 401);

    $this->model->update('tb_karyawan', ['nik' => $nik, 'id_dinas' => $id_dinas], ['device_id' => null]);

    $this->response(['message' => "Reset ID Smartphone Pegawai dengan nama " . $cek_user[0]->nama . " Berhasil", 'stat' => true], 200);
  }

  public function detail_kegiatan_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_laporan = $this->get('id_laporan');

    if ($id_laporan == null || $id_laporan == '') {
      $this->response(['message' => 'Laporan Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_laporan = $this->model->tampil_data_where('tb_laporan_karyawan', ['no_laporan' => $id_laporan])->result();

    if (count($cek_laporan) == 0) return $this->response(['message' => 'Laporan Tidak Ditemukan', 'stat' => false], 401);

    $this->response(['data' =>  $cek_laporan[0], 'message' => "Laporan Ditemukan", 'stat' => true], 200);
  }

  public function check_jadwal_get()
  {
    if ($this->session->userdata('level') != 'Admin' && $this->session->userdata('level') != 'Kepala Dinas') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->get('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $hari = $this->get('hari');



    if ($hari == null || $hari == '') {
      $this->response(['message' => 'Hari Tidak Ditemukan', 'stat' => false], 401);
    }
    // convert $hari string to lowercase
    $hari = strtolower($hari);

    $cek_jadwal = $this->model->tampil_data_where('tb_pengaturan_jam_kerja_harian', ['id_dinas' => $id_dinas, 'hari' => $hari])->result();

    if (count($cek_jadwal) == 0) return $this->response(['message' => 'Jadwal Tidak Ditemukan', 'stat' => false], 401);

    $this->response(['data' =>  $cek_jadwal[0], 'message' => "Jadwal Ditemukan", 'stat' => true], 200);
  }

  public function ganti_data_admin_post()
  {
    if ($this->session->userdata('level') != 'Admin') return $this->response(['message' => 'Failed', 'stat' => false], 401);

    $id_dinas = $this->post('id_dinas');

    if ($id_dinas == null || $id_dinas == '') {
      $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_dinas = $this->model->tampil_data_where('tb_dinas', ['id_dinas' => $id_dinas])->result();

    if (count($cek_dinas) == 0) return $this->response(['message' => 'Dinas Tidak Ditemukan', 'stat' => false], 401);

    $nik = $this->post('nik');

    if ($nik == null || $nik == '') {
      $this->response(['message' => 'Nik Tidak Ditemukan', 'stat' => false], 401);
    }

    $cek_user = $this->model->tampil_data_where('tb_karyawan', ['nik' => $nik, 'id_dinas' => $id_dinas])->result();

    if (count($cek_user) == 0) return $this->response(['message' => 'User Tidak Ditemukan', 'stat' => false], 401);

    $username = $this->post('username');
    $password = $this->post('password');

    if ($username == null || $username == '' || $password == null || $password == '') return $this->response(['message' => 'Username dan Password Tidak Boleh Kosong', 'stat' => false], 401);

    $this->model->update('tb_login_admin', ['nik' => $nik], ['username' => $username, 'password' => md5($password)]);

    $this->response(['message' => "Ganti Data Admin Berhasil", 'stat' => true], 200);
  }
}
