<?php

namespace App\Http\Controllers;

use App\Bank;
use App\Cawangan;
use App\Gadai;
use App\StokAudit1;
use App\StokAudit2;
use App\StokAudit3;
use App\StokAudit4;
use App\StokAudit5;
use App\StokAudit6;
use App\StokAudit7;
use App\StokAudit8;
use App\StokAudit9;
use App\StokAudit10;
use App\StokAudit11;
use App\StokAudit12;
use App\Support\v2\Calculation as V2Calculation;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class BackupStokAuditController extends Controller
{
    public function backupStokAudit(Request $request){
        if($request->zone == 'all'){
            $cawangan = Cawangan::on('mysql7')->where('version','v2')->get();
        }else{
            $cawangan = Cawangan::on('mysql7')->where('zone',$request->zone)->get();
        }

        $tarikh = Carbon::now();
        $tarikh = $tarikh->subDay(1);

        $month = $tarikh->month;
        $year = $tarikh->year;

        foreach($cawangan as $cawangan_mysql){
            $all_gadai = Gadai::on($cawangan_mysql['mysql'])
                ->where([['tagpalsu','=',0],['sttebus','=','']])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC')->get();
            $data = [];
            foreach($all_gadai as $gadai){
                $tarikh_gadai = Carbon::parse($gadai['t_gadai']. ' 00:00:00');
                $current = Carbon::now();
                $current = $current->subDay(1);

                $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($gadai['tagbaru'] == 0)
                    $upah_semasa = $this->kiraupahTawarruqStokAudit($tempoh_gadai,$gadai['tempohbayar'],$gadai['kadarupah'],$gadai['bakipjm']);
                else
                    $upah_semasa_v2 = $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' => ($gadai['tagbaru'] == 0) ? $upah_semasa : 0,
                    'tunggakanujrah' => ($gadai['tagbaru'] == 1) ? ((isset($upah_semasa_v2)) ? $upah_semasa_v2['ujrah'] : 0) : 0,
                    'tunggakanonepercent' => ($gadai['tagbaru'] == 1) ? ((isset($upah_semasa_v2)) ? $upah_semasa_v2['keuntungan'] : 0) : 0,
                ));

                $data_gadai = [
                    'tahun' => $year,
                    'bulan' => $month,
                    'norujukan' => $gadai['norujukan'],
                    'tempoh' => $tempoh_gadai,
                    'nokp' => $gadai['nokp'],
                    'berat' => $gadai['berat'],
                    'nilaimarhun' => $gadai['nilaimarhun'],
                    'pinjaman' => $gadai['pinjaman'],
                    'bakipjm' => $gadai['bakipjm'],
                    'kadarupah' => $gadai['kadarupah'],
                    'tempohblmbyar' => $gadai['tempoh'] - $gadai['tempohbayar'],
                    'upahblmbyar' => ($gadai['tagbaru'] == 0) ? $upah_semasa : 0,
                    'lanjutan' => $gadai['lelong_tawarruq'],
                    'utgonepercent' => ($gadai['tagbaru'] == 1) ? ((isset($upah_semasa_v2)) ? $upah_semasa_v2['keuntungan'] : 0) : 0,
                    'ujrah' => ($gadai['tagbaru'] == 1) ? ((isset($upah_semasa_v2)) ? $upah_semasa_v2['ujrah'] : 0) : 0,
                ];

                array_push($data,$data_gadai);
            }

            if($month == 1){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit1::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 2){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit2::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 3){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit3::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 4){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit4::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 5){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit5::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 6){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit6::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 7){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit7::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 8){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit8::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 9){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit9::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 10){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit10::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 11){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit11::on($cawangan_mysql['mysql'])->insert($t);
                }
            }elseif($month == 12){
                foreach (array_chunk($data,1000) as $t)
                {
                    StokAudit12::on($cawangan_mysql['mysql'])->insert($t);
                }
            }
        }

        return 'success';
    }

    public function backupStokAuditProblem(Request $request){
        // if($request->zone == 'all'){
        //     $cawangan = Cawangan::on('mysql7')->get();
        // }else{
        //     $cawangan = Cawangan::on('mysql7')->where('zone',$request->zone)->get();
        // }
        $cawangan = Cawangan::on('mysql7')->where('kodcaw',$request->kodcaw)->first();
        // $tarikh = Carbon::now();
        // $tarikh = $tarikh->subDay(1);
        $tarikh = Carbon::parse($request->dateProblem . ' 00:00:00');
        $month = $tarikh->month;
        $year = $tarikh->year;

        $all_gadai = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['sttebus','=','']])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC')->get();
        $data = [];
        foreach($all_gadai as $gadai){
            $tarikh_gadai = Carbon::parse($gadai['t_gadai']. ' 00:00:00');
            // $current = Carbon::now();
            // $current = $current->subDay(1);
            $current = Carbon::parse($request->dateProblem . ' 00:00:00');

            $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'])->where('norujukan','=',$gadai['norujukan'])->update(array(
                'jbg' => $tempoh_gadai,
                'tempoh' => $tempoh_gadai,
                'tunggakan' => $upah_semasa
            ));

            $data_gadai = [
                'tahun' => $year,
                'bulan' => $month,
                'norujukan' => $gadai['norujukan'],
                'tempoh' => $tempoh_gadai,
                'nokp' => $gadai['nokp'],
                'berat' => $gadai['berat'],
                'nilaimarhun' => $gadai['nilaimarhun'],
                'pinjaman' => $gadai['pinjaman'],
                'bakipjm' => $gadai['bakipjm'],
                'kadarupah' => $gadai['kadarupah'],
                'tempohblmbyar' => $gadai['tempoh'] - $gadai['tempohbayar'],
                'upahblmbyar' => $upah_semasa,
                'lanjutan' => $gadai['lelong_tawarruq']
            ];

            array_push($data,$data_gadai);
        }

        if($month == 1){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit1::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 2){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit2::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 3){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit3::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 4){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit4::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 5){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit5::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 6){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit6::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 7){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit7::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 8){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit8::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 9){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit9::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 10){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit10::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 11){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit11::on($cawangan['mysql'])->insert($t);
            }
        }elseif($month == 12){
            foreach (array_chunk($data,1000) as $t)
            {
                StokAudit12::on($cawangan['mysql'])->insert($t);
            }
        }
        // foreach($cawangan as $cawangan_mysql){

        // }

        return 'success';
    }

    public function kiraupahTawarruqStokAudit($tempoh,$tempohbayar,$kadarupah,$bakipinjaman){
        $tempoh = ($tempoh > 12) ? 12 : $tempoh;
        $bilang_bln = $tempoh - $tempohbayar;

        if($bilang_bln > 12){
            $bilang_bln = 12;
        }

        $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 LaporanAuditBackdate(Request $request)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $bulan = $request->bulan;
        $tahun = $request->tahun;

        if($bulan == 1){
            $audit = StokAudit1::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 2){
            $audit = StokAudit2::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 3){
            $audit = StokAudit3::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 4){
            $audit = StokAudit4::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 5){
            $audit = StokAudit5::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 6){
            $audit = StokAudit6::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 7){
            $audit = StokAudit7::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 8){
            $audit = StokAudit8::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 9){
            $audit = StokAudit9::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 10){
            $audit = StokAudit10::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 11){
            $audit = StokAudit11::on($cawangan['mysql'])->where('tahun',$tahun);
        }elseif($bulan == 12){
            $audit = StokAudit12::on($cawangan['mysql'])->where('tahun',$tahun);
        }

        $audit->where('pinjaman', '!=', '0.0');

        $rekodaudit = $audit->get();
        $totalrekod = $audit->sum('pinjaman');
        $totalberat = $audit->sum('berat');
        $totalnilaimarhun = $audit->sum('nilaimarhun');
        $totalpinjaman = $audit->sum('pinjaman');
        $totalbakipjm = $audit->sum('bakipjm');
        $totaltunggakan = $audit->sum('upahblmbyar');
        $totalonepercent = $audit->sum('utgonepercent');
        $totalujrah = $audit->sum('ujrah');

        $arrayrekod = ['rekod' => $rekodaudit, 'total' => $totalrekod,'totalberat' => $totalberat,'totalnilaimarhun' =>  $totalnilaimarhun,'totalpinjaman'=>$totalpinjaman,'totalbakipjm'=>$totalbakipjm,'totaltunggakan'=>$totaltunggakan,'totalujrah'=>$totalujrah,'totalonepercent'=>$totalonepercent];

        if(sizeof($rekodaudit) == 0){
            return response()->json('failed',200);
        }else{
            return response()->json($arrayrekod,200);
        }
    }

    public function backupStokAuditProblemAkru(Request $request){

        /* Classify all possible error */

        $this->validate($request, [
            'month' => 'required|numeric',
            'kodcaw' => 'required',
            'year' => 'required|numeric'
        ]);

        try{
            $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->firstOrFail();
        }catch(ModelNotFoundException $e){
            return response(['status' => 'error', 'message' => '[500]: Cawangan not found']);
        }catch(\Exception $e){
            return response(['status' => 'error', 'message' => '[500]: An exception found']);
        }

        $month = $request->month;
        $className = "App\StokAudit{$month}";

        if(class_exists($className))
            $stock_connection = $className::on($cawangan['mysql']);
        else
            return response(['status' => 'error', 'message' => '[500]: error not found class']);

        /* Algorithm to update the data */

        try{
            DB::beginTransaction();

            $stokaudit = $className::on($cawangan['mysql'])->where('tahun',$request->year)->where('kadarupah','<',1)->get();
            $stokaudit->filter(function ($q) use ($className,$cawangan) {
                $calculation = new V2Calculation();

                $kiraan = $calculation->kiraanKeuntunganRebet($q['bakipjm'],$q['nilaimarhun'],$q['kadarupah'],(($q['bakipjm']/$q['nilaimarhun']) * 100));
                
                $className::on($cawangan['mysql'])->where('norujukan',$q['norujukan'])->update(array(
                    'upahblmbyar' => 0,
                    'utgonepercent' => $calculation->getRoundedMethod($kiraan['onepercent'] * $q['tempohblmbyar']),
                    'ujrah' => $calculation->getRoundedMethod($kiraan['ujrah'] * $q['tempohblmbyar']),
                ));
            });

            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            return response(['status' => 'error', 'message' => '[500]: Transaction Failed - ' . $e->getMessage()]);
        }

        return response(['status' => 'success', 'message' => '[200]: update all data']);
    }

    public function kiraupahTawarruqStokAuditUjrahOnePercent($tempoh,$tempohbayar,$kadarupah,$bakipinjaman,$nilaimarhun,$margin_semasa){
        $onepercentservices = new V2Calculation();
        $upah = $onepercentservices->kiraanKeuntunganRebet($bakipinjaman,$nilaimarhun,$kadarupah,$margin_semasa);
        $tempoh = ($tempoh > 12) ? 12 : $tempoh;
        $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;
    }
}
