<?php

namespace App\Support\v2;

use App\Audit;
use App\Cawangan;
use App\Customer;
use App\KadarUpah;
use App\Support\v2\Calculation;
use Carbon\Carbon;
use App\Gadai;
use App\Marhun;
use App\Support\OnePercent;
use App\Transaction;
use App\TransaksiGadai;
use App\TransaksiKeuntungan;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PDO;

class GadaiV2
{
    protected $kodcaw;
    protected $cawangan_info;

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

    public function create(HttpRequest $request){
        $current = Carbon::now();
        $current = new Carbon();
        
        $kodcaw = $this->kodcaw;
        $cawangan = $this->cawangan_info;
        try{
            DB::transaction(function () use ($cawangan, $kodcaw, $request, $current) {
                $gadai = Gadai::on($cawangan['mysql'])->create([
                    'kodcaw'=>$kodcaw,
                    'norujukan' => $request->norujukan,
                    'nopelanggan' => $request->nopelanggan,
                    'nokp' => $request->nokp,
                    'sirig' => $request->sirig,
                    't_gadai' => $current->toDateString(),
                    'sttebus' => '',
                    'masa' =>$current->toTimeString(),
                    'tagbaru' => 1
                ]);
                return response()->json($gadai, 201);
            });


        }catch(\Exception $e){

            echo "Gadaian Gagal: " . $e->getMessage();
        }
    }

    private function getKadarUpahAnggota($nokp,$total_nilai_marhun = 0,$groupid = 2) : Float{
        //Log::info('DEBUG NOKP:' . $nokp);
        if($nokp){
            $customer = Customer::on('mysql7')
                ->select('tag_anggota')
                ->where(function($q) use ($nokp) {
                    $q->where('kpbaru', $nokp)
                        ->orWhere('kplama', $nokp);
                })
                ->first();
            $customer = $customer ? $customer->toArray() : [];
            if(isset($customer) && $customer['tag_anggota'] == 1){
                return 0.16;
            }else{
                return KadarUpah::where('min', '<=', $total_nilai_marhun)
                    ->where('max', '>=', $total_nilai_marhun)
                    ->where('group_id', $groupid)
                    ->value('kadarujrah');
            }
        }

        return 0.0;

    }

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

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

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

            $margin_pinjam = $request->percentpinj *100;
            $cawangan = Cawangan::on('mysql7')
                        ->where('kodcaw','=',$request->kodcaw)
                        ->first();
            if($request->transaction == 'Ubah Gadai'){
                $old_data = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();
            }

            $bil_marhun = Marhun::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->sum('bil');

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

           $kadar_raw = $this->getKadarUpahAnggota($request->nokp, $total_nilai_marhun, $cawangan['group_id']);

            if (empty($kadar_raw) || $kadar_raw == 0) {

            Log::error('[BLOCKED] Kadar upah kosong / 0', [
                'nokp' => $request->nokp,
                'total_nilai_marhun' => $total_nilai_marhun,
                'group_id' => $cawangan['group_id'],
            ]);

            throw new \Exception("Kadar upah kosong / 0, transaksi dibatalkan!");
        }


            // query kadar upah lama
            // $kadar_raw = KadarUpah::where('min','<=',$total_nilai_marhun)->where('max','>=',$total_nilai_marhun)->first();

            $onepercentservices = new Calculation();
            $keuntungan = $onepercentservices->kiraanKeuntunganSebenar($request->pinjaman,$total_nilai_marhun,$kadar_raw,$margin_pinjam);
            // $upah1 = $request->pinjaman * ($kadar_raw['kadarupdah']/100);
            // $upah6 = $upah1 * 6;
            // $upah12 = $upah1 * 12;
            $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']);

            $hargajualan = $request->pinjaman + $upah12;

            $akrual = $this->kiraupahTawarruqStokAuditUjrahOnePercent(0.5,0,$kadar_raw,$request->pinjaman,$total_nilai_marhun,$margin_pinjam);

            $gadai = Gadai::on($cawangan['mysql'])
                ->where('norujukan','=',$norujukan)
                ->update(array(
                    'nilaimarhun' => $total_nilai_marhun,
                    'berat'=> $total_berat,
                    'pinjaman' => $request->pinjaman,
                    'kadarupah' => $kadar_raw,
                    'marhun' => $request->marhun,
                    'percentpinj' => $margin_pinjam,
                    'teller' => $request->teller,
                    'bakipjm' => $request->pinjaman,
                    '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' => $bil_marhun,
                    'tagkomuditi' => 0,
                    'upahdibayar' => 0.00,
                    'tempohbayar' => 0.00,
                    'lelong_tawarruq' => 1,
                    'kadarujrah' => $kadar_raw,
                    'ujrah' => $ujrah,
                    'onepercent' => $onepercent,
                    'margin_semasa' => $margin_pinjam,
                    'tagbaru' => 1,
                    'tunggakanujrah' => $akrual['ujrah'],
                    'tunggakanonepercent' => $akrual['keuntungan'],
                ));

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

            $audit = new Audit();
            $audit->users = $request->teller;
            $audit->actions = $request->transaction;
            $audit->norujukan = $norujukan;
            $audit->new_data = $new_data;
            if($request->transaction == 'Ubah Gadai'){
                $audit->old_data = $old_data;
            }
            $audit->kodcaw = $request->kodcaw;
            $audit->created_at = $current;
            $audit->updated_at = $current;
            $audit->save();

            return 'true';
    }

    public function kiraupahOnePercent($norujukan){
            $onepercentservices = new Calculation();

            $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'];

            $upah = $onepercentservices->kiraanKeuntunganSebenar($gadai_data['pinjaman'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['percentpinj']);
            //$upahsemasa_raw = $bilang_bln * $upah['keuntungan'];
            $onepercent = $onepercentservices->getRoundedMethod($bilang_bln * $upah['onepercent']);
            $ujrah = $onepercentservices->getRoundedMethod($bilang_bln * $upah['ujrah']);
            $upahsemasa_raw = $onepercent + $ujrah;
	    $upahsemasa_raw = $onepercentservices->getRoundedMethod($upahsemasa_raw);

            return $upahsemasa_raw;
    }

    public function kiraupahRebet($norujukan){
        $onepercentservices = new Calculation();

        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$this->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'];

        $upah = $onepercentservices->kiraanKeuntunganRebet($gadai_data['bakipjm'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['margin_semasa']);

        //$upahrebet_raw = $bilang_bln * $upah['keuntungan'];
        $onepercent = $onepercentservices->getRoundedMethod($bilang_bln * $upah['onepercent']);
        $ujrah = $onepercentservices->getRoundedMethod($bilang_bln * $upah['ujrah']);
        $upahrebet_raw = $onepercent + $ujrah;
        $upahrebet_raw = $onepercentservices->getRoundedMethod($upahrebet_raw);
        
        return $upahrebet_raw;
    }

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

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

            $upahsemasa = $this->kiraupahOnePercent($norujukan);
            $upahrebet = $this->kiraUpahRebet($norujukan);

            $total_bayaran_prev = Transaction::on('mysql7')->where([['norujukan','=',$norujukan],['trans_type','=','A']])->sum('duit_masuk');

            $total_bayaran_semasa = $total_bayaran_prev + $request->bayaran;

            if($total_bayaran_semasa >= $gadai['bakiupah']){
                $lelong_tawarruq = 0;
            }else{
                $lelong_tawarruq = 1;
            }
            $onepercent = new Calculation();

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

            $baki_hargajualan = $gadai['bakihargajualan'] - $request->bayaran;

            $baki_bayaran = $request->bayaran - $upahsemasa;

            $baki_pinjaman = $gadai['bakipjm'] - $baki_bayaran;

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

            $keuntungan = $onepercent->kiraanKeuntunganRebet($gadai['bakipjm'],$gadai['nilaimarhun'],$gadai['kadarupah'],$gadai['margin_semasa']);
            $ujrahasal = $onepercent->kiraanUjrahSebenar($gadai['nilaimarhun'],$gadai['kadarupah'],$gadai['percentpinj']);

            $onepercentasal = $gadai['pinjaman'] * (1/100);
            $ujrahasal = $onepercent->getRoundedMethod($ujrahasal);
            $onepercentasal = $onepercent->getRoundedMethod($onepercentasal);

            try {

                DB::connection('mysql7')->transaction(function () use($onepercentasal,$ujrahasal,$keuntungan,$norujukan,$gadai,$request,$kodcaw,$current,$baki_hargajualan,$upahsemasa,$baki_bayaran,$upahrebet,$cawangan,$old_data,$baki_pinjaman,$lelong_tawarruq,$margin_semasa,$onepercent) {

                    $transaction = Transaction::on('mysql7')->create([
                        'trans_type' => 'A',
                        'norujukan' => $norujukan,
                        'nokp' => $gadai['nokp'],
                        'teller' => $request->teller,
                        'kodcaw' => $kodcaw,
                        'duit_masuk' => $request->bayaran,
                        'created_at' => $current,
                        'bakiharga' => $baki_hargajualan,
                        'nowakil' => (int)$request->nowakil,
                        'duitpelanggan' => $request->duitpelanggan,
                        'bakipelanggan' => $request->bakipelanggan
                    ]);

                    if($gadai['tempoh'] >= 12.0){
                        $tempoh = 12;
                    }else{
                        $tempoh = $gadai['tempoh'];
                    }
                    $bilang_bln = $tempoh - $gadai['tempohbayar'];
        
                    $ujrah = $onepercent->getRoundedMethod($ujrahasal * $bilang_bln);
                    $ujrah_rebate = $onepercent->getRoundedMethod($keuntungan['ujrah'] * $bilang_bln);
                    $keun = $onepercent->getRoundedMethod($onepercentasal * $bilang_bln);
                    $keuntungan_rebate = $onepercent->getRoundedMethod($keuntungan['onepercent'] * $bilang_bln);

                    $transaction_upah = TransaksiKeuntungan::on('mysql7')->create([
                        'norujukan' => $norujukan,
                        'bayaran_keuntungan' => $upahsemasa,
                        'bayaran_pembiayaan' => $baki_bayaran,
                        'keuntungan_rebet'=> $upahrebet,
                        'tarikh_bayaran'=> $current,
                        'kodcaw'=> $kodcaw,
                        'ujrah' => $ujrah,
                        'ujrah_rebet' => $ujrah_rebate,
                        'onepercent' => $keun,
                        'onepercent_rebet' => $keuntungan_rebate,
                        'tempoh' => $gadai['tempoh'],
                        'beza_tempoh' => $bilang_bln,
                        'margin_semasa' => $margin_semasa,
                    ]);

                    $transaksi_gadai = TransaksiGadai::on('mysql7')->create([
                        'kodcaw' => $old_data['kodcaw'],
                        'norujukan' => $old_data['norujukan'],
                        'percentpinj' => $old_data['percentpinj'],
                        'bakipjm' => $old_data['bakipjm'],
                        'tempoh' => $old_data['tempoh'],
                        't_update' => $old_data['t_update'],
                        'bakihargajualan' => $old_data['bakihargajualan'],
                        'tempohbayar' => $old_data['tempohbayar'],
                        'lelong_tawarruq' => $old_data['lelong_tawarruq'],
                        'margin_semasa' => $old_data['margin_semasa'],
                        'tunggakanujrah' => $old_data['tunggakanujrah'], 
                        'tunggakanonepercent' => $old_data['tunggakanonepercent'],
                        'transaction_id' => $transaction->id,
                        'transaksiupah_id' => $transaction_upah->id,
                        'softDelete' => 0           
                    ]);

                    DB::connection($cawangan['mysql'])->transaction(function () use($cawangan,$baki_pinjaman,$current,$norujukan,$gadai,$baki_hargajualan,$lelong_tawarruq,$margin_semasa){

                        $margin_updated = ($baki_pinjaman / $gadai['nilaimarhun']) * 100;
                        
                        $tempoh_gadai = $this->tempohTransactionGadai($gadai);
                        $akrual = $this->kiraupahTawarruqStokAuditUjrahOnePercent($tempoh_gadai,$gadai['tempoh'],$gadai['kadarujrah'],$gadai['bakipjm'],$gadai['nilaimarhun'],$margin_semasa);
                        $update_gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
                            'bakipjm' => $baki_pinjaman,
                            'jbg' => 0,
                            't_update' => $current->toDateString(),
                            'bakihargajualan' => $baki_hargajualan,
                            'tempohbayar' => $gadai['tempoh'],
                            'lelong_tawarruq' => $lelong_tawarruq,
                            'margin_semasa' => $margin_updated,
                            'tunggakanujrah' => $akrual['ujrah'],
                            'tunggakanonepercent' => $akrual['keuntungan']
                        ));
                    });

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

                    $audit = new Audit();
                    $audit->users = $request->teller;
                    $audit->actions = 'Bayaran Ansuran';
                    $audit->norujukan = $norujukan;
                    $audit->new_data = $new_data;
                    $audit->old_data = $old_data;
                    $audit->kodcaw = $kodcaw;
                    $audit->created_at = $current;
                    $audit->updated_at = $current;
                    $audit->save();

                    if(!$transaction || !$transaction_upah) {
                        throw new \Exception('One of the database operations failed.');
                    }

                    DB::commit();

                });
            }catch(\Exception $e){
                Log::error("Transaction failed: " . $e->getMessage());
                return response()->json("Transaction failed: " . $e->getMessage(),500);
            }

            return response()->json("success",200);
    }

    public function updateJBG(HttpRequest $request){
        $cawangan_mysql = $this->cawangan_info;
        $all_gadai = Gadai::on($cawangan_mysql['mysql'])->whereNotIn('sttebus',['L','T'])->get();
        foreach($all_gadai as $gadai){
            if($gadai['t_update'] == null){
                $tarikh_update = Carbon::parse($gadai['t_gadai'].' '. $gadai['masa']);
            }else{
                $tarikh_update = Carbon::parse($gadai['t_update'].' 00:00:00' );
            }
            $tarikh_gadai = Carbon::parse($gadai['t_gadai']. ' 00:00:00');
            $current = Carbon::now();
            $tahun_gadai = $tarikh_gadai->year;
            $bulan_gadai = $tarikh_gadai->month;
            $hari_gadai = $tarikh_gadai->day;
            $tahun_semasa = $current->year;
            $bulan_semasa = $current->month;
            $hari_semasa = $current->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;
            
            if(isset($gadai['tagbaru'])){
                if($gadai['tagbaru'] == 1){
                    $upah_semasa = $this->kiraupahTawarruqStokAuditUjrahOnePercent($tempoh_gadai,$gadai['tempohbayar'],$gadai['kadarupah'],$gadai['bakipjm'],$gadai['nilaimarhun'],$gadai['margin_semasa']);
                    Gadai::on($cawangan_mysql['mysql'])->where('norujukan','=',$gadai['norujukan'])->update(array(
                        'jbg' => $tempoh_gadai,
                        'tempoh' => $tempoh_gadai,
                        'tunggakan' => 0,
                        'tunggakanujrah' => $upah_semasa['ujrah'],
                        'tunggakanonepercent' => $upah_semasa['keuntungan'],
                    ));
                }
                else{
                    $upah_semasa = $this->kiraupahTawarruqStokAudit($tempoh_gadai,$gadai['tempohbayar'],$gadai['kadarupah'],$gadai['bakipjm']);                
                    Gadai::on($cawangan_mysql['mysql'])->where('norujukan','=',$gadai['norujukan'])->update(array(
                        'jbg' => $tempoh_gadai,
                        'tempoh' => $tempoh_gadai,
                        'tunggakan' => $upah_semasa,
                    ));
                }
            }else{
                $upah_semasa = $this->kiraupahTawarruqStokAudit($tempoh_gadai,$gadai['tempohbayar'],$gadai['kadarupah'],$gadai['bakipjm']);                
                Gadai::on($cawangan_mysql['mysql'])->where('norujukan','=',$gadai['norujukan'])->update(array(
                    'jbg' => $tempoh_gadai,
                    'tempoh' => $tempoh_gadai,
                    'tunggakan' => $upah_semasa,
                ));
            }
        }
    return response()->json('successful',200); 
}
public function kiraupahTawarruqStokAudit($tempoh,$tempohbayar,$kadarupah,$bakipinjaman){
    $bilang_bln = $tempoh - $tempohbayar;
    $upahsemasa_raw = $bilang_bln * (($kadarupah/100 )* $bakipinjaman);
    $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 kiraupahTawarruqStokAuditUjrahOnePercent($tempoh,$tempohbayar,$kadarupah,$bakipinjaman,$nilaimarhun,$margin_semasa){
    $onepercentservices = new Calculation();
    $upah = $onepercentservices->kiraanKeuntunganRebet($bakipinjaman,$nilaimarhun,$kadarupah,$margin_semasa);
    $bilang_bln = $tempoh - $tempohbayar;
    $keuntungan_semasa = $bilang_bln * $upah['onepercent'];
    $ujrah_semasa = $bilang_bln * $upah['ujrah'];
    $keuntungan_semasa = $onepercentservices->getRoundedMethod($keuntungan_semasa);
    $ujrah_semasa = $onepercentservices->getRoundedMethod($ujrah_semasa);

    $pendapatan = $keuntungan_semasa + $ujrah_semasa;
    $arraypendapatan = [
        'keuntungan' => $keuntungan_semasa,
        'ujrah' => $ujrah_semasa,
        'pendapatan' => $pendapatan,
    ];
    return $arraypendapatan;
}

private function tempohTransactionGadai($gadai) : Float{
    if($gadai['t_update'] == null){
        Carbon::parse($gadai['t_gadai'].' '. $gadai['masa']);
    }else{
        Carbon::parse($gadai['t_update'].' 00:00:00' );
    }

    $tarikh_gadai = Carbon::parse($gadai['t_gadai']. ' 00:00:00');
    $current = Carbon::now();
    $tahun_gadai = $tarikh_gadai->year;
    $bulan_gadai = $tarikh_gadai->month;
    $hari_gadai = $tarikh_gadai->day;
    $tahun_semasa = $current->year;
    $bulan_semasa = $current->month;
    $hari_semasa = $current->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;
}


}

