<?php
namespace nota\controllers;

use Yii;
use yii\web\Controller;
use nota\models\Usermember;
use common\helper\Helper;
use yii\web\NotFoundHttpException;
use yii\helpers\ArrayHelper;
use yii\base\Exception;

class ValidationHelper extends Controller {
  public static function generateUID(){
    return sprintf( '%04x-%04x-%04x-%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000
    );
  }

  public static function currency($angka){

      return "Rp. " . number_format($angka,2,',','.');

  }
  
  public static function bulan($bln)
    {
    	if($bln == 1){
		  	$namabulan = 'JANUARI';
		  }else if($bln == 2){
		  	$namabulan = 'FEBRUARI';
		  }else if($bln == 3){
		  	$namabulan = 'MARET';
		  }else if($bln == 4){
		  	$namabulan = 'APRIL';
		  }else if($bln == 5){
		  	$namabulan = 'MEI';
		  }else if($bln == 6){
		  	$namabulan = 'JUNI';
		  }else if($bln == 7){
		  	$namabulan = 'JULI';
		  }else if($bln == 8){
		  	$namabulan = 'AGUSTUS';
		  }else if($bln == 9){
		  	$namabulan = 'SEPTEMBER';
		  }else if($bln == 10){
		  	$namabulan = 'OKTOBER';
		  }else if($bln == 11){
		  	$namabulan = 'NOVEMBER';
		  }else if($bln == 12){
		  	$namabulan = 'DESEMBER';
		  }else{
		  	$namabulan = '';
		  }

        return $namabulan;
    }

  // public static function dateConvert($date){
  //
  // }

  // cek diskon per barang
  public function haveDiscount($customers, $product){
    return TOrderDt::find()
            ->where([
              'iPelangganId'  =>$customers,
              'DATE_FORMAT(tCreated, "%Y-%m")'=>date('Y-m'),
              'eStatus'       => ['Kirim','Kirim Sebagian'],
              'eDisckaryawan' => 'Ya',
              'iBarangId'     => $product
            ])
            ->count();
  }

  /*
   * apakah menggunakan domain kantor?
  */
  public static function emailChecker($email){
    $whatIWant = substr($email, strpos($email, "@") + 1);
    $needles = [
      'novellpharm',
      'clinisindo',
      'medicastore',
      'ams',
      'eterconpharma',
      'axcelor',
      'flexfreeclinic'
    ];
    $collection = [];
    foreach ($needles as $needle) {
      $rslt = strpos($whatIWant, $needle);

      if($rslt !== false){
        $collection[$needle] = $rslt;
      }
    }
    if($collection){
      return true;
    }else{
      return false;
    }
  }

  /*
   * apakah email nya valid?
  */
  public static function isEmail($email){
    return filter_var($email, FILTER_VALIDATE_EMAIL);
  }

  /*
   * apakah email atau no hape sudah terdaftar?
  */
  public static function isExist($str, $state = "email"){
    if($state == 'email'){
      return Usermember::find()->where(['email'=>$str])->asArray()->one();
    }else{
      return Usermember::find()->where(['email'=>$str])->asArray()->one();
    }
  }

  /*
    Array
      (
        [cNip] => C00484
        [vName] => BIMA SAMUDRA
        [vEmail] => bima.samudra@medicastore.co.id
        [vPersonalEmail] => bimarossoneri@gmail.com
        [dresign] => 0000-00-00
        [iWorkArea] => 181
      )
    apakah user tsb karyawan?
  */
  public static function isEmailKantor($email){
    $karyawan = Helper::karyawan($email);
    // var_dump($karyawan);die;
    if($karyawan){
      $obj = json_decode($karyawan, true);
      if($obj['data']){
        $data = $obj['data'][0];

        return [
          'nip'           => $data['cNip'],
          'email_kantor'  => $data['vEmail'],
          'email_pribadi' => $data['vPersonalEmail'],
          'is_resign'     => ($data['dresign'] == '0000-00-00') ? false : true,
          'work_area'     => $data['iWorkArea']
        ];
      }else{
          return false;
      }
    }else{
      return false;
    }
  }

  public static function isNipUsed($nip){
    return User::find()->where(['cNip'=>$nip])->one();
  }

  public static function generateOTP($n = 6, $useNumber = false){

      $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if($useNumber){
          $number = '0123456789';
          $characters = $characters.$number;
      }

      $randomString = '';

      for ($i = 0; $i < $n; $i++) {
          $index = rand(0, strlen($characters) - 1);
          $randomString .= $characters[$index];
      }

      return $randomString;
  }

  public static function generateKode($n = 6, $useNumber = false){

      $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if($useNumber){
          $number = '0123456789';
          $characters = $characters.$number;
      }

      $randomString = '';

      for ($i = 0; $i < $n; $i++) {
          $index = rand(0, strlen($characters) - 1);
          $randomString .= $characters[$index];
      }

      return $randomString;
  }
  
  public static function generateIPL($n = 6, $useNumber = false){

      $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if($useNumber){
          $number = '0123456789';
          $characters = $characters.$number;
      }

      $randomString = '';

      for ($i = 0; $i < $n; $i++) {
          $index = rand(0, strlen($characters) - 1);
          $randomString .= $characters[$index];
      }

      return 'IPL-'.$randomString;
  }

  public static function oAuth($token){
    try {
      if($token['authorization']){
        $split = explode(" ", $token['authorization']);
        //var_dump($split);die;
        if($split && isset($split[1])){
          $user = Usermember::find()->where(['auth_key'=>$split[1]])->one();
          //echo 'dd';
          if($split[0] != 'Bearer'){
            return ['status'=>false, 'msg'=>'error, Skema auth tidak sesuai !!!','is_login'=>false];
          }else if($user){
            //$isKaryawan = ValidationHelper::isEmailKantor($user->username);
            //$status = ($isKaryawan) ? !$isKaryawan['is_resign'] : false;

            return [
              'status'=>true,
              'msg'=>'berhasil memvalidasi request.',
              'id'=>$user->id,
              'karyawan'=>true,
              'is_login'=> true
            ];
          }else{
            return [
              'status'=>false,
              'msg'=>'error, token request tidak ditemukan, Anda akan logout otomatis.',
              'id'=>0,
              'karyawan'=>false,
              'is_login'=> false
            ];
          }
        }else{
          return ['status'=>false, 'msg'=>'error, format request yang diminta tidak sesuai!!! ok','is_login'=>false];
        }
      }else{
        return ['status'=>false, 'msg'=>'error saat memvalidasi request ss !!!','is_login'=>false];
      }
    } catch (\Exception $e) {
      return ['status'=>false, 'msg'=>$e->getMessage().' on '.$e->getLine()];
    }
  }

  /*
   * params : array_barang, id_pelanggan, is_karyawan
   * diperbaiki lagi nanti disesuaikan kebutuhan
  */
  public static function _generateData($array, $pelanggan, $isKaryawan){
    try {
      $i_produk   = 0;
    	$i_count  	= 0;
    	$i_total	= 0;
      $results	= [];
      $pebanding = 0;

	    if($array){
	    	$i = 0;

	    	foreach ($array as $key => $value) {
	    		$pebanding  = 2 * $value['iIsiKemasanKecil'];
          $status_karyawan = $isKaryawan;
	    		$stock = (isset($value['stock']) && $value['stock'])?$value['stock'] : 0;
    			$harga_kecil = $value['fHNA'] / $value['iIsiKemasanKecil'];
    			$harga_besar = $value['fHNA'];

    			$array_kecil = ValidationHelper::_hargasatuan($harga_kecil, $value['fMargin']);

    			$array_besar = ValidationHelper::_hargasatuan($harga_besar, $value['fMargin'], $value['iIsiKemasanKecil']);

          $harga_satuan = $array_besar['harga_satuan'];
    			// $harga_satuan = $harga_jual = 0;
    			// if($value['iKemasanBesarId'] == $value['iKemasanKecilId']){
    			// 	$harga_satuan = $array_besar['harga_satuan'];
          // }
    			// }else if($value['iKemasanBesarId'] != $value['iKemasanKecilId']){
    			// 	$harga_satuan = $array_kecil['harga_satuan'];
    			// }
          // print_r('Kemasan besar : '.$value['iKemasanBesarId']);
          // print_r('Harga : '.$value['fHNA'].'<br>');
          // print_r('Margin : '.$value['fMargin'].'<br>');
          // print_r($array_besar);die;
    			$promo = TPromoHD::find()
    			->select(['t_promo_hd.*', 'a.iBarangId'])
    			->leftJoin('t_promo_dt a', 't_promo_hd.iId = a.iIdHeader')
    			// ->where([
    			// 	't_promo_hd.eStatus' => 'Aktif',
    			// 	't_promo_hd.eDeleted'=> 'Tidak',
    			// 	'a.iBarangid'	 	 => $value['iId']
    			// ])
          ->where([
            't_promo_hd.eStatus' => 'Aktif',
            't_promo_hd.ePublish' => 'Ya',
            't_promo_hd.eDeleted' => 'Tidak',
            't_promo_hd.eTampil' => 'Ya',
            'a.iBarangid'	 	 => $value['iId']
          ])
    			->andWhere(['<=', 't_promo_hd.dStart', date('Y-m-d')])
    			->andWhere(['>=', 't_promo_hd.dEnd', date('Y-m-d')])
    			->one();

          $promo = TPromoDT::find()
                      ->select(['b.*','t_promo_dt.*'])
                      ->leftJoin('t_promo_hd b', 'b.iId = t_promo_dt.iIdHeader')
                      ->where([
                        'b.eStatus'           => 'Aktif',
                        'b.ePublish'          => 'Ya',
                        'b.eDeleted'          => 'Tidak',
                        'b.eTampil'           => 'Ya',
                        't_promo_dt.iBarangid'=> $value['iId']
                      ])
                			->andWhere(['<=', 'b.dStart', date('Y-m-d')])
                			->andWhere(['>=', 'b.dEnd', date('Y-m-d')])
                      ->asArray()->one();

    			$diskonBarang = 0; $promos = false; $getBonus = false;
    			if($promo){

        			$Promo = true;
        			$diskonBarang = $promo['dDiscount'];
        			$minPrice = $promo['dMinPrice'];
        			$minBeli = $promo['iMinQty'];

        			if($promo['dDiscount']){

      					if($minPrice > 0 && $array_kecil['harga_jual'] > $minPrice){
      						$getBonus = true;
      					}

        				if($minBeli > 0 && $minBeli <= 1){
        					$getBonus = true;
        				}
        			}else{
        				$harga_jual = '0';
        			}
    			}
          $count_order = 0;
          $counter_barang = 0;
          // if($value['iId'] == 2835){
          //   print_r($promo);die;
          // }
          
    			if($status_karyawan){
    				$diskonPrincipal = (isset($value['iDisckaryawan']) && $value['iDisckaryawan']) ? $value['iDisckaryawan'] : 0;

    				// Jika diskon atas barang lebih kecil dari diskon distributor?
    				if($diskonBarang < $diskonPrincipal && $pelanggan){
    					$diskonOrder = ValidationHelper::_haveDiscount($pelanggan, $value['iIsiKemasanKecil']);
    					$diskonItem = ValidationHelper::_haveDiscount($pelanggan, $value['iIsiKemasanKecil'], $value['iId']);

              if(($diskonOrder && count($diskonOrder) >= 6) || ($diskonItem && $diskonItem['totalconv'] >= $pebanding)){
                $status_karyawan = false;
              }
              
              /*
               * update module
              */
              if($diskonOrder && count($diskonOrder) >= 6){
                foreach($diskonOrder as $v){

                  $brg = Mbarang::findOne($v['iBarangId']);

                  $pebanding = 2 * $brg->iIsiKemasanKecil;
                  // print_r($v);die($value['iId']);
                  if($v['totalconv'] < $pebanding && $v['iBarangId'] == $value['iId']){
                    $status_karyawan = true;   
                  }
                }  
              }
               
              // print_r($diskonOrder);die;
	    				if($status_karyawan){
	    					$diskonBarang = $diskonPrincipal;
	    					$getBonus = true;
	    				}

    				}else{
    					$status_karyawan = false;
    				}
    			}else{
            if($diskonBarang){
              $getBonus = true;
            }
          }

    			if($getBonus){
    				$harga_jual = $harga_satuan;
    				$harga_satuan = $harga_satuan - ($harga_satuan * ($diskonBarang / 100));
            // print_r("diskon: ".$diskonBarang.'<br>');
            // print_r("diskon: ".($harga_satuan * ($diskonBarang / 100)).'<br>');
    			}else{
    				$harga_jual = 0;
    			}
          // print_r("Nama Barang: ".$value['vAlias'].'<br>');
          // print_r('harga Jual : '.$harga_satuan.'<br>');

    			$results[$i] = [
	                // 'Ada'                   => $ada,
	                'Karyawan'              => $status_karyawan,
	                'IsiKecil'              => $value['iIsiKemasanKecil'],
	                'Pebanding'             => $pebanding,
	                'Total_Produk_Kary_Ini' => $count_order,
	                'Total_Karyawan'        => $i_count . "",
	                'iId'                   => $value['iId'],
	                'eJenis'                => $value['eJenis'],
	                'eGolongan'             => $value['eGolongan'],
	                'vNama'                 => $value['vAlias'],
	                'foto'                  => ($value['path_foto']) ? $value['path_foto'] : '',
	                'Diskon'                => ($diskonBarang)? $diskonBarang : 0,
	                'DiskonSampai'          => "",
                  'stock'                 => $stock,
                  'pilihanKemasan'        => $value['ePilihankemasan'],
	                // 'HargaAtas'             => ValidationHelper::currency($harga_jual),
	                // 'HargaBawah'            => ValidationHelper::currency($harga_satuan),
                  'HargaAtas'             => ceil($harga_jual),
	                'HargaBawah'            => ceil($harga_satuan),
	                'KemasanKecil'          => $value['kemasan_kecil'],
	                'KemasanBesar'          => $value['kemasan_besar'],
	                'Promo'                 => $promo,
	            ];
              // print_r($results);die;
	            $i++;

	    	}

	    }else{
        // var_dump($result);die('else');
        $results = [];
      }
      if($results){
        return ['status'=>true, 'data'=>$results];
      }else{
        return ['status'=>false, 'data'=>[]];
      }
    } catch (\Exception $e) {
      return ['status'=>false, 'msg'=>$e->getMessage()];
    }

  }
  /*
   * modul cek diskon by order,
   * params:
   * pelangganid => id pelanggan,
   * isi => isi dari kemasan kecil (ambil dari m_barang),
   * iBarangid => spesifik id barang, untuk mempersempit query
  */
  public static function _haveDiscount($pelangganId, $isi = 1, $iBarangId = 0){
    $yrs = date('Y');
    $mth = date('m');

    $where = [
      'a.iPelangganId' 			=> $pelangganId,
      'b.eDisckaryawan' 	=> 'Ya',
      'MONTH(a.tCreated)' 		=> $mth,
      'YEAR(a.tCreated)'  		=> $yrs,
    ];

    // tambah where jika barang id tersedia
    if($iBarangId){
      $where['b.iBarangId'] = $iBarangId;
    }

    $data = TOrderDt::find()
      ->alias('b')
      ->select([
        'b.iBarangId',
        // 't_order_dt.eDisckaryawan',
        // 't_order_dt.iIsiKemasanKecil',
        'SUM(b.iQty) AS total',
        'SUM(b.iQconv) AS totalconv',
      ])
      ->leftJoin('t_order_hd a', 'a.vNoFaktur = b.vNoFaktur')
      ->where($where)
      // ->andWhere(['b.eStatusRelease'=>'Ya'])
      ->andWhere(['not in', 'a.eStatus', ['Batal','Close']]);

      // ->andWhere(['!=', 'a.eStatus', 'Batal']);
      // if($iBarangId){
      //   $data->having(['>=', 'SUM(b.iQconv)', (2 * $isi)]);
      // }
      $data->groupBy(['b.iBarangId']);
      // $data = $data->asArray()->one();
      //
      
    if($iBarangId){
      $res = $data->asArray()->one();
    }else{
      $res = $data->asArray()->all();
    }
    return $res;
  }

  /*
   * perhitungan harga: hna + margin + $ppn
   * hna harus di bagi kemasan kecil dahulu
   * di hitung margin, lalu di jumlahkan
   * baru di kali dengan kemasan kecil lagi
  */
  public static function _hargasatuan($harga, $margin, $isiKemasan = 1){
    $little = $harga / $isiKemasan;
    $fmargin 	= ($little * ($margin / 100));

    $harga_baru = ceil($little + $fmargin);

    $harga_baru = $harga_baru * $isiKemasan;

    $ppn 		= $harga_baru * 0.1;
    // print_r($harga_baru);die;
    $satuan 	= ceil($harga_baru) + ceil($ppn);
    $harga_jual = ceil($harga_baru);


  return [
      'margin' 		=> $fmargin,
      'ppn'	 		=> $ppn,
      'harga_satuan'	=> $satuan,
      'harga_jual'	=> $harga_jual
    ];
  }
}
