<?php

namespace App\Http\Controllers;

//Events
use App\Events\Dashboard\TebusNotify;
use App\Events\Dashboard\KeuntunganNotify;
use App\Events\Dashboard\GadaiNotify;
use App\Events\SerahanPenilai;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\AliranTunaiController;
use Illuminate\Support\Facades\Log;

use Carbon\Carbon;

class PenebusanController extends Controller
{

    protected $AliranTunaiController;

    public function __construct()
    {
        $this->middleware('auth');
        $this->AliranTunaiController = New AliranTunaiController();

    }

    public function index($norujukan){
        $auth_user = Auth::user();
        $api_url = config('api.url');
        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();

        $gadaidetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $norujukan)->json();
        $noic = $gadaidetail[0][0]['nokp'];
        $customerdetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $noic)->json();
        $marhundetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $norujukan)->json();

        $marhun = $marhundetail[0];
        $nama = $customerdetail['nama'];

        $gadai = $gadaidetail[0][0];

        $nilaihargasemasa = $this->tukaranhargaemas($norujukan);

        $pertambahpinjaman = 0.80;
        return view('penebusan.' . $cawangan_info['version'] . '.index',compact('cawangan_info','api_url','gadai','marhun','nama','nilaihargasemasa','pertambahpinjaman'));
    }

    public function tebuspenuh(Request $request)
    {
        $api_url = config('api.url');

        $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updatetebus/'. $request->kodcaw .'/' . $request->norujukan,[
            "nopelanggan" => $request->nopelanggan,
            "jenistebus" => $request->jenistebus,
            "jbg" => $request->jbg,
            "kadarupah" => $request->kadarupah,
            "nilai_marhun" => $request->nilai_marhun,
            "pinjaman" => $request->pinjaman,
            "ansuran" => $request->ansuran,
            "addpinjaman" => $request->addpinjaman,
            "bakipinjaman" => $request->bakipinjaman,
            "bakiupah" => $request->bakiupah,
            "historygadaian" => $request->historygadaian,
            "marhun" => $request->marhun,
            "nowakil" => $request->nowakil,
            "jenisbayarantebus" => $request->jenisbayarantebus,
            "teller" => $request->teller,
            'jeniskeuntungan' => $request->jeniskeuntungan,
            "duitpelanggan" => $request->duitpelanggan,
            "bakipelanggan" => $request->bakipelanggan
        ])->json();

        if($updatetebus)
        {
            event(new TebusNotify('lulus',Auth::user()->cawangan));

            return response('success');
        }else{
            return response('fail');
        }
    }

    public function bayaransuransTawarruq(Request $request)
    {
        $api_url = config('api.url');

        $updategadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadaikaunter/'. $request->kodcaw .'/norujukan/' . $request->norujukan,[
            'bayaran' => $request->bayaran,
            'teller' => $request->teller,
            'nowakil' => $request->nowakil,
            'duitpelanggan' => $request->duitpelanggan,
            'bakipelanggan' => $request->bakipelanggan,
            'jeniskeuntungan' => $request->jeniskeuntungan
        ])->json();

        if($updategadai == 'success')
        {
            $getTunai2=Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url').'/api/GetCurrentTunai/'.$request->kodcaw,['kodlaluan' => $request->teller])->json();

            $keluar=$getTunai2['keluar'];
            $baki=$getTunai2['baki'];
            $masuk=$getTunai2['masuk'];
            $bakiawal=$getTunai2['bakiawal'];
            $pendahuluan=$getTunai2['tambah'];
            $serahan=$getTunai2['kurang'];
            $totalmasuk = 0;
            $bakiakhir = 0;

            $totalmasuk = $request->bayaran + $masuk;

            // $bakiakhir = $bakiawal-$keluar+$totalmasuk+$pendahuluan-$serahan;
            $bakiakhir = $baki + $request->bayaran;

            // // Add on 20210411
            // $gadaidetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $request->kodcaw.'/'.$request->norujukan)->json();
            // $tempohGadai=$gadaidetail[0]['tempoh'];
            // $upah12bulan=$gadaidetail[0]['upah12'];
            // $bakiPinjaman=$gadaidetail[0]['bakipjm'];
            // $teller=$gadaidetail[0]['teller'];
            // $upah6bulan= $upah12bulan/2;                   //add on 202104011
            // $tempoh_bayar=$gadaidetail[0]['tempohbayar']; //add on 202104011
            // $tarikhgadai=$gadaidetail[0]['t_gadai'];//Add on 20210411

            //masuk dalam tunai aliran
            $updateTunai=Http::withOptions(['verify' => config('app.api_verify')])->put( config('api.url').'/api/updateTunaiGT/'.$request->kodcaw, [
                'kodlaluan' => $request->teller,
                'keluar' => $keluar,
                'masuk' => $totalmasuk,
                'bakiakhir' => $bakiakhir
            ])->json();

            event(new KeuntunganNotify('lulus',Auth::user()->cawangan));

            return response()->json($updategadai,200);

        }else{
            return response('error');
        }

    }

    public function bayaransurans(Request $request)
    {
        $api_url = config('api.url');
        $current = Carbon::now();
        $current = new Carbon();
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

        $auth_user = Auth::user();

        ////////////////////////
       /// UPDATE TEBUS API////
       ///////////////////////
       $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updatetebus/'. $auth_user['cawangan'] .'/' . $request->norujukan,[
            'nopelanggan' => $request->nopelanggan,
            'jenistebus' => $request->jenistebus,
            'jbg' => $request->jbg,
            'kadarupah' => $request->kadarupah,
            'nilai_marhun' => $request->nilai_marhun,
            'pinjaman' => $request->pinjaman,
            'ansuran' => $request->ansuran,
            'addpinjaman'=> $request->addpinjaman,
            'bakipinjaman' => $request->bakipinjaman,
            'bakiupah' => $request->bakiupah,
            'nowakil' => $request->nowakil,
            'historygadaian' => $request->historygadaian,
            'marhun' => $request->marhun,
            'jenisbayarantebus' => $request->jenisbayarantebus,
            'teller' => $request->teller
        ])->json();

        //////////////////////
       /// MAKING NEW SAG////
       /////////////////////
       $gadai_transaction = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/'. $auth_user['cawangan'] . '/' . $current->toDateString())->json();
       if($gadai_transaction){
           $new_sirig = $gadai_transaction['sirig'] + 1;

       }else{
           $new_sirig = 1;
       }

       $new_transaction = sprintf("%04d",$new_sirig);
       $norujukanbaru = strtoupper($auth_user['cawangan']) . $curent_year . $curent_month . $current_day . '-' .$new_transaction;

       // dd($norujukan);
       $gadai = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/gadai/'.$auth_user['cawangan'],[
           'norujukan' => $norujukanbaru,
           'nopelanggan' => $request->nopelanggan,
           'nokp' => $request->noic,
           'sirig' => $new_sirig
       ]);

      //////////////////////
      ////Update SAG BARU///
      /////////////////////

      $total_nilai_marhun = $request->nilai_marhun;
      $margin_pinjaman = $request->pinjaman / $total_nilai_marhun;
      $kadarupah = $request->kadarkeuntungan * 100;
      $keuntungan6bulan = $request->keuntungan_6bln;
      $keuntungan12bulan = $request->keuntungan_sebulan*12;
      $hargajualan = $request->pinjaman + $keuntungan12bulan;


      $gadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/norujukan/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
          'kodcaw' => $auth_user['cawangan'],
          'nilaimarhun' => round($total_nilai_marhun, 2),
          'berat' => round($request->total_berat, 2),
          'pinjaman' => round($request->pinjaman, 2),
          'kadarupah' => round($kadarupah, 2),
          'marhun' => $request->marhun,
          'percentpinj' => $margin_pinjaman,
          'teller'=> $auth_user['name'],
          'upah6' => $keuntungan6bulan,
          'upah12' => $keuntungan12bulan,
          'hargajualan' => $hargajualan,
          'kuantiti_marhun' => $request->kuantiti_marhun
      ])->json();


        ////////////////////////////
       ////Update History Gadaian///
       ////////////////////////////

       $updatehistorygadaian = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/updatehistory/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
        'historygadaian' => $request->norujukan
        ])->json();


        ///////////////////////////
       /// MARHUN UPDATE TABLE////
       //////////////////////////


       $arraymarhunbaru = [];

       $marhunsediada = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $request->norujukan)->json();

       $marhunyangdiambil = $marhunsediada[0];
       foreach($marhunyangdiambil as $index=>$marhunloop)
       {
            array_push($arraymarhunbaru, ["bil" => $marhunloop['bil'],"marhun" => $marhunloop['marhun'],"nota" => $marhunloop['nota'],"karat" => $marhunloop['karat'], "berat" => $marhunloop['berat'], "harga" => $marhunloop['harga'], "n_marhun" => $marhunloop['n_marhun']]);
       }

       foreach($arraymarhunbaru as $array1)
        {
            $updatemarhun = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/marhun/'. $auth_user['cawangan'],[
            'norujukan' => $norujukanbaru,
            'marhun' => $array1['marhun'],
            'nota' => $array1['nota'],
            'karat' => $array1['karat'],
            'berat_emas' => $array1['berat'],
            'harga' => $array1['harga'],
            'nilai_marhun' => $array1['n_marhun'],
	    'kuantiti' => $array1['bil']
        ])->json();

        }

    }

    public function tambahpinjaman(Request $request)
    {
        $api_url = config('api.url');
        $current = Carbon::now();
        $current = new Carbon();
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

        $auth_user = Auth::user();


        ////////////////////////
       /// UPDATE TEBUS API////
       ///////////////////////
        $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updatetebus/'. $auth_user['cawangan'] .'/' . $request->norujukan,[
            'nopelanggan' => $request->nopelanggan,
            'jenistebus' => $request->jenistebus,
            'jbg' => $request->jbg,
            'kadarupah' => $request->kadarupah,
            'nilai_marhun' => $request->nilai_marhun,
            'pinjaman' => $request->pinjaman_lama,
            'ansuran' => $request->ansuran,
            'nowakil' => $request->nowakil,
            'addpinjaman'=> $request->addpinjaman,
            'bakipinjaman' => $request->bakipinjaman,
            'bakiupah' => $request->bakiupah,
            'historygadaian' => $request->historygadaian,
            'marhun' => $request->marhun,
            'jenisbayarantebus' => $request->jenisbayarantebus,
            'jeniskeuntungan' => $request->jeniskeuntungan,
            'teller' => $request->teller,
            "duitpelanggan" => $request->bayaran,
            "bakipelanggan" => $request->bakipelanggan,
        ])->json();

        if($updatetebus == 'duplicate'){
            return response()->json('duplicate');
        }

        //////////////////////
        /// MAKING NEW SAG////
        /////////////////////

        $gadai_transaction = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/'. $auth_user['cawangan'] . '/' . $current->toDateString())->json();
        if($gadai_transaction){
            $new_sirig = $gadai_transaction['sirig'] + 1;

        }else{
            $new_sirig = 1;
        }

        $new_transaction = sprintf("%04d",$new_sirig);
        $norujukanbaru = strtoupper($auth_user['cawangan']) . $curent_year . $curent_month . $current_day . '-' .$new_transaction;

        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/gadai/'.$auth_user['cawangan'],[
            'norujukan' => $norujukanbaru,
            'nopelanggan' => $request->nopelanggan,
            'nokp' => $request->noic,
            'sirig' => $new_sirig
        ]);

        ///////////////////////////
        /// MARHUN UPDATE TABLE////
        //////////////////////////


        $arraymarhunbaru = [];

        $marhunsediada = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $request->norujukan)->json();

        $marhunyangdiambil = $marhunsediada[0];
        foreach($marhunyangdiambil as $index=>$marhunloop)
        {
            $karatbaru = str_replace('.','-',$marhunloop['karat']);
            $hargabaru = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/harga_emas/'. $karatbaru)->json();

            $nilaimarhun = (floatval($hargabaru['harga']) * floatval($marhunloop['berat']));

            array_push($arraymarhunbaru, ["bil" => $marhunloop['bil'],"tag_permata" => $marhunloop['tag_permata'],"berat_batu_permata" => $marhunloop['berat_batu_permata'],"marhun" => $marhunloop['marhun'],"nota" => $marhunloop['nota'],"karat" => $marhunloop['karat'], "berat" => $marhunloop['berat'], "harga" => $hargabaru['harga'], "n_marhun" => $nilaimarhun]);
        }

        foreach($arraymarhunbaru as $array1){
            $updatemarhun = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/marhun/'. $auth_user['cawangan'],[
                'norujukan' => $norujukanbaru,
                'marhun' => $array1['marhun'],
                'nota' => $array1['nota'],
                'karat' => $array1['karat'],
                'berat_emas' => $array1['berat'],
                'harga' => $array1['harga'],
                'tag_permata' => $array1['tag_permata'],
                'berat_batu_permata' => $array1['berat_batu_permata'],
		'kuantiti' => $array1['bil']
            ])->json();
        }



       //////////////////////
      ////Update SAG BARU///
      /////////////////////

        $total_nilai_marhun = $request->nilai_marhun;
        $margin_pinjaman = $request->pinjaman / $total_nilai_marhun;
        $kadarupah = $request->kadarkeuntungan * 100;

        $onepercent = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/onepercent',[
            'pembiayaan' => $request->pinjaman,
            'nilaimarhun' => $total_nilai_marhun,
            'kadarujrah' => $request->kadarkeuntungan,
            'margin' => ($margin_pinjaman*100),
            'kodcaw' => Auth::user()->cawangan
        ])->json();

        $keuntungan_sebln = $onepercent['keuntungan'];
        $keuntungan_sebln = str_replace(',','',$keuntungan_sebln);
        $keuntungan6bulan = $keuntungan_sebln * 6;
        $keuntungan12bulan = $keuntungan_sebln * 12;
        $hargajualan = $request->pinjaman + $keuntungan12bulan;




        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/norujukan/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
            'kodcaw' => $auth_user['cawangan'],
            'nilaimarhun' => round($total_nilai_marhun, 2),
            'berat' => round($request->total_berat, 2),
            'pinjaman' => round($request->pinjaman, 2),
            'kadarupah' => round($kadarupah, 2),
            'marhun' => $request->marhun,
            'percentpinj' => $margin_pinjaman,
            'teller'=> $auth_user['name'],
            'upah6' => $keuntungan6bulan,
            'upah12' => $keuntungan12bulan,
            'hargajualan' => $hargajualan,
            'kuantiti_marhun' => $request->kuantiti_marhun
        ])->json();

        $komuditi = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/komuditi/transaksi',[
            'unit_komuditi' => round($request->pinjaman, 2),
            'norujukan' => $norujukanbaru,
            'kodcaw' => $auth_user['cawangan'],
            'teller' => $auth_user['name']
        ]);

        ////////////////////////////
        ////Update History Gadaian///
        ////////////////////////////

        $updatehistorygadaian = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/updatehistory/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
            'historygadaian' => $request->norujukan,
            'jenistebus' => $request->jenistebus,
        ])->json();


        event(new TebusNotify('lulus',Auth::user()->cawangan));
        event(new GadaiNotify('lulus',Auth::user()->cawangan));
        $this->AliranTunaiController->alirantunaiTebus($request);

    }

    public function tambahpinjaman_latest(Request $request)
    {
        $api_url = config('api.url');
        $current = Carbon::now();
        $current = new Carbon();
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

        $auth_user = Auth::user();


        ////////////////////////
       /// UPDATE TEBUS API////
       ///////////////////////
       $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updatetambahpinjaman/'. $auth_user['cawangan'] .'/' . $request->norujukan,[
            "nopelanggan" => $request->nopelanggan,
            "jenistebus" => $request->jenistebus,
            "jbg" => $request->jbg,
            "kadarupah" => $request->kadarupah,
            "nilai_marhun" => $request->nilai_marhun,
            "pinjamanbaru" => $request->pinjaman,
            "pinjaman" => $request->pinjaman_lama,
            "ansuran" => $request->ansuran,
            "addpinjaman" => $request->addpinjaman,
            "bakipinjaman" => $request->bakipinjaman,
            "bakiupah" => $request->bakiupah,
            "historygadaian" => $request->historygadaian,
            "marhun" => $request->marhun,
            "kuantiti_marhun" => $request->kuantiti_marhun,
            "total_berat" => $request->total_berat,
            "kadarkeuntungan" => $request->kadarkeuntungan,
            "keuntungan_6bln" => $request->keuntungan_6bln,
            "keuntungan_sebulan" => $request->keuntungan_sebulan,
            "noic" => $request->noic,
            "norujukan" => $request->norujukan,
            "jenisbayarantebus" => $request->jenisbayarantebus,
            "jeniskeuntungan" => $request->jeniskeuntungan,
            "teller" => $request->teller,
            "bayaran" => $request->bayaran,
            "bakipelanggan" => $request->bakipelanggan,
            "nowakil" => isset($request->nowakil) ? $request->nowakil : 0
        ])->json();


        if($updatetebus['result'] == 'success'){
            event(new TebusNotify('lulus',Auth::user()->cawangan));
            event(new GadaiNotify('lulus',Auth::user()->cawangan));
            $this->AliranTunaiController->alirantunaiTebus($request);
        }
        return response()->json($updatetebus['result'],200);

    }

    public function tebusautotawarruq(Request $request)
    {
        $auth_user = Auth::user();

        ////////////////////////
       /// UPDATE TEBUS API////
       ///////////////////////
       $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updateautotawarruq/'. $auth_user['cawangan'] .'/' . $request->norujukan,[
            'nopelanggan' => $request->nopelanggan,
            'jenistebus' => $request->jenistebus,
            'jbg' => $request->jbg,
            'kadarupah' => $request->kadarupah,
            'nilai_marhun' => $request->nilai_marhun,
            'pinjaman' => $request->pinjaman_lama,
            'pinjamanbaru' => $request->pinjaman,
            'ansuran' => $request->ansuran,
            'addpinjaman'=> $request->addpinjaman,
            'bakipinjaman' => $request->bakipinjaman,
            'bakiupah' => $request->bakiupah,
            'nowakil' => $request->nowakil,
            'historygadaian' => $request->historygadaian,
            'marhun' => $request->marhun,
            'jenisbayarantebus' => $request->jenisbayarantebus,
            'teller' => $request->teller,
            'jeniskeuntungan' => $request->jeniskeuntungan,
            'totalbayaran' => $request->totalbayaran,
            "duitpelanggan" => $request->bayaran,
            "bakipelanggan" => $request->bakipelanggan,
            "noic" => $request->noic,
            "jenisAT" => $request->jenisAT,
        ])->json();
        if($updatetebus['result'] == 'success'){
            $alirantunai = new AliranTunaiController();
            event(new TebusNotify('lulus',Auth::user()->cawangan));
            event(new GadaiNotify('lulus',Auth::user()->cawangan));
            $alirantunai->alirantunaiTebusAutoTawarruq($request);
        }
        return response()->json($updatetebus['result'],200);
    }

    public function tebusseparuh(Request $request)
    {
        $api_url = config('api.url');
        $current = Carbon::now();
        $current = new Carbon();
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

        $auth_user = Auth::user();

        ////////////////////////
       /// UPDATE TEBUS API////
       ///////////////////////
        $updatetebus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/updatetebus/'. $auth_user['cawangan'] .'/' . $request->norujukan,[
            'nopelanggan' => $request->nopelanggan,
            'jenistebus' => $request->jenistebus,
            'jbg' => $request->jbg,
            'kadarupah' => $request->kadarupah,
            'nilai_marhun' => $request->nilai_marhun,
            'pinjaman' => $request->pinjaman_lama,
            'ansuran' => $request->ansuran,
            'addpinjaman'=> $request->addpinjaman,
            'bakipinjaman' => $request->bakipinjaman,
            'bakiupah' => $request->bakiupah,
            'nowakil' => $request->nowakil,
            'historygadaian' => $request->historygadaian,
            'marhun' => $request->marhun,
            'jenisbayarantebus' => $request->jenisbayarantebus,
            'jeniskeuntungan' => $request->jeniskeuntungan,
            'teller' => $request->teller,
            "duitpelanggan" => $request->bayaran,
            "bakipelanggan" => $request->bakipelanggan,
        ])->json();

        if($updatetebus == 'duplicate'){
            return response()->json('duplicate');
        }

        //////////////////////
       /// MAKING NEW SAG////
       /////////////////////
        $gadai_transaction = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/'. $auth_user['cawangan'] . '/' . $current->toDateString())->json();
        if($gadai_transaction){
            $new_sirig = $gadai_transaction['sirig'] + 1;

        }else{
            $new_sirig = 1;
        }

        $new_transaction = sprintf("%04d",$new_sirig);
        $norujukanbaru = strtoupper($auth_user['cawangan']) . $curent_year . $curent_month . $current_day . '-' .$new_transaction;

        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/gadai/'.$auth_user['cawangan'],[
            'norujukan' => $norujukanbaru,
            'nopelanggan' => $request->nopelanggan,
            'nokp' => $request->noic,
            'sirig' => $new_sirig
        ]);

        ///////////////////////////
       /// MARHUN UPDATE TABLE////
       //////////////////////////


       $arraymarhunbaru = [];

       $arraydiola = $request->arrayrecno;

       $marhunsediada = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $request->norujukan)->json();

       $marhunyangdiambil = $marhunsediada[0];
       foreach($marhunyangdiambil as $index=>$marhunloop)
       {
            if(!in_array($marhunloop['recno'], $arraydiola))
            {
                $karatbaru = str_replace('.','-',$marhunloop['karat']);
                $hargabaru = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/harga_emas/'. $karatbaru)->json();

                $nilaimarhun = (floatval($hargabaru['harga']) * floatval($marhunloop['berat']));

                array_push($arraymarhunbaru, ["bil" => $marhunloop['bil'],"tag_permata" => $marhunloop['tag_permata'],"berat_batu_permata" => $marhunloop['berat_batu_permata'],"marhun" => $marhunloop['marhun'],"nota" => $marhunloop['nota'],"karat" => $marhunloop['karat'], "berat" => $marhunloop['berat'], "harga" => $hargabaru['harga'], "n_marhun" => $nilaimarhun]);
            }
       }

       foreach($arraymarhunbaru as $array1)
        {
            $updatemarhun = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/marhun/'. $auth_user['cawangan'],[
                'norujukan' => $norujukanbaru,
                'marhun' => $array1['marhun'],
                'nota' => $array1['nota'],
                'karat' => $array1['karat'],
                'berat_emas' => $array1['berat'],
                'harga' => $array1['harga'],
                'tag_permata' => $array1['tag_permata'],
                'berat_batu_permata' => $array1['berat_batu_permata'],
                'nilai_marhun' => $array1['n_marhun'],
                'kuantiti' => $array1['bil']
            ])->json();

        }


        //////////////////////
       ////Update SAG BARU///
       /////////////////////

        $total_nilai_marhun = $request->total_nilai_marhun;
        $margin_pinjaman = $request->pinjaman / $total_nilai_marhun;
        $kadarupah = $request->kadarkeuntungan * 100;

        $total_nilai_marhun = $request->total_nilai_marhun;
        $margin_pinjaman = ($request->pinjaman / $total_nilai_marhun);

        $onepercent = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/onepercent',[
            'pembiayaan' => $request->pinjaman,
            'nilaimarhun' => $total_nilai_marhun,
            'kadarujrah' => $request->kadarkeuntungan,
            'margin' => ($margin_pinjaman*100),
            'kodcaw' => Auth::user()->cawangan
        ])->json();

        $keuntungan_sebln = $onepercent['keuntungan'];
        $keuntungan_sebln = str_replace(',','',$keuntungan_sebln);
        $keuntungan6bulan = $keuntungan_sebln * 6;
        $keuntungan12bulan = $keuntungan_sebln * 12;
        $hargajualan = $request->pinjaman + $keuntungan12bulan;


        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/norujukan/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
            'kodcaw' => $auth_user['cawangan'],
            'nilaimarhun' => round($total_nilai_marhun, 2),
            'berat' => round($request->total_berat, 2),
            'pinjaman' => round($request->pinjaman, 2),
            'kadarupah' => round($kadarupah, 2),
            'marhun' => $request->marhun_detail,
            'percentpinj' => $margin_pinjaman,
            'teller'=> $auth_user['name'],
            'upah6' => $keuntungan6bulan,
            'upah12' => $keuntungan12bulan,
            'hargajualan' => $hargajualan,
            'kuantiti_marhun' => $request->kuantiti_marhun
        ])->json();
        
        $komuditi = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/komuditi/transaksi',[
            'unit_komuditi' => round($request->pinjaman, 2),
            'norujukan' => $norujukanbaru,
            'kodcaw' => $auth_user['cawangan'],
            'teller' => $auth_user['name']
        ]);

        ////////////////////////////
       ////Update History Gadaian///
       ////////////////////////////

        $updatehistorygadaian = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/updatehistory/'. $auth_user['cawangan'] .'/' . $norujukanbaru,[
            'historygadaian' => $request->norujukan,
            'jenistebus' => $request->jenistebus,
        ])->json();


        $alirantunai = new AliranTunaiController();
        event(new TebusNotify('lulus',Auth::user()->cawangan));
        event(new GadaiNotify('lulus',Auth::user()->cawangan));

        $alirantunai->alirantunaiTebus($request);


        return response()->json($updatemarhun,200);

    }


    //Wakil Function

    public function getfirstWakil()
    {
        $auth_user = Auth::user();

        $getfirstwakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getwakil/'. $auth_user['cawangan'])->json();

        if(sizeof($getfirstwakil) != 0)
            return $getfirstwakil[0]['nowakil'];
        else
            return $getfirstwakil;
    }


    public function getWakil(Request $request)
    {
        $auth_user = Auth::user();

        $getwakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getwakil/'. $auth_user['cawangan'] . '/' . $request->wakil)->json();

        if(sizeof($getwakil) > 0)
            return $getwakil[0];
        else
            return 'no-data';
    }

    public function createWakil(Request $request)
    {
        $auth_user = Auth::user();

        $createwakil = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url') . '/api/createwakil/'. $auth_user['cawangan'] . '/' . $request->icno,[

            'nopelanggan' => $request->nopelanggan,
            'nowakil' => $request->nowakil,
            'nama' => $request->nama,
            'hubungan' => $request->hubungan,
            'alamat' => $request->alamat,
            'telefon' => $request->telefon,
            'nota' => $request->nota,
            'teller' => $auth_user['name']
 
        ])->json();

        if($createwakil)
            return 1;
        else
            return 0;
    }

    public function tukaranhargaemas($norujukan)
    {

       $marhunsaglama = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $norujukan)->json();

       $marhunsaglama = $marhunsaglama[0];
       $totalnilaimarhun = 0;

       foreach($marhunsaglama as $index=>$marhunloop)
       {
            $karatbaru = str_replace('.','-',$marhunloop['karat']);
            $hargabaru = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/harga_emas/'. $karatbaru)->json();

            $nilaimarhun = (floatval($hargabaru['harga']) * floatval($marhunloop['berat']));

            $totalnilaimarhun += $nilaimarhun;
       }

       return $totalnilaimarhun;
    }

    public function PenebusanKhazanah($norujukan){
        $auth_user = Auth::user();
        $api_url = config('api.url');
        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();

        $gadaidetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $norujukan)->json();
        $noic = $gadaidetail[0][0]['nokp'];
        $customerdetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $noic)->json();
        $marhundetail = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/'. $norujukan)->json();

        $marhun = $marhundetail[0];
        $nama = $customerdetail['nama'];

        $gadai = $gadaidetail[0][0];

        $nilaihargasemasa = $this->tukaranhargaemas($norujukan);

        $view = sprintf('penebusan.%s.index-khazanah', $cawangan_info['version']);
        return view($view, compact('cawangan_info','api_url','gadai','marhun','nama','nilaihargasemasa'));
    }

}
