<?php

namespace App\Support\v1;

use App\Advansur;
use App\Audit;
use App\Cawangan;
use App\KadarUpah;
use App\Support\v2\Calculation;
use Carbon\Carbon;
use App\Gadai;
use App\HargaEmas;
use App\InOutMar;
use App\KomuditiPurchase;
use App\KomuditiTransaksi;
use App\Marhun;
use App\Moratorium;
use App\Palsu;
use App\Pampasan;
use App\Support\OnePercent;
use App\Support\Tawarruq;
use App\Support\v1\Calculation as V1Calculation;
use App\Tebus;
use App\Transaction;
use App\TransaksiKeuntungan;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PDO;

class Penebusan
{
    protected $kodcaw;
    protected $cawangan_info;

    public function __construct(String $kodcaw,Object $cawangan_info){
        $this->kodcaw = $kodcaw;
        $this->cawangan_info = $cawangan_info;
    }

    public function tebusTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $rebet = $this->rebetselepastawarruq($kodcaw,$norujukan);

        $harga_tebus = $gadai_data['bakihargajualan'] - $rebet;

        $hargatebus = bcdiv(round($harga_tebus,2),1,1);
        $hargatebus = number_format($hargatebus,2);
        if(strpos($hargatebus,',')){
            $hargatebus = str_replace(',','',$hargatebus);
        }

        return response()->json($hargatebus);
    }

    public function hargaTebusTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $rebet = $this->rebetselepastawarruq($kodcaw,$norujukan);

        $harga_tebus = $gadai_data['bakihargajualan'] - $rebet;

        $hargatebus = bcdiv(round($harga_tebus,2),1,1);
        $hargatebus = number_format($hargatebus,2);
        if(strpos($hargatebus,',')){
            $hargatebus = str_replace(',','',$hargatebus);
        }

        return $hargatebus;
    }

    public function kiraupahTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }
        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];

        $upahsemasa_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['pinjaman']);

        $upah_semasa_round = number_format($upahsemasa_raw,2);
	    if(strpos($upah_semasa_round,',')){
            $upah_semasa_round = str_replace(',','',$upah_semasa_round);
        }
        $upah_semasa = substr($upah_semasa_round, 0, -1);
	    if(strpos($upah_semasa,',')){
            $upah_semasa = str_replace(',','',$upah_semasa);
        }

        return $upah_semasa;
    }

    public function kiraUpahRebet($norujukan){
        $cawangan = $this->cawangan_info;

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }

        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];

        $upahrebet_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['bakipjm']);

        $upah_rebet_round = number_format($upahrebet_raw,2);
	    if(strpos($upah_rebet_round,',')){
            $upah_rebet_round = str_replace(',','',$upah_rebet_round);
        }
        $upah_rebet = substr($upah_rebet_round, 0, -1);
	    if(strpos($upah_rebet,',')){
            $upah_rebet = str_replace(',','',$upah_rebet);
        }

        return $upah_rebet;
    }

    public function kiraUpahRebetSebenar($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }

        $bilang_bln = $gadai_data['tempoh'] - $gadai_data['tempohbayar'];

        $upahrebet_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['bakipjm']);

        // $upah_rebet = round($upahrebet_raw,PHP_ROUND_HALF_UP);
        $upah_rebet_round = number_format($upahrebet_raw,2);
	    if(strpos($upah_rebet_round,',')){
            $upah_rebet_round = str_replace(',','',$upah_rebet_round);
        }
        $upah_rebet = substr($upah_rebet_round, 0, -1);
	    if(strpos($upah_rebet,',')){
            $upah_rebet = str_replace(',','',$upah_rebet);
        }

        $total_untung_rebet = TransaksiKeuntungan::on('mysql7')->where('norujukan','=',$norujukan)->sum('keuntungan_rebet');
        $total_untung_asal = TransaksiKeuntungan::on('mysql7')->where('norujukan','=',$norujukan)->sum('bayaran_keuntungan');
        $beza_keuntungan = $total_untung_asal - $total_untung_rebet;

        $keuntungan_rebet_sebenar = $upah_rebet - $beza_keuntungan;
        return $keuntungan_rebet_sebenar;
    }

    public function upahTawarruq($kodcaw,$norujukan,$jeniskeuntungan){
        $cawangan = $this->cawangan_info;

        $gadai_data = Gadai::on($cawangan['mysql'])
        ->where('norujukan','=',$norujukan)
        ->first();

        if($gadai_data['tempoh'] >= 12.0){
        $tempoh = 12;
        }else{
        $tempoh = $gadai_data['tempoh'];
        }
        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];

        $tawarruqservices = new V1Calculation();
        //$keuntungan = $tawarruqservices->kiraanTawarruq($gadai_data['pinjaman'],$gadai_data['kadarupah']);
	$keuntungan = $tawarruqservices->kiraanTawarruq(($gadai_data['pinjaman'] !== null) ? $gadai_data['pinjaman'] : 0,($gadai_data['kadarupah'] !== null) ? $gadai_data['kadarupah'] : 0);
        $upahsemasa_raw = $bilang_bln * $keuntungan;

        $upah_semasa_round = number_format($upahsemasa_raw,2);
        $upah_semasa = substr($upah_semasa_round, 0, -1);
        // $upah_semasa = floatval(preg_replace('/[^\d.]/', '', $upah_semasa));
        if(strpos($upah_semasa,',')){
        $upah_semasa = str_replace(',','',$upah_semasa);
        }
        return $upah_semasa;
    }

    public function upahRebetTawarruq($kodcaw,$norujukan,$jeniskeuntungan){

        $upah_rebet = $this->kiraUpahRebet($norujukan);

        return response()->json(number_format($upah_rebet,2));
    }

    public function tebusSeparuhTawarruq($kodcaw,$norujukan,HttpRequest $request){

        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upahsemasa = $this->kiraupahTawarruq($kodcaw,$norujukan,$request->jeniskeuntungan);

        $array_recno_marhun = $request->array_recno;

        $margin_pembiayaan = round(($gadai_data['bakipjm']/$gadai_data['nilaimarhun'])*100,2);
        // $margin_pembiayaan = round(($gadai_data['bakipjm']/$request->hargasemasa)*100,2);

        $nilai_marhun = $gadai_data['nilaimarhun'];
        $total_harga_tebus = 0;
        foreach($array_recno_marhun as $recno){
            $marhun = Marhun::on($cawangan['mysql'])->where([['recno','=',$recno],['norujukan','=',$norujukan]])->first();

            $harga_tebus = ($margin_pembiayaan/100)*$marhun['n_marhun'];

            $total_harga_tebus += $harga_tebus;
        }

        $total_harga_tebus_round = round($total_harga_tebus,2);

        $totalhargatebus = substr($total_harga_tebus_round, 0, -1);

        return response()->json($totalhargatebus);
    }

    public function tebusNotTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upah_semasa = $this->kiraUpahNotTawarruq($kodcaw,$norujukan);

        $harga_tebus = $upah_semasa + $gadai_data['pinjaman'];

        return response()->json($harga_tebus);
    }

    public function hargaTebusNotTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upah_semasa = $this->kiraUpahNotTawarruq($kodcaw,$norujukan);

        $harga_tebus = $upah_semasa + $gadai_data['pinjaman'];

        return $harga_tebus;
    }

    public function kiraUpahNotTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upahtelahbayar = Advansur::on($cawangan['mysql'])
                        ->where('norujukan','=',$norujukan)
                        ->sum('upahdibayar');

        $upah_asal = $gadai_data['nilaimarhun'] / 100 * $gadai_data['kadarupah'];
        $margin_pinjaman = $gadai_data['pinjaman'] / $gadai_data['nilaimarhun'] * 100;
        $margin_kadarupah = 80;
        $rebet = ($margin_kadarupah-$margin_pinjaman)/$margin_kadarupah * $upah_asal;

        $bln_mora = Moratorium::first();

        $upah_sebenar = $upah_asal - $rebet;
        $bln_upah = $gadai_data['tempoh'];
        if($bln_upah > $bln_mora['bln_mora']){
            $bln_upah = $bln_mora['bln_mora'];
        }
        $upahsemasa = $upah_sebenar * $bln_upah;
        $upah_semasa = bcdiv(round($upahsemasa,2),1,1);
        $upah_semasa = number_format($upah_semasa,2);
        if(strpos($upah_semasa,',')){
            $upah_semasa = str_replace(',','',$upah_semasa);
        }
        $upah_semasa = (float)$upah_semasa - $upahtelahbayar;

        if($upah_semasa <= 0){
            $upah_semasa = 0;
        }

        return $upah_semasa;
    }

    public function upahNotTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upahtelahbayar = Advansur::on($cawangan['mysql'])
                        ->where('norujukan','=',$norujukan)
                        ->sum('upahdibayar');

        $upah_asal = $gadai_data['nilaimarhun'] / 100 * $gadai_data['kadarupah'];
        $margin_pinjaman = $gadai_data['pinjaman'] / $gadai_data['nilaimarhun'] * 100;
        $margin_kadarupah = 80;
        $rebet = ($margin_kadarupah-$margin_pinjaman)/$margin_kadarupah * $upah_asal;

        $bln_mora = Moratorium::first();

        $upah_sebenar = $upah_asal - $rebet;
        $bln_upah = $gadai_data['tempoh'];
        if($bln_upah > $bln_mora['bln_mora']){
            $bln_upah = $bln_mora['bln_mora'];
        }
        $upahsemasa = $upah_sebenar * $bln_upah;
        $upah_semasa = bcdiv(round($upahsemasa,2),1,1);
        $upah_semasa = number_format($upah_semasa,2);
        if(strpos($upah_semasa,',')){
            $upah_semasa = str_replace(',','',$upah_semasa);
        }
        $upah_semasa = (float)$upah_semasa - $upahtelahbayar;

	    if($upah_semasa <= 0){
            $upah_semasa = 0;
        }

        return response()->json($upah_semasa);
    }

    public function tebusSeparuhNotTawarruq($kodcaw,$norujukan,HttpRequest $request){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $upah_asal = $gadai_data['nilaimarhun'] / 100 * $gadai_data['kadarupah'];
        $margin_pinjaman = $gadai_data['pinjaman'] / $gadai_data['nilaimarhun'] * 100;
        $margin_kadarupah = 80;
        $rebet = ($margin_kadarupah-$margin_pinjaman)/$margin_kadarupah * $upah_asal;

        $upah_sebenar = $upah_asal - $rebet;

        $upah_semasa = bcdiv(round($upah_sebenar * $gadai_data['jbg'],2),1,1);
        $upah_semasa = (float)number_format($upah_semasa,2);

        $array_recno_marhun = $request->array_recno;

        $margin_pembiayaan = round(($gadai_data['pinjaman']/$gadai_data['nilaimarhun'])*100,2);

        $nilai_marhun = $gadai_data['nilaimarhun'];
        $total_harga_tebus = 0;
        foreach($array_recno_marhun as $recno){
            $marhun = Marhun::on($cawangan['mysql'])->where([['recno','=',$recno],['norujukan','=',$norujukan]])->first();

            $harga_tebus = ($margin_pembiayaan/100)*$marhun['n_marhun'];

            $total_harga_tebus += $harga_tebus;
        }

        // $total_harga_tebus += $upah_semasa;

        return response()->json($total_harga_tebus);
    }

    function rebet($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
            ->where('kodcaw','=',$kodcaw)
            ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$norujukan)
            ->first();

        $upah_asal = $gadai_data['nilaimarhun'] / 100 * $gadai_data['kadarupah'];
        $margin_pinjaman = $gadai_data['pinjaman'] / $gadai_data['nilaimarhun'] * 100;
        $margin_kadarupah = 80;

        $rebet = ($margin_kadarupah-$margin_pinjaman)/$margin_kadarupah * $upah_asal;

        return floatval(number_format($rebet,2));
    }

    function rebetselepastawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $transaction_keuntungan = TransaksiKeuntungan::on('mysql7')
                    ->where('norujukan','=',$norujukan)
                    ->sum('keuntungan_rebet');

        $upah_rebet = $this->kiraUpahRebet($norujukan);

        $rebet_raw =$gadai_data['upah12'] - $transaction_keuntungan - $upah_rebet;

        $rebet_round = bcdiv(round($rebet_raw,2),1,1);
        $rebet_round = number_format($rebet_round,2);

        if(strpos($rebet_round,',')){
            $rebet_round = str_replace(',','',$rebet_round);
        }
        $rebet = substr($rebet_round, 0, -1);

        return $rebet;
    }

    public function tebusUpdate($kodcaw,$norujukan,HttpRequest $request){
        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        if($request->jenisbayarantebus == "tawarruq")
        {
            $rebet = $this->rebetselepastawarruq($kodcaw,$norujukan);
        }
        else if($request->jenisbayarantebus == "nottawarruq")
        {
            $rebet = $this->rebet($kodcaw,$norujukan);
        }
        else{
            $rebet = 0;
        }

        //check duplicate
        $data = Transaction::on('mysql7')->where('norujukan','=',$norujukan)->where('trans_type','=','T')->first();
        if(!empty($data)){
            return response()->json('duplicate');
        }

        $gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();

        if($gadai['hargajualan'] == null){
            $harga_tebus = $this->hargaTebusNotTawarruq($kodcaw,$norujukan);
            $upah_tebus = $this->kiraUpahNotTawarruq($kodcaw,$norujukan);
            $upah_rebet = 0;
            $upah_rebet_sebenar = 0;
        }else{
            $harga_tebus = $this->hargaTebusTawarruq($kodcaw,$norujukan);
            $upah_tebus = $this->kiraupahTawarruq($kodcaw,$norujukan);
            $upah_rebet = $this->kiraUpahRebetSebenar($kodcaw,$norujukan);
            $upah_rebet_sebenar = $harga_tebus - $gadai['bakipjm'];
        }

        $isPampasan = Pampasan::on($cawangan['mysql'])->where('norujukan', $request->norujukan)->exists();

        if($isPampasan){
            $barang_kes = Palsu::on($cawangan['mysql'])->where('norujukan', $norujukan)->first();

            $harga_tebus = $barang_kes->untung + $barang_kes->pembiayaan;
            $upah_tebus = $barang_kes->untung;
            $upah_rebet = $this->kiraUpahRebetSebenar($kodcaw,$norujukan);
            $upah_rebet_sebenar = $barang_kes->untung;
            $rebet = $gadai['hargajualan'] - $harga_tebus;
        }

        $create_tebus = Tebus::on($cawangan['mysql'])->create([
            'kodcaw'=> $kodcaw,
            'norujukan'=> $norujukan,
            'nopelanggan' => $request->nopelanggan,
            'jenisbyr' => "TN",
            'jenistebus' => $request->jenistebus,
            'glcode' => "0",
            't_tebus' => $current->toDateString(),
            'jbg' => $gadai['tempoh'],
            'kadarupah' => $gadai['kadarupah'],
            'nilaimarhun' => $gadai['nilaimarhun'],
            'pinjaman' => $gadai['pinjaman'],
            'ansuran' => 0.00,
            'addpinjaman' => $request->addpinjaman,
            'bakipjm' => $harga_tebus,
            'bakiupah' => $upah_tebus,
            'terima' => "*",
            'kodgl' => "0",
            'nowakil' => $request->nowakil,
            'rebate' => $rebet,
            'marhuntebus' => $request->marhun,
            'historygadaian' => $norujukan,
            'tarikhbyrn' => $current->toDateString(),
            'teller' => $request->teller
        ]);

        $create_inoutmar = InOutMar::on($cawangan['mysql'])->create([
            'tarikh' => $current->toDateString(),
            'masa' => $current->toTimeString(),
            'norujukan' => $norujukan,
            'nm' => $request->nilai_marhun,
            'pkd' => $request->teller,
            'drp' => $request->teller,
            'bln' => $current->month,
            'thn' => $current->year,
            'tag' => 0,
            'jenistebus' => $request->jenistebus,
            'namateller' => $request->teller
        ]);

        $transaction_upah = TransaksiKeuntungan::on('mysql7')->create([
            'norujukan' => $norujukan,
            'bayaran_keuntungan' => $upah_tebus,
            'bayaran_pembiayaan' => $gadai['bakipjm'],
            'keuntungan_rebet' => $upah_rebet_sebenar,
            'tarikh_bayaran'=> $current,
            'kodcaw'=> $kodcaw
        ]);

        if($request->jenistebus == 'P'){
            $baki_hargajualan = $gadai['bakihargajualan'] - $request->bakiupah;
            $transaction = Transaction::on('mysql7')->create([
                'trans_type' => $request->jenistebus,
                'norujukan' => $norujukan,
                'nokp' => $gadai['nokp'],
                'teller' => $request->teller,
                'kodcaw' => $kodcaw,
                'duit_masuk' => $request->bakiupah,
                'created_at' => $current,
                'bakiharga' => $baki_hargajualan,
            ]);
        }else{
            $baki_hargajualan = $gadai['bakihargajualan'] - $request->bakipinjaman;
            $transaction = Transaction::on('mysql7')->create([
                'trans_type' => $request->jenistebus,
                'norujukan' => $norujukan,
                'nokp' => $gadai['nokp'],
                'teller' => $request->teller,
                'kodcaw' => $kodcaw,
                'duit_masuk' => $harga_tebus,
                'created_at' => $current,
                'bakiharga' => $baki_hargajualan,
                'nowakil' => (int)$request->nowakil,
                'duitpelanggan' => isset($request->duitpelanggan) ? $request->duitpelanggan : 0,
                'bakipelanggan' => isset($request->bakipelanggan) ? $request->bakipelanggan : 0,
            ]);
        }

        $update_gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
            'sttebus' => "T",
            't_update' => $current->toDateString(),
        ));

        $audit = new Audit();
        $audit->users = $request->teller;
        if($request->jenistebus == 'P'){
            $audit->actions = "Tambah Pembiayaan";
        }else if($request->jenistebus == 'S'){
            $audit->actions = "Tebus Separuh";
        }else if($request->jenistebus == 'T'){
            $audit->actions = "Tebus Penuh";
        }
        $audit->norujukan = $norujukan;
        $audit->new_data = $create_tebus;
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();

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

    public function tebusUpdateAutoTawarruq($kodcaw,$norujukan,HttpRequest $request){
        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        if($request->jenisbayarantebus == "tawarruq")
        {
            $rebet = $this->rebetselepastawarruq($kodcaw,$norujukan);
        }
        else if($request->jenisbayarantebus == "nottawarruq")
        {
            $rebet = $this->rebet($kodcaw,$norujukan);
        }
        else{
            $rebet = 0;
        }

        $gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();

        //check duplicate
        $data = Transaction::on('mysql7')->where('norujukan','=',$norujukan)->where('trans_type','=','AT')->first();
        if(!empty($data)){
            return response()->json('duplicate');
        }

        $update_gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
            'sttebus' => "T",
            't_update' => $current->toDateString(),
        ));

        $upah_rebet = $this->kiraUpahRebet($norujukan);

        $create_tebus = Tebus::on($cawangan['mysql'])->create([
            'kodcaw'=> $kodcaw,
            'norujukan'=> $norujukan,
            'nopelanggan' => $request->nopelanggan,
            'jenisbyr' => "TN",
            'jenistebus' => $request->jenistebus,
            'glcode' => "0",
            't_tebus' => $current->toDateString(),
            'jbg' => $request->jbg,
            'kadarupah' => $request->kadarupah,
            'nilaimarhun' => $request->nilai_marhun,
            'pinjaman' => $request->pinjaman,
            'ansuran' => $request->ansuran,
            'addpinjaman' => $request->addpinjaman,
            'bakipjm' => $request->bakipinjaman,
            'bakiupah' => $request->bakiupah,
            'terima' => "*",
            'kodgl' => "0",
            'nowakil' => $request->nowakil,
            'rebate' => $rebet,
            'marhuntebus' => $request->marhun,
            'historygadaian' => $request->historygadaian,
            'tarikhbyrn' => $current->toDateString(),
            'teller' => $request->teller
        ]);

        $create_inoutmar = InOutMar::on($cawangan['mysql'])->create([
            'tarikh' => $current->toDateString(),
            'masa' => $current->toTimeString(),
            'norujukan' => $norujukan,
            'nm' => $request->nilai_marhun,
            'pkd' => $request->teller,
            'drp' => $request->teller,
            'bln' => $current->month,
            'thn' => $current->year,
            'tag' => 0,
            'jenistebus' => $request->jenistebus,
            'namateller' => $request->teller
        ]);

        $bayaran_pembiayaan = $request->totalbayaran - $request->bakiupah;

        $transaction_upah = TransaksiKeuntungan::on('mysql7')->create([
            'norujukan' => $norujukan,
            'bayaran_keuntungan' => $request->bakiupah,
            'bayaran_pembiayaan' => $bayaran_pembiayaan,
            'keuntungan_rebet' => $request->bakiupah,
            'tarikh_bayaran'=> $current,
            'kodcaw'=> $kodcaw
        ]);

        $transaction = Transaction::on('mysql7')->create([
            'trans_type' => $request->jenistebus,
            'norujukan' => $norujukan,
            'nokp' => $gadai['nokp'],
            'teller' => $request->teller,
            'kodcaw' => $kodcaw,
            'duit_masuk' => $request->totalbayaran,
            'created_at' => $current,
            'bakiharga' => 0,
            'duitpelanggan' => isset($request->duitpelanggan) ? $request->duitpelanggan : 0,
            'bakipelanggan' => isset($request->bakipelanggan) ? $request->bakipelanggan : 0
        ]);

        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = "Auto Tawarruq";
        $audit->norujukan = $norujukan;
        $audit->new_data = $create_tebus;
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();

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

    public function kiraupahTawarruqByTarikh($kodcaw,$norujukan,$tarikh){
        $onepercentservices = new Calculation();
        
        $cawangan = Cawangan::on('mysql7')
            ->where('kodcaw','=',$kodcaw)
            ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$norujukan)
            ->first();

        $transaction_keuntungan = TransaksiKeuntungan::on('mysql7')
            ->where('norujukan','=',$norujukan)
            ->sum('keuntungan_rebet');

        $tempoh_func = $this->kiraanTarikhJBG($gadai_data['t_gadai'],$tarikh);

        if($tempoh_func >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $tempoh_func;
        }
        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];

        $upahsemasa_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['pinjaman']);

        // $upah_semasa_round = number_format($upahsemasa_raw,2);
        // if(strpos($upah_semasa_round,',')){
        // $upah_semasa_round = str_replace(',','',$upah_semasa_round);
        // }
        // $upah_semasa = substr($upah_semasa_round, 0, -1);
        // if(strpos($upah_semasa,',')){
        // $upah_semasa = str_replace(',','',$upah_semasa);
        // }
        $upah_semasa = $onepercentservices->getRoundedMethod($upahsemasa_raw);

        $upahrebet_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['bakipjm']);
        $upah_rebet = $onepercentservices->getRoundedMethod($upahrebet_raw);
        $rebet_raw =$gadai_data['upah12'] - $transaction_keuntungan - $upah_rebet;


        $harga_tebus = $gadai_data['bakihargajualan'] - $rebet_raw;


        $array_return = [
            'upahsemasa' => $upah_semasa,
            'tempoh' => $tempoh,
            'harga_tebus' => $harga_tebus,
        ];

        return $array_return;
    }

    private function kiraanTarikhJBG($tarikhgadai,$tarikh){
       
        $tarikh_gadai = Carbon::parse($tarikhgadai. ' 00:00:00');
        $tarikh = new Carbon($tarikh);
        $tahun_gadai = $tarikh_gadai->year;
        $bulan_gadai = $tarikh_gadai->month;
        $hari_gadai = $tarikh_gadai->day;
        $tahun_semasa = $tarikh->year;
        $bulan_semasa = $tarikh->month;
        $hari_semasa = $tarikh->day;
        if($hari_semasa >= $hari_gadai){
            $beza_hari = $hari_semasa - $hari_gadai + 1;
        }else if($hari_semasa < $hari_gadai){
            $bulan_semasa = $bulan_semasa - 1;
            $beza_hari = ($hari_semasa + 30) - $hari_gadai + 1;
        }
        $extensivemonth_gadai = 0;
        if($beza_hari >= 1 && $beza_hari <= 15){
            $extensivemonth_gadai = 0.5;
        }else if($beza_hari >= 16){
            $extensivemonth_gadai = 1;
        }else{
            $extensivemonth_gadai = 0;
        }
        $beza_tahun = $tahun_semasa - $tahun_gadai;
        $beza_bulan = ($bulan_semasa + ($beza_tahun * 12)) - $bulan_gadai;
        $tempoh_gadai = $beza_bulan + $extensivemonth_gadai;

        return $tempoh_gadai;
    }

    public function transaksiPembiayaanSemula($kodcaw,$norujukan,HttpRequest $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();
        $gadai = optional($gadai)->toArray();
        
        //check duplicate
        $data = Transaction::on('mysql7')->where('norujukan','=',$norujukan)->where('trans_type','=','AT')->first();

        if(!empty($data)){
            return 'duplicate';
        }

        if(!$gadai){
            return 'gadai no-data';
        }

        $array_tebus = $request->only(['jeniskeuntungan', 'nopelanggan','jenistebus','addpinjaman','nowakil','marhun','teller','bakipinjaman','bakiupah']);
        $array_trans = $request->only(['nopelanggan', 'noic','jenisAT','pinjaman','pinjamanbaru','marhun','teller','jenistebus']);
        $array_tebus_base = $request->only(['totalbayaran', 'bakiupah','jeniskeuntungan','bakipinjaman','jenistebus','teller','nowakil','duitpelanggan']);
        $array_trans_base = $request->only(['pinjaman','teller','pinjamanbaru']);

        try{
            DB::connection($cawangan['mysql'])->beginTransaction();
            $this->saveTebus($kodcaw,$norujukan,$gadai,$cawangan,$array_tebus);
            $this->createTransaction($cawangan,$kodcaw,$norujukan,$array_trans);

            DB::connection('mysql7')->beginTransaction();
            $this->saveTebusBase($kodcaw,$norujukan,$gadai,$array_tebus_base);
            $this->createTransactionBase($norujukan,$kodcaw,$array_trans_base);
            $array_response = [
                'result' => 'success',
                'data' => 1
            ];

            DB::connection($cawangan['mysql'])->commit();
            DB::connection('mysql7')->commit();

            return response()->json($array_response);

        }catch(\Exception $e){
            DB::connection($cawangan['mysql'])->rollBack();
            DB::connection('mysql7')->rollBack();
            $array_response = [
                'result' => 'error',
                'data' => $e->getMessage()
            ];

            Log::error('Transaction failed', [
                'exception' => $e->getMessage(),
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
 
            return response()->json($array_response);
        }

    }

    private function saveTebus($kodcaw,$norujukan,$gadai,$cawangan,$array_tebus){
        $current = Carbon::now();

        $rebet = 0;

        $rebet = $this->rebetselepastawarruq($kodcaw,$norujukan);

        $upah_rebet = $this->kiraUpahRebet($norujukan);
  
        try{
            Tebus::on($cawangan['mysql'])->create([
                'kodcaw'=> $kodcaw,
                'norujukan'=> $norujukan,
                'nopelanggan' => $array_tebus['nopelanggan'],
                'jenisbyr' => "TN",
                'jenistebus' => $array_tebus['jenistebus'],
                'glcode' => "0",
                't_tebus' => $current->toDateString(),
                'jbg' => $gadai['tempoh'],
                'kadarupah' => $gadai['kadarupah'],
                'nilaimarhun' => $gadai['nilaimarhun'],
                'pinjaman' => $gadai['pinjaman'],
                'ansuran' => 0.00,
                'addpinjaman' => $array_tebus['addpinjaman'],
                'bakipjm' => $array_tebus['bakipinjaman'],
                'bakiupah' => $array_tebus['bakiupah'],
                'terima' => "*",
                'kodgl' => "0",
                'nowakil' => $array_tebus['nowakil'],
                'rebate' => $rebet,
                'marhuntebus' => $array_tebus['marhun'],
                'historygadaian' => $norujukan,
                'tarikhbyrn' => $current->toDateString(),
                'teller' => $array_tebus['teller'],
            ]);
        }catch(\Exception $e){
            throw new \Exception("Error in Tebus: " . $e->getMessage());
        }
    }

    private function saveTebusBase($kodcaw,$norujukan,$gadai,$array_tebus_base){
        $current = Carbon::now();
        
        if($array_tebus_base['jenistebus'] == 'AT'){
            $bayaran_pembiayaan = $array_tebus_base['totalbayaran'] - $array_tebus_base['bakiupah'];
        }else{
            $bayaran_pembiayaan = $array_tebus_base['bakipinjaman'];
        }

        $margin_semasa = ($gadai['bakipjm']/$gadai['nilaimarhun']) * 100;

        $harga_tebus = $this->hargaTebusTawarruq($kodcaw,$norujukan,$array_tebus_base['jeniskeuntungan']);
        $upah_rebet = $this->kiraUpahRebetSebenar($kodcaw,$norujukan);

        $bayaran_pembiayaan = $array_tebus_base['totalbayaran'] - $array_tebus_base['bakiupah'];

        $upah_rebet_sebenar = $harga_tebus - $gadai['bakipjm'];

        try{
            TransaksiKeuntungan::on('mysql7')->create([
                'norujukan' => $norujukan,
                'bayaran_keuntungan' => $array_tebus_base['bakiupah'],
                'bayaran_pembiayaan' => $bayaran_pembiayaan,
                'keuntungan_rebet' => $array_tebus_base['bakiupah'],
                'tarikh_bayaran'=> $current,
                'kodcaw'=> $kodcaw
            ]);

            if($array_tebus_base['jenistebus'] == 'P'){
                $duit_masuk = $array_tebus_base['bakiupah'];
            }else if($array_tebus_base['jenistebus'] == 'AT'){
                $duit_masuk = $array_tebus_base['totalbayaran'];
            }else{
                $duit_masuk = $harga_tebus['harga'];
            }

            $baki_hargajualan = ($array_tebus_base['jenistebus'] == 'P') ? $gadai['bakihargajualan'] = $array_tebus_base['bakiupah'] : $gadai['bakihargajualan'] - $array_tebus_base['bakipinjaman'];
            Transaction::on('mysql7')->create([
                'trans_type' => $array_tebus_base['jenistebus'],
                'norujukan' => $norujukan,
                'nokp' => $gadai['nokp'],
                'teller' => $array_tebus_base['teller'],
                'kodcaw' => $kodcaw,
                'duit_masuk' => $array_tebus_base['totalbayaran'],
                'created_at' => $current,
                'bakiharga' => 0,
                'duitpelanggan' => isset($array_tebus_base['duitpelanggan']) ? $array_tebus_base['duitpelanggan'] : 0,
                'bakipelanggan' => isset($array_tebus_base['bakipelanggan']) ? $array_tebus_base['bakipelanggan'] : 0
            ]);
        }catch(\Exception $e){
            throw new \Exception("Error in TebusBase: " . $e->getMessage());
        }
    }

    private function createTransaction($cawangan,$kodcaw,$norujukan,$array_trans){
        $current = Carbon::now();

        /* Create Gadai */
        $gadaiTransaction = Gadai::on($cawangan['mysql'])->where('t_gadai','=',$current->toDateString())->orderBy('sirig', 'desc')->first();
        $gadaiTransaction = optional($gadaiTransaction)->toArray();

        $new_sirig = ($gadaiTransaction) ? $gadaiTransaction['sirig'] + 1 : 1;
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

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

        try{
            Gadai::on($cawangan['mysql'])->create([
                'kodcaw'=>$kodcaw,
                'norujukan' => $new_sag_number,
                'nopelanggan' => $array_trans['nopelanggan'],
                'nokp' => $array_trans['noic'],
                'sirig' => $new_sirig,
                't_gadai' => $current->toDateString(),
                'sttebus' => '',
                'masa' =>$current->toTimeString(),
                'tagbaru' => 1
            ]);

            $marhun = Marhun::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->get();

            foreach($marhun as $marhunloop){
                $karatbaru = (strpos($marhunloop['karat'], '.') !== false) ? str_replace('-','.',$marhunloop['karat']) : $marhunloop['karat'];
                $karatbaru = $marhunloop['karat'];
                $harga_emas = HargaEmas::on('mysql7')->select('harga')->where('karat','=',$karatbaru)->first();

                if(isset($array_trans['jenisAT'])){
                    $harga = ($array_trans['jenisAT'] == 'hargalama') ? $marhunloop['harga'] : $harga_emas['harga'];
                }else{
                    $harga = $harga_emas['harga'];
                }

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

                $marhunToCreate = [
                    'kodcaw'=> $kodcaw,
                    'norujukan'=> $new_sag_number,
                    't_gadai' => $current->toDateString(),
                    'bil' => $marhunloop['kuantiti'],
                    'marhun' => $marhunloop['marhun'],
                    'nota' => $marhunloop['nota'],
                    'tag_permata' => $marhunloop['tag_permata'] != null ? $marhunloop['tag_permata'] : 0,
                    'berat_batu_permata' => $marhunloop['berat_batu_permata'] != null ? $marhunloop['berat_batu_permata'] : '',
                    'karat' => $marhunloop['karat'],
                    'berat' => $marhunloop['berat'],
                    'harga' => $harga,
                    'n_marhun' => $nilai_marhun
                ];

                if($marhunToCreate['berat_batu_permata'] == '') {
                    $marhunToCreate['berat_batu_permata'] = null;
                };

                Marhun::on($cawangan['mysql'])->create($marhunToCreate);
            }

            $total_nilai_marhun = Marhun::on($cawangan['mysql'])->where('norujukan',$new_sag_number)->sum('n_marhun');
            $total_bil_marhun = Marhun::on($cawangan['mysql'])->where('norujukan',$new_sag_number)->sum('bil');
            $total_berat_marhun = Marhun::on($cawangan['mysql'])->where('norujukan',$new_sag_number)->sum('berat');

            $margin_pinjaman = ($array_trans['pinjamanbaru'] / $total_nilai_marhun);

            $t_matang = Carbon::now();
            $t_matang = $t_matang->addMonths(6)->subDays(1);

            $t_kontrak = Carbon::now();
            $t_kontrak = $t_kontrak->addMonths(12)->subDays(1);

            $kadar_raw = KadarUpah::where('min','<=',$total_nilai_marhun)->where('max','>=',$total_nilai_marhun)->where('group_id',$cawangan['group_id'])->first();

            $onepercentservices = new Calculation();
            $keuntungan = $onepercentservices->kiraanKeuntunganSebenar($array_trans['pinjamanbaru'],$total_nilai_marhun,$kadar_raw['kadarujrah'],$margin_pinjaman);

            $upah1 = $onepercentservices->getRoundedMethod($keuntungan['keuntungan']);
            $upah6 = $onepercentservices->getRoundedMethod($upah1 * 6);
            $upah12 = $onepercentservices->getRoundedMethod($upah1 * 12);
            $ujrah = $onepercentservices->getRoundedMethod($keuntungan['ujrah']);
            $onepercent = $onepercentservices->getRoundedMethod($keuntungan['onepercent']);
            $akrual_ujrah = $onepercentservices->getRoundedMethod($keuntungan['ujrah'] * 0.5);
            $akrual_onepercent = $onepercentservices->getRoundedMethod($keuntungan['onepercent'] * 0.5);

            $hargajualan = $array_trans['pinjaman'] + $upah12;

            Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$new_sag_number)
            ->update(array(
                'nilaimarhun' => $total_nilai_marhun,
                'berat'=> $total_berat_marhun,
                'pinjaman' => $array_trans['pinjamanbaru'],
                'kadarupah' => $kadar_raw['kadarujrah'],
                'marhun' => $array_trans['marhun'],
                'percentpinj' => $margin_pinjaman,
                'teller' => $array_trans['teller'],
                'bakipjm' => $array_trans['pinjamanbaru'],
                'bakiupah' => $upah6,
                'jbg' => 0.5,
                't_update' => $current->toDateString(),
                'cetak' => 0,
                'upah12' => $upah12,
                'hargajualan' => $hargajualan,
                'bakihargajualan' => $hargajualan,
                'tagserah' => 0,
                't_matang' => $t_matang,
                't_matang1' => $t_kontrak,
                'tempoh' => 0.5,
                'kuantiti' => $total_bil_marhun,
                'tagkomuditi' => 0,
                'upahdibayar' => 0.00,
                'tempohbayar' => 0.00,
                'lelong_tawarruq' => 1,
                'kadarujrah' => $kadar_raw['kadarujrah'],
                'ujrah' => $ujrah,
                'onepercent' => $onepercent,
                'margin_semasa' => $margin_pinjaman,
                'tagbaru' => 1,
                'tunggakanujrah' => $akrual_ujrah,
                'tunggakanonepercent' => $akrual_onepercent,
                'historygadaian' => $norujukan,
                'tag_tebus' => $array_trans['jenistebus'],
            ));

            Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
                'sttebus' => "T",
                't_update' => $current->toDateString(),
            ));

        }catch(\Exception $e){
            throw new \Exception("Error in Transaction: " . $e->getMessage());
        }

    }

    private function createTransactionBase($norujukan,$kodcaw,$array_trans_base){
        $current = Carbon::now();

        $komuditi_current = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();

        $unit_current = isset($komuditi_current['unit_komuditi']) ? $komuditi_current['unit_komuditi']: 0;

        try{
            $update_unit = $unit_current - $array_trans_base['pinjamanbaru'];

            KomuditiPurchase::on('mysql7')->where('id','=',$komuditi_current['id'])->update([
                'unit_komuditi' => $update_unit
            ]);

            KomuditiTransaksi::on('mysql7')->create([
                'unit_komuditi' => $update_unit,
                'nosijil'=>$komuditi_current['no_sijil'],
                'norujukan' => $norujukan,
                'kodcaw' => $kodcaw,
                'teller' => $array_trans_base['teller'],
                'masa' => $current->toTimeString(),
                'tarikh' => $current->toDateString()
            ]);
        }catch(\Exception $e){
            throw new \Exception("Error in TransactionBase: " . $e->getMessage());
        }
    }
}