<?php

namespace App\Services;

use App\CawanganAR;
use App\ImbangDuga;
use Illuminate\Support\Facades\Http;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class ImbangdugaServices
{

    protected float $tunaiditangan = 0;
    protected float $pembiayaantawarruq = 0;
    protected float $bayaranpendahuluan = 0;
    protected float $pinjamankoop = 0;
    protected float $emaspalsu = 0;
    protected float $serahan = 0;
    protected float $pindahkekpkb = 0;
    protected float $penghutangkaki = 0;
    protected float $phapuskira = 0;
    protected float $belian1stop = 0;
    protected float $keun_penggadai = 0;
    protected float $bds = 0;
    protected float $perubatan = 0;
    protected float $keraian = 0;
    protected float $rugilelong = 0;
    protected float $bakilelong = 0;
    protected float $wtd = 0;
    protected float $untungrugiterkumpul = 0;
    protected float $keun_sebenar = 0;
    protected float $pendahuluan = 0;
    protected float $cajlelong = 0;
    protected float $pend_terakru = 0;
    protected float $cajperkhidmatan = 0;
    protected float $cajlelongxtra = 0;
    protected float $upahsimpan = 0;
    protected float $bakilelongxtra = 0;
    protected float $kerugianlelong = 0;
    protected float $utgterkumpulxtra = 0;
    protected float $jualan1stop = 0;
    protected float $hapuskira = 0;
    protected float $ujrah = 0;
    protected float $onepercent = 0;

    private function SwitchFuncImbangDuga($value = 0.0,$name_variable = null,$tarikh,$kodcaw) : Float{      
        $value = floatval($value);
        switch ($name_variable) {
            case 'tunaiditangan' : 
                if($tarikh >= '2021-04-22' && $tarikh < '2021-05-05'){
                    $advansurharini = Http::get(config('api.url').'/api/advansurharini/' . $kodcaw,['tarikh' => $tarikh])->json();
                    $data = floatval($value) - floatval($advansurharini);
                }else $data = $value;
                
                if($kodcaw == '010219')
                    if($tarikh >= '2022-11-24')
                        $data = $value;
                    else $data = $value;
                else $data = $value;
            break;
            case 'penghutangkaki' : 
                if($kodcaw == '010219')
                    if($tarikh < '2022-11-24')
                        $data = $value - 78379.9;
                    else if($tarikh >= '2023-02-16'){
                            $hutang = Http::get(config('api.url').'/admin/ig/penghutang' ,['kodcaw' => $kodcaw, 'tarikh' => $tarikh])->json();
                            $bayaran_hutang = Http::get(config('api.url').'/admin/ig/bayaran_penghutang' ,['kodcaw' => $kodcaw, 'tarikh' => $tarikh])->json();
                            $data = $hutang['bakihutang'] - $bayaran_hutang;
                    }else $data = $value;
                    //else $data = $value;
                else $data = $value;
            break;
            case 'jualan1stop':
                $data = ($kodcaw === '1STOP') ? floatval(129857.00) : 0;
              break;
            case 'belian1stop':
                $data = ($kodcaw === '1STOP') ? floatval(122446.50) : 0;
              break;
            case 'utgterkumpulxtra':
                $data = ($kodcaw === '1STOP') ? floatval(6727.10) : $value;
              break;
            case 'rugilelongxtra':
                $data = ($kodcaw === '1STOP') ? floatval(-10079.30) : -($value);
            break;
            case 'bakilelongxtra':
                $data = ($kodcaw === '1STOP') ? floatval(123.20) : $value;
            break;
            case 'cajlelongxtra':
                $data = ($kodcaw === '1STOP') ? floatval(25.50) : 0;
            break;
            case 'upahsimpanxtra':
                $data = ($kodcaw === '1STOP') ? floatval(4894.40) : $value;
            break;
            case null:
                $data = 0;
            break;
            default:
                $data = $value;
            break;
          }

          return floatval($data);
    }

    private function InsertImbangDugaBackup($tarikh,$kodcaw,$sum_harta = 0.0,$sum_tanggungan = 0.0,$tagtally = 0) : String{

        $insert_imbangduga_backup = Http::get(config('api.url'). '/admin/laporan/akrual/insertImbangDuga',[
            'tarikh' => $tarikh,
            'kodcaw' => $kodcaw,
            'tunaiditangan' => ($this->tunaiditangan) ? $this->tunaiditangan : 0,
            'pembiayaantawarruq' => ($this->pembiayaantawarruq) ? $this->pembiayaantawarruq : 0,
            'bayaranpendahuluan' => ($this->bayaranpendahuluan) ? $this->bayaranpendahuluan : 0,
            'pinjamankoop' => ($this->pinjamankoop) ? $this->pinjamankoop : 0,
            'emaspalsu' => ($this->emaspalsu) ? $this->emaspalsu : 0,
            'serahan' => ($this->serahan) ? $this->serahan : 0,
            'bds' => ($this->bds) ? $this->bds : 0,
            'perubatan' => ($this->perubatan) ? $this->perubatan : 0,
            'keraian' => ($this->keraian) ? $this->keraian : 0,
            'rugilelong' => ($this->rugilelong) ? $this->rugilelong : 0,
            'bakilelong' => ($this->bakilelong) ? $this->bakilelong: 0,
            'wtd' => ($this->wtd) ? $this->wtd : 0,
            'untungrugiterkumpul' => ($this->untungrugiterkumpul) ? $this->untungrugiterkumpul : 0,
            'keun_sebenar' => ($this->keun_sebenar) ? $this->keun_sebenar : 0,
            'pendahuluan' => ($this->pendahuluan) ? $this->pendahuluan : 0,
            'cajlelong' => ($this->cajlelong) ? $this->cajlelong : 0,
            'pindahkekpkb' => ($this->pindahkekpkb) ? $this->pindahkekpkb : 0,
            'penghutangkaki' => ($this->penghutangkaki) ? $this->penghutangkaki : 0,
            'phapuskira' => ($this->phapuskira) ? $this->phapuskira : 0,
            'belian1stop' => ($this->belian1stop) ? $this->belian1stop : 0,
            'keun_penggadai' => ($this->keun_penggadai) ? $this->keun_penggadai : 0,
            'pend_terakru' => ($this->pend_terakru) ? $this->pend_terakru : 0,
            'cajperkhidmatan' => ($this->cajperkhidmatan) ? $this->cajperkhidmatan : 0,
            'cajlelongxtra' => ($this->cajlelongxtra) ? $this->cajlelongxtra : 0,
            'upahsimpanxtra' => ($this->upahsimpan) ? $this->upahsimpan : 0,
            'bakilelongxtra' => ($this->bakilelongxtra) ? $this->bakilelongxtra : 0,
            'rugilelongxtra' => ($this->kerugianlelong) ? $this->kerugianlelong : 0,
            'utgterkumpulxtra' => ($this->utgterkumpulxtra) ? $this->utgterkumpulxtra : 0,
            'jualan1stop' => ($this->jualan1stop) ? $this->jualan1stop : 0,
            'hapuskira' => ($this->hapuskira) ? $this->hapuskira : 0,
            'ujrah' => ($this->ujrah) ? $this->ujrah : 0,
            'onepercent' => ($this->onepercent) ? $this->onepercent : 0,
            'totalharta' => $sum_harta,
            'totaltanggungan' => $sum_tanggungan,
            'tagtally' => $tagtally,
        ])->json();

        if($insert_imbangduga_backup == 'success')
            return 'successful';
        else
            return 'error';
    }

    public function OperationImbangDuga($kodcaw){
        $current = Carbon::now();
        $current = new Carbon();
        
        $tarikh = $current->toDateString();
        $yesterday = Carbon::now()->subDays(1)->toDateString();
        
        $imbangdugadata = ImbangDuga::orderBy('glcode')->get();
        $array_harta = [];
        $array_tanggungan = [];
        $summation_harta = 0;
        $summation_tanggungan = 0;

        $penyelarasan = CawanganAR::select('penyelarasan')->where('kodcaw',$kodcaw)->get()->toArray();
        $penyelarasan = $penyelarasan[0];

        foreach($imbangdugadata as $index => $imbangdugaiteration){
            if($imbangdugaiteration->api_redirect != null){
                if($imbangdugaiteration['variable'] == 'keun_sebenar' || $imbangdugaiteration['variable'] == 'pend_terakru'){
                    // ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'],['tarikh' => $tarikh,'kodcaw' => $kodcaw])->json();
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'],['tarikh' => ($imbangdugaiteration['variable'] == 'pend_terakru') ? $tarikh : $yesterday,'kodcaw' => $kodcaw])->json();
                }else{
                    // ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'] . $kodcaw,['tarikh' => $tarikh])->json();
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'] . $kodcaw,['tarikh' => ($imbangdugaiteration['variable'] == 'keun_penggadai' || $imbangdugaiteration['variable'] == 'onepercent' || $imbangdugaiteration['variable'] == 'ujrah') ? $tarikh : $yesterday])->json();
                }

                if(is_object($imbangdugaiteration)) $data = ($imbangdugaiteration->is_array == 1) ? ${$imbangdugaiteration['variable']}[$imbangdugaiteration['single_var']] : ${$imbangdugaiteration['variable']};
                $data = ($imbangdugaiteration->neg_values == 1) ? $data = -1 * abs($data) : $data;
                $data = ($imbangdugaiteration['variable'] == 'untungrugiterkumpul') ? $data + $penyelarasan['penyelarasan'] : $data;
            }else $data = 0;

            $data = $this->SwitchFuncImbangDuga($data,$imbangdugaiteration['variable'],$tarikh,$kodcaw);

            /* declare for protected above */
            if($imbangdugaiteration->is_array == 1){
                $nama = $imbangdugaiteration['single_var'];
                if($imbangdugaiteration['variable'] == 'bakilelongxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }else if($imbangdugaiteration['variable'] == 'utgterkumpulxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }
                $this->$nama = $data;
            }else $this->{$imbangdugaiteration['variable']} = $data;
            

            if($imbangdugaiteration->jenis == 'harta'){
                $summation_harta += $data;
                array_push($array_harta,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }else{
                $summation_tanggungan += $data;
                array_push($array_tanggungan,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }
        }

        $tagtally = (number_format($summation_harta,2) == number_format($summation_tanggungan,2)) ? 1 : 0;
        $response = $this->InsertImbangDugaBackup($yesterday,$kodcaw,$summation_harta,$summation_tanggungan,$tagtally);

        if($response == 'successful'){
            return response('succesful');
        }else{
            return response('error');
        }
    }

    public function ViewImbangDugaAROS($kodcaw,$tarikh){
        
        $tarikh = new Carbon($tarikh);
        $tarikh = $tarikh->toDateString();

        $imbangdugadata = ImbangDuga::orderBy('glcode')->get();
        $array_harta = [];
        $array_tanggungan = [];
        $summation_harta = 0;
        $summation_tanggungan = 0;

        $penyelarasan = CawanganAR::select('penyelarasan')->where('kodcaw',$kodcaw)->get()->toArray();
        $penyelarasan = $penyelarasan[0];

        foreach($imbangdugadata as $index => $imbangdugaiteration){
            if($imbangdugaiteration->api_redirect != null){
                if($imbangdugaiteration['variable'] == 'keun_sebenar' || $imbangdugaiteration['variable'] == 'pend_terakru'){
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'],['tarikh' => $tarikh,'kodcaw' => $kodcaw])->json();
                }else{
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'] . $kodcaw,['tarikh' => $tarikh])->json();
                }

                if(is_object($imbangdugaiteration)) $data = ($imbangdugaiteration->is_array == 1) ? ${$imbangdugaiteration['variable']}[$imbangdugaiteration['single_var']] : ${$imbangdugaiteration['variable']};
                $data = ($imbangdugaiteration->neg_values == 1) ? $data = -1 * abs($data) : $data;
                $data = ($imbangdugaiteration['variable'] == 'untungrugiterkumpul') ? $data + $penyelarasan['penyelarasan'] : $data;
            }else $data = 0;
            
            $data = $this->SwitchFuncImbangDuga($data,$imbangdugaiteration['variable'],$tarikh,$kodcaw);

            /* declare for protected above */
            if($imbangdugaiteration->is_array == 1){
                $nama = $imbangdugaiteration['single_var'];
                if($imbangdugaiteration['variable'] == 'bakilelongxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }else if($imbangdugaiteration['variable'] == 'utgterkumpulxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }
                $this->$nama = $data;
            }else $this->{$imbangdugaiteration['variable']} = $data;
            

            if($imbangdugaiteration->jenis == 'harta'){
                $summation_harta += $data;
                array_push($array_harta,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }else{
                $summation_tanggungan += $data;
                array_push($array_tanggungan,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }

        }

        $array_ig = ['array_harta' => $array_harta,'array_tanggungan' => $array_tanggungan,'sum_harta' => $summation_harta,'sum_tanggungan' => $summation_tanggungan];
        return response($array_ig);
    }

    public function GetImbangDugaBackup($kodcaw,$tarikh){

        $date = date_create_from_format('j-m-Y', $tarikh);
        $new_date = date_format($date, 'Y-m-d');

        $response = Http::get(config('api.url'). '/api/Backup/ImbangDuga/' . $kodcaw,['tarikh' => $new_date])->json();

        if($response == 'notfound' || $response == null)
        {
            return response('notfound');
        }else{
            $array_harta = [];
            $array_tanggungan = [];
            foreach($response as $variable=>$res)
            {
                if($variable !== 'recno' && $variable !== 'kodcaw' && $variable !== 'tarikh' && $variable !== 'totalharta' && $variable !== 'totaltanggungan' && $variable !== 'tagtally' && $variable !== 'created_at' && $variable !== 'updated_at'){
                    $imbangdugadata = ImbangDuga::orderBy('glcode')->where('variable',$variable)->orWhere('single_var',$variable)->first()->toArray();
                    if($imbangdugadata['jenis'] == 'harta'){
                        array_push($array_harta,['glcode' => $imbangdugadata['glcode'],'descpt' => $imbangdugadata['descpt'],'amaun' => $res]);
                    }else{
                        array_push($array_tanggungan,['glcode' => $imbangdugadata['glcode'],'descpt' => $imbangdugadata['descpt'],'amaun' => $res]);
                    }
                }
            }


	    uasort($array_harta, array($this,'glcode_compare'));
	    uasort($array_tanggungan, array($this,'glcode_compare'));

            $array_all = ['array_harta' => $array_harta,'array_tanggungan' => $array_tanggungan,'sum_harta' => $response['totalharta'],'sum_tanggungan' => $response['totaltanggungan']];
            return response($array_all);
        }
        
    }

    private static function glcode_compare($a, $b) {
        return strcmp($a['glcode'], $b['glcode']);
    }

    public function OperationImbangDugaByDate($kodcaw,$tarikh){
        $current = new Carbon($tarikh);
        
        $tarikh = $current->toDateString();

        $imbangdugadata = ImbangDuga::orderBy('glcode')->get();
        $array_harta = [];
        $array_tanggungan = [];
        $summation_harta = 0;
        $summation_tanggungan = 0;

        $penyelarasan = CawanganAR::select('penyelarasan')->where('kodcaw',$kodcaw)->get()->toArray();
        $penyelarasan = $penyelarasan[0];

        foreach($imbangdugadata as $index => $imbangdugaiteration){
            if($imbangdugaiteration->api_redirect != null){
                if($imbangdugaiteration['variable'] == 'untungrugiterkumpul' || $imbangdugaiteration['variable'] == 'keun_sebenar' || $imbangdugaiteration['variable'] == 'pend_terakru'){
                    if($imbangdugaiteration['variable'] == 'keun_sebenar' || $imbangdugaiteration['variable'] == 'keun_penggadai'){
                        ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'],['tarikh' => $tarikh,'kodcaw' => $kodcaw])->json();
                    }else
                        ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). '/admin/laporan/akrual/getImbangDugaBackupData',['tarikh' => $tarikh,'kodcaw' => $kodcaw,'data_name' => $imbangdugaiteration['variable']])->json();

                }elseif($imbangdugaiteration['variable'] == 'onepercent' || $imbangdugaiteration['variable'] == 'ujrah'){
                    // ${$imbangdugaiteration['variable']} = 0;
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'] . $kodcaw,['tarikh' => $tarikh])->json();

                }else{
                    ${$imbangdugaiteration['variable']} = Http::get(config('api.url'). $imbangdugaiteration['api_redirect'] . $kodcaw,['tarikh' => $tarikh])->json();
                }

                if(is_object($imbangdugaiteration)) $data = ($imbangdugaiteration->is_array == 1) ? ${$imbangdugaiteration['variable']}[$imbangdugaiteration['single_var']] : ${$imbangdugaiteration['variable']};
                $data = ($imbangdugaiteration->neg_values == 1) ? $data = -1 * abs($data) : $data;
                $data = ($imbangdugaiteration['variable'] == 'untungrugiterkumpul') ? $data : $data;
            }else $data = 0;

            $data = $this->SwitchFuncImbangDuga($data,$imbangdugaiteration['variable'],$tarikh,$kodcaw);

            /* declare for protected above */
            if($imbangdugaiteration->is_array == 1){
                $nama = $imbangdugaiteration['single_var'];
                if($imbangdugaiteration['variable'] == 'bakilelongxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }else if($imbangdugaiteration['variable'] == 'utgterkumpulxtra'){
                    $nama = $imbangdugaiteration['variable'];
                }
                $this->$nama = $data;
            }else $this->{$imbangdugaiteration['variable']} = $data;
            

            if($imbangdugaiteration->jenis == 'harta'){
                $summation_harta += $data;
                array_push($array_harta,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }else{
                $summation_tanggungan += $data;
                array_push($array_tanggungan,['variable' => ($imbangdugaiteration->is_array == 1) ? $imbangdugaiteration->single_var : $imbangdugaiteration->variable,'glcode' => $imbangdugaiteration->glcode, 'descpt' => $imbangdugaiteration->descpt,'amaun' => ($data) ? $data : 0]);
            }
        }

        $tagtally = (number_format($summation_harta,2) == number_format($summation_tanggungan,2)) ? 1 : 0;
        // dd($summation_harta,$summation_tanggungan,$array_harta,$array_tanggungan,$tagtally,$kodcaw);
        $response = $this->UpdateImbangDugaBackupByDate($tarikh,$kodcaw,$summation_harta,$summation_tanggungan,$tagtally);

        if($response == 'successful'){
            return response('succesful');
        }else{
            return response('error');
        }
    }

    private function UpdateImbangDugaBackupByDate($tarikh,$kodcaw,$sum_harta = 0.0,$sum_tanggungan = 0.0,$tagtally = 0) : String{

        $update_imbangduga_backup = Http::get(config('api.url'). '/admin/laporan/akrual/updateImbangDugaRefined',[
            'tarikh' => $tarikh,
            'kodcaw' => $kodcaw,
            'tunaiditangan' => ($this->tunaiditangan) ? $this->tunaiditangan : 0,
            'pembiayaantawarruq' => ($this->pembiayaantawarruq) ? $this->pembiayaantawarruq : 0,
            'bayaranpendahuluan' => ($this->bayaranpendahuluan) ? $this->bayaranpendahuluan : 0,
            'pinjamankoop' => ($this->pinjamankoop) ? $this->pinjamankoop : 0,
            'emaspalsu' => ($this->emaspalsu) ? $this->emaspalsu : 0,
            'serahan' => ($this->serahan) ? $this->serahan : 0,
            'bds' => ($this->bds) ? $this->bds : 0,
            'perubatan' => ($this->perubatan) ? $this->perubatan : 0,
            'keraian' => ($this->keraian) ? $this->keraian : 0,
            'rugilelong' => ($this->rugilelong) ? $this->rugilelong : 0,
            'bakilelong' => ($this->bakilelong) ? $this->bakilelong: 0,
            'wtd' => ($this->wtd) ? $this->wtd : 0,
            'untungrugiterkumpul' => ($this->untungrugiterkumpul) ? $this->untungrugiterkumpul : 0,
            'keun_sebenar' => ($this->keun_sebenar) ? $this->keun_sebenar : 0,
            'pendahuluan' => ($this->pendahuluan) ? $this->pendahuluan : 0,
            'cajlelong' => ($this->cajlelong) ? $this->cajlelong : 0,
            'pindahkekpkb' => ($this->pindahkekpkb) ? $this->pindahkekpkb : 0,
            'penghutangkaki' => ($this->penghutangkaki) ? $this->penghutangkaki : 0,
            'phapuskira' => ($this->phapuskira) ? $this->phapuskira : 0,
            'belian1stop' => ($this->belian1stop) ? $this->belian1stop : 0,
            'keun_penggadai' => ($this->keun_penggadai) ? $this->keun_penggadai : 0,
            'pend_terakru' => ($this->pend_terakru) ? $this->pend_terakru : 0,
            'cajperkhidmatan' => ($this->cajperkhidmatan) ? $this->cajperkhidmatan : 0,
            'cajlelongxtra' => ($this->cajlelongxtra) ? $this->cajlelongxtra : 0,
            'upahsimpanxtra' => ($this->upahsimpan) ? $this->upahsimpan : 0,
            'bakilelongxtra' => ($this->bakilelongxtra) ? $this->bakilelongxtra : 0,
            'rugilelongxtra' => ($this->kerugianlelong) ? $this->kerugianlelong : 0,
            'utgterkumpulxtra' => ($this->utgterkumpulxtra) ? $this->utgterkumpulxtra : 0,
            'jualan1stop' => ($this->jualan1stop) ? $this->jualan1stop : 0,
            'hapuskira' => ($this->hapuskira) ? $this->hapuskira : 0,
            'ujrah' => ($this->ujrah) ? $this->ujrah : 0,
            'onepercent' => ($this->onepercent) ? $this->onepercent : 0,
            'totalharta' => $sum_harta,
            'totaltanggungan' => $sum_tanggungan,
            'tagtally' => $tagtally,
        ])->json();

        if($update_imbangduga_backup == 'success')
            return 'successful';
        else
            return 'error';
    }



}
