<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Setting extends CI_Controller
{

  public function __construct()
  {
    parent::__construct();
    $this->load->model('user_model', 'user');
    $this->load->model('Setting_m', 'setting_m');
    $this->load->library('form_validation');
    is_logged_in();
  }
  public function index()
  {
    $data['title'] = 'Setting';
    $data['idDesa'] = $this->user->idDesa();
    $data['menu'] = $this->db->get('user_menu')->result_array();
    $data['kop'] = $this->db->get('kop_surat')->result_array();
    $data['provinsi'] = $this->db->get('provinces')->result_array();
    $queryUser = "SELECT * FROM user WHERE role_id='1' OR role_id='2' ";
    $queryOperator = "SELECT * FROM user WHERE role_id='5'";
    $data['dataUser'] = $this->db->query($queryUser)->result_array();
    $data['dataOperator'] = $this->db->query($queryOperator)->result_array();
    // var_dump($data['user']);
    // die;
    $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
    $this->form_validation->set_rules('menu', 'Menu', 'required', array('required' => 'Form menu tidak boleh Kosong'));
    if ($this->form_validation->run() == false) {
      $this->load->view('themplate/admin/header', $data);
      $this->load->view('themplate/admin/sidebar', $data);
      $this->load->view('themplate/admin/topbar', $data);
      $this->load->view('setting/index', $data);
      $this->load->view('themplate/admin/footer', $data);
    } else {
      $this->db->insert('user_menu', ['menu' => $this->input->post('menu')]);
      $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data menu berhasil ditambah!!
      </div>');
      redirect('menu'); 
    }
  }

  public function aktifForm()
  {
    $data['setting'] = $this->db->get('kop_surat')->row_array();
    $colom = $_POST['kolom'];
    $form = '';
    if ($data['setting'][$colom] == 1) {
      $form = 0;
    } else if ($data['setting'][$colom] == 0) {
      $form = 1;
    }

    $edit = [
      $colom => $form
    ];

    $this->db->set($edit);
    $this->db->where('id', $_POST['id']);
    $this->db->update('kop_surat');
    echo "sukses";
  }

  public function updateKop()
  {

    $foto = $_FILES['logo'];
    $ttd = $_FILES['ttd'];

    $newLogo = $this->renameFile($foto);
    $newTtd = $this->renameFile($ttd);

    // jika tidak upload logo dan ttd
    if ($foto['error'] == 4 && $ttd['error']) {
      $data = [
        'nama_sekolah' => $this->input->post('nama'),
        'alamat' => $this->input->post('alamat'),
        'kecamatan' => $this->input->post('kecamatan'),
        'desa' => $this->input->post('desa'),
        'npsn' => $this->input->post('npsn'),
        'JumlahRombel' => $this->input->post('JumlahRombel'),
        'longitude' => $this->input->post('long'),
      
      ];
      $this->db->set($data);
      $this->db->where('id', $this->input->post('id'));
      $this->db->update('kop_surat');
      $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data Seting berhasil Ubah!!
      </div>');
      redirect('setting');

      // jika tida upload logo
    } else if ($foto['error'] == 4) {
      // panggil configurasi config
      $config = $this->setUpload($newTtd);
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload('ttd')) {
        $this->session->set_flashdata('message', '
      <div class="alert alert-danger" role="alert">
      TTD kelapa sekolah gagal di update
      </div>');
        redirect('setting');
      } else {
        $this->upload->data('file_name');
        $data = [
          'nama_sekolah' => $this->input->post('nama'),
          'alamat' => $this->input->post('alamat'),
          'kecamatan' => $this->input->post('kecamatan'),
          'desa' => $this->input->post('desa'),
          'npsn' => $this->input->post('npsn'), 'JumlahRombel' => $this->input->post('JumlahRombel'),
          'longitude' => $this->input->post('long'),
          'ttd_kepsek'   => $newTtd
        ];
        $this->db->set($data);
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('kop_surat');
        $this->session->set_flashdata('message', '
        <div class="alert alert-success" role="alert">
       Data Seting berhasil Ubah!!
        </div>');
        redirect('setting');
      }

      // Jika tidak upload ttd
    } else if ($ttd['error'] == 4) {
      $config = $this->setUpload($newLogo);
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload('logo')) {
        $this->session->set_flashdata(
          'message',
          '
      <div class="alert alert-danger" role="alert">
      Logo Sekolah gagal di update
      </div>'
        );
        redirect('setting');
      } else {
        $this->upload->data('file_name');
        $data = [
          'nama_sekolah' => $this->input->post('nama'),
          'alamat' => $this->input->post('alamat'),
          'kecamatan' => $this->input->post('kecamatan'),
          'desa' => $this->input->post('desa'),
          'npsn' => $this->input->post('npsn'), 'JumlahRombel' => $this->input->post('JumlahRombel'),
          'longitude' => $this->input->post('long'),
          'logo'   => $newLogo
        ];
        $this->db->set($data);
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('kop_surat');
        $this->session->set_flashdata('message', '
        <div class="alert alert-success" role="alert">
       Data Seting berhasil Ubah!!
        </div>');
        redirect('setting');
      }
      // jika ubah ttd dan logo berbarengan
    } else {

      foreach ($_FILES as $key => $value) {

        $this->uploadGambar($key, $value);
      }
      $this->session->set_flashdata(
        'message',
        '
      <div class="alert alert-success" role="alert">
     Data Seting berhasil Ubah!!
      </div>'
      );
      redirect('setting');
    }
  }

  private function uploadGambar($key, $file)
  {
    if ($key == 'ttd') {
      $newName = $this->renameFile($file);
      $config = $this->setUpload($newName);
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload($key)) {
        $this->session->set_flashdata(
          'message',
          '
    <div class="alert alert-danger" role="alert">
    TTD gagal di update
    </div>'
        );
        redirect('setting');
      } else {
        $this->upload->data('file_name');
        $data = [
          'nama_sekolah' => $this->input->post('nama'),
          'alamat' => $this->input->post('alamat'),
          'kecamatan' => $this->input->post('kecamatan'),
          'desa' => $this->input->post('desa'),
          'npsn' => $this->input->post('npsn'), 'JumlahRombel' => $this->input->post('JumlahRombel'),
          'longitude' => $this->input->post('long'),
          'ttd_kepsek' => $newName
        ];
        $this->db->set($data);
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('kop_surat');
      }
    } else if ($key == 'logo') {
      $newName = $this->renameFile($file);
      $config = $this->setUpload($newName);
      $this->load->library('upload', $config);
      if (!$this->upload->do_upload($key)) {
        $this->session->set_flashdata(
          'message',
          '
    <div class="alert alert-danger" role="alert">
    Logo gagal di update
    </div>'
        );
        redirect('setting');
      } else {
        $this->upload->data('file_name');
        $data = [
          'nama_sekolah' => $this->input->post('nama'),
          'alamat' => $this->input->post('alamat'),
          'kecamatan' => $this->input->post('kecamatan'),
          'desa' => $this->input->post('desa'),
          'npsn' => $this->input->post('npsn'), 'JumlahRombel' => $this->input->post('JumlahRombel'),
          'longitude' => $this->input->post('long'),
          'logo'   => $newName
        ];
        $this->db->set($data);
        $this->db->where('id', $this->input->post('id'));
        $this->db->update('kop_surat');
      }
    }
  }

  // rename file logo dan foto
  public function renameFile($file)
  {

    $extend = explode('/', $file['type']);
    $ext = end($extend);
    $newName = rand(10, 100000);
    $newjadi = $newName . '.' . $ext;
    return $newjadi;
  }

  // configurasi library upload foto
  private function setUpload($fileName)
  {
    $config['upload_path'] = 'assets/img/logo';
    $config['allowed_types'] = 'jpg|png|gif|jpeg';
    $config['file_name'] = $fileName;
    return $config;
  }

  // ubah kepala sekolah

  public function ubahKepsek()
  {
    $data = [
      'nama_kepala' => $this->input->post('namaKep'),
      'nip_kepsek' => $this->input->post('nip'),
      'no_surat' => $this->input->post('noSurat'),
      'longitude' => $this->input->post('long'),
      'tanggalKelulusan' => $this->input->post('tanggakKelulusan'),
      'jumlahRombel' => $this->input->post('JumlahRombel')
    ];

    $this->db->set($data);
    $this->db->where('id', $this->input->post('id'));
    $this->db->update('kop_surat');
    $this->session->set_flashdata('message', '
    <div class="alert alert-success" role="alert">
   Data Seting berhasil Ubah!!
    </div>');
    redirect('setting');
  }

  // ajak ubah data kepala sekolah
  public function ubahDataKepsek()
  {
    echo json_encode($this->setting_m->prosesUbahKepsek($_POST));
  }


  // ajax data user

  public function getDataUser()
  {

    echo json_encode($this->db->get_where('user', ['id' => $_POST['id']])->row_array());
  }

  public  function editUser()
  {

    if ($this->user->editProsesUser($_POST) > 0) {
      $this->session->set_flashdata('message', '
    <div class="alert alert-success" role="alert">
   Data Seting berhasil Ubah!!
    </div>');
      redirect('setting');
    } else {
      $this->session->set_flashdata('message', '
    <div class="alert alert-danger" role="alert">
   Data Seting Gagal di Ubah!!
    </div>');
      redirect('setting');
    }
  }

  // edit data operator
  public  function editOperator()
  {

    if ($this->user->editProsesOperator($_POST) > 0) {
      $this->session->set_flashdata('message', '
    <div class="alert alert-success" role="alert">
    Data Data Operator Berhasil Di ruba!!
    </div>');
      redirect('setting');
    } else {
      $this->session->set_flashdata('message', '
    <div class="alert alert-danger" role="alert">
  Data Operator Gagal Di ubah
    </div>');
      redirect('setting');
    }
  }

  public function tambahUser()
  {
    $data['title'] = 'Setting';
    $data['menu'] = $this->db->get('user_menu')->result_array();
    $data['kop'] = $this->db->get('kop_surat')->result_array();
    $queryUser = "SELECT * FROM user WHERE role_id=1 OR role_id=3";
    $data['dataUser'] = $this->db->query($queryUser)->result_array();
    $data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
    $this->form_validation->set_rules($this->rulesUser());
    if ($this->form_validation->run() == false) {
      $this->load->view('themplate/admin/header', $data);
      $this->load->view('themplate/admin/sidebar', $data);
      $this->load->view('themplate/admin/topbar', $data);
      $this->load->view('setting/index', $data);
      $this->load->view('themplate/admin/footer', $data);
    } else {
      if ($this->user->tambahProsesUser($_POST) > 0) {
        $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data Seting berhasil Ubah!!
      </div>');
        redirect('setting');
      } else {
        $this->session->set_flashdata('message', '
      <div class="alert alert-danger" role="alert">
     Data Seting Gagal di Ubah!!
      </div>');
        redirect('setting');
      }
    }
  }


  public function tambahUserOperator()
  {
    $this->form_validation->set_rules($this->rulesOperator());
    if ($this->form_validation->run() == false) {
      // echo "validasi is not";
      // die;
      redirect('setting');
    } else {
      if ($this->user->tambahUserOperator($_POST) > 0) {
        $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data Operator Berhasil Ditambah
      </div>');
        redirect('setting');
      } else {
        $this->session->set_flashdata('message', '
      <div class="alert alert-danger" role="alert">
     Data Operator Gagal Ditambah
      </div>');
        redirect('setting');
      }
    }
  }


  public function hapusUser($id)
  {
    if ($this->user->hapusUserProses($id) > 0) {
      $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data User Berhasil di Hapus!!
      </div>');
      redirect('setting');
    } else {
      $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data User Gagal di Hapus!!
      </div>');
      redirect('setting');
    }
  }

  public function rulesUser()
  {
    $dataRules = array(
      array(
        'field' => 'email',
        'label' => 'Email',
        'rules' => 'required|trim|valid_email',
        'errors' => array(
          'required' => 'Email Harus Di isi',
          'valid_email' => 'Email yg anda masukan tidak benar'
        )

      ), array(
        'field' => 'password',
        'label' => 'Password',
        'rules' => 'required|min_length[3]',
        'errors' => array(
          'required' => 'Password tidak boleh kosong',
          'min_length' => 'Password Minimal 3 Karakter'
        )
      ),

      array(
        'field' => 'password2',
        'label' => 'Password2',
        'rules' => 'required|min_length[3]|matches[password]',
        'errors' => array(
          'required' => 'Password tidak boleh kosong',
          'min_length' => 'Password Minimal 3 Karakter',
          'matches' => 'Password tidak sama'
        )
      ),

      array(
        'field' => 'nama',
        'label' => 'Nama',
        'rules' => 'required',
        'errors' => array(
          'required' => 'nama tidak boleh kosong'
        )
      )

    );

    return  $dataRules;
  }

  public function rulesOperator()
  {
    $dataRules = array(
      array(
        'field' => 'email',
        'label' => 'Email',
        'rules' => 'required|trim|valid_email',
        'errors' => array(
          'required' => 'Email Harus Di isi',
          'valid_email' => 'Email yg anda masukan tidak benar'
        )

      ), array(
        'field' => 'password',
        'label' => 'Password',
        'rules' => 'required|min_length[3]',
        'errors' => array(
          'required' => 'Password tidak boleh kosong',
          'min_length' => 'Password Minimal 3 Karakter'
        )
      ),

      array(
        'field' => 'password_repeat',
        'label' => 'Password_repeat',
        'rules' => 'required|min_length[3]|matches[password]',
        'errors' => array(
          'required' => 'Password tidak boleh kosong',
          'min_length' => 'Password Minimal 3 Karakter',
          'matches' => 'Password tidak sama'
        )
      ),
      
      array(
        'field' => 'nama',
        'label' => 'Nama',
        'rules' => 'required',
        'errors' => array(
          'required' => 'nama tidak boleh kosong'
        )
      )

    );

    return  $dataRules;
  }
  public function uploadFIle()
  {
    $foto = $_FILES['pengumuman'];
    // var_dump($foto);
    // die;
    $pdfLama = $this->db->get_where('kop_surat', ['id' => $this->input->post('id')])->row_array();
    $extend = explode('/', $foto['type']);
    $ext = end($extend);
    $newName = rand(10, 100000);
    $newjadi = $newName . '.' . $ext;


    $config['upload_path'] = 'assets/HomeAssets/file/';
    $config['allowed_types'] = 'pdf';
    $config['file_name'] = $newjadi;
    $this->load->library('upload', $config);


    if (!$this->upload->do_upload('pengumuman')) {
      $this->session->set_flashdata('message', '
      <div class="alert alert-danger" role="alert">
       Upload pengumuman Gagal
      </div>');
      redirect('setting');
    } else {
      $file = ('assets/HomeAssets/file/' . $pdfLama);
      unlink($file);
      $this->upload->data('file_name');

      $data = [
        'filePengumuman'   => $newjadi
      ];


      $this->db->set($data);
      $this->db->where('id', htmlspecialchars($this->input->post('id')));
      $this->db->update('kop_surat');
      $this->session->set_flashdata('message', '
        <div class="alert alert-success" role="alert">
      Upload Pengumuman Berhasil
        </div>');
      redirect('setting');
    }
  }

  public function backup()
  {
    $this->load->dbutil();
    $prefs = array(
      'tables'     => array('register', 'wali', 'nilai', 'kejuaraansiswa', 'afirmasi', 'user'),
      'format'     => 'sql',
      // gzip, zip, txt format filenya
      'filename'   => 'bacup_' . date('y-m-d-H-i-s') . '.sql',
    );
    // Backup database dan dijadikan variable
    $backup = $this->dbutil->backup($prefs);
    // // Load file helper dan menulis ke server untuk keperluan restore  
    $db_name = 'dataBacup_' . date('y-m-d-H:i:s') . '.sql';
    // $save = FCPATH . 'assets/db/' . $db_name;
    // $this->load->helper('file');
    // write_file($save, $backup);
    // // Load the download helper dan melalukan download ke komputer
    $this->load->helper('download');
    force_download($db_name, $backup);
  }

  public function backup2()
  {
    $this->load->dbutil();
    $tanggal = date('YmdS-His');

    // pengaturan bacup 
    $config = array(
      'format' => 'zip',
      'filename' => 'bacupdb_' . $tanggal . 'ppdb.sql',
      'add_drop' => TRUE,
      'add_insert' => TRUE,
      'newline' => "\n",
      'foreign_key_checks' => FALSE
    );

    $bacup = &$this->dbutil->backup($config);
    $nama_file = "bacup_" . $tanggal . '.zip';
    $this->load->helper('download');
    force_download($nama_file, $bacup);
  }

  public function kosongkan()
  {
    if ($this->user->KosongkanDatabase() > 0) {
      $this->session->set_flashdata(
        'message',
        '
      <div class="alert alert-success" role="alert">
    Database Berhasil dikosongkan
      </div>'
      );
      redirect('setting');
    } else {
      $this->session->set_flashdata('message', '
      <div class="alert alert-danger" role="alert">
    Database Gagal dikosongkan
      </div>');
      redirect('setting');
    }
  }

  public function ttd()
  {
    $foto = $_FILES['ttd'];
    // var_dump($foto);
    // die;
    $pdfLama = $this->db->get_where('kop_surat', ['id' => $this->input->post('id')])->row_array();
    $extend = explode('/', $foto['type']);
    $ext = end($extend);
    $newName = rand(10, 100000);
    $newjadi = $newName . '.' . $ext;
    $config['upload_path'] = 'assets/HomeAssets/file/';
    $config['allowed_types'] = 'jpg|png|gif|jpeg';
    $config['file_name'] = $newjadi;
    $this->load->library('upload', $config);
    $this->upload->do_upload('ttd');
    $file = ('assets/HomeAssets/file/' . $pdfLama);
    unlink($file);
    $this->upload->data('file_name');

    $data = [
      'ttd_kepsek'   => $newjadi
    ];
    $this->db->set($data);
    $this->db->where('id', htmlspecialchars($this->input->post('id')));
    $this->db->update('kop_surat');
    $this->session->set_flashdata('message', '
        <div class="alert alert-success" role="alert">
      Upload Tanda Tangan Berhasil
        </div>');
    redirect('setting');
  }
  // ambil datadesa
  public function getDataDesa()
  {
    $list = $this->setting_m->get_desa();
    // var_dump($list);
    // die;
    $data = array();
    $no = @$_POST['start'];
    foreach ($list as $item) {
      $no++;
      $row = array();
      $row[] = $no . ".";
      $row[] = $item->propinsi;
      $row[] = $item->kota;
      $row[] = $item->kecamatan;
      $row[] = $item->desa;
      $row[] = '<a href="' . base_url('Admin/hapusPendaftar/') . $item->id . '" class="badge badge-danger tombolHapus"><i class="fa fa-print" aria-hidden="true"></i> Hapus</a>';
      $data[] = $row;
    }
    $output = array(
      "draw" => @$_POST['draw'],
      "recordsTotal" => $this->setting_m->count_all(),
      "recordsFiltered" => $this->setting_m->count_filtered(),
      "data" => $data,
    );
    // output to json format

    echo json_encode($output);
  }

  public function GetdataKotaByid()
  {
    echo json_encode($this->db->get_where('regencies', ['province_id' => $_POST['id']])->result_array());
  }

  public function GetdatakecamatanByidKota()
  {
    echo json_encode($this->db->get_where('districts', ['regency_id' => $_POST['id']])->result_array());
  }

  public function tambahDesa()
  {
    if ($this->user->prosesTambahDesa($_POST) > 0) {
      $this->session->set_flashdata('message', '
      <div class="alert alert-success" role="alert">
     Data Desa Berhasil di Tambah!!
      </div>');
      redirect('setting');
    } else {
      $this->session->set_flashdata('message', '
      <div class="alert alert-warning" role="alert">
      Data Desa Gagal di Tambah!!
      </div>');
      redirect('setting');
    }
  }

  public function resetCabut()
  {
    if ($this->db->get_where('register', ['koreg' => $_POST['Koreg']])->num_rows() > 0) {
      $tujuan = "";
      if ($_POST['cabutKe'] == 2) {
        $tujuan = "Dashboard";
      } else {
        $tujuan = "Admin";
      }
      if ($this->user->prosesResetCabut($_POST) > 0) {
        $this->session->set_flashdata('message', '
        <div class="alert alert-success" role="alert">
       Kode Registrasi ' . $_POST['Koreg'] . ' Berhasil Di Kembalikan ' . $tujuan . '
        </div>');
        redirect('Setting');
      }
    } else {
      $this->session->set_flashdata('message', '
       <div class="alert alert-danger" role="alert">
      Kode Registrasi ' . $_POST['Koreg'] . ' Tidak Ditemukan
      </div>');
      redirect('Admin');
    }
  }

  public function resetPIN()
  {
    $nisn = htmlspecialchars($_POST['nisn']);
    echo json_encode($this->user->resetPeserta($nisn));
  }

  public function resetPINOperator()
  {
    $id = htmlspecialchars($_POST['id']);
    echo json_encode($this->user->resetOperator($id));
  }
}
