<?php
namespace App\Helpers;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use DateTime;
use Session;
use DB;


class GlobalHelper {

    public $controller_name;

    public function __construct($controller_name = NULL){
        return $this->controller_name = $controller_name;
    }

    public static function curl_post($url, $parameter){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 100,
            CURLOPT_TIMEOUT => 300,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($parameter),
            CURLOPT_HTTPHEADER => array(
                "accept: /",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $response = json_decode('['.$response.']');
        curl_close($curl);

        return $response;
    }

    public static function curl_get($url){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 100,
            CURLOPT_TIMEOUT => 300,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "accept: /",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public static function date_range($bulan){

      $pisah=explode('-',$bulan);
      $startOfMonth = Carbon::createFromDate($pisah[1], $pisah[0], 1);
      $endOfMonth = $startOfMonth->copy()->endOfMonth();
      $hari=$startOfMonth->diffInDays($endOfMonth) + 1;
      for($i=1;$i<=$hari;$i++){
        if($i<=9){
          $date=$pisah[1].'-'.$pisah[0].'-0'.$i;
        }
        else{
          $date=$pisah[1].'-'.$pisah[0].'-'.$i;
        }
        $nama_hari=Self::nama_hari($date);
        $range[]=array('tanggal'=>$date,'nama_hari'=>$nama_hari);
      }
      return $data=array('jumlah-hari'=>$hari,'date-range'=>$range);
    }

    public static function nama_hari($tgl){
      $day = date('D', strtotime($tgl));
      $dayList = array(
       'Sun' => 'Minggu',
       'Mon' => 'Senin',
       'Tue' => 'Selasa',
       'Wed' => 'Rabu',
       'Thu' => 'Kamis',
       'Fri' => 'Jumat',
       'Sat' => 'Sabtu'
      );
      return $dayList[$day];
    }

    public static function dateFormat($date,$format){
       $date=date_create($date);
       $date_new=date_format($date,$format);
       return $date_new;
    }

    public static function tgl_indo($tgl){
      $tanggal = substr($tgl,8,2);
     	$bulan = Self::find_bulan(substr($tgl,5,2));
     	$tahun = substr($tgl,0,4);
     	return $tanggal.' '.$bulan.' '.$tahun;
    }

    public static function tgl_indo_custom($tgl){
      $tanggal = substr($tgl,8,2);
     	$bulan = Self::find_bulan_custom(substr($tgl,5,2));
     	$tahun = substr($tgl,0,4);
     	return $tanggal.' '.$bulan.' '.$tahun;
    }

    public static function nama_bulan($bulan){
      $pisah=explode('-',$bulan);
      $nama_bulan=Self::find_bulan($pisah[0]);
      return $nama_bulan.' '.$pisah[1];
    }

    public static function find_bulan($bln){
    	switch ($bln){
    		case 1:
    			return "Januari";
    			break;
    		case 2:
    			return "Februari";
    			break;
    		case 3:
    			return "Maret";
    			break;
    		case 4:
    			return "April";
    			break;
    		case 5:
    			return "Mei";
    			break;
    		case 6:
    			return "Juni";
    			break;
    		case 7:
    			return "Juli";
    			break;
    		case 8:
    			return "Agustus";
    			break;
    		case 9:
    			return "September";
    			break;
    		case 10:
    			return "Oktober";
    			break;
    		case 11:
    			return "November";
    			break;
    		case 12:
    			return "Desember";
    			break;
    	}
    }

    public static function find_bulan_custom($bln){
    	switch ($bln){
    		case 1:
    			return "Jan";
    			break;
    		case 2:
    			return "Feb";
    			break;
    		case 3:
    			return "Mar";
    			break;
    		case 4:
    			return "Apr";
    			break;
    		case 5:
    			return "Mei";
    			break;
    		case 6:
    			return "Jun";
    			break;
    		case 7:
    			return "Jul";
    			break;
    		case 8:
    			return "Agt";
    			break;
    		case 9:
    			return "Sep";
    			break;
    		case 10:
    			return "Okt";
    			break;
    		case 11:
    			return "Nov";
    			break;
    		case 12:
    			return "Des";
    			break;
    	}
    }

    public static function add_periode($nip,$tahun){
      $field=new Periode;
      $field->tahun=$tahun;
      $field->tanggal_mulai=$tahun.'-01-01';
      $field->tanggal_akhir=$tahun.'-12-31';
      $field->nip_pegawai=$nip;
      $field->save();
      return $field->id;
    }

    public static function jumlah_waktu($mulai,$selesai){
      $awal  = strtotime($mulai);
      $akhir = strtotime($selesai);
      $diff  = $akhir - $awal;
      $menit   = floor($diff/60);
      return $menit;
    }

    public static function jumlah_hari($bulan){
      $calendar=CAL_GREGORIAN;
      $pisah=explode('-',$bulan);
      $hari=cal_days_in_month($calendar,$pisah[0],$pisah[1]);
      return $hari;
    }

    public static function bulan_lalu($bulan=null){
      $bulan = empty($bulan) ? date("Y-m") : Self::dateFormat('01-'.$bulan,'Y-m');
      $bulan_lalu=date('Y-m-d', strtotime(date($bulan) . '- 1 month'));
      return Self::dateFormat($bulan_lalu,'m-Y');
    }

    public static function get_bulan($bulan = NULL){
      $bulan = empty($bulan) ? date("m-Y") : $bulan;
      $bulanPisah=explode("-",$bulan);
      $bulanGabung=$bulanPisah[1]."-".$bulanPisah[0];

      if($bulanPisah[0]==10){
          $bln=$bulanPisah[0];
      } else {
          $bln=str_replace('0','',$bulanPisah[0]);
      }

      $namaBln=array(1 => "Januari", "Februari", "Maret", "April", "Mei","Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
      $bulanTampil=$namaBln[$bln]." ".$bulanPisah[1];

      $bulanLama=date('Y-m-d', strtotime(date($bulanGabung) . '- 1 month'));
      $bulanLamaPisah=explode("-",$bulanLama);
      $bulanLalu=$bulanLamaPisah[1]."-".$bulanLamaPisah[0];
      $data=array($bulanLalu,$bulanTampil,$bulanGabung);
      return $data;
    }

    public static function range_bulan($awal='yyyy-01-01',$akhir='yyyy-12-31'){
      $bulan_awal=explode('-',$awal);
      $bulan_akhir=explode('-',$akhir);
      for($bln=$bulan_awal[1];$bln<=$bulan_akhir[1];$bln++){
        $nama_bulan=Self::find_bulan($bln);
        if($bln<10 && $bln!='01'){
          $bulan='0'.$bln;
        }
        else{
          $bulan=$bln;
        }
        $data[]=array('bulan'=>$bulan,'nama_bulan'=>$nama_bulan);
      }
      return $data;
    }

    public static function range_bulan2($awal='yyyy-01-01',$akhir='yyyy-12-31'){
      $bulan_awal=explode('-',$awal);
      $bulan_akhir=explode('-',$akhir);
      for($bln=$bulan_awal[1];$bln<=$bulan_akhir[1];$bln++){
        $nama_bulan=Self::find_bulan($bln);
        if($bln<10 && $bln!='01'){
          $bulan='0'.$bln;
        }
        else{
          $bulan=$bln;
        }
        $data[]=$bulan;
      }
      return $data;
    }

    public static function list_modul($parent,$group){
      $data=DB::table('modul')->select('modul.id','modul.nama_modul','modul.order','modul.route','modul.icon')
        // ->join('otoritas_modul', function ($join) {
        //     $join->on('modul.id', '=', 'otoritas_modul.fid_modul');
        // })
        // ->where('otoritas_modul.fid_hak_akses','=',Session::get('useractive')->fid_hak_akses)
        // ->where('otoritas_modul.is_view','Y')
        ->where('modul.parent_id','=',$parent)
        ->where('modul.group',$group)
        ->where('modul.is_active',1)
        ->orderBy('modul.order')
        ->get();
      foreach ($data as $key => $value) {
        $submodul = Self::list_modul($value->id,$group);
        $data[$key]->link = (count($submodul) == 0 ? ( $value->route=='#' ? 'javascript: void(0);' : route($value->route) ) : 'javascript: void(0);' );
        $data[$key]->submodul = $submodul ;
      }
      return $data;
    }

    public static function otoritas_modul($hak_akses,$modul){
      $otoritas=DB::table('otoritas_modul')->where('fid_hak_akses','=',$hak_akses)->where('fid_modul','=',$modul)->first();
      if(!empty($otoritas)){
        $data=array('view'=>$otoritas->is_view,
                    'insert'=>$otoritas->is_insert,
                    'update'=>$otoritas->is_update,
                    'delete'=>$otoritas->is_delete);
      }
      else{
        $data=array('view'=>'N',
                    'insert'=>'N',
                    'update'=>'N',
                    'delete'=>'N');
      }
      return $data;
    }

    public static function post_title($string) {
      $string = strtolower($string);
      $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
      $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

      return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
    }

    public static function stok_bahan_baku($id){
      $bahan_baku = DB::table('bahan_baku')->find($id);
      if(!empty($bahan_baku)){
        $stok_awal = $bahan_baku->stok_awal;
        $pembelian_bahan = DB::table('pembelian_bahan_baku')->where('fid_bahan_baku',$id)->whereNull('deleted_at')->sum('jumlah');
        $penggunaan_bahan = DB::table('penggunaan_bahan_baku')->where('fid_bahan_baku',$id)->whereNull('deleted_at')->sum('jumlah');
        $stok = ($stok_awal+$pembelian_bahan) - $penggunaan_bahan;
        return $stok;
      }
    }

    public static function status_bahan_baku($id){
      $bahan_baku = DB::table('bahan_baku')->find($id);
      if(!empty($bahan_baku)){
        $stok = Self::stok_bahan_baku($id);
        if($stok > $bahan_baku->stok_maksimum ){
          return array('status'=>'kelebihan','color'=>'#8e44ad');
        }
        else if($stok <= $bahan_baku->stok_rendah && $stok > $bahan_baku->stok_kritis){
          return array('status'=>'rendah','color'=>'#f39c12');
        }
        else if($stok <= $bahan_baku->stok_kritis){
          return array('status'=>'kritis','color'=>'#c0392b');
        }
        else{
          return array('status'=>'normal','color'=>'#16a085');
        }
      }
    }

    public static function jumlah_bahan_baku($status){
      $query = DB::table('bahan_baku')->whereNull('bahan_baku.deleted_at');
      if($status != 'all'){
        $query = $query->where('status',$status);
      }
      return $query->count();
    }

    public static function get_jumlah_siswa($sekolah,$jenis_kelamin){
      if($jenis_kelamin != 'all'){
        $tanggal_cari = Carbon::parse(date('Y-m-d'));
        $semester = DB::table('semester')
                      ->whereDate('tanggal_mulai', '<=', $tanggal_cari)
                      ->whereDate('tanggal_akhir', '>=', $tanggal_cari)
                      ->first();

        $query = DB::table('jumlah_siswa')->where('fid_semester',(!empty($semester) ? $semester->id : 0 ));
        if($sekolah != 'all' ){
          $query = $query->where('fid_penerima_manfaat',$sekolah);
        }
        $jumlah_siswa = $query->whereNull('deleted_at')->sum('jumlah_'.$jenis_kelamin);
      }
      else{
        $laki_laki = Self::get_jumlah_siswa($sekolah,'laki_laki');
        $perempuan = Self::get_jumlah_siswa($sekolah,'perempuan');
        $jumlah_siswa = $laki_laki+$perempuan;
      }
      return $jumlah_siswa;
    }


    public static function get_counter_dapur($jenis,$jadwal_id){
      $data = DB::table('jadwal_menu_makanan')->find($jadwal_id);
      if(!empty($data)){
        $total = $data->jumlah;
        $sudah = DB::table('counter_dapur')->where('jenis',$jenis)->where('fid_jadwal_menu',$jadwal_id)->whereNull('deleted_at')->sum('jumlah');
        $belum = $total-$sudah;
        $persentase = round($sudah/$total*100,0);
        if($persentase >= 0 && $persentase <= 30 ){
          $color = '#e74c3c';
        }
        else if($persentase > 30 && $persentase <= 50 ){
          $color = '#f39c12';
        }
        else if($persentase > 50 && $persentase <= 70 ){
          $color = '#3498db';
        }
        else{
          $color ='#2ecc71';
        }
        return array('total'=>$total,'sudah'=>$sudah,'belum'=>$belum,'persentase'=>$persentase,'color'=>$color);
      }
    }

    public static function operasi($mathString){
      try {
        $mathString = trim($mathString);     // trim white spaces
        $result = eval('return '.$mathString.';');
      } catch (\Exception $e) {
        $result = 0;
      }
    	return $result;
    }

    public static function find_info_wilayah($id){
      $data=DB::table('wilayah')->find($id);
      if(!empty($data)){
        return $data->nama_wilayah;
      }
      else{
        return '';
      }
    }


}
