<?php

namespace App\Http\Controllers;

use App\ApprovalWithdrawal;
use App\Bank;
use App\Cawangan;
use App\Denominasi;
use App\DenoPendSer;
use App\GlDetail;
use App\Vault;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AutoSerahanController extends Controller
{
    public function getAutoSerahan(Request $request){
        $query = ApprovalWithdrawal::on('mysql7')->where('approval_status', 'PENDING');
        if (isset($request->kodcaw)) $query->where('kodcaw', '=', $request->kodcaw);
        $listapproval = $query->paginate(5);

        return response()->json($listapproval,200);
    }

    public function deleteAutoSerahan(Request $request){
        $current = Carbon::now();
  
        DB::connection('mysql7')->beginTransaction();

        try{
            if($request->version == 'v3'){
                $listapproval = ApprovalWithdrawal::on('mysql7')
                ->where('gldetail_id_v2',$request->recno)
                ->where('approval_status',"APPROVED")
                ->where('action','create')
                ->where('updated_serahan_v2',1)
                ->where('updated_pendahuluan_v3',1);

                $listapproval = optional($listapproval)->first();

                $approval = ApprovalWithdrawal::on('mysql7')->create([
                    'kodcaw' => ($request->version == 'v3') ? $this->interchangeCawangan($request->kodcaw,$request->version) : $request->kodcaw,
                    'action' => 'delete',
                    'pc_name' => $request->teller,
                    'operasi_name' => null,
                    'amount' => $request->amaun,
                    'approval_status' => 'PENDING',
                    'approval_timestamp' => null,
                    'gldetail_id_v3' => $listapproval['gldetail_id_v3'],
                    'gldetail_id_v2' => isset($request->recno) ? $request->recno : 0,
                    'denopendser_id_v3' => $listapproval['denopendser_id_v3'],
                    'denopendser_id_v2' => $listapproval['denopendser_id_v2'],
                    'updated_serahan_v2' => $listapproval['updated_serahan_v2'],
                    'updated_pendahuluan_v3' => $listapproval['updated_pendahuluan_v3'],
                    'created_at' => $current,
                    'updated_at' => $current,
                ]);
                DB::connection('mysql7')->commit();
                return response()->json(['status' => 'success','id' => $approval->id]);
            }

        }catch(\Exception $e){
            DB::connection('mysql7')->rollBack();
            return response()->json(['status' => 'failed','message' => $e->getMessage()]);   
        }
    }

    public function createAutoSerahan(Request $request)
    {
        $current = Carbon::now();
  
        DB::connection('mysql7')->beginTransaction();

        try{

            $deno_pendser = DenoPendSer::on('mysql7')->create([
                'tarikh' => $current->toDateString(),
                'masa' => $current->toTimeString(),
                'kodcaw' => ($request->version == 'v3') ? $this->interchangeCawangan($request->kodcaw,$request->version) : $request->kodcaw,
                'kodlaluan' => $request->teller,
                'amaun' => $request->amaun,
                'bd1' => 0,
                'bd5' => 0,
                'bd10' => 0,
                'bd20' => 0,
                'bd50' => 0,
                'bd100' => 0,
                'txtring1' => isset($request->txtring1) ? $request->txtring1 : 0,
                'txtring5' => isset($request->txtring5) ? $request->txtring5 : 0,
                'txtring10' => isset($request->txtring10) ? $request->txtring10 : 0,
                'txtring20' => isset($request->txtring20) ? $request->txtring20 : 0,
                'txtring50' => isset($request->txtring50) ? $request->txtring50 : 0,
                'txtring100' => isset($request->txtring100) ? $request->txtring100 : 0,
                'txtring1000' => isset($request->txtring1000) ? $request->txtring1000 : 0,
                'txtsen1' => isset($request->txtsen1) ? $request->txtsen1 : 0,
                'txtsen5' => isset($request->txtsen5) ? $request->txtsen5 : 0,
                'txtsen10' => isset($request->txtsen10) ? $request->txtsen10 : 0,
                'txtsen20' => isset($request->txtsen20) ? $request->txtsen20 : 0,
                'txtsen50' => isset($request->txtsen50) ? $request->txtsen50 : 0,
                'jenis' =>$request->jenis,
                'recno' => 0,
                'update' => 0
            ]);

            if($request->version == 'v3'){
                $approval = ApprovalWithdrawal::on('mysql7')->create([
                    'kodcaw' => ($request->version == 'v3') ? $this->interchangeCawangan($request->kodcaw,$request->version) : $request->kodcaw,
                    'action' => 'create',
                    'pc_name' => $request->teller,
                    'operasi_name' => null,
                    'amount' => $request->amaun,
                    'approval_status' => 'PENDING',
                    'approval_timestamp' => null,
                    'gldetail_id_v3' => 0,
                    'gldetail_id_v2' => 0,
                    'denopendser_id_v3' => $deno_pendser->id,
                    'denopendser_id_v2' => 0,
                    'updated_serahan_v2' => 0,
                    'updated_pendahuluan_v3' => 0,
                    'created_at' => $current,
                    'action' => 'create',
                    'updated_at' => $current,
                ]);
                DB::connection('mysql7')->commit();
                return response()->json(['status' => 'success','id' => $approval->id]);
            }else{
                if(!isset($request->id)){
                    return response()->json(['status' => 'failed','message' => 'ID is required']);
                }
                Log::debug($request->id);
                DB::connection('mysql7')->commit();
                return response()->json(['status' => 'success','denoid' => $deno_pendser->id]);
            }

        }catch(\Exception $e){
            DB::connection('mysql7')->rollBack();
           return response()->json(['status' => 'failed','message' => $e->getMessage()]);
        }
     }
  
    private function autoSerahanEngine($jenis, $kodcaw,$teller,$amaun,$id,$denopendser_id){
        $current = Carbon::now();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $vault = Vault::on($cawangan['mysql'])->where('kodcaw','=',$kodcaw)->where('tarikh','=',$current->toDateString())->orderby('tarikh','desc')->first();

        $bakiawal = $vault['bakiawal'];
        $keluar = $vault['keluar'];
        $masuk = $vault['masuk'];
        $bakiakhir = $vault['bakiakhir'];
        $pendahuluan = $vault['pendahuluan'];
        $serahan = $vault['serahan'];
        $totpanjaran = $vault['totpanjar'];
        
        DB::connection($cawangan['mysql'])->beginTransaction();
        DB::connection('mysql7')->beginTransaction();

        try{
            $approval = ApprovalWithdrawal::on('mysql7')->where('id',$id)->first();
        
            
            if($jenis == 'pendahuluan'){
        
                $pendserid = empty($approval) ? $denopendser_id : $approval['denopendser_id_v3'];

                $totalpendahuluan = $amaun + $pendahuluan;
        
                $bakiakhir = $bakiawal - $keluar + $masuk + $totalpendahuluan - $serahan - $totpanjaran;
        
                $denopendser = DenoPendSer::on('mysql7')->where('no',$pendserid)->first();

                $this->updateDenominasi($kodcaw,$denopendser,$jenis);

                $gldetail = GlDetail::on($cawangan['mysql'])->create([
                    'kodcaw' => $kodcaw,
                    'tarikh' => $current->toDateString(),
                    'dtacct' => '1000/010',
                    'ktacct' => '7000/102',
                    'descpt' => 'Pendahuluan Daripada V2',
                    'pendahuluan' => $amaun,
                    'teller' => $teller . ' (AUTO V2)',
                    'date_created' => $current
                ]);

                DenoPendSer::on('mysql7')->where('no',$pendserid)->update(array(
                    'recno' => $gldetail->id,
                    'update' => 1
                ));

                Vault::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()],['kodcaw','=', $kodcaw]])->update(array(
                    'pendahuluan' => $totalpendahuluan,
                    'bakiakhir' => $bakiakhir,
                    'bakieod' => $bakiakhir
                ));

                ApprovalWithdrawal::on('mysql7')->where('id',$id)->update(array(
                    'updated_pendahuluan_v3' => 1,
                    'gldetail_id_v3' => $gldetail->id
                ));

            }else if($jenis == 'serahan'){
        
                $pendserid = empty($approval) ? $denopendser_id : $approval['denopendser_id_v2'];

                $totalserahan = $amaun + $serahan;

                $bakiakhir = $bakiawal - $keluar  + $masuk + $pendahuluan - $totalserahan - $totpanjaran;

                $denopendser = DenoPendSer::on('mysql7')->where('no',$pendserid)->first();

                $this->updateDenominasi($kodcaw,$denopendser,$jenis);

                $gldetail = GlDetail::on($cawangan['mysql'])->create([
                    'kodcaw' => $kodcaw,
                    'tarikh' => $current->toDateString(),
                    'dtacct' => '1000/010',
                    'ktacct' => '1000/020',
                    'descpt' => 'Serahan Kepada V3',
                    'serahan' => $amaun,
                    'teller' => $teller . ' (AUTO V3)',
                    'date_created' => $current
                ]);

                DenoPendSer::on('mysql7')->where('no',$pendserid)->update(array(
                    'recno' => $gldetail->id,
                    'update' => 1
                ));

                Vault::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()],['kodcaw','=', $kodcaw]])->update(array(
                    'serahan' => $totalserahan,
                    'bakiakhir' => $bakiakhir,
                    'bakieod' => $bakiakhir
                ));

            }

            // Commit transactions
            DB::connection($cawangan['mysql'])->commit();
            DB::connection('mysql7')->commit();
            return ['status' => 'success','gldetail_id' => $gldetail->id];  

        }catch(\Exception $e){
            DB::connection($cawangan['mysql'])->rollBack();
            DB::connection('mysql7')->rollBack();
            throw $e;
        }
    }

    public function autoSerahanApproval(Request $request){
        $current = Carbon::now();
        
        DB::connection('mysql7')->beginTransaction();

        try{
            $approval = ApprovalWithdrawal::on('mysql7')->where('id',$request->id)->first();

            if($request->action == 'delete'){
                
            }

            if($approval->approval_status == 'PENDING' && $request->sendApproval == 'ACCEPTED'){
                $approval->operasi_name = $request->operasi_name;
                $approval->approval_status = 'APPROVED';
                $approval->approval_timestamp = $current;
                $approval->save();

                DB::connection('mysql7')->commit();
                return response()->json(['status' => 'success','approve_status' => 'approved'],200);
            }else{
                $approval->operasi_name = $request->operasi_name;
                $approval->approval_status = 'REJECTED';
                $approval->approval_timestamp = $current;
                $approval->save();

                DB::connection('mysql7')->commit();
                return response()->json(['status' => 'success','approve_status' => 'rejected'],200);
            }

        }catch(\Exception $e){
            DB::connection('mysql7')->rollBack();
            return response()->json(['status' => 'error','message' =>$e->getMessage(), 'line' => $e->getLine()]);
        }
    }

    private function updateDenominasi($kodcaw,$denopendser,$jenis){
        $current = Carbon::now();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $version = ($jenis == 'pendahuluan') ? 'v3' : 'v2';
        $current_denominasi = $this->checkDenominasi($kodcaw,$version);

        if($jenis == 'pendahuluan'){
            $k1 = ($denopendser['txtring1'] * 1) + $current_denominasi['k1'];
            $txtring1 = $denopendser['txtring1'] + $current_denominasi['txtring1'];
            $k5 = ($denopendser['txtring5'] * 5) + $current_denominasi['k5'];
            $txtring5 = $denopendser['txtring5'] + $current_denominasi['txtring5'];
            $k01 = ($denopendser['txtsen1'] * 0.01) + $current_denominasi['k01'];
            $txtsen1 = $denopendser['txtsen1'] + $current_denominasi['txtsen1'];
            $k05 = ($denopendser['txtsen5'] * 0.05) + $current_denominasi['k05'];
            $txtsen5 = $denopendser['txtsen5'] + $current_denominasi['txtsen5'];
            $k010 = ($denopendser['txtsen10'] * 0.10) + $current_denominasi['k010'];
            $txtsen10 = $denopendser['txtsen10'] + $current_denominasi['txtsen10'];
            $k020 = ($denopendser['txtsen20'] * 0.20) + $current_denominasi['k020'];
            $txtsen20 = $denopendser['txtsen20'] + $current_denominasi['txtsen20'];
            $k050 = ($denopendser['txtsen50'] * 0.50) + $current_denominasi['k050'];
            $txtsen50 = $denopendser['txtsen50'] + $current_denominasi['txtsen50'];
            $k10 = ($denopendser['txtring10'] * 10) + $current_denominasi['k10'];
            $txtring10 = $denopendser['txtring10'] + $current_denominasi['txtring10'];
            $k20 = ($denopendser['txtring20'] * 20) + $current_denominasi['k20'];
            $txtring20 = $denopendser['txtring20'] + $current_denominasi['txtring20'];
            $k50 = ($denopendser['txtring50'] * 50) + $current_denominasi['k50'];
            $txtring50 = $denopendser['txtring50'] + $current_denominasi['txtring50'];
            $k100 = ($denopendser['txtring100'] * 100) + $current_denominasi['k100'];
            $txtring100 = $denopendser['txtring100'] + $current_denominasi['txtring100'];
        }else{
            $k1 = $current_denominasi['k1'] - ($denopendser['txtring1'] * 1);
            $txtring1 = $current_denominasi['txtring1'] - $denopendser['txtring1'];
            $k5 = $current_denominasi['k5'] - ($denopendser['txtring5'] * 5);
            $txtring5 = $current_denominasi['txtring5'] - $denopendser['txtring5'];
            $k01 = $current_denominasi['k01'] - ($denopendser['txtsen1'] * 0.01);
            $txtsen1 = $current_denominasi['txtsen1'] - $denopendser['txtsen1'];
            $k05 = $current_denominasi['k05'] - ($denopendser['txtsen5'] * 0.05);
            $txtsen5 = $current_denominasi['txtsen5'] - $denopendser['txtsen5'];
            $k010 = $current_denominasi['k010'] - ($denopendser['txtsen10'] * 0.10);
            $txtsen10 = $current_denominasi['txtsen10'] - $denopendser['txtsen10'];
            $k020 = $current_denominasi['k020'] - ($denopendser['txtsen20'] * 0.20);
            $txtsen20 = $current_denominasi['txtsen20'] - $denopendser['txtsen20'];
            $k050 = $current_denominasi['k050'] - ($denopendser['txtsen50'] * 0.50);
            $txtsen50 = $current_denominasi['txtsen50'] - $denopendser['txtsen50'];
            $k10 = $current_denominasi['k10'] - ($denopendser['txtring10'] * 10);
            $txtring10 = $current_denominasi['txtring10'] - $denopendser['txtring10'];
            $k20 = $current_denominasi['k20'] - ($denopendser['txtring20'] * 20);
            $txtring20 = $current_denominasi['txtring20'] - $denopendser['txtring20'];
            $k50 = $current_denominasi['k50'] - ($denopendser['txtring50'] * 50);
            $txtring50 = $current_denominasi['txtring50'] - $denopendser['txtring50'];
            $k100 = $current_denominasi['k100'] - ($denopendser['txtring100'] * 100);
            $txtring100 = $current_denominasi['txtring100'] - $denopendser['txtring100'];
        }

        $totalkeping = $k01 + $k05 + $k010 + $k020 + $k050 + $k1 + $k5 + $k10 + $k20 + $k50 + $k100;

        Denominasi::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()]])->update(array(
            'bd1' => 0,
            'b1'=> 0,
            'bd5'=> 0,
            'b5'=> 0,
            'bd10'=> 0,
            'b10'=> 0,
            'bd20'=> 0,
            'b20'=> 0,
            'bd50'=> 0,
            'b50'=> 0,
            'bd100'=> 0,
            'b100'=> 0,
            'txtring1'=> $txtring1,
            'k1'=> $k1,
            'txtring5'=> $txtring5,
            'k5'=> $k5,
            'txtsen1'=> $txtsen1,
            'k01'=> $k01,
            'txtsen5'=> $txtsen5,
            'k05'=> $k05,
            'txtsen10'=> $txtsen10,
            'k010'=> $k010,
            'txtsen20'=> $txtsen20,
            'k020'=> $k020,
            'txtsen50'=> $txtsen50,
            'k050'=> $k050,
            'txtring10'=> $txtring10,
            'k10'=> $k10,
            'txtring20'=> $txtring20,
            'k20'=> $k20,
            'txtring50'=> $txtring50,
            'k50'=> $k50,
            'txtring100'=> $txtring100,
            'k100'=> $k100,
            'jumlahbundle'=> 0,
            'txtjumlah'=> $totalkeping,
            'jumlahkeping' => $totalkeping
        ));
    }

    private function updateDenominasiRemove($kodcaw,$denopendser,$jenis){
        $current = Carbon::now();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $version = ($jenis == 'pendahuluan') ? 'v3' : 'v2';
        $current_denominasi = $this->checkDenominasi($kodcaw,$version);

        if($jenis == 'pendahuluan'){
            $k1 = ($denopendser['txtring1'] * 1) - $current_denominasi['k1'];
            $txtring1 = $denopendser['txtring1'] - $current_denominasi['txtring1'];
            $k5 = ($denopendser['txtring5'] * 5) - $current_denominasi['k5'];
            $txtring5 = $denopendser['txtring5'] - $current_denominasi['txtring5'];
            $k01 = ($denopendser['txtsen1'] * 0.01) - $current_denominasi['k01'];
            $txtsen1 = $denopendser['txtsen1'] - $current_denominasi['txtsen1'];
            $k05 = ($denopendser['txtsen5'] * 0.05) - $current_denominasi['k05'];
            $txtsen5 = $denopendser['txtsen5'] - $current_denominasi['txtsen5'];
            $k010 = ($denopendser['txtsen10'] * 0.10) - $current_denominasi['k010'];
            $txtsen10 = $denopendser['txtsen10'] - $current_denominasi['txtsen10'];
            $k020 = ($denopendser['txtsen20'] * 0.20) - $current_denominasi['k020'];
            $txtsen20 = $denopendser['txtsen20'] - $current_denominasi['txtsen20'];
            $k050 = ($denopendser['txtsen50'] * 0.50) - $current_denominasi['k050'];
            $txtsen50 = $denopendser['txtsen50'] - $current_denominasi['txtsen50'];
            $k10 = ($denopendser['txtring10'] * 10) - $current_denominasi['k10'];
            $txtring10 = $denopendser['txtring10'] - $current_denominasi['txtring10'];
            $k20 = ($denopendser['txtring20'] * 20) - $current_denominasi['k20'];
            $txtring20 = $denopendser['txtring20'] - $current_denominasi['txtring20'];
            $k50 = ($denopendser['txtring50'] * 50) - $current_denominasi['k50'];
            $txtring50 = $denopendser['txtring50'] - $current_denominasi['txtring50'];
            $k100 = ($denopendser['txtring100'] * 100) - $current_denominasi['k100'];
            $txtring100 = $denopendser['txtring100'] - $current_denominasi['txtring100'];
        }else{
            $k1 = $current_denominasi['k1'] + ($denopendser['txtring1'] * 1);
            $txtring1 = $current_denominasi['txtring1'] + $denopendser['txtring1'];
            $k5 = $current_denominasi['k5'] + ($denopendser['txtring5'] * 5);
            $txtring5 = $current_denominasi['txtring5'] + $denopendser['txtring5'];
            $k01 = $current_denominasi['k01'] + ($denopendser['txtsen1'] * 0.01);
            $txtsen1 = $current_denominasi['txtsen1'] + $denopendser['txtsen1'];
            $k05 = $current_denominasi['k05'] + ($denopendser['txtsen5'] * 0.05);
            $txtsen5 = $current_denominasi['txtsen5'] + $denopendser['txtsen5'];
            $k010 = $current_denominasi['k010'] + ($denopendser['txtsen10'] * 0.10);
            $txtsen10 = $current_denominasi['txtsen10'] + $denopendser['txtsen10'];
            $k020 = $current_denominasi['k020'] + ($denopendser['txtsen20'] * 0.20);
            $txtsen20 = $current_denominasi['txtsen20'] + $denopendser['txtsen20'];
            $k050 = $current_denominasi['k050'] + ($denopendser['txtsen50'] * 0.50);
            $txtsen50 = $current_denominasi['txtsen50'] + $denopendser['txtsen50'];
            $k10 = $current_denominasi['k10'] + ($denopendser['txtring10'] * 10);
            $txtring10 = $current_denominasi['txtring10'] + $denopendser['txtring10'];
            $k20 = $current_denominasi['k20'] + ($denopendser['txtring20'] * 20);
            $txtring20 = $current_denominasi['txtring20'] + $denopendser['txtring20'];
            $k50 = $current_denominasi['k50'] + ($denopendser['txtring50'] * 50);
            $txtring50 = $current_denominasi['txtring50'] + $denopendser['txtring50'];
            $k100 = $current_denominasi['k100'] + ($denopendser['txtring100'] * 100);
            $txtring100 = $current_denominasi['txtring100'] + $denopendser['txtring100'];
        }

        $totalkeping = $k01 + $k05 + $k010 + $k020 + $k050 + $k1 + $k5 + $k10 + $k20 + $k50 + $k100;

        Denominasi::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()]])->update(array(
            'bd1' => 0,
            'b1'=> 0,
            'bd5'=> 0,
            'b5'=> 0,
            'bd10'=> 0,
            'b10'=> 0,
            'bd20'=> 0,
            'b20'=> 0,
            'bd50'=> 0,
            'b50'=> 0,
            'bd100'=> 0,
            'b100'=> 0,
            'txtring1'=> $txtring1,
            'k1'=> $k1,
            'txtring5'=> $txtring5,
            'k5'=> $k5,
            'txtsen1'=> $txtsen1,
            'k01'=> $k01,
            'txtsen5'=> $txtsen5,
            'k05'=> $k05,
            'txtsen10'=> $txtsen10,
            'k010'=> $k010,
            'txtsen20'=> $txtsen20,
            'k020'=> $k020,
            'txtsen50'=> $txtsen50,
            'k050'=> $k050,
            'txtring10'=> $txtring10,
            'k10'=> $k10,
            'txtring20'=> $txtring20,
            'k20'=> $k20,
            'txtring50'=> $txtring50,
            'k50'=> $k50,
            'txtring100'=> $txtring100,
            'k100'=> $k100,
            'jumlahbundle'=> 0,
            'txtjumlah'=> $totalkeping,
            'jumlahkeping' => $totalkeping
        ));
    }

    public function serahanAutoSerahan(Request $request){

        $this->checkVault($request->kodcaw,'v2');
        $this->checkDenominasi($request->kodcaw,'v2');

        $kodcaw = $this->interchangeCawangan($request->kodcaw,'v2');

        $updated_serahan = $this->autoSerahanEngine('serahan',$kodcaw,$request->teller,$request->amaun,$request->id,$request->denopendser_id);

        return response()->json(['status' => 'success','gldetail_id' => $updated_serahan['gldetail_id']],200);
    }

    public function pendahuluanAutoSerahan(Request $request){

        $this->checkVault($request->kodcaw,'v3');
        $this->checkDenominasi($request->kodcaw,'v3');
        
        $kodcaw = $this->interchangeCawangan($request->kodcaw,'v3');

        $updated_pendahuluan = $this->autoSerahanEngine('pendahuluan',$kodcaw,$request->teller,$request->amaun,$request->id,$request->denopendser_id);
        
        return response()->json(['status' => 'success','gldetail_id' => $updated_pendahuluan['gldetail_id']],200);
    }

    public function removeAutoSerahan(Request $request){
        $this->checkVault($request->kodcaw,'v2');
        $this->checkDenominasi($request->kodcaw,'v2');

        $kodcaw = $this->interchangeCawangan($request->kodcaw,'v2');

        $updated_serahan = $this->autoSerahanRemove('serahan',$kodcaw,$request->amaun,$request->array_approval);

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

    }

    public function removeAutoPendahuluan(Request $request){
        $this->checkVault($request->kodcaw,'v3');
        $this->checkDenominasi($request->kodcaw,'v3');
        
        $kodcaw = $this->interchangeCawangan($request->kodcaw,'v3');

        $updated_pendahuluan = $this->autoSerahanRemove('pendahuluan',$kodcaw,$request->amaun,$request->array_approval);

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

    private function autoSerahanRemove($jenis,$kodcaw,$amaun,$id){
        $current = Carbon::now();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $vault = Vault::on($cawangan['mysql'])->where('kodcaw','=',$kodcaw)->where('tarikh','=',$current->toDateString())->orderby('tarikh','desc')->first();

        $bakiawal = $vault['bakiawal'];
        $keluar = $vault['keluar'];
        $masuk = $vault['masuk'];
        $bakiakhir = $vault['bakiakhir'];
        $pendahuluan = $vault['pendahuluan'];
        $serahan = $vault['serahan'];
        $totpanjaran = $vault['totpanjar'];
        
        DB::connection($cawangan['mysql'])->beginTransaction();
        DB::connection('mysql7')->beginTransaction();

        try{
            if($jenis == 'pendahuluan'){
                $approval = $id;

                $totalpendahuluan = $pendahuluan - $amaun;
        
                $bakiakhir = $bakiawal - $keluar + $masuk + $totalpendahuluan - $serahan - $totpanjaran;
                $denopendser = Denopendser::on('mysql7')->where('no', $approval['denopendser_id_v3']);
                $denopendser = optional($denopendser)->first();

                $this->updateDenominasiRemove($kodcaw,$denopendser,'pendahuluan');

                Vault::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()],['kodcaw','=', $kodcaw]])->update(array(
                    'pendahuluan' => $totalpendahuluan,
                    'bakiakhir' => $bakiakhir,
                    'bakieod' => $bakiakhir
                ));

                $gldetail_remove = GlDetail::on($cawangan['mysql'])->where('recno', $approval['gldetail_id_v3'])->delete();
                DenoPendSer::on('mysql7')->where('no', $approval['denopendser_id_v3'])->delete();

                Log::info('gldetail');
                Log::debug($gldetail_remove);
                ApprovalWithdrawal::on('mysql7')->where('id',$id)->update(array(
                    'updated_pendahuluan_v3' => 1,
                ));
            }else{
                $approval = $id;

                $totalserahan = $serahan - $amaun;

                $bakiakhir = $bakiawal - $keluar  + $masuk + $pendahuluan - $totalserahan - $totpanjaran;
                $denopendser = Denopendser::on('mysql7')->where('no', $approval['denopendser_id_v2']);
                $denopendser = optional($denopendser)->first();

                $this->updateDenominasiRemove($kodcaw,$denopendser,'serahan');

                Vault::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()],['kodcaw','=', $kodcaw]])->update(array(
                    'serahan' => $totalserahan,
                    'bakiakhir' => $bakiakhir,
                    'bakieod' => $bakiakhir
                ));

                GlDetail::on($cawangan['mysql'])->where('recno', $approval['gldetail_id_v2'])->delete();
                DenoPendSer::on('mysql7')->where('no', $approval['denopendser_id_v2'])->delete();

                ApprovalWithdrawal::on('mysql7')->where('id',$id)->update(array(
                    'updated_serahan_v2' => 1,
                ));
            }

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

        }catch(\Exception $e){
            DB::connection($cawangan['mysql'])->rollBack();
            DB::connection('mysql7')->rollBack();
            throw $e;
        }
    }

    public function SetApprovalWithdrawal(Request $request){

    if($request->jenis == 'create'){
        ApprovalWithdrawal::on('mysql7')->where('id', $request->id)->update([                   
            'denopendser_id_v2' => $request->deno_id,
        ]);

        return response()->json(['status' => 'success'],200);
    }else{
        ApprovalWithdrawal::on('mysql7')->where('id', $request->id)->update([                   
            'updated_serahan_v2' => 1,
            'gldetail_id_v2' => $request->gldetail_id
        ]);
        return response()->json(['status' => 'success'],200);
    }

    }

    public function getAutoSerahanApproval(Request $request){
        $query = ApprovalWithdrawal::on('mysql7')->where('kodcaw',$request->kodcaw)->where('id',$request->id)->first();
        return response()->json($query,200);
    }

    private function checkVault($kodcaw,$version){

        $kodcaw = $this->interchangeCawangan($kodcaw,$version);
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        
        /* Check Tarikh Harini */
        $available_vault = Vault::on($cawangan['mysql'])->where('tarikh',Carbon::now()->toDateString())->first();

        if($available_vault){
            return $available_vault;
        }else{
            $last_vault = Vault::on($cawangan['mysql'])->where('kodcaw',$kodcaw)->orderby('tarikh','desc')->first();
            if(!$last_vault){
                $vaultcreate = Vault::on($cawangan['mysql'])->create([
                    'kodcaw'=>$kodcaw,
                    'tarikh'=> Carbon::now()->toDateString(),
                    'bakiawal' => 0,
                    'keluar' => 0,
                    'masuk' => 0,
                    'bakiakhir' => 0,
                    'bakieod' => 0,
                    'pendahuluan' => 0,
                    'serahan' => 0,
                    '1sen' => 0,
                    '5sen' => 0,
                    '10sen' => 0,
                    '20sen' => 0,
                    '50sen' => 0,
                    'rm1' => 0,
                    'rm2' => 0,
                    'rm5' => 0,
                    'rm10' => 0,
                    'rm50' => 0,
                    'rm100' => 0,
                    'rm1000' => 0,
                    'totpanjar' => 0
                ]);

                return $vaultcreate;
            }
            
            $new_vault = Vault::on($cawangan['mysql'])->create([
                'kodcaw'=>$kodcaw,
                'tarikh'=> Carbon::now()->toDateString(),
                'bakiawal' => $last_vault['bakiakhir'],
                'keluar' => 0,
                'masuk' => 0,
                'bakiakhir' => $last_vault['bakiakhir'],
                'bakieod' => $last_vault['bakiakhir'],
                'pendahuluan' => 0,
                'serahan' => 0,
                '1sen' => $last_vault['1sen'],
                '5sen' => $last_vault['5sen'],
                '10sen' => $last_vault['10sen'],
                '20sen' => $last_vault['20sen'],
                '50sen' => $last_vault['50sen'],
                'rm1' => $last_vault['rm1'],
                'rm2' => $last_vault['rm2'],
                'rm5' => $last_vault['rm5'],
                'rm10' => $last_vault['rm10'],
                'rm50' => $last_vault['rm50'],
                'rm100' => $last_vault['rm100'],
                'rm1000' => $last_vault['rm1000'],
                'totpanjar' => 0
            ]);
            return $new_vault;
        }
    }

    private function checkDenominasi($kodcaw,$version){
        $kodcaw = $this->interchangeCawangan($kodcaw,$version);

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $current = Carbon::now();
        $denominasi = Denominasi::on($cawangan['mysql'])->where('tarikh',$current->toDateString())->first();
        if($denominasi){
            return $denominasi;
        }else{
            $last_denominasi = Denominasi::on($cawangan['mysql'])->orderby('tarikh','desc')->first();
            if(!$last_denominasi){
                $savedeno = Denominasi::on($cawangan['mysql'])->create([ 
            
                    'tarikh' => $current->toDateString(),
                    'bd1' => 0,
                    'b1' => 0,
                    'bd5' => 0,
                    'b5' => 0,
                    'bd10' => 0,
                    'b10' => 0,
                    'bd20' => 0,
                    'b20' => 0,
                    'bd50' => 0,
                    'b50' => 0,
                    'bd100' => 0,
                    'b100' => 0,
                    'txtring1' => 0,
                    'k1' => 0,
                    'txtring5' => 0,
                    'k5' => 0,
                    'txtsen1' => 0,
                    'k01' => 0,
                    'txtsen5' => 0,
                    'k05' => 0,
                    'txtsen10' => 0,
                    'k010' => 0,
                    'txtsen20' => 0,
                    'k020' => 0,
                    'txtsen50' => 0,
                    'k050' => 0,
                    'txtring10' => 0,
                    'k10' => 0,
                    'txtring20' => 0,
                    'k20' => 0,
                    'txtring50' => 0,
                    'k50' => 0,
                    'txtring100' => 0,
                    'k100' => 0,
                    'txtring1000' => 0,
                    'k1000' => 0,
                    'jumlahbundle' => 0,
                    'txtjumlah' => 0,
                    'lebihan' => 0,
                    'nota' => 0,
                    'jumlahkeping' => 0
                 ]);
                 return $savedeno;
            }

            $savedeno = Denominasi::on($cawangan['mysql'])->create([ 
            
                'tarikh' => $current->toDateString(),
                'bd1' => $last_denominasi['bd1'],
                'b1' => $last_denominasi['b1'],
                'bd5' => $last_denominasi['bd5'],
                'b5' => $last_denominasi['b5'],
                'bd10' => $last_denominasi['bd10'],
                'b10' => $last_denominasi['b10'],
                'bd20' => $last_denominasi['bd20'],
                'b20' => $last_denominasi['b20'],
                'bd50' => $last_denominasi['bd50'],
                'b50' => $last_denominasi['b50'],
                'bd100' => $last_denominasi['bd100'],
                'b100' => $last_denominasi['b100'],
                'txtring1' => $last_denominasi['txtring1'],
                'k1' => $last_denominasi['k1'],
                'txtring5' => $last_denominasi['txtring5'],
                'k5' => $last_denominasi['k5'],
                'txtsen1' => $last_denominasi['txtsen1'],
                'k01' => $last_denominasi['k01'],
                'txtsen5' => $last_denominasi['txtsen5'],
                'k05' => $last_denominasi['k05'],
                'txtsen10' => $last_denominasi['txtsen10'],
                'k010' => $last_denominasi['k010'],
                'txtsen20' => $last_denominasi['txtsen20'],
                'k020' => $last_denominasi['k020'],
                'txtsen50' => $last_denominasi['txtsen50'],
                'k050' => $last_denominasi['k050'],
                'txtring10' => $last_denominasi['txtring10'],
                'k10' => $last_denominasi['k10'],
                'txtring20' => $last_denominasi['txtring20'],
                'k20' => $last_denominasi['k20'],
                'txtring50' => $last_denominasi['txtring50'],
                'k50' => $last_denominasi['k50'],
                'txtring100' => $last_denominasi['txtring100'],
                'k100' => $last_denominasi['k100'],
                'txtring1000' => $last_denominasi['txtring1000'],
                'k1000' => $last_denominasi['k1000'],
                'jumlahbundle' => $last_denominasi['jumlahbundle'],
                'txtjumlah' => $last_denominasi['txtjumlah'],
                'lebihan' => $last_denominasi['lebihan'],
                'nota' => $last_denominasi['nota'],
                'jumlahkeping' => $last_denominasi['jumlahkeping']
             ]);

             return $savedeno;

        }
    }

    public function checkProsesApproval(Request $request){
        $current = new Carbon();
        $current = Carbon::now();

        $proses = ApprovalWithdrawal::on('mysql7')
                ->where([
                    ['pc_name','=',$request->pc_name],
                    ['approval_status','=','PENDING'],
                    ])
                ->whereDate('created_at', $current->toDateString())
                ->get();

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

    private function interchangeCawangan($kodcaw,$version){
        
        if($version == 'v3'){
            switch($kodcaw) {
                case '1STOP':
                $newkodcaw = 'KT1ST';
                break;
                case '010621':
                $newkodcaw = 'PHKTN';
                break;
                case '010620':
                $newkodcaw = 'PHBNT';
                break;
                case '010617':
                $newkodcaw = 'PHRAU';
                break;
                case '010915':
                $newkodcaw = 'PLKGR';
                break;
                case '010219':
                $newkodcaw = 'KDSGP';
                break;
                case '011013':
                $newkodcaw = 'SLKJG';
                break;
                case '011412':
                $newkodcaw = 'KLRJL';
                break;
                case '010618':
                $newkodcaw = 'PHTMR';
                break;
                case '020301':
                $newkodcaw = 'KTJWT';
                break;
                case 'APM':
                $newkodcaw = 'KTPSM';
                break;
                case '020303':
                $newkodcaw = 'KTTMR';
                break;
                case 'WCY':
                $newkodcaw = 'KTWCY';
                break;
                case 'GC':
                $newkodcaw = 'KTGCH';
                break;
                case 'KB2':
                $newkodcaw = 'KTKB2';
                break;
                case '010311':
                $newkodcaw = 'KTGMS';
                break;
                case '020306':
                $newkodcaw = 'KTPSP';
                break;
                case '011238':
                $newkodcaw = 'SBPTT';
                break;
                case '011228':
                $newkodcaw = 'SBSDK';
                break;
                case '011229':
                $newkodcaw = 'SBTWU';
                break;
                case '011230':
                $newkodcaw = 'SBAPI';
                break;
                case '011231':
                $newkodcaw = 'SBBFT';
                break;
                case '011232':
                $newkodcaw = 'SBKBD';
                break;
                case 'ARP':
                $newkodcaw = 'KTRTP';
                break;
                case 'ARM':
                $newkodcaw = 'KTMCH';
                break;
                case 'WB':
                $newkodcaw = 'KTWFB';
                break;
                case 'JLI':
                $newkodcaw = 'KTJEL';
                break;
                case 'ALS':
                $newkodcaw = 'KTKLN';
                break;
                case '010136':
                $newkodcaw = 'JHPGD';
                break;
                case '011235':
                $newkodcaw = 'JHSKD';
                break;
                case '011234':
                $newkodcaw = 'SBTRN';
                break;
                case '011233':
                $newkodcaw = 'SBKNG';
                break;
                case '011237':
                $newkodcaw = 'SBSPN';
                break;
                case '011227':
                $newkodcaw = 'SBPTL';
                break;
                default:
                $newkodcaw = $kodcaw;
                break;
            }
        } else {
            switch($kodcaw) {
                case 'KT1ST':
                $newkodcaw = '1STOP';
                break;
                case 'PHKTN':
                $newkodcaw = '010621';
                break;
                case 'PHBNT':
                $newkodcaw = '010620';
                break;
                case 'PHRAU':
                $newkodcaw = '010617';
                break;
                case 'PLKGR':
                $newkodcaw = '010915';
                break;
                case 'KDSGP':
                $newkodcaw = '010219';
                break;
                case 'SLKJG':
                $newkodcaw = '011013';
                break;
                case 'KLRJL':
                $newkodcaw = '011412';
                break;
                case 'PHTMR':
                $newkodcaw = '010618';
                break;
                case 'KTJWT':
                $newkodcaw = '020301';
                break;
                case 'KTPSM':
                $newkodcaw = 'APM';
                break;
                case 'KTTMR':
                $newkodcaw = '020303';
                break;
                case 'KTWCY':
                $newkodcaw = 'WCY';
                break;
                case 'KTGCH':
                $newkodcaw = 'GC';
                break;
                case 'KTKB2':
                $newkodcaw = 'KB2';
                break;
                case 'KTGMS':
                $newkodcaw = '010311';
                break;
                case 'KTPSP':
                $newkodcaw = '020306';
                break;
                case 'SBPTT':
                $newkodcaw = '011238';
                break;
                case 'SBSDK':
                $newkodcaw = '011228';
                break;
                case 'SBTWU':
                $newkodcaw = '011229';
                break;
                case 'SBAPI':
                $newkodcaw = '011230';
                break;
                case 'SBBFT':
                $newkodcaw = '011231';
                break;
                case 'SBKBD':
                $newkodcaw = '011232';
                break;
                case 'KTRTP':
                $newkodcaw = 'ARP';
                break;
                case 'KTMCH':
                $newkodcaw = 'ARM';
                break;
                case 'KTWFB':
                $newkodcaw = 'WB';
                break;
                case 'KTJEL':
                $newkodcaw = 'JLI';
                break;
                case 'KTKLN':
                $newkodcaw = 'ALS';
                break;
                case 'JHPGD':
                $newkodcaw = '010136';
                break;
                case 'JHSKD':
                $newkodcaw = '011235';
                break;
                case 'SBTRN':
                $newkodcaw = '011234';
                break;
                case 'SBKNG':
                $newkodcaw = '011233';
                break;
                case 'SBSPN':
                $newkodcaw = '011237';
                break;
                case 'SBPTL':
                $newkodcaw = '011227';
                break;
                default:
                $newkodcaw = $kodcaw;
                break;
            }
        }

        return $newkodcaw;
    }
}