<?php

namespace App\Support\v1;

use App\Audit;
use App\Cawangan;
use App\Gadai;
use App\KadarUpah;
use App\Marhun;
use App\Support\v1\Calculation;
use App\Transaction;
use App\TransaksiKeuntungan;
use Carbon\Carbon;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\DB;

class GadaiV1
{
    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()
              ]);
              return response()->json($gadai, 201);
          });


      }catch(\Exception $e){

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

   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)->count();

        $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 = KadarUpah::where('min','<=',$total_nilai_marhun)->where('max','>=',$total_nilai_marhun)->first();
        $tawarruqservices = new Calculation();

        $upahcalculation = $tawarruqservices->kiraanTawarruq($request->pinjaman,$kadar_raw['kadarupdah']);
        $upah1 = $upahcalculation;
        $upah6 = $upah1 * 6;
        $upah12 = $upah1 * 12;

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

        $gadai = Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$norujukan)
            ->update(array(
                'nilaimarhun' => $total_nilai_marhun,
                'berat'=> $total_berat,
                'pinjaman' => $request->pinjaman,
                'kadarupah' => $kadar_raw['kadarupdah'],
                '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
            ));

        $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 response()->json($gadai, 200);
   }

   public function kiraupahTawarruq($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'];

        $tawarruqservices = new Calculation();
        $keuntungan = $tawarruqservices->kiraanTawarruq($gadai_data['pinjaman'],$gadai_data['kadarupah']);
        $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 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'];

        $tawarruqservices = new Calculation();
        $keuntungan = $tawarruqservices->kiraanTawarruq($gadai_data['pinjaman'],$gadai_data['kadarupah']);

        $upahrebet_raw = $bilang_bln * $keuntungan;

        $upah_rebet_round = number_format($upahrebet_raw,2);
        $upah_rebet = substr($upah_rebet_round, 0, -1);
        if(strpos($upah_rebet,',')){
        $upah_rebet = str_replace(',','',$upah_rebet);
        }
        // $upah_rebet = floatval(preg_replace('/[^\d.]/', '', $upah_rebet));

        return $upah_rebet;

    }

    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->kiraupahTawarruq($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;
        }

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

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

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

        $tempoh_gadai = $this->tempohTransactionGadai($gadai);
        $upah_semasa = $this->kiraupahTawarruqStokAudit($tempoh_gadai,$gadai['tempohbayar'],$gadai['kadarupah'],$gadai['bakipjm']);

        $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
        ));

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

        return response()->json("success",200);
        // return response()->json($update_gadai, 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;
            $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;
    }

    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;
    }

   

}
