<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Gadai;
use App\Tebus;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\Cawangan;
use App\Customer;
use App\TuntutBaki;
use App\Panjar;
use App\Lelong;
use App\Advansur;
use App\Vault;
use App\Tunai;
use App\Denominasi;
use App\HapusKira;
use App\GlCode;
use App\GlDetail;
use App\Audit;
use App\AkruNet;
use App\imbangdugabackup;
use Carbon\Carbon;
use App\imbangdugalama;
use App\Services\Reports\ImbangDugaService;
use App\Services\Reports\Account\GeneralLedger;
use App\Mohonid;

use Illuminate\Support\Facades\Log;

use DateTime;
use Illuminate\Support\Facades\DB;

class LaporanController extends Controller
{
    public function laporanHarian(Request $request){
        $tarikh_request = $request->tarikh;

        $startDate = Carbon::parse($tarikh_request);
        $firstDay = $startDate->firstOfMonth();
        $startDateYear = Carbon::parse($tarikh_request);
        $firstDayYear = $startDateYear->firstOfYear();
        
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $laporan_harian = [];
        //a
        $total_gadai = Gadai::on($cawangan['mysql'])->where('t_gadai','=',$request->tarikh)->sum('pinjaman');
        $total_tebus = Tebus::on($cawangan['mysql'])->where('t_tebus','=',$request->tarikh)->sum('pinjaman');
        $bayaranonlinequery = Transaction::on('mysql7')->whereDate('created_at',$request->tarikh)->where('teller','=','Online')->where('kodcaw',$request->kodcaw);

        $bayaranonline = $bayaranonlinequery->sum('duit_masuk');
        $bilbayaranonline = $bayaranonlinequery->count();
	        
        $ansurankaunter = TransaksiKeuntungan::on('mysql7') 
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) = ?',[$request->tarikh])
                        ->where([['trans.trans_type','=','A'],['teller','<>','Online'],['trans.kodcaw','=',$request->kodcaw]]);
           
        $ansuranonline = TransaksiKeuntungan::on('mysql7') 
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) = ?',[$request->tarikh])
                        ->where([['trans.trans_type','=','A'],['teller','=','Online'],['trans.kodcaw','=',$request->kodcaw]]);

        $total_ansuran = $ansurankaunter->sum('transaksi_keuntungan.bayaran_pembiayaan');
        $total_ansuranonline = $ansuranonline->sum('transaksi_keuntungan.bayaran_pembiayaan');

        // $total_keuntungan = TransaksiKeuntungan::on('mysql7')->whereDate('tarikh_bayaran','=',$request->tarikh)->sum('bayaran_keuntungan');
        $total_upah = Advansur::on($cawangan['mysql'])->where('tarikh','=',$request->tarikh)->sum('upahdibayar');
        $total_keuntungantebus = Tebus::on($cawangan['mysql'])->where('t_tebus','=',$request->tarikh)->sum('bakiupah');

        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                    ->leftJoin('transaction as trans', function($join)
                         {
                             $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                             $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                         })
                    ->whereDate('trans.created_at','=',$request->tarikh)
                    ->where('trans.teller','<>','Online')
                    ->where('trans.trans_type','=','A')
                    ->where('trans.kodcaw',$request->kodcaw)
                    // ->whereNotNull('db2.hargajualan')
                    // ->sum('bayaran_keuntungan');
                    // ->get();
                    ->pluck('transaksi_keuntungan.norujukan');
    
        $gadaiDataKaunter = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
                                            ->leftJoin('transaction as trans', function($join)
                                            {
                                                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                                                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                                            })
                                            ->where('trans.teller','<>','Online')
                                            ->where('trans.trans_type','=','A')
                                            ->whereIn('transaksi_keuntungan.norujukan',$gadaiDataKaunter)
                                            ->whereDate('transaksi_keuntungan.tarikh_bayaran','=',$request->tarikh);
                                            
                                            
        $total_keuntunganansuran_kaunter = $keuntunganansuran_kaunter_query->sum('bayaran_keuntungan');
        $bil_keuntunganansuran_kaunter = $keuntunganansuran_kaunter_query->count();
	
        // $total_keuntunganansuran = 0;
        // if($total_keuntunganansuran_data){
        //     foreach($total_keuntunganansuran_data as $index=>$total_keuntunganansuranData){
        //         $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$total_keuntunganansuranData['norujukan']],['hargajualan','<>',null]])->first();
        //         if($gadaiData){
        //             $total_keuntunganansuran += $total_keuntunganansuranData['bayaran_keuntungan'];
        //         }
        //     }
        // }

        $total_keuntunganansuran_data_online = TransaksiKeuntungan::on('mysql7')
        // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
        ->leftJoin('transaction as trans', function($join)
             {
                 $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                 $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
             })
        ->whereDate('trans.created_at','=',$request->tarikh)
        ->where('trans.teller','=','Online')
        ->where('trans.trans_type','=','A')
        ->where('trans.kodcaw',$request->kodcaw)
        ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataOnline = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
                                        ->leftJoin('transaction as trans', function($join)
                                        {
                                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                                        })
                                        ->whereDate('trans.created_at','=',$request->tarikh)
                                        ->where('trans.teller','=','Online')
                                        ->where('trans.trans_type','=','A')
                                        ->where('trans.kodcaw',$request->kodcaw)
                                        ->whereIn('trans.norujukan',$gadaiDataOnline)
                                        ->whereDate('transaksi_keuntungan.tarikh_bayaran','=',$request->tarikh);
                                        
        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('bayaran_keuntungan');
        $bil_keuntunganansuran_online = $keuntunganansuran_online_query->count();

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','!=','A')
                    ->where('trans.teller','<>','Online')
                    ->whereDate('trans.created_at','=',$request->tarikh)
                    ->where('trans.kodcaw','=',$request->kodcaw);
                    // ->whereNotNull('db2.hargajualan')
                    // ->sum('keuntungan_rebet');
                    // ->get();
                    // ->pluck('transaksi_keuntungan.norujukan');

        // dd($total_keuntunganbukanansuran_data_kaunter);
	
        // $gadaiDataKaunter = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganbukanansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');


        // $keuntunganbukanansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
        //                             ->selectRaw('sum(keuntungan_rebet) as sum')
        //                             ->whereIn('norujukan',$gadaiDataKaunter)
        //                             ->whereDate('tarikh_bayaran','=',$request->tarikh)
        //                             ->where('kodcaw','=',$request->kodcaw)
        //                             ->where('bayaran_pembiayaan','>', 0)
        //                             ->groupby('norujukan')
        //                             ->pluck('sum');
                                    // ->sum('sum');
                                    
        
        $total_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('keuntungan_rebet');

        $bil_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->count();
        

        // $total_keuntunganbukanansuran = 0;

        // if($total_keuntunganbukanansuran_data){
        //     foreach($total_keuntunganbukanansuran_data as $index=>$total_keuntunganbukanansuranData){
        //         $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$total_keuntunganbukanansuranData['norujukan']],['hargajualan','<>',null]])->first();
        //         if($gadaiData){
        //             $total_keuntunganbukanansuran += $total_keuntunganbukanansuranData['keuntungan_rebet'];
        //         }
        //     }
        // }

        $total_keuntunganbukanansuran_data_online = TransaksiKeuntungan::on('mysql7')
            // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
            ->leftJoin('transaction as trans', function($join)
            {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type','!=','A')
            ->where('trans.teller','=','Online')
            ->whereDate('trans.created_at','=',$request->tarikh)
            ->where('trans.kodcaw','=',$request->kodcaw)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataOnline = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        // $total_keuntunganbukanansuran_kaunter = TransaksiKeuntungan::on('mysql7')->whereIn('norujukan',$gadaiDataKaunter)->sum('keuntungan_rebet');  

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
                                ->whereIn('norujukan',$gadaiDataOnline)
                                ->whereDate('tarikh_bayaran','=',$request->tarikh);
                                

        $total_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->sum('keuntungan_rebet');
        $bil_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->count();

        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'=', $request->tarikh)
                    ->where('trans.teller','<>','Online')
                    // ->whereNull('db2.hargajualan')
                    // ->sum('bayaran_keuntungan');
                    // ->get();
                    ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');

        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
                            ->whereIn('norujukan',$gadaiDataKaunter);
                               
        
        $keuntungan_kaunter = $keuntungan_kaunter_query->sum('bayaran_keuntungan'); 
        $bil_keuntungan_kaunter = $keuntungan_kaunter_query->count(); 
        
        // $keuntungan = 0;

        // if($keuntungan_data){
        //     foreach($keuntungan_data as $index=>$keuntunganData){
        //         $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$keuntunganData['norujukan']],['hargajualan',null]])->first();
        //         if($gadaiData){
        //             $keuntungan += $keuntunganData['bayaran_keuntungan'];
        //         }
        //     }
        // }

        $upahtebus = Tebus::on($cawangan['mysql'])
                    ->where('t_tebus','=',$request->tarikh)
                    ->sum('upahdibayar');

        $upahlelong = Lelong::on($cawangan['mysql'])
                    ->where('t_jual','=',$request->tarikh)
                    ->sum('bakiupah');

        $upahansurKaunter = Advansur::on($cawangan['mysql'])
                    ->where('teller','<>','Online')
                    ->where('tarikh','=',$request->tarikh)
                    ->sum('upahdibayar');

        $upahansurOnlineQuery = Advansur::on($cawangan['mysql'])
                    ->where('teller','=','Online')
                    ->where('tarikh','=',$request->tarikh);

        $upahansurOnline = $upahansurOnlineQuery->sum('upahdibayar');
        $bilupahansurOnline = $upahansurOnlineQuery->count();

        
        $upahsimpankaunter = $keuntungan_kaunter + $upahtebus + $upahlelong + $upahansurKaunter + $total_keuntunganbukanansuran_kaunter;

        $keuntungansebenarkaunter = $total_keuntunganansuran_kaunter;

        $upahsimpanonline = $upahansurOnline;
        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $total_keuntungan_kaunter = floatval($upahsimpankaunter) + floatval($keuntungansebenarkaunter);
        $total_keuntungan_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        $totalbayaranonline = floatval($bayaranonline) + floatval($upahansurOnline);
        $biltotalbayaranonline =  $bilbayaranonline + $bilupahansurOnline;

        $tebus = Tebus::on($cawangan['mysql'])
                ->select('tebus.t_tebus', 'gad.t_gadai','gad.hargajualan','gad.bakihargajualan','gad.bakipjm as gadaibakipjm','tebus.nilaimarhun','tebus.tagterima', 'tebus.teller','tebus.jenistebus','tebus.pinjaman','tebus.bakiupah','tebus.bakipjm','gad.norujukan','gad.nokp','tebus.jbg')
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('tebus.t_tebus','=',$request->tarikh)
                ->get();

        $pembiayaanlelong = Lelong::on($cawangan['mysql'])
                ->where('t_jual','=',$request->tarikh)
                ->sum('pinjaman');

        $totalpenebusan = 0;

        foreach($tebus as $index1=>$teb)
        {
            if($teb['gad.hargajualan'] != $teb['bakihargajualan'])
            {
                $totalpenebusan += $teb['gadaibakipjm'];
            }else{
                $totalpenebusan += $teb['pinjaman'];
            }
        }

        //Lelongan Pembiayaan
        $totalpenebusan += $pembiayaanlelong;

        //b
        $bilangan_gadai = Gadai::on($cawangan['mysql'])->where('t_gadai','=',$request->tarikh)->where('pinjaman','>',0)->count();
        $bilangan_tebus = Tebus::on($cawangan['mysql'])->where('t_tebus','=',$request->tarikh)->count();
        $bilangan_ansuran = $ansurankaunter->count();
        $bilangan_ansuranonline = $ansuranonline->count();
        $bilangan_customer_baru = Customer::on('mysql7')->where([['tarikhdaftar','=',$request->tarikh],['kodcaw',$request->kodcaw]])->count();

        //c
        /* Sistem */
        $petibesi_sistem = Vault::on($cawangan['mysql'])->where('tarikh','=', $request->tarikh)->sum('bakiakhir');
       
        /* Imbang Duga */
        $totalbakiakhirtunai = 0;
  
        $vault=Vault::on($cawangan['mysql'])
                ->where('kodcaw','=',$request->kodcaw)
                ->where('tarikh','<=', $request->tarikh)
                ->orderby('tarikh','desc')->first();
  
        $tunai = Tunai::on($cawangan['mysql'])
                 ->where('kodcaw','=',$request->kodcaw)
                 ->where('tarikh','=', $request->tarikh)
                 ->get();
  
        $total = 0;
        foreach($tunai as $index=>$money)
        {
           $total+=$money['baki'];
        }
  
  
        if($total != 0)
        {
           $totalbakiakhirtunai = $vault['bakiakhir'] + $total;
        }else
        {
           $totalbakiakhirtunai = $vault['bakiakhir'];
        }

        /* Denominasi */
        $petibesi_deno = Denominasi::on($cawangan['mysql'])->where('tarikh','=', $request->tarikh)->sum('txtjumlah'); 


        //d
        $panjar_harian = Panjar::on($cawangan['mysql'])->where('tarikh','=',$request->tarikh)->sum('bayaran');
        $panjar_bulanan = Panjar::on($cawangan['mysql'])->where([['tarikh','<=',$request->tarikh],['tarikh','>=',$firstDay]])->sum('bayaran');
        $panjar_tahunan = Panjar::on($cawangan['mysql'])->where([['tarikh','<=',$request->tarikh],['tarikh','>=',$firstDayYear]])->sum('bayaran');
	
        //e

        $tarikhtawarruq = '';

        switch ($request->kodcaw) {
            case 'KB2':
                $tarikhtawarruq = '2021-04-13';
              break;
            case 'WCY':
                $tarikhtawarruq = '2021-05-04';
              break;
            case '1STOP':
                $tarikhtawarruq = '2021-05-09';
            break;
            case '020301':
                $tarikhtawarruq = '2021-05-18';
            break;
            case 'ALS':
                $tarikhtawarruq = '2021-05-24';
            break;
            case 'WB':
                $tarikhtawarruq = '2021-05-24';
            break;
            case 'APM':
                $tarikhtawarruq = '2021-06-08';
            break;
            case 'ARM':
                $tarikhtawarruq = '2021-06-08';
            break;
            case '020306':
                $tarikhtawarruq = '2021-06-08';
            break;
            case '010311':
                $tarikhtawarruq = '2021-06-13';
            break;
            case 'GC':
                $tarikhtawarruq = '2021-06-13';
            break;
            case 'JLI':
                $tarikhtawarruq = '2021-06-13';
            break;
            case '010621':
                $tarikhtawarruq = '2021-06-15';
            break;
            case 'ARP':
                $tarikhtawarruq = '2021-06-15';
            break;
            case '010621':
                $tarikhtawarruq = '2021-06-21';
            break;
            case '010136':
                $tarikhtawarruq = '2021-06-20';
            break;
            case '011235':
                $tarikhtawarruq = '2021-06-21';
            break;
            case '011227':
                $tarikhtawarruq = '2021-06-21';
            break;
            case '010620':
                $tarikhtawarruq = '2021-06-21';
            break;
            case '010617':
                $tarikhtawarruq = '2021-06-21';
            break;
            case '010915':
                $tarikhtawarruq = '2021-06-22';
            break;
            case '011228':
                $tarikhtawarruq = '2021-06-22';
            break;
            case '010219':
                $tarikhtawarruq = '2021-06-22';
            break;
            case '011229':
                $tarikhtawarruq = '2021-06-22';
            break;
            case '011230':
                $tarikhtawarruq = '2021-06-23';
            break;
            case '011013':
                $tarikhtawarruq = '2021-06-23';
            break;
            case '011412':
                $tarikhtawarruq = '2021-06-23';
            break;
            case '011234':
                $tarikhtawarruq = '2021-06-28';
            break;
            case '020303':
                $tarikhtawarruq = '2021-06-29';
            break;
            case '010618':
                $tarikhtawarruq = '2021-06-29';
            break;
            case '011231':
                $tarikhtawarruq = '2021-06-23';
            break;
            case '011232':
                $tarikhtawarruq = '2021-06-28';
            break;
            case '011233':
                $tarikhtawarruq = '2021-06-28';
            break;
          } 

        /* Imbang Duga */

        $rekodkoopquery = Gadai::on($cawangan['mysql'])
                            ->where('tagpalsu','=',0)
                            ->where([['t_gadai','<=',$tarikhtawarruq],['sttebus','=','']])
                            ->orWhere([['sttebus','!=',''],['t_update','>',$request->tarikh],['t_gadai','<=',$tarikhtawarruq]]);
                            // ->sum('pinjaman');

        $rekodkoop = $rekodkoopquery->sum('pinjaman');
        $rekodkoopnilaimarhun = $rekodkoopquery->sum('nilaimarhun');
        $rekodkoopbil = $rekodkoopquery->count();


        if($request->tarikh > '2021-04-13'){
            $rekodtawarruqquery = Gadai::on($cawangan['mysql'])
                ->where('tagpalsu','=',0)
                ->where([['t_gadai','<=',$request->tarikh],['hargajualan','<>','NULL'],['sttebus','=','']])
                ->orWhere([['t_update','>',$request->tarikh],['sttebus','!=',''],['t_gadai','<=',$request->tarikh],['hargajualan','<>','null']]);

            $rekodtawarruq = $rekodtawarruqquery->sum('pinjaman');
            $rekodtawarruqnilaimarhun = $rekodtawarruqquery->sum('nilaimarhun');
            $rekodtawarruqbil = $rekodtawarruqquery->count();
            }

        $daterequest = new Carbon($request->tarikh);
        $daterequest->addDays(1);
	
        //    $bayaranpendahuluan_data = TransaksiKeuntungan::on('mysql7')
        //    ->where('tarikh_bayaran' ,'<=', $daterequest)
        //    ->where('kodcaw',$request->kodcaw)
        //    ->pluck('norujukan');
        
       // $gadaiData = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$bayaranpendahuluan_data)
       //     ->where([['sttebus',''],['hargajualan','<>','null']])
       //     ->orWhere([['sttebus','!=',''],['t_update','>',$request->tarikh],['hargajualan','<>','null']])
       //     ->pluck('norujukan');
         
        //$bayaranpendahuluan = TransaksiKeuntungan::on('mysql7')
        //    ->whereIn('norujukan',$gadaiData)
        //    ->where('tarikh_bayaran' ,'<=', $daterequest)
        //    ->sum('bayaran_pembiayaan');

$date = new Carbon($request->tarikh);
            $lastDayPreviousMonth = $date->subMonthsNoOverflow()->endOfMonth()->toDateString();
            $get_imbangduga = imbangdugabackup::on($cawangan['mysql'])->where('tarikh',$lastDayPreviousMonth)->first()->toArray();
	    $start = new Carbon($request->tarikh);
	    $start_date = $start->startOfMonth()->toDateString();

            //$general_ledger = new GeneralLedger($request->kodcaw,$start_date,$request->tarikh);
            //$bayaran_pendahuluan = $general_ledger->getBayaranPendahuluan();
            //$total_bayaran_current = $bayaran_pendahuluan['keluar'] - $bayaran_pendahuluan['masuk'];
        //	Log::info($bayaran_pendahuluan);    
        //    $bayaranpendahuluan = $get_imbangduga['bayaranpendahuluan'] + $total_bayaran_current;
	$bayaranpendahuluan = 0;
	//$bayaranpendahuluan = 0;
	

        
        // $bayaranpendahuluan = 0;

        // if($bayaranpendahuluan_data){
        //     foreach($bayaranpendahuluan_data as $index=>$bayaranpendahuluanData){
        //         $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$bayaranpendahuluanData['norujukan']],['sttebus',''],['hargajualan','<>','null']])->first();
        //         if($gadaiData){
        //             $bayaranpendahuluan += $bayaranpendahuluanData['bayaran_pembiayaan'];
        //         }
        //     }
        // }

        // dd($bayaranpendahuluan);
        

        $outstandingimbangduga = floatval($rekodkoop) + floatval($rekodtawarruq) - floatval($bayaranpendahuluan);
   
        /* Stok Audit */

        $stokaudit = Gadai::on($cawangan['mysql'])
                    ->where('tagpalsu','=',0)
                    ->where([['t_gadai','<=',$request->tarikh],['sttebus','=','']])
                    ->orWhere([['t_update','>',$request->tarikh],['sttebus','!=',''],['t_gadai','<=',$request->tarikh]]);

        $stokauditget = $stokaudit->get();         
        $stokauditnilaimarhun = $stokaudit->sum('nilaimarhun'); 
        $stokauditcount = $stokaudit->count(); 

        $totalstokaudit = 0;
        foreach($stokauditget as $index1=>$stokA)
        {
            if($stokA['hargajualan'] == null)
                $totalstokaudit += $stokA['pinjaman'];
            else
                $totalstokaudit += $stokA['bakipjm'];
        }


        /* Kawalan Stok */

        //f
        $data_lelong = Lelong::on($cawangan['mysql'])->where('t_jual','=',$request->tarikh)->get();
        $bilangan_lelong = Lelong::on($cawangan['mysql'])->where('t_jual','=',$request->tarikh)->count();
        
        $cas_lelong = 0;
        $jumlah_lelong = 0;
        $baki_lelong = 0;
        $rugi_lelong = 0;

        foreach($data_lelong as $index=>$lelong){
            if($lelong['baki'] >= 0){
                $cas_lelong += $lelong['cajlelong'];
                $jumlah_lelong += $lelong['hargajual'];
                $baki_lelong += $lelong['baki'];
            }elseif($lelong['baki'] < 0){
                $cas_lelong += $lelong['cajlelong'];
                $jumlah_lelong += $lelong['hargajual'];
                $rugi_lelong += abs($lelong['baki']);
            }
        }

        //g
        $tuntut_baki_rugi = TuntutBaki::on($cawangan['mysql'])->where('tarikh','=',$request->tarikh)->where('jumlah','<',0);
        $tuntut_baki_bayar = TuntutBaki::on($cawangan['mysql'])->where('tarikh','=',$request->tarikh)->where('jumlah','>',0);

        $bayar_rugi_lelong = $tuntut_baki_rugi->sum('jumlah');
        $bayar_baki_lelong = $tuntut_baki_bayar->sum('jumlah');


        //h
        $gadai_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','<=',70]])->sum('pinjaman');
        $gadai_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',70],['percentpinj','<=',75]])->sum('pinjaman');
        $gadai_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',75],['percentpinj','<=',80]])->sum('pinjaman');

        $total_gadaian = floatval($gadai_70) + floatval($gadai_75) + floatval($gadai_80);

        $nilaimarhun_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','<=',70]])->sum('nilaimarhun');
        $nilaimarhun_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',70],['percentpinj','<=',75]])->sum('nilaimarhun');
        $nilaimarhun_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',75],['percentpinj','<=',80]])->sum('nilaimarhun');

        $total_nm = floatval($nilaimarhun_70) + floatval($nilaimarhun_75) + floatval($nilaimarhun_80);

        $bilangan_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','<=',70]])->count();
        $bilangan_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',70],['percentpinj','<=',75]])->count();
        $bilangan_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','=',$request->tarikh],['percentpinj','>',75],['percentpinj','<=',80]])->count();

        $total_bilangan = floatval($bilangan_70) + floatval($bilangan_75) + floatval($bilangan_80);

        //i serahan dan pendahuluan

        $serahanpkb = '1000/020';
        $serahanjmc = '1000/026';
        $pendahuluanpkb = '7000/102';
        $pendahuluanjmc = '7000/106';
        $serahankoperasi = '1000/090';

        $serahanpkbTawarruq = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$serahanpkb)
            ->where('descpt','not like', 'SERAHAN BAYAR ONLINE%')
            ->where('tarikh','=', $request->tarikh)
            ->where('tarikh','>','2021-03-24')
            ->sum('serahan');

        $serahanbayaranOnline = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$serahanpkb)
            ->where('descpt','like', 'SERAHAN BAYAR ONLINE%')
            ->where('tarikh','=', $request->tarikh)
            ->where('tarikh','>','2021-03-24')
            ->sum('serahan');

         //Sebelum Tawarruq
        if($request->kodcaw == 'KB2' || $request->kodcaw == 'WCY' || $request->kodcaw == '1STOP' || $request->kodcaw == 'ARM' || $request->kodcaw == 'APM' || $request->kodcaw == '010621' || $request->kodcaw == '010915')
        {
            $serahanpkb = GlDetail::on($cawangan['mysql'])
                ->where('dtacct','=',$serahanpkb)
                ->where('tarikh','=', $request->tarikh)
                ->where('tarikh','>','2013-12-31')
                ->sum('amaun');

            $serahanJMC = GlDetail::on($cawangan['mysql'])
                ->where('dtacct','=',$serahanjmc)
                ->where('tarikh','=', $request->tarikh)
                ->where('tarikh','>','2013-12-31')
                ->sum('amaun');


            if($request->tarikh <= '2013-12-31')
            {
                $serahanpkblama = imbangdugalama::on($cawangan['mysql'])
                ->sum('serahan_pkb');

                $serahanjmclama = imbangdugalama::on($cawangan['mysql'])
                ->sum('serahan_jmc');

                $totaljmc = $serahanJMC + $serahanjmclama;
                $totalpkb = $serahanpkb + $serahanpkblama;
        
                $totalserahan = $serahanpkbTawarruq + $totaljmc + $totalpkb;
                
            }else{
    
                $totalserahan = $serahanpkbTawarruq + $serahanJMC + $serahanpkb;
            }
            
        
        }else{

            if($request->kodcaw == '020301')
                $serahanbaru = '1000/030';
            else
                $serahanbaru = '1000/026';

            $serahanpkb = GlDetail::on($cawangan['mysql'])
                ->where('dtacct','=',$serahanpkb)
                ->where('tarikh','=', $request->tarikh)
                ->sum('amaun');

            $serahanJMC = GlDetail::on($cawangan['mysql'])
                ->where('dtacct','=',$serahanbaru)
                ->where('tarikh','=', $request->tarikh)
                ->sum('amaun');

            $totalserahan = $serahanpkbTawarruq + $serahanpkb + $serahanJMC;
        }


         //Selepas Tawarruq

        $pendahuluanPKBtawarruq = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$pendahuluanpkb)
            ->where([['tarikh','=', $request->tarikh],['tarikh','>','2021-03-24']])
            ->sum('pendahuluan');

        //Sebelum Tawarruq

        $pendahuluanPKB = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$pendahuluanpkb)
            ->where([['tarikh','=', $request->tarikh],['tarikh','>','2013-12-31']])
            ->sum('amaun');

        $pendahuluanJMC = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=','7000/106')
            ->where([['tarikh','=', $request->tarikh],['tarikh','>','2013-12-31']])
            ->sum('amaun');

        if($request->tarikh <= '2013-12-31')
        {
        $pendahuluanpkblama = imbangdugalama::on($cawangan['mysql'])
            ->sum('pendahuluan_pkb');

        $pendahuluanjmclama = imbangdugalama::on($cawangan['mysql'])
            ->sum('pendahuluan_jmc');

        $totalpendahuluan = $pendahuluanPKBtawarruq + $pendahuluanjmclama + $pendahuluanpkblama + $pendahuluanPKB + $pendahuluanJMC;

        $pindahkekpkb = GlCode::on($cawangan['mysql'])
            ->where('glcode','=',$serahankoperasi)
            ->sum('amaun');
        }else{

            $totalpendahuluan = $pendahuluanPKBtawarruq + $pendahuluanPKB + $pendahuluanJMC;

            $pindahkekpkb = 0;
        }


        array_push($laporan_harian,[
            'total_gadai'=>$total_gadai,
            'total_tebus'=>$totalpenebusan,
            'total_ansuran'=>$total_ansuran,
            'total_ansuranonline'=>$total_ansuranonline,
            'bilangan_gadai'=>$bilangan_gadai,
            'bilangan_tebus'=>$bilangan_tebus,
            'bilangan_ansuran'=>$bilangan_ansuran,
            'bilangan_ansuranonline'=>$bilangan_ansuranonline,
            'bilangan_customer_baru'=>$bilangan_customer_baru,
            'bayar_baki_lelong'=>$bayar_baki_lelong,
            'bayar_rugi_lelong'=>$bayar_rugi_lelong,
            'gadai_70'=>$gadai_70,
            'gadai_75'=>$gadai_75,
            'gadai_80'=>$gadai_80,
            'total_gadaian'=>$total_gadaian,
            'nilaimarhun_70'=>$nilaimarhun_70,
            'nilaimarhun_75'=>$nilaimarhun_75,
            'nilaimarhun_80'=>$nilaimarhun_80,
            'total_nm'=>$total_nm,
            'bilangan_70'=>$bilangan_70,
            'bilangan_75'=>$bilangan_75,
            'bilangan_80'=>$bilangan_80,
            'total_bilangan'=>$total_bilangan,
            'panjar_harian'=>$panjar_harian,
            'panjar_bulanan'=>$panjar_bulanan,
            'panjar_tahunan'=>$panjar_tahunan,
            'bilangan_lelong'=>$bilangan_lelong,
            'cas_lelong'=>$cas_lelong,
            'jumlah_lelong'=>$jumlah_lelong,
            'baki_lelong'=>$baki_lelong,
            'rugi_lelong'=>$rugi_lelong,
            'total_keuntungan_kaunter'=>floatval($total_keuntungan_kaunter),
            'total_keuntungan_online'=>floatval($total_keuntungan_online),
            'totalbayaranonline' => floatval($totalbayaranonline),
            'biltotalbayaranonline' => $biltotalbayaranonline,
            'petibesi_sistem'=>$petibesi_sistem,
            'petibesi_deno'=>$petibesi_deno,
            'stokauditpembiayaan'=>$totalstokaudit,
            'stokauditnilaimarhun'=>$stokauditnilaimarhun,
            'stokauditcount'=>$stokauditcount,
            'petibesiimbangduga'=>$totalbakiakhirtunai,
            'outstandingimbangduga'=>$outstandingimbangduga,
            'rekodpinj' => floatval($rekodkoop),
            'rekodpinjnm' => floatval($rekodkoopnilaimarhun),
            'rekodpinjbil' => floatval($rekodkoopbil),
            'rekodpemb' => floatval($rekodtawarruq),
            'rekodpembnm' => floatval($rekodtawarruqnilaimarhun),
            'rekodpembbil' => floatval($rekodtawarruqbil),
            'bayaranpend' => floatval($bayaranpendahuluan),
            'upahsimpankaunter' => floatval($upahsimpankaunter),
            'keuntungansebenarkaunter' => floatval($keuntungansebenarkaunter),
            'totalserahan' => floatval($totalserahan),
            'serahanbayaranOnline' => floatval($serahanbayaranOnline),
            'totalpendahuluan' => floatval($totalpendahuluan),
            ]);
            
        return response()->json($laporan_harian);
    }

    public function laporanTerkumpul(Request $request){
     
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $laporan_terkumpul = [];

        $gadai = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir]])->where('pinjaman','>',0);
        
        $tebus = Tebus::on($cawangan['mysql'])
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where([['t_tebus','>=',$request->mula],['t_tebus','<=',$request->akhir],['tebus.jenistebus','=','T']]);
        
        $ansuran = Transaction::on('mysql7')->whereDate('created_at','>=',$request->mula)->whereDate('created_at','<=',$request->akhir)->where([['trans_type','=','A'],['kodcaw','=',$request->kodcaw]]);
        $bayaranonlinequery = Transaction::on('mysql7')->whereDate('created_at','>=',$request->mula)->whereDate('created_at','<=',$request->akhir)->where('teller','=','Online')->where('kodcaw',$request->kodcaw);

        $bayaranonline = $bayaranonlinequery->sum('duit_masuk');
        $bilbayaranonline = $bayaranonlinequery->count();
        
        //a
        $total_gadai = $gadai->sum('pinjaman');
        $total_tebus = $tebus->when(['gad.hargajualan', '!=' ,'gad.bakihargajualan'], function ($query) {
                            return $query->sum('gad.bakipjm');
                        }, function ($query) {
                            return $query->sum('gad.pinjaman');
                        });
        // $total_ansuran = $ansuran->sum('duit_masuk');
        // $total_keuntungan = TransaksiKeuntungan::on('mysql7')->whereDate('tarikh_bayaran','=',$request->tarikh)->sum('bayaran_keuntungan');
        $total_upah = Advansur::on($cawangan['mysql'])->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->akhir]])->sum('upahdibayar');
        $total_keuntungantebus = Tebus::on($cawangan['mysql'])->where([['t_tebus','>=',$request->mula],['t_tebus','<=',$request->akhir]])->sum('bakiupah');

        $total_keuntunganansuran = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                         {
                             $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                             $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                         })
                    ->whereDate('trans.created_at','>=',$request->mula)
                    ->whereDate('trans.created_at','<=',$request->akhir)
                    ->where('trans.trans_type','=','A')
                    ->where('trans.kodcaw','=',$request->kodcaw)
                    // ->groupBy('trans.id')
                    ->sum('bayaran_keuntungan');

        // $total_ansuran = number_format($total_ansuran,2);

        $total_keuntungan = floatval($total_upah) + floatval($total_keuntunganansuran) + floatval($total_keuntungantebus);


        //b
        $bilangan_gadai = $gadai->count();
        $bilangan_tebus = $tebus->count();
        // $bilangan_ansuran = $ansuran->count();
        //$bilangan_customer_baru = Customer::on($cawangan['mysql'])->where([['tarikhdaftar','>=',$request->mula],['tarikhdaftar','<=',$request->akhir]])->count();
        $bilangan_customer_baru = Customer::on('mysql7')->whereBetween('tarikhdaftar', [$request->mula, $request->akhir])->where('kodcaw', $request->kodcaw)->count();

        //f
        $data_lelong = Lelong::on($cawangan['mysql'])->where([['t_jual','>=',$request->mula],['t_jual','<=',$request->akhir]])->get();
        $bilangan_lelong = Lelong::on($cawangan['mysql'])->where([['t_jual','>=',$request->mula],['t_jual','<=',$request->akhir]])->count();
        
        $cas_lelong = 0;
        $jumlah_lelong = 0;
        $baki_lelong = 0;
        $rugi_lelong = 0;

        foreach($data_lelong as $index=>$lelong){
            if($lelong['baki'] >= 0){
                $cas_lelong += $lelong['cajlelong'];
                $jumlah_lelong += $lelong['hargajual'];
                $baki_lelong += $lelong['baki'];
            }elseif($lelong['baki'] < 0){
                $cas_lelong += $lelong['cajlelong'];
                $jumlah_lelong += $lelong['hargajual'];
                $rugi_lelong += abs($lelong['baki']);
            }
        }

        //g
        $tuntut_baki_rugi = TuntutBaki::on($cawangan['mysql'])->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->akhir]])->where('jumlah','<',0);
        $tuntut_baki_bayar = TuntutBaki::on($cawangan['mysql'])->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->akhir]])->where('jumlah','>',0);

        $bayar_rugi_lelong = $tuntut_baki_rugi->sum('jumlah');
        $bayar_baki_lelong = $tuntut_baki_bayar->sum('jumlah');

        //h
        $gadai_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','<=',70]])->sum('pinjaman');
        $gadai_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',70],['percentpinj','<=',75]])->sum('pinjaman');
        $gadai_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',75],['percentpinj','<=',80]])->sum('pinjaman');

        $total_gadaian = floatval($gadai_70) + floatval($gadai_75) + floatval($gadai_80);

        $nilaimarhun_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','<=',70]])->sum('nilaimarhun');
        $nilaimarhun_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',70],['percentpinj','<=',75]])->sum('nilaimarhun');
        $nilaimarhun_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',75],['percentpinj','<=',80]])->sum('nilaimarhun');

        $total_nm = floatval($nilaimarhun_70) + floatval($nilaimarhun_75) + floatval($nilaimarhun_80);

        $bilangan_70 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','<=',70]])->count();
        $bilangan_75 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',70],['percentpinj','<=',75]])->count();
        $bilangan_80 = Gadai::on($cawangan['mysql'])->where([['t_gadai','>=',$request->mula],['t_gadai','<=',$request->akhir],['percentpinj','>',75],['percentpinj','<=',80]])->count();

        $total_bilangan = floatval($bilangan_70) + floatval($bilangan_75) + floatval($bilangan_80);

        //pendahuluan dan serahan

        $serahanpkb = '1000/020';
        $serahanjmc = '1000/026';
        $pendahuluanpkb = '7000/102';
        $pendahuluanjmc = '7000/106';
        $serahankoperasi = '1000/090';

        $totalserahan = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$serahanpkb)
            ->where('descpt','not like', 'SERAHAN BAYAR ONLINE%')
            ->where('tarikh','>=', $request->mula)
            ->where('tarikh','<=', $request->akhir)
            ->where('tarikh','>','2021-03-24')
            ->sum('serahan');

        $serahanbayaranOnline = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$serahanpkb)
            ->where('descpt','like', 'SERAHAN BAYAR ONLINE%')
            ->where('tarikh','>=', $request->mula)
            ->where('tarikh','<=', $request->akhir)
            ->where('tarikh','>','2021-03-24')
            ->sum('serahan');

        $totalpendahuluan = GlDetail::on($cawangan['mysql'])
            ->where('ktacct','=',$pendahuluanpkb)
            ->where([['tarikh','>=', $request->mula],['tarikh','<=', $request->akhir],['tarikh','>','2021-03-24']])
            ->sum('pendahuluan');

        $belanjaam = Panjar::on($cawangan['mysql'])->where('tag','=', 1)->where('tarikh','>=', $request->mula)->where('tarikh','<=', $request->akhir)->sum('bayaran');
        $baikidanselenggara = Panjar::on($cawangan['mysql'])->where('tag','=', 2)->where('tarikh','>=', $request->mula)->where('tarikh','<=', $request->akhir)->sum('bayaran');
        $keraian = Panjar::on($cawangan['mysql'])->where('tag','=', 3)->where('tarikh','>=', $request->mula)->where('tarikh','<=', $request->akhir)->sum('bayaran');

        //Ansuran

        $ansurankaunter = TransaksiKeuntungan::on('mysql7') 
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) >= ?',[$request->mula])
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) <= ?',[$request->akhir])
                        ->where([['trans.trans_type','=','A'],['teller','<>','Online'],['trans.kodcaw','=',$request->kodcaw]]);
           
        $ansuranonline = TransaksiKeuntungan::on('mysql7') 
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) >= ?',[$request->mula])
                        ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) <= ?',[$request->akhir])
                        ->where([['trans.trans_type','=','A'],['teller','=','Online'],['trans.kodcaw','=',$request->kodcaw]]);

        $total_ansuran = $ansurankaunter->sum('transaksi_keuntungan.bayaran_pembiayaan');
        $total_ansuranonline = $ansuranonline->sum('transaksi_keuntungan.bayaran_pembiayaan');

        $total_upah = Advansur::on($cawangan['mysql'])
                        ->where([['tarikh','>=', $request->mula],['tarikh','<=', $request->akhir]])
                        ->sum('upahdibayar');
        
        $total_keuntungantebus = Tebus::on($cawangan['mysql'])->where([['t_tebus','>=',$request->mula],['t_tebus','<=',$request->akhir]])->sum('bakiupah');

        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                         {
                             $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                             $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                         })
                    ->whereDate('trans.created_at','>=',$request->mula)
                    ->whereDate('trans.created_at','<=',$request->akhir)
                    ->where('trans.teller','<>','Online')
                    ->where('trans.trans_type','=','A')
                    ->where('trans.kodcaw',$request->kodcaw)
                    ->pluck('transaksi_keuntungan.norujukan');
    
        $gadaiDataKaunter = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
                                            ->whereIn('norujukan',$gadaiDataKaunter)
                                            ->whereDate('tarikh_bayaran','>=',$request->mula)
                                            ->whereDate('tarikh_bayaran','<=',$request->akhir);

                                            
                                            
        $total_keuntunganansuran_kaunter = $keuntunganansuran_kaunter_query->sum('bayaran_keuntungan');
        $bil_keuntunganansuran_kaunter = $keuntunganansuran_kaunter_query->count();

        $total_keuntunganansuran_data_online = TransaksiKeuntungan::on('mysql7')
        ->leftJoin('transaction as trans', function($join)
             {
                 $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                 $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
             })
        ->whereDate('trans.created_at','>=',$request->mula)
        ->whereDate('trans.created_at','<=',$request->akhir)
        ->where('trans.teller','=','Online')
        ->where('trans.trans_type','=','A')
        ->where('trans.kodcaw',$request->kodcaw)
        ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataOnline = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
                                        ->whereIn('norujukan',$gadaiDataOnline)
                                        ->whereDate('tarikh_bayaran','>=',$request->mula)
                                        ->whereDate('tarikh_bayaran','<=',$request->akhir);
                                        
        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('bayaran_keuntungan');
        $bil_keuntunganansuran_online = $keuntunganansuran_online_query->count();

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','!=','A')
                    ->where('trans.teller','<>','Online')
                    ->whereDate('trans.created_at','>=',$request->mula)
                    ->whereDate('trans.created_at','<=',$request->akhir)
                    ->where('trans.kodcaw','=',$request->kodcaw);
    
        $total_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('keuntungan_rebet');
        $bil_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->count();
    

        $total_keuntunganbukanansuran_data_online = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function($join)
            {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type','!=','A')
            ->where('trans.teller','=','Online')
            ->whereDate('trans.created_at','>=',$request->mula)
            ->whereDate('trans.created_at','<=',$request->akhir)
            ->where('trans.kodcaw','=',$request->kodcaw)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataOnline = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
                                ->whereIn('norujukan',$gadaiDataOnline)
                                ->whereDate('tarikh_bayaran','>=',$request->mula)
                                ->whereDate('tarikh_bayaran','<=',$request->akhir);

        $total_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->sum('keuntungan_rebet');
        $bil_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->count();

        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->akhir)
                    ->where('trans.teller','<>','Online')
                    ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');

        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
                            ->whereIn('norujukan',$gadaiDataKaunter);
                               
        
        $keuntungan_kaunter = $keuntungan_kaunter_query->sum('bayaran_keuntungan'); 
        $bil_keuntungan_kaunter = $keuntungan_kaunter_query->count(); 

        $bilangan_ansuran = $ansurankaunter->count();
        $bilangan_ansuranonline = $ansuranonline->count();

        
        $upahtebus = Tebus::on($cawangan['mysql'])
                    ->where('t_tebus','>=',$request->mula)
                    ->where('t_tebus','<=',$request->akhir)
                    ->sum('upahdibayar');

        $upahlelong = Lelong::on($cawangan['mysql'])
                    ->where('t_jual','>=',$request->mula)
                    ->where('t_jual','<=',$request->akhir)
                    ->sum('bakiupah');

        $upahansurKaunter = Advansur::on($cawangan['mysql'])
                    ->where('teller','<>','Online')
                    ->where('tarikh','>=',$request->mula)
                    ->where('tarikh','<=',$request->akhir)
                    ->sum('upahdibayar');

        $upahansurOnlineQuery = Advansur::on($cawangan['mysql'])
                    ->where('teller','=','Online')
                    ->where('tarikh','>=',$request->mula)
                    ->where('tarikh','<=',$request->akhir);

        $upahansurOnline = $upahansurOnlineQuery->sum('upahdibayar');
        $bilupahansurOnline = $upahansurOnlineQuery->count();

        
        $upahsimpankaunter = $keuntungan_kaunter + $upahtebus + $upahlelong + $upahansurKaunter + $total_keuntunganbukanansuran_kaunter;

        $keuntungansebenarkaunter = $total_keuntunganansuran_kaunter;

        $upahsimpanonline = $upahansurOnline;
        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $total_keuntungan_kaunter = floatval($upahsimpankaunter) + floatval($keuntungansebenarkaunter);
        $total_keuntungan_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        $totalbayaranonline = floatval($bayaranonline) + floatval($upahansurOnline);
        $biltotalbayaranonline =  $bilbayaranonline + $bilupahansurOnline;

        $tebus = Tebus::on($cawangan['mysql'])
                ->select('tebus.t_tebus', 'gad.t_gadai','gad.hargajualan','gad.bakihargajualan','gad.bakipjm as gadaibakipjm','tebus.nilaimarhun','tebus.tagterima', 'tebus.teller','tebus.jenistebus','tebus.pinjaman','tebus.bakiupah','tebus.bakipjm','gad.norujukan','gad.nokp','tebus.jbg')
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('tebus.t_tebus','>=',$request->mula)
                ->where('tebus.t_tebus','<=',$request->akhir)
                ->get();

        $pembiayaanlelong = Lelong::on($cawangan['mysql'])
                ->where('t_jual','>=',$request->mula)
                ->where('t_jual','<=',$request->akhir)
                ->sum('pinjaman');

        $totalpenebusan = 0;

        //Lelongan Pembiayaan
        $totalpenebusan = $total_tebus + $pembiayaanlelong;

        array_push($laporan_terkumpul,[
            'total_gadai'=>$total_gadai,
            'total_tebus'=>$totalpenebusan,
            'total_ansuran'=>$total_ansuran,
            'total_ansuranonline'=>$total_ansuranonline,
            'bilangan_gadai'=>$bilangan_gadai,
            'bilangan_tebus'=>$bilangan_tebus,
            'bilangan_ansuran'=>$bilangan_ansuran,
            'bilangan_ansuranonline'=>$bilangan_ansuranonline,
            'bilangan_customer_baru'=>$bilangan_customer_baru,
            'bayar_baki_lelong'=>$bayar_baki_lelong,
            'bayar_rugi_lelong'=>$bayar_rugi_lelong,
            'gadai_70'=>$gadai_70,
            'gadai_75'=>$gadai_75,
            'gadai_80'=>$gadai_80,
            'total_gadaian'=>$total_gadaian,
            'nilaimarhun_70'=>$nilaimarhun_70,
            'nilaimarhun_75'=>$nilaimarhun_75,
            'nilaimarhun_80'=>$nilaimarhun_80,
            'total_nm'=>$total_nm,
            'bilangan_70'=>$bilangan_70,
            'bilangan_75'=>$bilangan_75,
            'bilangan_80'=>$bilangan_80,
            'total_bilangan'=>$total_bilangan,
            'bilangan_lelong'=>$bilangan_lelong,
            'cas_lelong'=>$cas_lelong,
            'jumlah_lelong'=>$jumlah_lelong,
            'baki_lelong'=>$baki_lelong,
            'rugi_lelong'=>$rugi_lelong,
            'total_keuntungan'=>floatval($total_keuntungan),
            'totalserahan' => floatval($totalserahan),
            'serahanbayaranOnline' => floatval($serahanbayaranOnline),
            'totalpendahuluan' => floatval($totalpendahuluan),
            'belanjaam' => floatval($belanjaam),
            'baikidanselenggara' => floatval($baikidanselenggara),
            'keraian' => floatval($keraian),
            'keuntungansebenarkaunter' => floatval($keuntungansebenarkaunter),
            'total_keuntungan_kaunter'=>floatval($total_keuntungan_kaunter),
            'total_keuntungan_online'=>floatval($total_keuntungan_online),
            'upahsimpankaunter' => floatval($upahsimpankaunter)
            ]);
            
        return response()->json($laporan_terkumpul);
    }


    public function CalcHapusKira($kodcaw,Request $request)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $hapuskira = HapusKira::on($cawangan['mysql'])
                        ->where('kodcaw','=',$kodcaw)
                        ->where('tarikh','<',$request->tarikh)
                        ->sum('amaun');

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

    public function CalcXtra($kodcaw,Request $request)
    {

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
	
        $upahsimpan = GlCode::on($cawangan['mysql'])
                        ->where('glcode','=','5000/413')
                        ->sum('amaun');

        $bakilelongxtra = GlCode::on($cawangan['mysql'])
                        ->where('glcode','=','7000/190')
                        ->sum('amaun');
	
        $untungrugiterkumpul = GlCode::on($cawangan['mysql'])
                        ->where('glcode','=','7000/201')
                        ->sum('amaun');

        $kerugianlelongxtra = GlCode::on($cawangan['mysql'])
                            ->where('glcode','=','3000/120')
                            ->sum('amaun');	

       if($kodcaw == '011229')
        {
            $peruntukanhapuskira = GlCode::on($cawangan['mysql'])
            ->where('glcode','=','1000/015')
            ->sum('amaun');	
        }else{
            $peruntukanhapuskira = 0;
        }

        $arrayxtra = ['phapuskira' => floatval($peruntukanhapuskira),'upahsimpan' => floatval($upahsimpan), 'bakilelong' => floatval($bakilelongxtra), 'untungrugiterkumpul' => floatval($untungrugiterkumpul), 'kerugianlelong' => floatval($kerugianlelongxtra)];

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

    public function LaporanAuditTrail(Request $request)
    {
        $atarray = array();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();

        $audittrail = Audit::on('mysql7')
                        ->where('kodcaw','=',$request->kodcaw)
                        ->whereDate('created_at','=',$request->tarikh)
                        ->get();

        foreach($audittrail as $index=>$at)
        {
            $datetime = new DateTime($at['created_at']);
            
            $tarikh = $datetime->format('n/j/Y');
            $masa = $datetime->format('H:i');

            $atnewdata = json_decode($at['new_data'],true);
            $atolddata = json_decode($at['old_data'],true);

            $nokp = Gadai::on($cawangan['mysql'])->where('norujukan',$at['norujukan'])->pluck('nokp');

            array_push($atarray,[
                'tarikh' => $tarikh,
                'masa' => $masa,
                'users' => $at['users'],
                'pelulus' => isset($atnewdata['namapelulus']) ? $atnewdata['namapelulus'] : '-',
                'actions' => $at['actions'],
                'norujukan' => $at['norujukan'],
                'kodcaw' => $at['kodcaw'],
                'oldpinjaman' => isset($atolddata['pinjaman']) ? $atolddata['pinjaman'] : 0,
                'oldupah' => isset($atolddata['bakiupah']) ? $atolddata['bakiupah'] : 0,
                'newpinjaman' => isset($atnewdata['pinjaman']) ? $atnewdata['pinjaman'] : 0,
                'newupah' => isset($atnewdata['bakiupah']) ? $atnewdata['bakiupah'] : 0,
                'nota' => isset($atnewdata['nota']) ? $atnewdata['nota'] : '-',
                'nokp' => isset($nokp[0]) ? $nokp[0] : '-',
                'norujukanasal' => isset($atnewdata['norujukan']) ? $atnewdata['norujukan'] : '-' 
            ]);
        }

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

    public function SemakanKeuntunganLejer($kodcaw,Request $request){

        $gledger = new GeneralLedger($kodcaw,$request->mula,$request->hingga);
        $current_profit = $gledger->SemakanKeuntunganLejer();
        

        $array_keuntungan = ['keuntungan_sebenar' => $current_profit['keuntungan_sebenar'], 'keuntungan_semasa' => $current_profit['keuntungan_semasa']];

        return response($array_keuntungan);
    }

    public function SemakanPendapatanAkrual($kodcaw,Request $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $tarikh_carbon = new Carbon($request->mula);

        $akrual_net = AkruNet::on($cawangan['mysql'])
            ->where('bulan', (int)$tarikh_carbon->month)
            ->get()->toArray();

        $jumlah = ($akrual_net) ? $akrual_net[0]['jumlah'] : 0;

        return response($jumlah);
    }

    public function GenerateDailyAkrual(Request $request){

        $current = Carbon::now();
        $current = new Carbon();
        $month_generate = $current->format('m');
        $year_generate = $current->format('Y');
        $harini = $current->toDateString();

        $haripertama = $current->firstOfMonth(); 
        $haripertama_extension = $haripertama->toDateString();

        $month_sebelum = $current->subMonth()->format('m');

        $cawangan = Cawangan::on('mysql7')->where('zone',$request->zone)->get();

        $tebuscontroller = new TebusController();

        foreach($cawangan as $index=>$caw){
            DB::connection($caw['mysql'])->beginTransaction();

            if($year_generate == 2022 && (int)$month_sebelum > 4){
                $audit_backdate = $tebuscontroller->StokAuditGenerateTerakru($month_sebelum,$caw,$year_generate);
            }

            $audit_now = Gadai::on($caw['mysql'])
            ->where([['tagpalsu','=',0],['t_gadai','<=',$harini],['sttebus','=','']])
            ->orWhere([['tagpalsu','=',0],['t_update','>',$harini],['sttebus','!=',''],['t_gadai','<=',$harini]]);

            $totaltunggakan_now = $audit_now->sum('tunggakan');
            $totaltunggakan_past = $audit_backdate->sum('upahblmbyar');

            $request_generate = new \Illuminate\Http\Request([
                'mula' => $haripertama_extension,
                'hingga' => $harini,
                'kodcaw' => $caw['kodcaw'],
            ]);

            $keuntungan = $this->SemakanKeuntunganLejer($caw['kodcaw'],$request_generate);

            $data_keuntungan = $keuntungan->getContent();
            $data = json_decode($data_keuntungan, true);

            $calculation = $totaltunggakan_past - $data['keuntungan_semasa'];
            $accrual_net = $totaltunggakan_now - $calculation;

            $available_akru = AkruNet::on($caw['mysql'])
            ->where('bulan',(int)$month_generate)
            ->first()->toArray();
            
            try{
                if($available_akru){
                    if($available_akru['jumlah'] !== $accrual_net){
                        AkruNet::on($caw['mysql'])->where('bulan','=',$month_generate)
                        ->update(['jumlah' => $accrual_net]);
                    }
                }else{
                    $akrunet = new AkruNet();
                    $akrunet->setConnection($caw['mysql']);
                    $akrunet->tahun = $year_generate;
                    $akrunet->bulan = $month_generate;
                    $akrunet->jumlah = $accrual_net;
                    $akrunet->save();   
                }
                DB::connection($caw['mysql'])->commit();
            }catch (\Throwable $e){
                DB::connection($caw['mysql'])->rollBack();
                return response($e);
            }
        }

        return response('succesful');
    }

    public function GenerateMonthlyAkrual(Request $request){

        $tarikh = $request->tahun . '-' . $request->bulan . '-01';
        $month_request = $current = new Carbon($tarikh);
        $firstmonth_behind = clone $month_request;
        $secondmonth_behind = clone $month_request;
        $firstmonth_behind_end = clone $month_request;

        $firstmonth_behind->startOfMonth();
        $secondmonth_behind->startOfMonth()->subMonthsNoOverflow(1);
        $firstmonth_behind_end->endOfMonth();

        $firstmonth_behind_month = $firstmonth_behind->format('m');
        $secondmonth_behind_month = $secondmonth_behind->format('m');
        $firstmonth_behind_year = $firstmonth_behind->format('Y');
        $secondmonth_behind_year = $secondmonth_behind->format('Y');

        $firstmonth_behind_extension = $firstmonth_behind->toDateString();
        $firstmonth_behind_extension_end = $firstmonth_behind_end->toDateString();

        $cawangan = Cawangan::on('mysql7')->where('zone',$request->zone)->where('version','v1')->get();

        $tebuscontroller = new TebusController();

        foreach($cawangan as $index=>$caw){
            DB::connection($caw['mysql'])->beginTransaction();

            if($secondmonth_behind_year == 2022 && (int)$secondmonth_behind_month > 4){
                $audit_backdate = $tebuscontroller->StokAuditGenerateTerakru($secondmonth_behind_month,$caw,$secondmonth_behind_year);
            }else if($secondmonth_behind_year > 2022){
		$audit_backdate = $tebuscontroller->StokAuditGenerateTerakru($secondmonth_behind_month,$caw,$secondmonth_behind_year);
	    }

            $result_audit_stated = $tebuscontroller->StokAuditGenerateTerakru($firstmonth_behind_month,$caw,$firstmonth_behind_year);

            $totaltunggakan_now = $result_audit_stated->sum('upahblmbyar');
            $totaltunggakan_past = $audit_backdate->sum('upahblmbyar');

            $request_generate = new \Illuminate\Http\Request([
                'mula' => $firstmonth_behind_extension,
                'hingga' => $firstmonth_behind_extension_end,
                'kodcaw' => $caw['kodcaw'],
            ]);

            $keuntungan = $this->SemakanKeuntunganLejer($caw['kodcaw'],$request_generate);

            $data_keuntungan = $keuntungan->getContent();
            $data = json_decode($data_keuntungan, true);

            $calculation = $totaltunggakan_past - $data['keuntungan_semasa'];
            $accrual_net = $totaltunggakan_now - $calculation;

            $available_akru = AkruNet::on($caw['mysql'])
            ->where('bulan',(int)$firstmonth_behind_month)
	    ->where('tahun',(int)$firstmonth_behind_year)
            ->first();
            
            try{
                if($available_akru){
                    if($available_akru['jumlah'] !== $accrual_net){
                        AkruNet::on($caw['mysql'])
			->where('bulan','=',(int)$firstmonth_behind_month)
                        ->where('tahun','=',(int)$firstmonth_behind_year)
			->update(['jumlah' => $accrual_net]);
                    }
                }else{
                    $akrunet = new AkruNet();
                    $akrunet->setConnection($caw['mysql']);
                    $akrunet->tahun = $firstmonth_behind_year;
                    $akrunet->bulan = $firstmonth_behind_month;
                    $akrunet->jumlah = $accrual_net;
                    $akrunet->save();   
                }
                DB::connection($caw['mysql'])->commit();
            }catch (\Throwable $e){
                DB::connection($caw['mysql'])->rollBack();
                return response($e);
            }
        }

        return response('succesfully generated!');
    }

    public function InsertDailyImbangDuga(Request $request){

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $tarikh = new Carbon($request->tarikh);

        DB::connection($cawangan['mysql'])->beginTransaction();
        try{
            $imbangduga = new imbangdugabackup();
            $imbangduga->setConnection($cawangan['mysql']);
            $imbangduga->kodcaw = $request->kodcaw;
            $imbangduga->tarikh = $tarikh->toDateString();
            $imbangduga->tunaiditangan = $request->tunaiditangan;
            $imbangduga->pembiayaantawarruq = $request->pembiayaantawarruq;
            $imbangduga->bayaranpendahuluan = $request->bayaranpendahuluan;
            $imbangduga->pinjamankoop = $request->pinjamankoop;
            $imbangduga->emaspalsu = $request->emaspalsu;
            $imbangduga->serahan = $request->serahan;
            $imbangduga->bds = $request->bds;
            $imbangduga->perubatan = $request->perubatan;
            $imbangduga->keraian = $request->keraian;
            $imbangduga->rugilelong = $request->rugilelong;
            $imbangduga->bakilelong = $request->bakilelong;
            $imbangduga->wtd = $request->wtd;
            $imbangduga->untungrugiterkumpul = $request->untungrugiterkumpul;
            $imbangduga->keun_sebenar = $request->keun_sebenar;
            $imbangduga->pendahuluan = $request->pendahuluan;
            $imbangduga->cajlelong = $request->cajlelong;
            $imbangduga->pindahkekpkb = $request->pindahkekpkb;
            $imbangduga->penghutangkaki = $request->penghutangkaki;
            $imbangduga->phapuskira = $request->phapuskira;
            $imbangduga->belian1stop = $request->belian1stop;
            $imbangduga->keun_penggadai = $request->keun_penggadai;
            $imbangduga->pend_terakru = $request->pend_terakru;
            $imbangduga->cajperkhidmatan = $request->cajperkhidmatan;
            $imbangduga->cajlelongxtra = $request->cajlelongxtra;
            $imbangduga->upahsimpanxtra = $request->upahsimpanxtra;
            $imbangduga->bakilelongxtra = $request->bakilelongxtra;
            $imbangduga->rugilelongxtra = $request->rugilelongxtra;
            $imbangduga->utgterkumpulxtra = $request->utgterkumpulxtra;
            $imbangduga->jualan1stop = $request->jualan1stop;
            $imbangduga->hapuskira = $request->hapuskira;
            $imbangduga->ujrah = $request->ujrah;
            $imbangduga->onepercent = $request->onepercent;
            $imbangduga->totalharta = $request->totalharta;
            $imbangduga->totaltanggungan = $request->totaltanggungan;
            $imbangduga->tagtally = $request->tagtally;
            $imbangduga->created_at = $tarikh->toDateTimeString();
            $imbangduga->updated_at = $tarikh->toDateTimeString();
            $imbangduga->save();

            DB::connection($cawangan['mysql'])->commit();
            return response()->json('success',200);
        }catch (\Throwable $e){
            DB::connection($cawangan['mysql'])->rollBack();
            return response()->json($e,500);
        }
    }

    public function SemakanBackupImbangDuga($kodcaw,Request $request){

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $response = imbangdugabackup::on($cawangan['mysql'])->where('tarikh',$request->tarikh)->first()->toArray();

        if($response){
            return response()->json($response,200);
        }else{
            return response('notfound');
        }
    }

    public function UpdateDailyImbangDuga(Request $request){

        // $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->get();
        $tarikh = new Carbon($request->tarikh);
        $firstmonth_behind = clone $tarikh;
        $secondmonth_behind = clone $tarikh;
        $firstmonth_behind_end = clone $tarikh;

        $firstmonth_behind->startOfMonth();
        $secondmonth_behind->startOfMonth()->subMonthsNoOverflow(1);
        $firstmonth_behind_end->endOfMonth();

        $firstmonth_behind_month = $firstmonth_behind->format('m');
        $secondmonth_behind_month = $secondmonth_behind->format('m');
        $firstmonth_behind_year = $firstmonth_behind->format('Y');
        $secondmonth_behind_year = $secondmonth_behind->format('Y');

        $firstmonth_behind_extension = $firstmonth_behind->toDateString();
        $firstmonth_behind_extension_end = $firstmonth_behind_end->toDateString();

        $cawangan = Cawangan::on('mysql7')->where('zone',$request->zone)->where('version','v1')->get();

        $tebuscontroller = new TebusController();

        foreach($cawangan as $index=>$caw){
            DB::connection($caw['mysql'])->beginTransaction();

            if($secondmonth_behind_year == 2022 && (int)$secondmonth_behind_month > 4){
                $audit_backdate = $tebuscontroller->StokAuditGenerateTerakru($secondmonth_behind_month,$caw,$secondmonth_behind_year);
            }else if($secondmonth_behind_year > 2022){
                $audit_backdate = $tebuscontroller->StokAuditGenerateTerakru($secondmonth_behind_month,$caw,$secondmonth_behind_year);
            }

            $result_audit_stated = $tebuscontroller->StokAuditGenerateTerakru($firstmonth_behind_month,$caw,$firstmonth_behind_year);

            $totaltunggakan_now = $result_audit_stated->sum('upahblmbyar');
            $totaltunggakan_past = $audit_backdate->sum('upahblmbyar');

            $request_generate = new \Illuminate\Http\Request([
                'mula' => $firstmonth_behind_extension,
                'hingga' => $firstmonth_behind_extension_end,
                'kodcaw' => $caw['kodcaw'],
            ]);

            $keuntungan = $this->SemakanKeuntunganLejer($caw['kodcaw'],$request_generate);

            $data_keuntungan = $keuntungan->getContent();
            $data = json_decode($data_keuntungan, true);

            $calculation = $totaltunggakan_past - $data['keuntungan_semasa'];
            $accrual_net = $totaltunggakan_now - $calculation;

            $ab = imbangdugabackup::on($caw['mysql'])
            ->where('tarikh',$request->tarikh)
            ->first();

            $total_akru = AkruNet::on($caw['mysql'])
            ->where('bulan','<',(int)$firstmonth_behind_month)
            ->where('tahun',(int)$firstmonth_behind_year)
            ->sum('jumlah');

            $totalpend_terakru = ($total_akru + $accrual_net);
            $totalharta = $ab['tunaiditangan'] + $ab['pembiayaantawarruq'] + $ab['bayaranpendahuluan'] + $ab['pinjamankoop'] + $ab['emaspalsu'] + $ab['pindahkekpkb'] + $ab['penghutangkaki'] + $ab['phapuskira'] + $ab['belian1stop'] + $totaltunggakan_now + $ab['serahan'];
            $totaltanggungan = $totalpend_terakru + $ab['bds'] + $ab['perubatan'] + $ab['keraian'] + $ab['rugilelong'] + $ab['bakilelong'] + $ab['wtd'] + $ab['untungrugiterkumpul'] + $ab['keun_sebenar'] + $ab['pendahuluan'] + $ab['cajlelong'] + $ab['cajperkhidmatan'] + $ab['cajlelongxtra'] + $ab['upahsimpanxtra'] + $ab['bakilelongxtra'] + $ab['rugilelongxtra'] + $ab['utgterkumpulxtra'] + $ab['jualan1stop'] + $ab['hapuskira'];
            $tally = (round($totalharta,2) == round($totaltanggungan,2)) ? 1 : 0;

            try{
                if($ab){
                    imbangdugabackup::on($caw['mysql'])->where('tarikh',$request->tarikh)->update([
                        'tagtally' => $tally,
                        'totalharta' => $totalharta,
                        'totaltanggungan' => $totaltanggungan,
                        'keun_penggadai' => $totaltunggakan_now,
                        'pend_terakru' => ($total_akru + $accrual_net)
                    ]);
                }
            
                DB::connection($caw['mysql'])->commit();
            }catch (\Throwable $e){
                DB::connection($caw['mysql'])->rollBack();
                return response($e);
            }
        }

        return response('succesfully generated!');
    }

    public function UpdateDailyImbangDugaRefined(Request $request){

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $tarikh = new Carbon($request->tarikh);

        DB::connection($cawangan['mysql'])->beginTransaction();
        try{
            $imbangduga = imbangdugabackup::on($cawangan['mysql'])->whereDate('tarikh',$request->tarikh)->update(array(
                'kodcaw' => $request->kodcaw,
                'tarikh' => $tarikh->toDateString(),
                'tunaiditangan' => $request->tunaiditangan,
                'pembiayaantawarruq' => $request->pembiayaantawarruq,
                'bayaranpendahuluan' => $request->bayaranpendahuluan,
                'pinjamankoop' => $request->pinjamankoop,
                'emaspalsu' => $request->emaspalsu,
                'serahan' => $request->serahan,
                'bds' => $request->bds,
                'perubatan' => $request->perubatan,
                'keraian' => $request->keraian,
                'rugilelong' => $request->rugilelong,
                'bakilelong' => $request->bakilelong,
                'wtd' => $request->wtd,
                'untungrugiterkumpul' => $request->untungrugiterkumpul,
                'keun_sebenar' => $request->keun_sebenar,
                'pendahuluan' => $request->pendahuluan,
                'cajlelong' => $request->cajlelong,
                'pindahkekpkb' => $request->pindahkekpkb,
                'penghutangkaki' => $request->penghutangkaki,
                'phapuskira' => $request->phapuskira,
                'belian1stop' => $request->belian1stop,
                'keun_penggadai' => $request->keun_penggadai,
                'pend_terakru' => $request->pend_terakru,
                'cajperkhidmatan' => $request->cajperkhidmatan,
                'cajlelongxtra' => $request->cajlelongxtra,
                'upahsimpanxtra' => $request->upahsimpanxtra,
                'bakilelongxtra' => $request->bakilelongxtra,
                'rugilelongxtra' => $request->rugilelongxtra,
                'utgterkumpulxtra' => $request->utgterkumpulxtra,
                'jualan1stop' => $request->jualan1stop,
                'hapuskira' => $request->hapuskira,
                'ujrah' => $request->ujrah,
                'onepercent' => $request->onepercent,
                'totalharta' => $request->totalharta,
                'totaltanggungan' => $request->totaltanggungan,
                'tagtally' => $request->tagtally,
                'created_at' => $tarikh->toDateTimeString(),
                'updated_at' => $tarikh->toDateTimeString(),
            ));
            DB::connection($cawangan['mysql'])->commit();
            return response()->json('success',200);
        }catch (\Throwable $e){
            DB::connection($cawangan['mysql'])->rollBack();
            return response()->json($e,500);
        }
    }

    public function getImbangDugaBackupData(Request $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();

        $response = imbangdugabackup::on($cawangan['mysql'])->select($request->data_name)->whereDate('tarikh','=',$request->tarikh)->firstOr(function () {
            return ['message' => 'No Data'];
        });

        if(isset($response['message']) == false) $response = $response[$request->data_name];
        
        return $response;
    }

    public function getPenyelarasan($kodcaw,Request $request){

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        $response = Coordination::on($cawangan['mysql'])->where('tarikh',$request->tarikh)->first()->toArray();

        if($response){
            return response()->json($response,200);
        }else{
            return response('notfound');
        }
    }

    public function getImbangDugaBackup(Request $request){
        $cawangan = Cawangan::on('mysql7')->get();
        $array_imbangduga = [];
        foreach($cawangan as $caw){
            $igService = new ImbangDugaService($caw['kodcaw'],$request->tarikh);
            $imbangdugabackup = $igService->getImbangDugaBackupData($request->jenistally);

            if(!isset($imbangdugabackup['message'])){
                $ig = $imbangdugabackup->toArray();
                $ig['cawangan'] = $caw['details_caw'];
                array_push($array_imbangduga,$ig);
            }
        }

        usort($array_imbangduga, fn($a, $b) => $a['tagtally'] <=> $b['tagtally']);

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

    public function getLaporanKelulusan(Request $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();

        $laporan_kelulusan = Mohonid::on($cawangan['mysql'])
            ->whereBetween('tarikh', [$request->mula, $request->akhir])
            ->when($request->mohon, function($query, $mohon) {
                return $query->where('mohon', $mohon);
            })
            ->get();

        if($laporan_kelulusan->isEmpty()){
            return response()->json(['message' => 'No data found'], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Laporan kelulusan retrieved successfully',
            'data' => $laporan_kelulusan,
            'count' => $laporan_kelulusan->count(),
            'timestamp' => Carbon::now()->toISOString()
        ], 200);
    }

    public function getListofKelulusan(Request $request){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();

        $laporan_kelulusan = Mohonid::on($cawangan['mysql'])
            ->groupBy('mohon')
            ->pluck('mohon');

        if($laporan_kelulusan->isEmpty()){
            return response()->json(['message' => 'No data found'], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'List of Type Kelulusan retrieved successfully',
            'data' => $laporan_kelulusan,
            'count' => $laporan_kelulusan->count(),
            'timestamp' => Carbon::now()->toISOString()
        ], 200);
    }
}
