<?php

namespace App\Http\Controllers;

//Events
use App\Events\StatusLiked;
use App\Events\NotifikasiPembayaran;
use App\Events\Dashboard\GadaiNotify;
use App\Events\SerahanPenilai;


use Illuminate\Http\Request;
use App\Services\CustomerService;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Http\Controllers\AliranTunaiController;
use App\User;

class GadaianController extends Controller
{
    public $AliranTunaiController;
    public $customerService;

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

    public function index(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);
        $noic = $request->noic;
        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $noic)->json();
        $customer_info = $customers_info;
        $limit_pinjaman_semasa = 0;
        $auth_user = Auth::user();
        if($request->session()->get('page_reload') == null){
            $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);
            $norujukan = strtoupper($auth_user['cawangan']) . $curent_year . $curent_month . $current_day . '-' .$new_transaction;
            Session::put('norujukan',$norujukan);
            Session::put('nokp',$noic);
            Session::put('nopelanggan',$customer_info['nopelanggan']);
            Session::put('page_reload',true);
            $gadai = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url').'/api/gadai/'.$auth_user['cawangan'],[
                'norujukan' => $norujukan,
                'nopelanggan' => $customer_info['nopelanggan'],
                'nokp' => $noic,
                'sirig' => $new_sirig
            ]);
        }else{
            $norujukan = Session::get('norujukan');
            $nokp = Session::get('nokp');
            $nopelanggan = Session::get('nopelanggan');
            $gadai_session = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/check/sag',['kodcaw'=>$auth_user['cawangan'],'norujukan'=>$norujukan,'nokp'=>$nokp])->json();
            if($gadai_session == null){
                $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);
                $norujukan_baru = strtoupper($auth_user['cawangan']) . $curent_year . $curent_month . $current_day . '-' .$new_transaction;
                Session::put('norujukan',$norujukan_baru);
                Session::put('nokp',$nokp);
                Session::put('nopelanggan',$nopelanggan);
                Session::put('page_reload',true);
                $gadai_baru = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url') .'/api/gadai/'.$auth_user['cawangan'],[
                    'norujukan' => $norujukan_baru,
                    'nopelanggan' => $nopelanggan,
                    'nokp' => $nokp,
                    'sirig' => $new_sirig
                ]);
                $norujukan = $norujukan_baru;
            }
        }


        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        return view('gadaian.' . $cawangan_info['version'] . '.index',compact('customer_info','limit_pinjaman_semasa','cawangan_info','norujukan','api_url','current'));
    }

    public function edit(Request $request,$norujukan){

        $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);
        // dd($current_day);


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

        if(sizeof($gadaiannorujukan) != 0)
            $gadaiannorujukan = $gadaiannorujukan[0][0];

        $noic = $request->noic;
        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadaiannorujukan['nokp'])->json();
        $customer_info = $customers_info;

        $limit_pinjaman_semasa = 0;
        $auth_user = Auth::user();

        $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        return view('gadaian.' . $cawangan_info['version'] . '.edit',compact('customer_info','gadaiannorujukan','limit_pinjaman_semasa','cawangan_info','norujukan','api_url'));
    }

    public function editmarhun(Request $request){

        $api_url = config('api.url');

        $auth_user = Auth::user();

        $gadaiannorujukan = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url') . '/api/gadai/edit/marhun/'. $auth_user['cawangan'] . '/' . $request->norujukan,[
            "recno" => $request->recno
        ])->json();

        return $gadaiannorujukan;
    }

    public function ubahmarhun(Request $request){

        $api_url = config('api.url');

        $auth_user = Auth::user();

        $gadaiannorujukan = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url') . '/api/gadai/ubah/marhun/'. $auth_user['cawangan'] . '/' . $request->norujukedit,[
            'recno' => $request->recno,
            'karat' => $request->sltkarat,
            'berat' => $request->berat,
            'harga' => $request->harga1,
            'n_marhun' => $request->nilaimarhun

        ])->json();

        return redirect()->back();
    }

    public function store(Request $request){
        $auth_user = Auth::user();
        //$total_nilai_marhun = $request->total_nilai_marhun;
        //need to get total nilai marhun by api get from table marhun
        $marhun = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/marhun/gadai/'. $auth_user['cawangan'] .'/'. $request->norujukan_gadai)->json();
        $total_nilai_marhun = $marhun;
        $total_nilai_marhun = str_replace(',','',$total_nilai_marhun);
        $keuntungan_sebln = $request->keuntungan_sebulan;
        $keuntungan_sebln = str_replace(',','',$keuntungan_sebln);
        $onepercent = $request->onepercent;
        $ujrah = $request->ujrah;

        $margin_pinjaman = $request->pinjaman / $total_nilai_marhun;
        $kadarupah = $request->kadarkeuntungan * 100;
        $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'] .'/' . $request->norujukan_gadai,[
            '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,
            'transaction' => 'Daftar Gadai',
            'kadarujrah' => round($kadarupah, 2),
            'ujrah' => $ujrah,
            'onepercent' => $onepercent,
            'margin_semasa' => $margin_pinjaman,
        ])->json();


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

        $this->AliranTunaiController->alirantunaiGadai($request,$auth_user['name']);

        event(new GadaiNotify('lulus',$auth_user['cawangan']));

        $request->session()->forget('page_reload');
        $request->session()->forget('norujukan');
        $request->session()->flash('activate_tab', 'SAG_baru');

        return redirect()->route('customer_info');
    }

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

        $total_nilai_marhun = $request->total_nilai_marhun;
        $total_nilai_marhun = str_replace(',','',$total_nilai_marhun);
        $keuntungan_sebln = $request->keuntungan_sebulan;
        $keuntungan_sebln = str_replace(',','',$keuntungan_sebln);
        $onepercent = $request->onepercent;
        $ujrah = $request->ujrah;

        $margin_pinjaman = $request->pinjaman / $total_nilai_marhun;
        // dd($margin_pinjaman);
        $kadarupah = $request->kadarkeuntungan * 100;
        $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'] .'/' . $request->norujukan_gadai,[
            '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,
            'transaction' => 'Ubah Gadai',
            'kadarujrah' => round($kadarupah, 2),
            'ujrah' => $ujrah,
            'onepercent' => $onepercent,
            'margin_semasa' => $margin_pinjaman,
        ])->json();
        $update_komuditi = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/komuditi/update',[
            'unit_komuditi' => round($request->pinjaman, 2),
            'norujukan' => $request->norujukan_gadai
        ])->json();

        event(new GadaiNotify('lulus',$auth_user['cawangan']));

        $request->session()->forget('page_reload');
        $request->session()->forget('norujukan');
        return redirect()->route('customer_info');
    }

    public function batal(Request $request){
        $norujukan = $request->norujukan;
        $auth_user = Auth::user();

        Http::withOptions(['verify' => config('app.api_verify')])->delete(config('api.url').'/api/gadai/batal/'. $auth_user['cawangan'] .'/' . $norujukan);
        $request->session()->forget('page_reload');
        $request->session()->forget('norujukan');
        return redirect()->route('customer_info');
    }

    public function batalmarhun(Request $request){
        $norujukan = $request->norujukan;
        $auth_user = Auth::user();


        // Http::withOptions(['verify' => config('app.api_verify')])->delete(config('api.url').'/api/gadai/batal/'. $auth_user['cawangan'] .'/' . $norujukan);
        // $request->session()->forget('page_reload');
        // $request->session()->forget('norujukan');
        // return redirect()->route('customer_info');
    }

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

        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/norujukan/cetak/'.$auth_user['cawangan'].'/'.$request->norujukan_modal);

        return redirect()->route('home');
    }

    public function serahMarhun(Request $request){
        $auth_user = Auth::user();
        $norujukan_serah = $request->norujukanpilih;

        $arraynorujukan = explode(",",$norujukan_serah);

        $results=array_search("",$arraynorujukan,true);
        if($results !== false) {
            unset($arraynorujukan[$results]);
        }

        foreach($arraynorujukan as $index=>$norujukan){
            $gadai = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url'). '/api/gadai/norujukan/serah/'. $auth_user['cawangan'] .'/'. $norujukan);

            if($gadai->failed()){
                break;
            }
        }

        event(new SerahanPenilai($auth_user['cawangan'],"LULUS"));

        return redirect()->route('home');
    }

    public function printSAG(Request $request){
        $norujukan = $request->norujukan_modal;
        $auth_user = Auth::user();
        $auth_username = $auth_user['name'];
        $kodcaw = $auth_user['cawangan'];
        $api_url = config('api.url');

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

        if(isset($request->jenisprint))
        {

        $cetak_sag = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url').'/api/gadai/norujukan/cetak/'.$auth_user['cawangan'].'/'.$norujukan,[
            'penilai' => $auth_user['name']
        ]);

        }
        
        $kakitangan = User::where([['role_harian','khazanah'],['cawangan',$kodcaw]])->first();
        // dd($kakitangan);
 
        $customer = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai_detail['nokp'])->json();
        $customer_detail = $customer;

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

        $mutu = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url'). '/api/marhun/mutu/sag',[
            'kodcaw' => $auth_user['cawangan'],
            'norujukan' => $norujukan
        ])->json();

        // dd($mutu);

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

        $cawangan_detail = $cawangan[0];

        $kadar_ujrah = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/kadarujrah/by_group_id/', [
            'kodcaw' => $cawangan_detail['kodcaw']
        ])->json();

        // $pembayaran_segera = "https://spare.arrahn.com.my/pembayaransegera";
        $pembayaran_segera = "https://pay.arrahn.com.my";

        $komoditi = Http::withOptions(['verify' => config('app.api_verify')])
        ->get($api_url . '/api/komuditi/check')
        ->json();
        $product = Http::withOptions(['verify' => config('app.api_verify')])
        ->get($api_url . '/api/komuditi/description', ['kodproduk' => $komoditi['kodproduct']])
        ->json();
        $kuantiti = $gadai_detail['pinjaman'] / $komoditi['nilai'];

        if ($gadai_detail['tagbaru'] == 1) {
            return view('print.sag_ujrah_3', compact('komoditi', 'product', 'kuantiti', 'gadai_detail', 'customer_detail', 'marhun_detail', 'cawangan_detail', 'api_url', 'pembayaran_segera', 'auth_username', 'mutu', 'kadar_ujrah','kakitangan'));
        } else {
            return view('print.sag', compact('gadai_detail', 'customer_detail', 'marhun_detail', 'cawangan_detail', 'api_url', 'pembayaran_segera', 'auth_username', 'mutu','kakitangan'));
        }
    }

    public function resit($id)
    {
        $auth_user = Auth::user();
        $totaltransaction = 0;

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

        if(sizeof($transaction) != 0)
            $transaction = $transaction[0];

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

        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        // $customers_info = $customers_info[0];

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

        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];

        if($gadai['tagbaru'] == 1) {
            return view('print.resitansuran_ujrah',compact('transaction','gadai','customers_info','wakil'));
        } else {
            return view('print.resitansuran',compact('transaction','gadai','customers_info','wakil'));
            // return view('print.resittebus',compact('transaction','gadai','cawangan_info','customers_info','penebusan','wakil','totaltransaction','totalBayaranAnsuran'));
        }
    }

    public function resitansurans($id)
    {
        $auth_user = Auth::user();
        $totaltransaction = 0;

        $transaction = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/one/'. $id)->json();


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

        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];

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

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

        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];

        if($gadai['tagbaru'] == 1) {
            return view('print.resitansuran_ujrah',compact('transaction','gadai','customers_info','wakil'));
        } else {
            return view('print.resitansuran',compact('transaction','gadai','customers_info','wakil'));
            // return view('print.resittebus',compact('transaction','gadai','cawangan_info','customers_info','penebusan','wakil','totaltransaction','totalBayaranAnsuran'));
        }
    }

    public function resitbelumansurans($id)
    {

        $auth_user = Auth::user();
        // $totaltransaction = 0;

        // if(sizeof($transaction) != 0)
        //     $transaction = $transaction[0];

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

        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        // $customers_info = $customers_info[0];

        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'],[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

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

        // dd($wakil);
        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];

        return view('print.resitansuransebelum',compact('gadai','customers_info','wakil','penebusan'));
    }

    public function resittebusseparuh($id)
    {

        $auth_user = Auth::user();

        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $id)->json();
        $transaction_tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/one/'. $id)->json();

        $totaltransaction = 0;

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

        foreach($transaction as $trans)
        {
                $totaltransaction += $trans['duit_masuk'];
        }

        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];


        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'],[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

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

        // dd($wakil);
        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];

        $totalBayaranAnsuran = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/norujukan/total/ansuran',['norujukan'=>$id])->json();
        $khazanah_user = User::where('role_harian', 'khazanah')->where('cawangan', $auth_user['cawangan'])->select('name')->first();
        $totalrebate = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/reports/totalrebate',['norujukan'=>$id])->json();
    

        return view('print.resit.tebus_separuh',compact('totalrebate','khazanah_user','totalBayaranAnsuran','transaction_tebus','gadai','customers_info','penebusan','wakil'));
    }

    public function resitautotawarruq($id)
    {

        $auth_user = Auth::user();

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

        $totaltransaction = 0;

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

        foreach($transaction as $trans)
        {
                $totaltransaction += $trans['duit_masuk'];
        }

        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        $transaction_keuntungan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url'). '/api/transaksi_keuntungan_latest/'. $id)->json();
        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];

        $transaction_tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/one/'. $id)->json();

        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'],[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

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

        // dd($wakil);
        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];

        $khazanah_user = User::where('role_harian', 'khazanah')->where('cawangan', $auth_user['cawangan'])->select('name')->first();

        return view('print.resittebusautotawarruq',compact('transaction_tebus', 'transaction','gadai','customers_info','penebusan','wakil','totaltransaction','transaction_keuntungan', 'khazanah_user'));
    }

    public function resittebus($id)
    {

        $auth_user = Auth::user();

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

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

        $totaltransaction = 0;

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

        $transaction_tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/one/'. $id)->json();

        foreach($transaction as $trans)
        {
                $totaltransaction += $trans['duit_masuk'];
        }


        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'. $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];


        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'],[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

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

        $totalBayaranAnsuran = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/norujukan/total/ansuran',['norujukan'=>$id])->json();

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

        // dd($wakil);
        $surat_wakil = [];
        if(sizeof($wakil) != 0) {
            $wakil = $wakil[0];
            $surat_wakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getsuratwakil/' . $auth_user['cawangan'] . '/' . $id)->json();
        }

        $khazanah_user = User::where('role_harian', 'khazanah')->where('cawangan', $auth_user['cawangan'])->select('name')->first();

        if($gadai['tagbaru'] == 1) {
            return view('print.resittebus_ujrah',compact('surat_wakil','totalrebate','transaction_tebus', 'transaction','gadai','cawangan_info','customers_info','penebusan','wakil','totaltransaction','totalBayaranAnsuran', 'khazanah_user'));
        } else {
            return view('print.resittebus',compact('surat_wakil', 'transaction_tebus', 'transaction','gadai','cawangan_info','customers_info','penebusan','wakil','totaltransaction','totalBayaranAnsuran', 'khazanah_user'));
        }
    }

    public function resitbelumtebus($id)
    {

        $auth_user = Auth::user();

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


        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'.  $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];


        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'] ,[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

        // dd($penebusan['nowakil']);

        if($penebusan['nowakil'] != 0)
        {
        $wakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getwakil/' . $auth_user['cawangan']  . '/code/' . $penebusan['nowakil'])->json();

        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];
        }
        else
        {
            $wakil = [];
        }

        return view('print.resittebussebelum',compact('gadai','customers_info','penebusan','wakil'));
    }

    public function resitadvansur($id)
    {

        $auth_user = Auth::user();

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


        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'.  $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];

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

        if($advansur['nowakil'] != 0){
            $wakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getwakil/' . $auth_user['cawangan']  . '/code/' . $advansur['nowakil'])->json();

            if(sizeof($wakil) != 0){
                $wakil = $wakil[0];
            }
        }
        else
        {
            $wakil = [];
        }

        return view('print.resitadvansur',compact('gadai','customers_info','advansur','wakil'));
    }

    public function resittambahpinjam($id)
    {

        $auth_user = Auth::user();

        $gadai = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $id)->json();
        $transaction_tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/one/'. $id)->json();


        if(sizeof($gadai) != 0)
            $gadai = $gadai[0][0];

        $customers_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/customers/'.  $gadai['nokp'])->json();

        // if(sizeof($customers_info) != 0)
        //     $customers_info = $customers_info[0];


        $penebusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/' . $auth_user['cawangan'] ,[ "norujukan" => $id])->json();

        if(sizeof($penebusan) != 0)
            $penebusan = $penebusan[0];

        // dd($penebusan['nowakil']);

        if($penebusan['nowakil'] != 0)
        {
        $wakil = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/getwakil/' . $auth_user['cawangan']  . '/code/' . $penebusan['nowakil'])->json();

        if(sizeof($wakil) != 0)
            $wakil = $wakil[0];
        }
        else
        {
            $wakil = [];
        }

        $totalBayaranAnsuran = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/transaction/norujukan/total/ansuran',['norujukan'=>$id])->json();
        $khazanah_user = User::where('role_harian', 'khazanah')->where('cawangan', $auth_user['cawangan'])->select('name')->first();
        $totalrebate = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/reports/totalrebate',['norujukan'=>$id])->json();

        return view('print.resit.tambah_pinjaman',compact('totalrebate','khazanah_user','totalBayaranAnsuran','transaction_tebus','gadai','customers_info','penebusan','wakil'));
    }

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

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

        if(sizeof($gadai) > 0)
        {
            $history = $gadai[0][0]['historygadaian'];
            $dahtebus = $gadai[0][0]['sttebus'];
            $norujukan = $gadai[0][0]['norujukan'];

        }

        $count = 0;
        $arrayhist = [];

        while($history != "0" && $history != '' || $dahtebus == 'T')
        {
            if($history != "0" && $history != '')
            {
                $gadai = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $history)->json();
                $tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/'. $auth_user['cawangan'],[
                        "norujukan" => $history
                ])->json();

                if(sizeof($gadai) > 0)
                {
                    if($history == $gadai[0][0]['historygadaian'])
                        $history = 0;
                    else{
                        array_push($arrayhist,["historygadaian" => ((isset($gadai[0][0]['historygadaian'])) ? $gadai[0][0]['historygadaian'] : 0),"tagbaru" => ((isset($gadai[0][0]['tagbaru'])) ? $gadai[0][0]['tagbaru'] : 0),"hargajualan" => ((isset($gadai[0][0]['hargajualan'])) ? $gadai[0][0]['hargajualan'] : ''), "pinjaman" => ((isset($tebus[0])) ? $tebus[0]['pinjaman'] : 0),"norujukan" => $history,"jenistebus" => ((isset($tebus[0])) ? $tebus[0]['jenistebus'] : 0),"jbg" => ((isset($tebus[0])) ? $tebus[0]['jbg'] : 0),"t_tebus" => ((isset($tebus[0])) ? $tebus[0]['t_tebus'] : 0)]);
                        $history = $gadai[0][0]['historygadaian'];
                    }
                }

            $count++;

            }
            else{
                $gadai = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadai/norujukan/'. $norujukan)->json();
                $tebus = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/listpenebusanhistory/'. $auth_user['cawangan'],[
                        "norujukan" => $norujukan
                ])->json();


                array_push($arrayhist,["historygadaian" => ((isset($gadai[0][0]['historygadaian'])) ? $gadai[0][0]['historygadaian'] : 0),"tagbaru" => ((isset($gadai[0][0]['tagbaru'])) ? $gadai[0][0]['tagbaru'] : 0), "hargajualan" => ((isset($gadai[0][0]['hargajualan'])) ? $gadai[0][0]['hargajualan'] : ''),"pinjaman" => ((isset($tebus[0])) ? $tebus[0]['pinjaman'] : 0),"norujukan" => $norujukan,"jenistebus" => ((isset($tebus[0])) ? $tebus[0]['jenistebus'] : 0),"jbg" => ((isset($tebus[0])) ? $tebus[0]['jbg'] : 0),"t_tebus" => ((isset($tebus[0])) ? $tebus[0]['t_tebus'] : 0)]);
                break;
            }
        }

        return response()->json($arrayhist,200);
    }

    /// KELULUSAN///

    public function getkelulusan(Request $request)
    {
        $auth_user = Auth::user();
        $api_url = config('api.url');

        $norujukan = $request->norujukan;

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

        $kelulusan = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/GetLulus/' . $auth_user['cawangan'],[
            "norujukan" => $norujukan
        ])->json();

        if(sizeof($kelulusan) > 0)
        {
            $kelulusan = $kelulusan['benar'];
        }
        else
        {
            $kelulusan = '';
        }

        return response($kelulusan);
    }

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

        $api_url = config('api.url');

        $norujukan = $request->norujukan;

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

        $updatelulus = Http::withOptions(['verify' => config('app.api_verify')])->put(config('api.url') . '/api/UpdateKelulusan/kepohonan/' . $auth_user['cawangan'] . '/' . $norujukan)->json();

        return response()->json($updatelulus,200);
    }

    public function createkelulusan(Request $request)
    {
        $auth_user = Auth::user();
        $api_url = config('api.url');

        $norujukan = $request->norujukan;

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

        $pinjaman = ($gadai_info[0][0]['pinjaman']) ? $gadai_info[0][0]['pinjaman'] : '-';
        $nilaimarhun = ($gadai_info[0][0]['nilaimarhun']) ? $gadai_info[0][0]['nilaimarhun'] : '-';
        $berat = ($gadai_info[0][0]['berat']) ? $gadai_info[0][0]['berat'] : '-';
        $percentpinj = ($gadai_info[0][0]['percentpinj']) ? $gadai_info[0][0]['percentpinj'] : '-';

        $createlulus = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url') . '/api/CreateLulus/' . $auth_user['cawangan'] . '/' . $norujukan, [
            'mohon' => $request->mohon,
            'pinjaman' => $pinjaman,
            'nilaimarhun' => $nilaimarhun,
            'berat' => $berat,
            'margin' => $percentpinj,
            'teller' => $auth_user['name']
        ])->json();

        event(new StatusLiked($auth_user['cawangan'],$auth_user['name']));

        return response()->json($createlulus,201);
    }

    ///END KELULUSAN///

}
