<?php
/**
 * Created by thomas Maya Graha Kencana.
 * Date: 12/04/18
 * Time: 20:30
 */
define('MODUL_URL', base_url() . url_segment(1) . "/".url_segment(2) ."/".url_segment(3));
define('MODUL_PATH', base_url() . url_segment(1) . "/");
define('MODUL_CONFIG_PATH', "../../modules/" . url_segment(1) . "/config/");
define('MODUL_TEMPLATE_PATH', "application/modules/" . url_segment(1) . "/");
/* ---------------------------------------------------------------------
 * domain untuk web admin
 * ---------------------------------------------------------------------*/
//define('ADM_DOMAIN', 'https://boga.mayagrahakencana.com');
define('ADM_DOMAIN', 'https://demo.mayagrahakencana.com/new_m88');
//define('ADM_DOMAIN', 'https://demo.mayagrahakencana.com/tho_boga');
define('ADM_LOCAL_DOMAIN', 'https://mm88.mgk.com');
/* ---------------------------------------------------------------------
 * -digunakan pada heAPI untuk mendefine domain aPI---
 * ---------------------------------------------------------------------*/
define('EXT_DOMAIN', ADM_DOMAIN);

function apiDiskonProduk(){
    //        "saveFreeProduk" => ADM_DOMAIN . "/eusvc/proDiskon/saveFreeProduk",
    $url = array(
        "saveFreeProduk" => ADM_DOMAIN."/eusvc/proDiskon/saveFreeProduk",
    );

    return $url;
}

function url_segment($key = "")
{
    //    return "kekeke $key";
    $ci = &get_instance();
    if($key == ""){
        return $ci->uri->segment_array();
    }
    else{

        return $ci->uri->segment($key);
    }
}

function modul(){
    return url_segment(1);
}

function url_cleanup ($url_e){
    $var = str_replace("=","",$url_e);
    return $var;
}

function url_referer()
{
    if (isset($_SERVER['HTTP_REFERER'])) {
        return $_SERVER['HTTP_REFERER'];
    }
}

function ipadd(){
    return $_SERVER['REMOTE_ADDR'];
}

function local_version()
{
    return "1.0.6-sumber-boga-local";
}

function cdn_upload_images()
{
//    return "https://cdn.mayagrahakencana.com/images/Upload/files";
    return base_url()."cdn/images/Upload/files";
}

function cdn_suport()
{
    return base_url()."cdn/";
}

function local_suport()
{
    return base_url() . "assets/";
}

function img_produk()
{
    return base_url() . "public/images/produks/";
}

function img_profile()
{
    return base_url() . "public/images/profiles";
}

function img_sys()
{
    return base_url() . "public/images/sys";
}

function img_blank()
{
    // return base_url(). "assets/images/img_blank.gif";
    return base_url() . "public/images/produks/img_blank.png";
}

function img_maintenace()
{
    // return base_url(). "assets/images/img_blank.gif";
    return base_url() . "public/images/sys/under-maintenance.png";
}

function img_construction()
{
    return base_url() . "public/images/sys/under-construction.png";
}

function img_working()
{
    return base_url() . "public/images/sys/the-Lumber-jack.gif";
}

function img_logo_header(){

    return img_profile() . "/logo_header.png";
}

function img_logo_header_full()
{

    return img_profile() . "/logo_header.png";
}

function img_favicon(){

    return img_profile() . "/favicon.ico";
}

//function url_sanhistory()
//{
//    return "https://sanhistory.mayagrahakencana.com/";
//    // return "http://boga.mayagrahakencana.com/san/";
//}

function upload_image($files)
{
    // $files = $_FILES['file'];

    $request = curl_init(cdn_upload_images());
    $realpath = realpath($files['tmp_name']);
    curl_setopt($request, CURLOPT_POST, true);
    $fields = array(
        //tested di centos
        'file' => new \CurlFile($realpath, $files['type'], $files['name']),
        //tested di ubuntu
//        'file'          => "@".$realpath.";filename=".$files['name'].";type=".$files['type'],
        'server_source' => $_SERVER['HTTP_HOST'],
    );
    curl_setopt($request, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    $cUrl_result = json_decode(curl_exec($request));
    curl_close($request);

    return $cUrl_result;

    /* =========================
    $url_img = $cUrl_result->full_url;
    // ========================= */
}

function download_tpl($tpl_name)
{
    $vars = array(
        "customer" => "tpl_konsumen.xlsx",
        "produk" => "tpl_produk.xlsx",
        "bahan" => "tpl_bahan_baku.xlsx",
        "komposisi" => "tpl_produk_komposisi_resep.xlsx",
    );
    $tpl_file = $vars[$tpl_name];

    return base_url()."download/$tpl_file";
}

function detectMachineID(){
    $file = __DIR__ . "/MachineID";
    if( file_exists($file) ){
        $myfile = fopen($file, "r") or die("Unable to open file!");
        $string = fread($myfile,filesize($file));
        fclose($myfile);
        $arrDatas = explode("\r", $string);
        return preg_replace('/[^A-Za-z0-9\.]/i', '', trim($arrDatas[1]));
    }
    else{
        return "no-machineID";
    }
}

if(detectMachineID()!='no-machineID'){
    define('MACHINE_ID', detectMachineID() );
}
else{
    define('MACHINE_ID', "no-machineID" );
}

function detectCpuINFO(){
    $file = __DIR__ . "/cpuINFO";
    if( file_exists($file) ){
        $myfile = fopen($file, "r") or die("Unable to open file!");
        $string = fread($myfile,filesize($file));
        fclose($myfile);
        $arrDatas = explode("\r", $string);
        return preg_replace('/[^A-Za-z0-9\.]/i', '', trim($arrDatas[1]));
    }
    else{
        return "no-cpuINFO";
    }
}

if(detectCpuINFO()!='no-cpuINFO'){
    define('CPU_INFO', detectCpuINFO() );
}
else{
    define('CPU_INFO', "no-cpuINFO" );
}

function detectComINFO(){
    $file = __DIR__ . "/com";
    if( file_exists($file) ){
        $myfile = fopen($file, "r") or die("Unable to open file!");
        $string = fread($myfile,filesize($file));
        fclose($myfile);
        $arrDatas = explode("\r", $string);
        return preg_replace('/[^A-Za-z0-9\.]/i', '', trim($arrDatas[1]));
    }
    else{
        return "no-comINFO";
    }
}

if(detectComINFO()!='no-COM_INFO'){
    define('COM_INFO', detectComINFO() );
}
else{
    define('COM_INFO', "no-COM_INFO" );
}

function checkSaldoKas(){

    $dateNow = date("Y-m-d");
//    $dateNow = date("Y-m-d", strtotime( '-1 days', strtotime( date("Y-m-d") )) );

    $ci = &get_instance();

    $arrLogin = $ci->session->login;

    $saldoNow=array();
    if($arrLogin!=null){
        if($arrLogin['jenis']=="admin"){
            $ci->db->select("id,transaksi_jenis,oleh_id,oleh_nama,nomer,fulldate,transaksi_nilai");
            $ci->db->where(array('link_id'=>0, "settlement_id"=>1 ));
            $ci->db->where("fulldate = '$dateNow'");
            $ci->db->where("jenis = '582'");
            $ci->db->order_by("id", "DESC");
            $ci->db->limit(0);
            $saldoNow = $ci->db->get('transaksi')->result();
        }
        else{
            $ci->db->select("id,transaksi_jenis,oleh_id,oleh_nama,nomer,fulldate,transaksi_nilai");
//            $ci->db->where(array('link_id'=>0, "settlement_id"=>1, "oleh_id"=> $arrLogin['id'] ));
            $ci->db->where(array('link_id'=>0, "settlement_id"=>1 ));
            $ci->db->where("fulldate = '$dateNow'");
            $ci->db->where("jenis = '582'");
            $ci->db->order_by("id", "DESC");
            $ci->db->limit(0);
            $saldoNow = $ci->db->get('transaksi')->result();
        }
    }

    $saldo_kas_now = 0;
    $tmp_by_kasir_now = array();
    $tmp_data_total_now = array();
    if(!empty($saldoNow)){

        foreach($saldoNow as $k => $val){
            $saldo_kas_now += $val->transaksi_nilai*1;
            if(!isset($tmp_by_kasir_now[$val->oleh_id])){
                $tmp_by_kasir_now[$val->oleh_id] = array();
            }
            if(!isset($tmp_by_kasir_now[$val->oleh_id]['nota'])){
                $tmp_by_kasir_now[$val->oleh_id]['nota'] = 0;
            }
            if(!isset($tmp_by_kasir_now[$val->oleh_id]['data'])){
                $tmp_by_kasir_now[$val->oleh_id]['data'] = array();
            }
            if(!isset($tmp_by_kasir_now[$val->oleh_id]['saldo'])){
                $tmp_by_kasir_now[$val->oleh_id]['saldo'] = 0;
            }
            if(!isset($tmp_by_kasir_now[$val->oleh_id]['data'][$val->fulldate])){
                $tmp_by_kasir_now[$val->oleh_id]['data'][$val->fulldate] = 0;
            }

            $tmp_by_kasir_now[$val->oleh_id]['nota'] += 1;

            if($arrLogin!=null&&$arrLogin['jenis']=="admin"){
                $tmp_by_kasir_now[$val->oleh_id]['details'][] = $val;
            }
            $tmp_by_kasir_now[$val->oleh_id]['data'][$val->fulldate] += $val->transaksi_nilai;
            $tmp_by_kasir_now[$val->oleh_id]['oleh_nama'] = $val->oleh_nama;
            $tmp_by_kasir_now[$val->oleh_id]['saldo'] += $val->transaksi_nilai;

        }

        $tmp_data_total_now['saldo_kas'] = $saldo_kas_now*1;
        $tmp_data_total_now['data_by_seller'] = $tmp_by_kasir_now;
        $tmp_data_total_now['query'] = $ci->db->last_query();

    }

    $ci->db->select("id,transaksi_jenis,oleh_id,oleh_nama,nomer,fulldate,transaksi_nilai");
    $ci->db->where(array('link_id'=>0, "settlement_id"=>1));
    $ci->db->where("fulldate < '$dateNow'");
    $ci->db->where("jenis = '582'");
    $ci->db->order_by("id", "DESC");
    $ci->db->limit(0);
    $saldo = $ci->db->get('transaksi')->result();

    $saldo_kas = 0;
    $tmp_by_kasir = array();
    $tmp_data_total = array();
    if( !empty($saldo) ){

        foreach($saldo as $k => $val){
            $saldo_kas += $val->transaksi_nilai*1;
            if(!isset($tmp_by_kasir[$val->oleh_id])){
                $tmp_by_kasir[$val->oleh_id] = array();
            }
            if(!isset($tmp_by_kasir[$val->oleh_id]['nota'])){
                $tmp_by_kasir[$val->oleh_id]['nota'] = 0;
            }
            if(!isset($tmp_by_kasir[$val->oleh_id]['data'])){
                $tmp_by_kasir[$val->oleh_id]['data'] = array();
            }
            if(!isset($tmp_by_kasir[$val->oleh_id]['saldo'])){
                $tmp_by_kasir[$val->oleh_id]['saldo'] = 0;
            }
            if(!isset($tmp_by_kasir[$val->oleh_id]['data'][$val->fulldate])){
                $tmp_by_kasir[$val->oleh_id]['data'][$val->fulldate] = 0;
            }

            $tmp_by_kasir[$val->oleh_id]['nota'] += 1;

            if($arrLogin!=null&&$arrLogin['jenis']=="admin"){
                $tmp_by_kasir[$val->oleh_id]['details'][] = $val;
            }

            $tmp_by_kasir[$val->oleh_id]['data'][$val->fulldate] += $val->transaksi_nilai;
            $tmp_by_kasir[$val->oleh_id]['oleh_nama'] = $val->oleh_nama;
            $tmp_by_kasir[$val->oleh_id]['saldo'] += $val->transaksi_nilai;

        }

        $tmp_data_total['saldo_kas'] = $saldo_kas*1;
        $tmp_data_total['data_by_seller'] = $tmp_by_kasir;
        $tmp_data_total['query'] = $ci->db->last_query();

//        $result = array(
//            "status" => 0,
//            "reason" => "ada saldo gantung",
//            "yesterday" => $tmp_data_total,
//            "today" => $tmp_data_total_now,
//            "login" => $arrLogin,
//        );
//
////        echo( json_encode($result) );
//        return $result;
    }

    if( isset($tmp_data_total['saldo_kas']) && $tmp_data_total['saldo_kas']*1> 0 ){

        $result = array(
            "status" => 0,
            "reason" => "ada saldo gantung",
            "yesterday" => $tmp_data_total,
            "today" => $tmp_data_total_now,
            "login" => $arrLogin,
        );
        return $result;

    }
    else{

        $my_id = $arrLogin['id'];
        $my_saldo = isset($tmp_data_total_now['data_by_seller']) ? $tmp_data_total_now['data_by_seller'] : array();
        $nilai_saldo = isset($tmp_data_total_now['saldo_kas']) ? $tmp_data_total_now['saldo_kas'] : 0;

        if( $nilai_saldo*1>0 && !isset($my_saldo[$my_id]) ){
            $result = array(
                "status" => 0,
                "reason" => "ada saldo gantung",
                "yesterday" => $tmp_data_total,
                "today" => $tmp_data_total_now,
                "login" => $arrLogin,
                "nilai_saldo" => $nilai_saldo,
                "my_id" => $my_id,
            );
            return $result;
        }
        else{
            $result = array(
                "status" => 1,
                "reason" => "tidak ada saldo gantung",
                "login" => $ci->session->login,
//                "nilai_saldo" => $nilai_saldo,
//                "my_saldo[my_id]" => $my_saldo[$my_id],
//                "tmp_data_total" => $tmp_data_total,
//                "saldo" => $saldo,
            );
            return $result;
        }

    }

//    else{
//
//        $result = array(
//            "status" => 1,
//            "reason" => "tidak ada saldo gantung",
//            "login" => $ci->session->login,
//        );
//
////        echo( json_encode($result) );
//        return $result;
//    }

}

function phantomJs($nomer='582-TLXC-0005-0141-0005',$modul='penjualan',$jenistr='582'){

    //https://boga.mgk.com/penjualan/Printing/viewSmallReceipt/582/582-TLXC-0005-0141-0005?mobMode=0&st=2
//        $filename = __DIR__ . "/NonRest/" . $namaFile;

    $machine_id = detectMachineID();

    $app         = "C:\\xampp\\phantomjs.exe";
    $command     = "C:\\xampp\\phantomjs\\rasterize2.js";

    $https_url = base_url();

    $custom_link = $https_url . "$modul/Printing/viewSmallReceipt/$jenistr/$nomer";

    $ukuran      = "200px";
    $zoom        = "1";
    $aux        = "--debug=yes --ignore-ssl-errors=true --ssl-protocol=any --web-security=true";

    $this_Yea = date("Y");
    $this_Bul = date("m");
    $this_Day = date("d");

    $__DIR__ = "C:\\xampp\\htdocs\\boga\\application\\controllers\\eusvc//NonRest//";

    if (!file_exists($__DIR__ . "/NonRest/$modul")) {
        $oldmask = umask(0);
        mkdir(__DIR__ . "/NonRest/$modul", 0777, true);
        umask($oldmask);
    }

    if (!file_exists($__DIR__ . "/NonRest/$modul/$this_Yea")) {
        $oldmask = umask(0);
        mkdir($__DIR__ . "/NonRest/$modul/$this_Yea", 0777, true);
        umask($oldmask);
    }
    if (!file_exists($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul")) {
        $oldmask = umask(0);
        mkdir($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul", 0777, true);
        umask($oldmask);
    }
    if (!file_exists($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul/$this_Day")) {
        $oldmask = umask(0);
        mkdir($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul/$this_Day", 0777, true);
        umask($oldmask);
    }
    if (!file_exists($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul/$this_Day/".$machine_id)) {
        $oldmask = umask(0);
        mkdir($__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul/$this_Day/".$machine_id, 0777, true);
        umask($oldmask);
    }

    $output      = $__DIR__ . "/NonRest/$modul/$this_Yea/$this_Bul/$this_Day/". $machine_id ."/".$nomer.".pdf";

//        $ee = shell_exec("$app $aux '$command' '$custom_link' '$output' $ukuran $zoom");
    $ee = exec("$app $aux $command $custom_link $output $ukuran $zoom");

    $result = array(
        "exec" => $ee,
        "exec_command" => "$app $aux $command $custom_link $output $ukuran $zoom",
//            "app" => $app,
//            "aux" => $aux,
//            "command" => $command,
//            "custom_link" => $custom_link,
//            "output" => $output,
//            "ukuran" => $ukuran,
//            "zoom" => $zoom,
    );

    echo json_encode($result);
}

function list_update_table(){

    $arrList = array(
        "produk"               => "perubahan produk",
        "price"                => "perubahan harga",
        "price_last_purchase"  => "perubahan harga last purchase",
        "price_per_area"       => "perubahan harga area",
        "satuan_produk_relasi" => "perubahan relasi produk satuan",
        "satuan"               => "perubahan satuan",
        "diskon"               => "perubahan diskon",
        "diskon_customer"      => "perubahan diskon",
        "produk_folders"       => "perubahan kategori produk",
        "per_cabang"           => "perubahan cabang",
        "per_cabang_device"    => "perubahan device cabang",
        "per_customer_level"   => "perubahan diskon level",
        "per_customers"        => "perubahan data konsumen",
        "bank"                 => "perubahan akun bank",
        "company_profile"      => "perubahan data perusahaan",
        "setting_struk"        => "perubahan setingan struk",
        "fifo_avg"             => "perubahan hpp",

        // "_rek_pembantu_customer_cache"     => "sal point kons",
        // "__rek_pembantu_customer__2010050" => "mut point kons",
        // "__raw_rek_pembantu__1010040050"   => "COBA ADD TABLE",
        // "acc_coa"                          => "perubahan data coa",
        // "per_employee"                     => "perubahan akun karyawan",

    );

    return $arrList;
}