<?php

namespace App\Controllers\backend;

use PHPExcel;
use PHPExcel_IOFactory;
use App\Models\backend\KaryawanModel;
use App\Models\backend\MenuModel;
use App\Models\backend\SubmenuModel;
use App\Models\backend\JabatanModel;
use App\Models\backend\StatusPegawaiModel;
use App\Models\backend\DivisiModel;
use App\Models\backend\UserDivisiModel;
use App\Models\backend\AbsenPegawaiModel;
use App\Models\backend\SlipPegawaiModel;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\Request;
use DateTime;
use CodeIgniter\HTTP\Files\UploadedFile;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


class Keuangan extends Controller
{
  protected $karyawanModel;
  protected $menuModel;
  protected $submenuModel;
  protected $jabatanModel;
  protected $statusPegawaiModel;
  protected $divisiModel;
  protected $userDivisiModel;
  protected $absenPegawaiModel;
  protected $slipPegawaiModel;

  public function __construct()
  {
    helper('fisi');
    $this->karyawanModel = new KaryawanModel();
    $this->menuModel = new MenuModel();
    $this->submenuModel = new SubmenuModel();
    $this->jabatanModel = new JabatanModel();
    $this->statusPegawaiModel = new StatusPegawaiModel();
    $this->divisiModel = new DivisiModel();
    $this->userDivisiModel = new UserDivisiModel();
    $this->absenPegawaiModel = new AbsenPegawaiModel();
    $this->slipPegawaiModel = new SlipPegawaiModel();
  }

  // controller Absen untuk keuangan
  public function absen()
  {
    $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();

    $data = [
      'title' => 'Data Absen Pegawai',
      'user' => $cekuser,
      'validation' => \Config\Services::validation()
    ];

    return view('backend/keuangan/absen', $data);
  }

  public function fetchabsenpegawai()
  {

    if ($this->request->isAJAX()) {
      if ($absen = $this->absenPegawaiModel->findAll()) {
        // dd($absen);
        $data = [
          'responce' => 'success',
          'absen' => $absen
        ];
      } else {
        $data = [
          'responce' => 'error',
          'pesan' => 'gagal fetch'
        ];
      }
      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  // controller Absen untuk keuangan
  public function slip()
  {
    $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();
    $pegawai = $this->karyawanModel->findAll();
    $data = [
      'title' => 'Slip Gaji Pegawai',
      'user' => $cekuser,
      'pegawai' => $pegawai,
      'validation' => \Config\Services::validation()
    ];

    return view('backend/keuangan/slip', $data);
  }

  public function fetchslippegawai()
  {

    if ($this->request->isAJAX()) {
      if ($slip = $this->slipPegawaiModel->getslipsemua()) {
        // dd($absen);
        $data = [
          'responce' => 'success',
          'slip' => $slip
        ];
      } else {
        $data = [
          'responce' => 'error',
          'pesan' => 'gagal fetch'
        ];
      }
      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  public function saveslippegawai()
  {
    if ($this->request->isAJAX()) {
      if (!$this->validate([
        'nip' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'NIP tidak boleh kosong'
          ]
        ],
        'nogaji' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Nomor Gaji tidak boleh kosong'
          ]
        ],
        'bulan' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Bulan tidak boleh kosong'
          ]
        ],
        'tahun' => [
          'rules' => 'required|numeric',
          'errors' => [
            'required' => 'Tahun tidak boleh kosong',
            'numeric' => 'Tahun harus berupa angka'
          ]
        ],
        'jmlhgator' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah gaji kotor tidak boleh kosong'
          ]
        ],
        'jmlhpotongan' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah potongan tidak boleh kosong'
          ]
        ],
        'jmlhgajiditerima' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah gaji diterima tidak boleh kosong'
          ]
        ]
      ])) {
        $validation = \Config\Services::validation();
        $data = [
          'responce' => 'error',
          'pesan' => $validation->listErrors()
        ];
      } else {
        // validasi sukses
        $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();

        $nip = $this->request->getVar('nip');
        $idkaryawan = $this->karyawanModel->where('nip', $nip)->get()->getRowArray();


        $insert = [
          'nip' => $nip,
          'id_karyawan' => $idkaryawan['id'],
          'bulan' => $this->request->getVar('bulan'),
          'tahun' => $this->request->getVar('tahun'),
          'nogaji' => $this->request->getVar('nogaji'),

          'gapok' => hilangtitik($this->request->getVar('gapok')),
          'tunjjabatan' => hilangtitik($this->request->getVar('tunjjabatan')),
          'tunjprofesi' => hilangtitik($this->request->getVar('tunjprofesi')),
          'tunjkinerja' => hilangtitik($this->request->getVar('tunjkinerja')),
          'tunjtgs' => hilangtitik($this->request->getVar('tunjtgs')),
          'tunjkomunikasi' => hilangtitik($this->request->getVar('tunjkomunikasi')),
          'bkk' => hilangtitik($this->request->getVar('bkk')),
          'tunjkehadiran' => hilangtitik($this->request->getVar('tunjkehadiran')),
          'jmlhkehadiran' => $this->request->getVar('jmlhkehadiran'),
          'jmlhpuasa' => $this->request->getVar('jmlhpuasa'),
          'tunjpuasa' => hilangtitik($this->request->getVar('tunjpuasa')),
          'jmlhgaji' => hilangtitik($this->request->getVar('jmlhgaji')),
          'jmlhtunjangan' => hilangtitik($this->request->getVar('jmlhtunjangan')),
          'jmlhgator' => hilangtitik($this->request->getVar('jmlhgator')),
          'spp' => hilangtitik($this->request->getVar('spp')),
          'uangpangkal' => hilangtitik($this->request->getVar('uangpangkal')),
          'uangkbm' => hilangtitik($this->request->getVar('uangkbm')),
          'tagihankomunikasi' => hilangtitik($this->request->getVar('tagihankomunikasi')),
          'danasosial' => hilangtitik($this->request->getVar('danasosial')),
          'simpananpokok' => hilangtitik($this->request->getVar('simpananpokok')),
          'cicilan' => hilangtitik($this->request->getVar('cicilan')),
          'kuponbelanja' => hilangtitik($this->request->getVar('kuponbelanja')),
          'tabungankoperasi' => hilangtitik($this->request->getVar('tabungankoperasi')),
          'bpjstenaga' => hilangtitik($this->request->getVar('bpjstenaga')),
          'bpjskesehatan' => hilangtitik($this->request->getVar('bpjskesehatan')),
          'zakatprofesi' => hilangtitik($this->request->getVar('zakatprofesi')),
          'qurban' => hilangtitik($this->request->getVar('qurban')),
          'dll' => hilangtitik($this->request->getVar('dll')),
          'user_update' => $cekuser['nama_lengkap'],
          'jmlhpotongan' => hilangtitik($this->request->getVar('jmlhpotongan')),
          'jmlhgajiditerima' => hilangtitik($this->request->getVar('jmlhgajiditerima'))
        ];

        $this->slipPegawaiModel->insert($insert);

        $data = [
          'responce' => 'success',
          'pesan' => 'Slip berhasil ditambah'
        ];
      }
      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  public function editmodalslip()
  {
    if ($this->request->isAJAX()) {
      $idslip = $this->request->getVar('idslip');
      // if ($slip = $this->slipPegawaiModel->where('id', $idslip)->get()->getRowArray()) {
      if ($slip = $this->slipPegawaiModel->getSlipPersonal($idslip)) {
        $data = [
          'responce' => 'success',
          'slip' => $slip
        ];
      } else {
        $data = [
          'responce' => 'error',
          'pesan' => 'gagal memunculkan modal edit data'
        ];
      }
      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  public function editslippegawai()
  {
    if ($this->request->isAJAX()) {
      if (!$this->validate([
        'nip' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'NIP tidak boleh kosong'
          ]
        ],
        'nogaji' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Nomor Gaji tidak boleh kosong'
          ]
        ],
        'bulan' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Bulan tidak boleh kosong'
          ]
        ],
        'tahun' => [
          'rules' => 'required|numeric',
          'errors' => [
            'required' => 'Tahun tidak boleh kosong',
            'numeric' => 'Tahun harus berupa angka'
          ]
        ],
        'jmlhgator' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah gaji kotor tidak boleh kosong'
          ]
        ],
        'jmlhpotongan' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah potongan tidak boleh kosong'
          ]
        ],
        'jmlhgajiditerima' => [
          'rules' => 'required',
          'errors' => [
            'required' => 'Jumlah gaji diterima tidak boleh kosong'
          ]
        ]
      ])) {
        $validation = \Config\Services::validation();
        $data = [
          'responce' => 'error',
          'pesan' => $validation->listErrors()
        ];
      } else {
        // validasi sukses
        $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();
        $idslip = $this->request->getVar('idslip');
        $update = [

          'bulan' => $this->request->getVar('bulan'),
          'tahun' => $this->request->getVar('tahun'),
          'nogaji' => $this->request->getVar('nogaji'),

          'gapok' => hilangtitik($this->request->getVar('gapok')),
          'tunjjabatan' => hilangtitik($this->request->getVar('tunjjabatan')),
          'tunjprofesi' => hilangtitik($this->request->getVar('tunjprofesi')),
          'tunjkinerja' => hilangtitik($this->request->getVar('tunjkinerja')),
          'tunjtgs' => hilangtitik($this->request->getVar('tunjtgs')),
          'tunjkomunikasi' => hilangtitik($this->request->getVar('tunjkomunikasi')),
          'bkk' => hilangtitik($this->request->getVar('bkk')),
          'tunjkehadiran' => hilangtitik($this->request->getVar('tunjkehadiran')),
          'jmlhkehadiran' => $this->request->getVar('jmlhkehadiran'),
          'jmlhpuasa' => $this->request->getVar('jmlhpuasa'),
          'tunjpuasa' => hilangtitik($this->request->getVar('tunjpuasa')),
          'jmlhgaji' => hilangtitik($this->request->getVar('jmlhgaji')),
          'jmlhtunjangan' => hilangtitik($this->request->getVar('jmlhtunjangan')),
          'jmlhgator' => hilangtitik($this->request->getVar('jmlhgator')),
          'spp' => hilangtitik($this->request->getVar('spp')),
          'uangpangkal' => hilangtitik($this->request->getVar('uangpangkal')),
          'uangkbm' => hilangtitik($this->request->getVar('uangkbm')),
          'tagihankomunikasi' => hilangtitik($this->request->getVar('tagihankomunikasi')),
          'danasosial' => hilangtitik($this->request->getVar('danasosial')),
          'simpananpokok' => hilangtitik($this->request->getVar('simpananpokok')),
          'cicilan' => hilangtitik($this->request->getVar('cicilan')),
          'kuponbelanja' => hilangtitik($this->request->getVar('kuponbelanja')),
          'tabungankoperasi' => hilangtitik($this->request->getVar('tabungankoperasi')),
          'bpjstenaga' => hilangtitik($this->request->getVar('bpjstenaga')),
          'bpjskesehatan' => hilangtitik($this->request->getVar('bpjskesehatan')),
          'zakatprofesi' => hilangtitik($this->request->getVar('zakatprofesi')),
          'qurban' => hilangtitik($this->request->getVar('qurban')),
          'dll' => hilangtitik($this->request->getVar('dll')),
          'user_update' => $cekuser['nama_lengkap'],
          'jmlhpotongan' => hilangtitik($this->request->getVar('jmlhpotongan')),
          'jmlhgajiditerima' => hilangtitik($this->request->getVar('jmlhgajiditerima'))
        ];


        $this->slipPegawaiModel->update($idslip, $update);

        $data = [
          'responce' => 'success',
          'pesan' => 'Slip berhasil diupdate'
        ];
      }
      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  public function deleteslippegawai()
  {
    if ($this->request->isAJAX()) {
      if ($id = $this->request->getVar('checkbox_value')) {
        for ($count = 0; $count < count($id); $count++) {
          $this->slipPegawaiModel->where('id', $id[$count])->delete();
        }

        $data = [
          'responce' => 'success',
          'pesan' => 'Data slip berhasil dihapus'
        ];

        echo json_encode($data);
      }
    } else {
      echo "No direct script access allowed";
    }
  }

  public function importslippegawai()
  {
    if ($this->request->isAJAX()) {

      $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();
      $file = $this->request->getFile('fileslip');

      if ($file) {

        $ext = $file->getClientExtension();

        if ($ext == 'xls') {
          $render = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
        } else {
          $render = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        }

        $spreadsheet = $render->load($file);

        $sheet = $spreadsheet->getActiveSheet()->toArray("", true, true, true);


        // $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();

        $angkakosong = 0;
        // $ceknip = array();
        $barisgagal = array();
        foreach ($sheet as $cekidx => $cekdata) {
          //skip index 1 karena title excel
          if ($cekidx == 1) {
            continue;
          }
          if ($cekidx == 2) {
            continue;
          }

          $cnip = $cekdata['B'];
          // array_push($ceknip, $cnip);

          if ($this->karyawanModel->where('nip', $cnip)->countAllResults() == 0) {
            $angkakosong++;
            array_push($barisgagal, $cekidx);
          }
        }

        if ($angkakosong > 0) {
          //upload gagal
          $data = [
            'responce' => 'errorkosong',
            'pesan' => 'Import slip pegawai gagal',
            'barisgagal' => $barisgagal
          ];
        } else {
          foreach ($sheet as $idx => $data) {
            //skip index 1 karena title excel
            if ($idx == 1) {
              continue;
            }
            if ($idx == 2) {
              continue;
            }

            $nip = $data['B'];

            $nogaji = date('Y') . '' . date('m') . '' . date('d') . '' . substr($nip, -4);

            $bulan = $data['D'];
            $tahun = $data['E'];
            $gapok = $data['F'];
            $tunjjabatan = $data['G'];
            $tunjprofesi = $data['H'];
            $tunjkinerja = $data['I'];
            $tunjtgs = $data['J'];
            $tunjkomunikasi = $data['K'];
            $bkk = $data['L'];

            $jmlhgaji = (int)$gapok + (int)$tunjjabatan + (int)$tunjprofesi + (int)$tunjkinerja + (int)$tunjtgs + (int)$tunjkomunikasi + (int)$bkk;

            $jmlhkehadiran = $data['N'];
            $tunjkehadiran = $data['O'];
            $jmlhpuasa = $data['P'];
            $tunjpuasa = $data['Q'];

            $jmlhtunjangan = (int)$tunjkehadiran + (int)$tunjpuasa;

            $jmlhgator = $jmlhgaji + $jmlhtunjangan;

            $spp = $data['T'];
            $uangpangkal = $data['U'];
            $uangkbm = $data['V'];
            $tagihankomunikasi = $data['W'];
            $danasosial = $data['X'];
            $simpananpokok = $data['Y'];
            $cicilan = $data['Z'];
            $kuponbelanja = $data['AA'];
            $tabungankoperasi = $data['AB'];
            $bpjstenaga = $data['AC'];
            $bpjskesehatan = $data['AD'];
            $zakatprofesi = $data['AE'];
            $qurban = $data['AF'];
            $dll = $data['AG'];

            $jmlhpotongan = (int)$spp + (int)$uangpangkal + (int)$uangkbm + (int)$tagihankomunikasi + (int)$danasosial + (int)$simpananpokok + (int)$cicilan + (int)$kuponbelanja + (int)$tabungankoperasi + (int)$bpjstenaga + (int)$bpjskesehatan + (int)$zakatprofesi + (int)$qurban + (int)$dll;

            $jmlhgajiditerima = $jmlhgator - $jmlhpotongan;


            $idkaryawan = $this->karyawanModel->where('nip', $nip)->get()->getRowArray();

            // insert data
            $this->slipPegawaiModel->insert([
              'nogaji'        =>    $nogaji,
              'nip'        =>    $nip,
              'id_karyawan' => $idkaryawan['id'],
              'bulan'        =>    strtolower($bulan),
              'tahun'       =>    $tahun,
              'gapok'       =>    $gapok,
              'tunjjabatan'       =>    $tunjjabatan,
              'tunjprofesi'       =>    $tunjprofesi,
              'tunjkinerja'       =>    $tunjkinerja,
              'tunjtgs'       =>    $tunjtgs,
              'tunjkomunikasi'       =>    $tunjkomunikasi,
              'bkk'       =>    $bkk,
              'jmlhkehadiran'       =>    $jmlhkehadiran,
              'tunjkehadiran'       =>    $tunjkehadiran,
              'jmlhpuasa'       =>    $jmlhpuasa,
              'tunjpuasa'       =>    $tunjpuasa,
              'jmlhgaji'       =>    $jmlhgaji,
              'jmlhtunjangan'       =>    $jmlhtunjangan,
              'jmlhgator'       =>    $jmlhgator,
              'spp'       =>    $spp,
              'uangpangkal'       =>    $uangpangkal,
              'uangkbm'       =>    $uangkbm,
              'tagihankomunikasi'       =>    $tagihankomunikasi,
              'danasosial'       =>    $danasosial,
              'simpananpokok'       =>    $simpananpokok,
              'cicilan'       =>    $cicilan,
              'kuponbelanja'       =>    $kuponbelanja,
              'tabungankoperasi'       =>    $tabungankoperasi,
              'bpjstenaga'       =>    $bpjstenaga,
              'bpjskesehatan'       =>    $bpjskesehatan,
              'zakatprofesi'       =>    $zakatprofesi,
              'qurban'       =>    $qurban,
              'dll'       =>    $dll,
              'jmlhpotongan'       =>    $jmlhpotongan,
              'jmlhgajiditerima'       =>    $jmlhgajiditerima,

              'user_update'       =>    $cekuser['nama_lengkap']
            ]);

            $data = [
              'responce' => 'success',
              'pesan' => 'Import slip pegawai berhasil'
            ];
          }
        }
      } else {
        //upload gagal
        $data = [
          'responce' => 'error',
          'pesan' => 'Import slip pegawai gagal'
        ];
      }

      echo json_encode($data);
    } else {
      echo "No direct script access allowed";
    }
  }

  public function detailslip($id)
  {
    $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();

    // $siswa = $this->siswaModel->where('id', $id)->get()->getRowArray();

    $arr_id = explode(" ", $id);

    $slip = $this->slipPegawaiModel->getSlipPersonal($arr_id[0]);

    $data = [
      'title' => 'Detail Slip',
      'user' => $cekuser,
      'slip' => $slip

    ];

    return view('backend/keuangan/detailslip', $data);
  }

  public function pdfdetailslip($id)
  {

    $cekuser = $this->karyawanModel->where('id', session('id'))->get()->getRowArray();

    $arr_id = explode(" ", $id);

    $slip = $this->slipPegawaiModel->getSlipPersonal($arr_id[0]);

    $data = [
      'title' => 'Detail Slip',
      'user' => $cekuser,
      'slip' => $slip

    ];

    // return view('backend/tatausaha/pdfsiswa', $data);

    // $content = file_get_contents(view('backend/tatausaha/pdfsiswa', $data));
    $content = view('backend/keuangan/pdfslip', $data);


    $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [220, 350], 'orientation' => 'P']);

    $mpdf->SetDisplayMode('fullpage', 'single');


    $mpdf->WriteHTML($content, \Mpdf\HTMLParserMode::DEFAULT_MODE);
    $mpdf->Output('data' .  $slip['nama_lengkap'] . '' . $slip['bulan'] . '' . $slip['tahun'] . '.pdf', 'd');
  }
}
