<?php

namespace App\Http\Controllers\Reports;

use App\Cawangan;
use App\Gadai;
use App\Http\Controllers\Controller;
use App\Services\Reports\OnePercentService as ReportOne;
use App\TransaksiKeuntungan;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Support\v1\Calculation as V1Calculation;
use App\Support\v2\Calculation as V2Calculation;

use Lcobucci\JWT\Signer\Rsa;

class OnePercentController extends Controller
{

    public function getKeuntunganImbangDuga(string $kod_cawangan,Request $request)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalKeuntungan('B',$request->tarikh);

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

    public function getUjrahImbangDuga(string $kod_cawangan,Request $request)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalUjrah('B',$request->tarikh);

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

    public function getRoundedImbangDuga(string $kod_cawangan)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalRounded('B');

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

    public function getKeuntunganLejerAm(string $kod_cawangan,Request $request)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalKeuntungan('L',$request->mula,$request->hingga);

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

    public function getUjrahLejerAm(string $kod_cawangan,Request $request)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalUjrah('L',$request->mula,$request->hingga);

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

    public function getRoundedLejerAm(string $kod_cawangan)
    {
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->getTotalRounded('B');

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

    public function getTotalRebate(Request $request){
        $totalrebate = TransaksiKeuntungan::on('mysql7')
            ->where('norujukan',$request->norujukan)
            ->selectRaw('SUM(ujrah - ujrah_rebet) as ujrah')
            ->selectRaw('SUM(onepercent - onepercent_rebet) as onepercent')
            ->first();

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

    public function getAccruedincome(Request $request){
        $reports = new ReportOne($request->kodcaw);
        $response = $reports->calculateAccruedIncome($request);

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

    public function getAllCawanganAccruedIncome(Request $request){
        $reports = new ReportOne($request->kodcaw);
        $response = $reports->getAllCawanganAccruedIncome($request);

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

    public function getCurrentProfit($kod_cawangan,Request $request){
        $reports = new ReportOne($kod_cawangan);
        $response = $reports->CurrentProfit($request->mula,$request->hingga,$kod_cawangan);

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

    public function getStokAuditBackdate(Request $request){
        $cawangan = Cawangan::where('kodcaw','KB2')->first();
        $tarikh = '2024-02-01';

    $akrual = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['t_gadai','<=',$tarikh],['sttebus','=','']])
            ->orWhere([['tagpalsu','=',0],['t_update','>',$tarikh],['sttebus','!=',''],['t_gadai','<=',$tarikh]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC')
            ->get();

            $chunkSize = 100;
            $summationonepercent = 0;
            $summationujrah = 0;
            $summationupah = 0;
            $count = 0;
            $summationbkpjm = 0;
            $array_test = [];

        $akrual->chunk($chunkSize)->each(function ($chunk) use(&$summationupah,&$array_test,$tarikh,&$summationonepercent,&$summationujrah,&$count,&$summationbkpjm) {
            // Process each chunk of items
            foreach ($chunk as $item) {
                $sagbaru = ($item->tagbaru) ? true : false;
                $trans_keun = TransaksiKeuntungan::on('mysql7')->where([['norujukan','=',$item->norujukan],['bayaran_pembiayaan','>=',0]])->whereDate('tarikh_bayaran','<=',$tarikh)->get();
                
                if($sagbaru == false){
                $tawarruqservices = new V1Calculation();
                }else{
                    $calculation = new V2Calculation();
                }

                if($trans_keun->isNotEmpty()){
                    $bakipinjaman = $item->pinjaman;
                    $last_transaction = Carbon::parse($trans_keun->last()->tarikh_bayaran)->toDateString();
                    if($last_transaction > $tarikh){
                        $last_transaction = $tarikh;
                    }

                    $trans_keun->each(function($trans) use(&$bakipinjaman){
                        $bakipinjaman -= $trans['bayaran_pembiayaan'];
                    });
                    
                    

                    $kiraan = ($sagbaru) ? $calculation->kiraanKeuntunganRebet($bakipinjaman,$item->nilaimarhun,$item->kadarupah,(($bakipinjaman/$item->nilaimarhun) * 100)) : $tawarruqservices->kiraanTawarruq($bakipinjaman,$item->kadarupah);
                    $tempoh = $this->kiraanTarikhJBG($item->t_gadai,$tarikh);
                    $tempoh_last_transaction = $this->kiraanTarikhJBG($item->t_gadai,$last_transaction);
                    $tempoh_belum_bayar = $tempoh - $tempoh_last_transaction;

                    if($sagbaru){
                        $onepercent = $calculation->getRoundedMethod($kiraan['onepercent'] * $tempoh_belum_bayar);
                        $ujrah = $calculation->getRoundedMethod($kiraan['ujrah'] * $tempoh_belum_bayar);
                        $summationonepercent += $onepercent;
                        $summationujrah += $ujrah;
                        $summationbkpjm += $bakipinjaman;
                        array_push($array_test,['norujukan' => $item->norujukan,'ujrah' => $ujrah,'onepercent' => $onepercent,'pinjaman' => $item->pinjaman, 'bakipjm' => $bakipinjaman,'tempoh' => $tempoh_belum_bayar]);
                    }else{
                        $upahsemasa_raw = $tempoh_belum_bayar * $kiraan;

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

                        $summationupah += $upah_semasa;

                        array_push($array_test,['norujukan' => $item->norujukan,'upah' => $upah_semasa,'pinjaman' => $item->pinjaman, 'bakipjm' => $item->pinjaman,'tempoh' => $tempoh_belum_bayar]);
                    }

                }else{

                    $kiraan = ($sagbaru) ? $calculation->kiraanKeuntunganRebet($item->pinjaman,$item->nilaimarhun,$item->kadarupah,(($item->pinjaman/$item->nilaimarhun) * 100)) : $tawarruqservices->kiraanTawarruq($item->pinjaman,$item->kadarupah);
                    $tempoh = $this->kiraanTarikhJBG($item->t_gadai,$tarikh);
                    
                    if($sagbaru){
                        $onepercent = $calculation->getRoundedMethod($kiraan['onepercent'] * $tempoh);
                        $ujrah = $calculation->getRoundedMethod($kiraan['ujrah'] * $tempoh);
                        $summationonepercent += $onepercent;
                        $summationujrah += $ujrah;
                        $summationbkpjm += $item->pinjaman;

                        array_push($array_test,['norujukan' => $item->norujukan,'ujrah' => $ujrah,'onepercent' => $onepercent,'pinjaman' => $item->pinjaman, 'bakipjm' => $item->pinjaman,'tempoh' => $tempoh]);
                    }else{
                        $upahsemasa_raw = $tempoh * $kiraan;
                        $upah_semasa_round = number_format($upahsemasa_raw,2);
                        $upah_semasa = substr($upah_semasa_round, 0, -1);
                        if(strpos($upah_semasa,',')){
                            $upah_semasa = str_replace(',','',$upah_semasa);
                        }
                        $summationupah += $upah_semasa;
                        array_push($array_test,['norujukan' => $item->norujukan,'upah' => $upah_semasa,'pinjaman' => $item->pinjaman, 'bakipjm' => $item->pinjaman,'tempoh' => $tempoh]);
                    }

                }
                $count++;

            }
        });

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

    }

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