<?php

namespace App\Http\Controllers;

use App\Cawangan;
use App\Customer;
use App\Transaction;
use App\Gadai;
use App\Lelong;
use App\Tebus;
use App\Vault;
use App\GlDetail;
use App\Panjar;
use App\TransactionOnline;
use App\Tunai;
use App\AddTunai;
use App\TuntutBaki;
use App\Advansur;
use App\AkruNet;
use App\AkruNetPecahan;
use App\TransaksiKeuntungan;
use App\Bajet;
use App\BajetTahunan;
use App\Blacklist;
use App\Pelelong;
use App\Mohon;
use App\Pengesahan;
use App\Permohonan;
use App\Status;
use App\LookupStatus;
use App\ARFiles;
use App\WTDDraft;
use App\WTDSimulasi;
use App\SerahBaki;
use App\WTD;
use App\StokAudit1;
use App\StokAudit2;
use App\StokAudit3;
use App\StokAudit4;
use App\StokAudit5;
use App\StokAudit6;
use App\StokAudit7;
use App\StokAudit8;
use App\StokAudit9;
use App\StokAudit10;
use App\StokAudit11;
use App\StokAudit12;
use App\AuditCustomer;
use App\BayaranHutang;
use App\imbangdugalama;
use App\HapusKira;
use App\MaxPinjaman;
use App\Penghutang;
use App\Services\Reports\AccountService;
use App\imbangdugabackup;
use App\Services\RingkasanHarianServices;
use Illuminate\Support\Facades\DB;
use DateTime;
use Carbon\Carbon;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Jobs\AccountCheckJob;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;

class AdminPageController extends Controller
{

    public function showAllCawangans()
    {
        return response()->json(Cawangan::on('mysql7')->get());
    }

    public function showOneCustomer($id){
        $customer = Customer::on('mysql7')
        ->where('id','=',$id)
        ->first();

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

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

        $current = Carbon::now();
        $current = new Carbon();

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

        $tunai=Tunai::on($cawangan['mysql'])
        ->where([['kodcaw','=',$kodcaw],['tarikh','<=',$current->toDateString()],['kodlaluan','=',$request->kodlaluan]])
        ->orderBy('tarikh','desc')
        ->paginate(5);

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

    }

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

        $current = Carbon::now();
        $current = new Carbon();

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

        $tunai=Tunai::on($cawangan['mysql'])
        ->where([['kodcaw','=',$kodcaw],['tarikh','=',$request->tarikh],['kodlaluan','=',$request->kodlaluan]])
        ->orderBy('tarikh','desc')
        ->first();

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

    }

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

        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $addtunai=AddTunai::on($cawangan['mysql'])->where([['kodcaw','=',$kodcaw],['kodlaluan','=',$request->kodlaluan],['tarikh','=',$request->tarikh]])->get();
        return response()->json($addtunai);
    }

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

        $current = Carbon::now();
        $current = new Carbon();

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

        $listadvansur = Advansur::on($cawangan['mysql'])
        ->where('teller','=',$request->kodlaluan)
        ->where('tarikh','=',$request->tarikh)
        ->orderBy('tarikh','desc')
        ->get();

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

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

        $current = Carbon::now();
        $current = new Carbon();

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

        $tuntutbaki = TuntutBaki::on($cawangan['mysql'])
            ->where('tarikh','=', $request->tarikh)
            ->where('teller','=', $request->teller)
            ->get();

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

    public function LelonganTarikh($kodcaw,Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();

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

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

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


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

        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $vault=Vault::on($cawangan['mysql'])
                ->where('kodcaw','=',$kodcaw)
                ->orderby('tarikh','desc')
                ->paginate(5);

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

    public function TahunanGadai(Request $request)
    {

        $current = Carbon::now();
        $current = new Carbon();

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

        $arrayGadai = [];
        $bajetgroup = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('jenisbajet','=','Gadai')
                ->whereYear('bajettahunan.tahun', '=', $request->year)
                ->sum('nilaibajet');

        $gadai = Gadai::on($cawangan['mysql'])
                ->selectRaw('SUM(pinjaman) AS totalpinjaman')
                ->whereYear('t_gadai',$request->year)
                ->sum('pinjaman');


        array_push($arrayGadai,['bajet' => $bajetgroup,'total' => $gadai]);

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

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

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

        $arrayTebus = [];

        $bajetgroup = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('jenisbajet','=','Penebusan')
                ->whereYear('bajettahunan.tahun', '=', $request->year)
                ->sum('nilaibajet');

        $tebus = Gadai::on($cawangan['mysql'])
                ->whereYear('t_update',$request->year)
                ->where('sttebus','!=','')
                ->sum('pinjaman');


        array_push($arrayTebus,['bajet' => $bajetgroup,'total' => $tebus]);

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

    public function TahunanKeuntungan(Request $request)
    {

        $current = Carbon::now();
        $current = new Carbon();

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

        $arrayKeuntungan = [];

        $monthly = Carbon::now();
        $monthly = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

        $bajetgroup = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('jenisbajet','=','Keuntungan')
                ->whereYear('bajettahunan.tahun', '=', $request->year)
                ->sum('nilaibajet');

        $tebus_arrahn = Tebus::on($cawangan['mysql'])
                ->rightJoin('gadai', 'gadai.norujukan', '=', 'tebus.norujukan')
                ->selectRaw('SUM(tebus.bakiupah) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(t_tebus, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(t_tebus,'%Y%m')"))
                ->whereYear('t_tebus',$request->year)
                ->where([['tebus.jenistebus','=','T'],['gadai.hargajualan','=',null],['t_tebus','<=',$current->toDateString()]])
                ->orderBy('t_tebus','asc')
                ->get()->toArray();

        $advansur = Advansur::on($cawangan['mysql'])
                ->selectRaw('SUM(upahDibayar) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(tarikh, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(tarikh,'%Y%m')"))
                ->whereYear('tarikh',$request->year)
                ->where([['tarikh','<=',$current->toDateString()]])
                ->get()->toArray();

        $ansuran = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.bayaran_keuntungan) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(transaction.created_at, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(transaction.created_at,'%Y%m')"))
                ->whereYear('transaction.created_at',$request->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                ->where('transaction.trans_type','=','A')
                ->where([['trans.tarikh_bayaran','<=',$current->toDateString(). ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->get()->toArray();

        $tebus_upah_tawarruq = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.keuntungan_rebet) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(transaction.created_at, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(transaction.created_at,'%Y%m')"))
                ->whereYear('transaction.created_at',$request->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                ->where('transaction.trans_type','!=','A')
                ->where([['trans.tarikh_bayaran','<=',$current->toDateString() . ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->get()->toArray();


        $lelongupahsimpan = Lelong::on($cawangan['mysql'])
                ->selectRaw('SUM(bakiupah) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(t_jual, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(t_jual,'%Y%m')"))
                ->whereYear('t_jual',$request->year)
                ->orderBy('t_jual','asc')
                ->get()->toArray();

        $totalall = 0;
        $variable = ['lelongupahsimpan','ansuran','tebus_arrahn','advansur','tebus_upah_tawarruq'];

        foreach($variable as $index => $var)
        {
                foreach(${$var} as $indextemp => $temp)
                {
                        $totalall += $temp['total'];
                }
        }


        // $tebus = Tebus::on($cawangan['mysql'])
        //                 ->selectRaw('SUM(bakiupah) AS totalupahsimpan')
        //                 ->addSelect(DB::connection($cawangan['mysql'])
        //                 ->raw('DATE_FORMAT(t_tebus, "%Y-%m") as t_tebus'))
        //                 ->groupBy(DB::connection($cawangan['mysql'])
        //                 ->raw("DATE_FORMAT(t_tebus,'%Y%m')"))
        //                 ->where(function($query) use ($current){
        //                         $query
        //                         ->where([['jenistebus','=','T'],['t_tebus','<=',$current->toDateString()]])
        //                         ->whereYear('t_tebus',$current->year);
        //                 })
        //                 ->orWhere(function($query) use ($current){
        //                         $query
        //                         ->where([['jenistebus','=','T'],['t_tebus','<=',$current->toDateString()]])
        //                         ->whereYear('t_tebus',$current->year);
        //                 })
        //             ->orderBy('t_tebus','asc')
        //             ->get();

        // $totaltebus = 0;
        // foreach($tebus as $index=>$teb)
        // {
        //         $totaltebus += $teb['totalupahsimpan'];
        // }


        // $total = $totaltebus + $totallelong;

        array_push($arrayKeuntungan,['bajet' => $bajetgroup,'total' => $totalall]);

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

    }

    public function PembiayaanBulanan(Request $request){

        $current = Carbon::now();
        $current = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

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

        $arraybulanan = [];
        $array_totalup = [];

        for($i=0;$i<12;$i++){

                    switch($i+1){
                        case 1: $namabulan = 'Jan';
                                $tarikh = $request->year . '-' . '01';
                                break;
                        case 2: $namabulan = 'Feb';
                                $tarikh = $request->year . '-' . '02';
                                break;
                        case 3: $namabulan = 'Mac';
                                $tarikh = $request->year . '-' . '03';
                                break;
                        case 4: $namabulan = 'Apr';
                                $tarikh = $request->year . '-' . '04';
                                break;
                        case 5: $namabulan = 'Mei';
                                $tarikh = $request->year . '-' . '05';
                                break;
                        case 6: $namabulan = 'Jun';
                                $tarikh = $request->year . '-' . '06';
                                break;
                        case 7: $namabulan = 'Jul';
                                $tarikh = $request->year . '-' . '07';

                                break;
                        case 8: $namabulan = 'Aug';
                                $tarikh = $request->year . '-' . '08';

                                break;
                        case 9: $namabulan = 'Sep';
                                $tarikh = $request->year . '-' . '09';

                                break;
                        case 10: $namabulan = 'Okt';
                                $tarikh = $request->year . '-' . '10';

                                break;
                        case 11: $namabulan = 'Nov';
                                $tarikh = $request->year . '-' . '11';

                                break;
                        case 12: $namabulan = 'Dis';
                                $tarikh = $request->year . '-' . '12';
                                break;

                    }
                    array_push($array_totalup,['tarikh'=>$tarikh,'namabulan'=>$namabulan,'pembiayaan'=>0,'bajetgadai'=> 0]);
        }


        // $bajetgadai = [2259500,2259500,2582280,2582280,2905070,3066460,2582280,2582280,2743680,2743680,2905070,3066460];
        $bajetgadai = [];

        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->where('jenisbajet','=','Gadai')
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->get();

        foreach($bajetgroup as $index1=>$bj)
        {
            array_push($bajetgadai,floatval($bj['nilaibajet']));
        }

        $arrayPembiayaan = array();
        $goals = [['name' => 'Expected','value' => 200000,'strokeHeight' => 5, 'strokeColor' => '#e74c3c']];


            $gadai = Gadai::on($cawangan['mysql'])
                        ->selectRaw('SUM(pinjaman) AS totalpinjaman')
                        ->addSelect(DB::connection($cawangan['mysql'])
                        ->raw('DATE_FORMAT(t_gadai, "%Y-%m") as t_gadai'))
                        ->groupBy(DB::connection($cawangan['mysql'])
                        ->raw("DATE_FORMAT(t_gadai,'%Y%m')"))
                        ->whereYear('t_gadai',$request->year)
                        ->where([['t_gadai','<=',$current->toDateString()],['t_gadai','>=',$monthly_date]])
                        ->orderBy('t_gadai','asc')
                        ->get();

        $total_gadai = 0;
            foreach($array_totalup as $array_index=>$totalup){
                foreach($gadai as $indexgadai=>$gadai_detail){
                    if($totalup['tarikh'] == $gadai_detail['t_gadai']){
                        $total_gadai = $totalup['pembiayaan'];
                        $total_gadai += $gadai_detail['totalpinjaman'];
                    }
                }
                $goals[0]['value'] = (sizeof($bajetgadai) > 0) ? $bajetgadai[$array_index] : 0;
                array_push($arrayPembiayaan,['x' => $array_totalup[$array_index]['namabulan'],'y' => $total_gadai,'goals' => (array) $goals]);
                $total_gadai = 0;

            }

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

    public function BilanganGadaianBulanan(Request $request){

        $current = Carbon::now();
        $current = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

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

        $arraybulanan = [];
        $array_totalup = [];

        for($i=0;$i<12;$i++){

                    switch($i+1){
                        case 1: $namabulan = 'Jan';
                                $tarikh = $request->year . '-' . '01';
                                break;
                        case 2: $namabulan = 'Feb';
                                $tarikh = $request->year . '-' . '02';
                                break;
                        case 3: $namabulan = 'Mac';
                                $tarikh = $request->year . '-' . '03';
                                break;
                        case 4: $namabulan = 'Apr';
                                $tarikh = $request->year . '-' . '04';
                                break;
                        case 5: $namabulan = 'Mei';
                                $tarikh = $request->year . '-' . '05';
                                break;
                        case 6: $namabulan = 'Jun';
                                $tarikh = $request->year . '-' . '06';
                                break;
                        case 7: $namabulan = 'Jul';
                                $tarikh = $request->year . '-' . '07';

                                break;
                        case 8: $namabulan = 'Aug';
                                $tarikh = $request->year . '-' . '08';

                                break;
                        case 9: $namabulan = 'Sep';
                                $tarikh = $request->year . '-' . '09';

                                break;
                        case 10: $namabulan = 'Okt';
                                $tarikh = $request->year . '-' . '10';

                                break;
                        case 11: $namabulan = 'Nov';
                                $tarikh = $request->year . '-' . '11';

                                break;
                        case 12: $namabulan = 'Dis';
                                $tarikh = $request->year . '-' . '12';
                                break;

                    }
                    array_push($array_totalup,['tarikh'=>$tarikh,'namabulan'=>$namabulan,'bilgadai'=>0,'bajetgadai'=> 0]);
        }


        // $bajetgadai = [300,700,500,300,400,360,470,860,400,432,444,654];
        $bajetgadai = [];

        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->where('jenisbajet','=','Bilangan-Gadai')
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->get();

        foreach($bajetgroup as $index1=>$bj)
        {
            array_push($bajetgadai,floatval($bj['nilaibajet']));
        }

        $arrayPembiayaan = array();
        $goals = [['name' => 'Expected','value' => 200000,'strokeHeight' => 5, 'strokeColor' => '#e74c3c']];


            $gadai = Gadai::on($cawangan['mysql'])
                        ->selectRaw('COUNT(*) AS bilangangadai')
                        ->addSelect(DB::connection($cawangan['mysql'])
                        ->raw('DATE_FORMAT(t_gadai, "%Y-%m") as t_gadai'))
                        ->groupBy(DB::connection($cawangan['mysql'])
                        ->raw("DATE_FORMAT(t_gadai,'%Y%m')"))
                        ->whereYear('t_gadai',$request->year)
                        ->where([['t_gadai','<=',$current->toDateString()],['t_gadai','>=',$monthly_date]])
                        ->orderBy('t_gadai','asc')
                        ->get();

        $total_gadai = 0;

            foreach($array_totalup as $array_index=>$totalup){
                foreach($gadai as $indexgadai=>$gadai_detail){
                    if($totalup['tarikh'] == $gadai_detail['t_gadai']){
                        $total_gadai = $totalup['bilgadai'];
                        $total_gadai += $gadai_detail['bilangangadai'];
                    }
                }
                $goals[0]['value'] = (sizeof($bajetgadai) > 0) ? $bajetgadai[$array_index] : 0;
                array_push($arrayPembiayaan,['x' => $array_totalup[$array_index]['namabulan'],'y' => $total_gadai,'goals' => (array) $goals]);
                $total_gadai = 0;

            }

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

    public function PenebusanBulanan(Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

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

        $arraybulanan = [];
        $array_totalup = [];

        for($i=0;$i<12;$i++){

                    switch($i+1){
                        case 1: $namabulan = 'Jan';
                                $tarikh = $request->year . '-' . '01';
                                break;
                        case 2: $namabulan = 'Feb';
                                $tarikh = $request->year . '-' . '02';
                                break;
                        case 3: $namabulan = 'Mac';
                                $tarikh = $request->year . '-' . '03';
                                break;
                        case 4: $namabulan = 'Apr';
                                $tarikh = $request->year . '-' . '04';
                                break;
                        case 5: $namabulan = 'Mei';
                                $tarikh = $request->year . '-' . '05';
                                break;
                        case 6: $namabulan = 'Jun';
                                $tarikh = $request->year . '-' . '06';
                                break;
                        case 7: $namabulan = 'Jul';
                                $tarikh = $request->year . '-' . '07';

                                break;
                        case 8: $namabulan = 'Aug';
                                $tarikh = $request->year . '-' . '08';

                                break;
                        case 9: $namabulan = 'Sep';
                                $tarikh = $request->year . '-' . '09';

                                break;
                        case 10: $namabulan = 'Okt';
                                $tarikh = $request->year . '-' . '10';

                                break;
                        case 11: $namabulan = 'Nov';
                                $tarikh = $request->year . '-' . '11';

                                break;
                        case 12: $namabulan = 'Dis';
                                $tarikh = $request->year . '-' . '12';
                                break;

                    }
                    array_push($array_totalup,['tarikh'=>$tarikh,'namabulan'=>$namabulan,'penebusan'=>0,'bajettebus' => 0]);
        }

        // $bajettebus = [2040110,2040110,2331560,2331560,2623000,2768720,2331560,2331560,2331560,2477280,2477280,2623000];
        $bajettebus = [];
        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->where('jenisbajet','=','Penebusan')
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->get();

        foreach($bajetgroup as $index1=>$bj)
        {
            array_push($bajettebus,floatval($bj['nilaibajet']));
        }



        $arrayPenyelesaian = array();
        $goals = [['name' => 'Expected','value' => 200000,'strokeHeight' => 5, 'strokeColor' => '#e74c3c']];


        $tebus = Gadai::on($cawangan['mysql'])
                        ->selectRaw('SUM(bakipjm) AS totalpinjaman')
                        ->addSelect(DB::connection($cawangan['mysql'])
                        ->raw('DATE_FORMAT(t_update, "%Y-%m") as t_update'))
                        ->groupBy(DB::connection($cawangan['mysql'])
                        ->raw("DATE_FORMAT(t_update,'%Y%m')"))
                        ->whereYear('t_update',$request->year)
                        ->where([['sttebus','!=',''],['t_update','<=',$current->toDateString()],['t_update','>=',$monthly_date]])
                        ->orderBy('t_update','asc')
                        ->get()->toArray();

        $ansuran = Transaction::on('mysql7')
                        ->selectRaw('SUM(trans.bayaran_pembiayaan) AS total')
                        ->addSelect(DB::connection($cawangan['mysql'])
                        ->raw('DATE_FORMAT(transaction.created_at, "%Y-%m") as tarikh'))
                        ->groupBy(DB::connection($cawangan['mysql'])
                        ->raw("DATE_FORMAT(transaction.created_at,'%Y%m')"))
                        ->whereYear('transaction.created_at',$request->year)
                        ->leftJoin('transaksi_keuntungan as trans', function($join)
                        {
                                $join->on('transaction.norujukan', '=', 'trans.norujukan');
                                $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                        })
                        ->where('transaction.trans_type','=','A')
                        ->where([['trans.tarikh_bayaran','>=',$monthly_date . ' 00:00:00'],['trans.tarikh_bayaran','<=',$current->toDateString() . ' 23:59:59']])
                        ->where('trans.kodcaw','=',$request->kodcaw)
                        ->get()->toArray();

        $total_tebus = 0;
        foreach($array_totalup as $array_index=>$totalup){
            foreach($tebus as $indextebus=>$tebus_detail){
                if($totalup['tarikh'] == $tebus_detail['t_update']){
                    $total_tebus = $totalup['penebusan'];
                    $total_tebus += $tebus_detail['totalpinjaman'];
                    $total_tebus += $ansuran[$indextebus]['total'];
                    $array_totalup[$array_index]['penebusan'] = $total_tebus;
                    $array_totalup[$array_index]['bajettebus'] = (sizeof($bajettebus) > 0) ? $bajettebus[$array_index] : 0;
                }
            }
            $goals[0]['value'] = (sizeof($bajettebus) > 0) ? $bajettebus[$array_index] : 0;
            array_push($arrayPenyelesaian,['x' => $array_totalup[$array_index]['namabulan'],'y' => $total_tebus,'goals' => (array) $goals]);
            $total_tebus = 0;

        }

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

    }
    public function BilanganPenebusanBulanan(Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

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

        $arraybulanan = [];
        $array_totalup = [];

        for($i=0;$i<12;$i++){

                    switch($i+1){
                        case 1: $namabulan = 'Jan';
                                $tarikh = $request->year . '-' . '01';
                                break;
                        case 2: $namabulan = 'Feb';
                                $tarikh = $request->year . '-' . '02';
                                break;
                        case 3: $namabulan = 'Mac';
                                $tarikh = $request->year . '-' . '03';
                                break;
                        case 4: $namabulan = 'Apr';
                                $tarikh = $request->year . '-' . '04';
                                break;
                        case 5: $namabulan = 'Mei';
                                $tarikh = $request->year . '-' . '05';
                                break;
                        case 6: $namabulan = 'Jun';
                                $tarikh = $request->year . '-' . '06';
                                break;
                        case 7: $namabulan = 'Jul';
                                $tarikh = $request->year . '-' . '07';

                                break;
                        case 8: $namabulan = 'Aug';
                                $tarikh = $request->year . '-' . '08';

                                break;
                        case 9: $namabulan = 'Sep';
                                $tarikh = $request->year . '-' . '09';

                                break;
                        case 10: $namabulan = 'Okt';
                                $tarikh = $request->year . '-' . '10';

                                break;
                        case 11: $namabulan = 'Nov';
                                $tarikh = $request->year . '-' . '11';

                                break;
                        case 12: $namabulan = 'Dis';
                                $tarikh = $request->year . '-' . '12';
                                break;

                    }
                    array_push($array_totalup,['tarikh'=>$tarikh,'namabulan'=>$namabulan,'bilpenebusan'=>0,'bajettebus' => 0]);
        }



        // $bajettebus = [600,540,520,510,540,607,650,300,400,500,800,200];
        $bajettebus = [];
        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->where('jenisbajet','=','Bilangan-Tebus')
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->get();

        foreach($bajetgroup as $index1=>$bj)
        {
            array_push($bajettebus,floatval($bj['nilaibajet']));
        }



        $arrayPenyelesaian = array();
        $goals = [['name' => 'Expected','value' => 200000,'strokeHeight' => 5, 'strokeColor' => '#e74c3c']];


        $tebus = Gadai::on($cawangan['mysql'])
                        ->selectRaw('COUNT(*) AS bilangantebus')
                        ->addSelect(DB::connection($cawangan['mysql'])
                        ->raw('DATE_FORMAT(t_update, "%Y-%m") as t_update'))
                        ->groupBy(DB::connection($cawangan['mysql'])
                        ->raw("DATE_FORMAT(t_update,'%Y%m')"))
                        ->whereYear('t_update',$request->year)
                        ->where([['sttebus','=','T'],['t_update','<=',$current->toDateString()],['t_update','>=',$monthly_date]])
                        ->orderBy('t_update','asc')
                        ->get();

        $total_tebus = 0;
        foreach($array_totalup as $array_index=>$totalup){
            foreach($tebus as $indextebus=>$tebus_detail){
                if($totalup['tarikh'] == $tebus_detail['t_update']){
                    $total_tebus = $totalup['bilpenebusan'];
                    $total_tebus += $tebus_detail['bilangantebus'];
                    $array_totalup[$array_index]['bilpenebusan'] = $total_tebus;
                    $array_totalup[$array_index]['bajettebus'] = (sizeof($bajettebus) > 0) ? $bajettebus[$array_index] : 0;
                }
            }
            $goals[0]['value'] = (sizeof($bajettebus) > 0) ? $bajettebus[$array_index] : 0;
            array_push($arrayPenyelesaian,['x' => $array_totalup[$array_index]['namabulan'],'y' => $total_tebus,'goals' => (array) $goals]);
            $total_tebus = 0;

        }

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

    }

    public function KeuntunganBulanan(Request $request){
        $current = Carbon::now();
        $current = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();

        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();

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

        $arraybulanan = [];
        $array_totalup = [];

        for($i=0;$i<12;$i++){


                    switch($i+1){
                        case 1: $namabulan = 'Jan';
                                $tarikh = $request->year . '-' . '01';
                                break;
                        case 2: $namabulan = 'Feb';
                                $tarikh = $request->year . '-' . '02';
                                break;
                        case 3: $namabulan = 'Mac';
                                $tarikh = $request->year . '-' . '03';
                                break;
                        case 4: $namabulan = 'Apr';
                                $tarikh = $request->year . '-' . '04';
                                break;
                        case 5: $namabulan = 'Mei';
                                $tarikh = $request->year . '-' . '05';
                                break;
                        case 6: $namabulan = 'Jun';
                                $tarikh = $request->year . '-' . '06';
                                break;
                        case 7: $namabulan = 'Jul';
                                $tarikh = $request->year . '-' . '07';

                                break;
                        case 8: $namabulan = 'Aug';
                                $tarikh = $request->year . '-' . '08';

                                break;
                        case 9: $namabulan = 'Sep';
                                $tarikh = $request->year . '-' . '09';

                                break;
                        case 10: $namabulan = 'Okt';
                                $tarikh = $request->year . '-' . '10';

                                break;
                        case 11: $namabulan = 'Nov';
                                $tarikh = $request->year . '-' . '11';

                                break;
                        case 12: $namabulan = 'Dis';
                                $tarikh = $request->year . '-' . '12';
                                break;

                    }
                    array_push($array_totalup,['tarikh'=>$tarikh,'namabulan'=>$namabulan,'keuntungan'=>0,'bajetkeuntungan' => 0]);
        }

        // $bajetkeuntungan = [236850,224390,211920,211920,199460,199460,236850,224390,199460,199460,114520,174520];
        // $bajetkeuntungan = array_reverse($bajetkeuntungan);

        $bajetkeuntungan = [];

        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->where('jenisbajet','=','Keuntungan')
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->get();

        foreach($bajetgroup as $index1=>$bj)
        {
            array_push($bajetkeuntungan,floatval($bj['nilaibajet']));
        }


        $arrayKeuntungan = array();
        $goals = [['name' => 'Expected','value' => 0,'strokeHeight' => 5, 'strokeColor' => '#e74c3c']];



        $lelongupahsimpan = Lelong::on($cawangan['mysql'])
                    ->selectRaw('SUM(bakiupah) AS total')
                    ->addSelect(DB::connection($cawangan['mysql'])
                    ->raw('DATE_FORMAT(t_jual, "%Y-%m") as tarikh'))
                    ->groupBy(DB::connection($cawangan['mysql'])
                    ->raw("DATE_FORMAT(t_jual,'%Y%m')"))
                    ->whereYear('t_jual',$request->year)
                    ->where([['t_jual','<=',$current->toDateString()],['t_jual','>=',$monthly_date]])
                    ->orderBy('t_jual','asc')
                    ->get()->toArray();



        $tebus_arrahn = Tebus::on($cawangan['mysql'])
                ->rightJoin('gadai', 'gadai.norujukan', '=', 'tebus.norujukan')
                    ->selectRaw('SUM(tebus.bakiupah) AS total')
                    ->addSelect(DB::connection($cawangan['mysql'])
                    ->raw('DATE_FORMAT(t_tebus, "%Y-%m") as tarikh'))
                    ->groupBy(DB::connection($cawangan['mysql'])
                    ->raw("DATE_FORMAT(t_tebus,'%Y%m')"))
                    ->whereYear('t_tebus',$request->year)
                    ->where([['tebus.jenistebus','=','T'],['gadai.hargajualan','=',null],['t_tebus','<=',$current->toDateString()],['t_tebus','>=',$monthly_date]])
                    ->orderBy('t_tebus','asc')
                    ->get()->toArray();

        $advansur = Advansur::on($cawangan['mysql'])
                ->selectRaw('SUM(upahDibayar) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(tarikh, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(tarikh,'%Y%m')"))
                ->whereYear('tarikh',$request->year)
                ->where([['tarikh','<=',$current->toDateString()],['tarikh','>=',$monthly_date]])
                ->get()->toArray();

        $ansuran = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.bayaran_keuntungan) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(transaction.created_at, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(transaction.created_at,'%Y%m')"))
                ->whereYear('transaction.created_at',$request->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                 ->where('transaction.trans_type','=','A')
                ->where([['trans.tarikh_bayaran','>=',$monthly_date . ' 00:00:00'],['trans.tarikh_bayaran','<=',$current->toDateString(). ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->get()->toArray();

        $tebus_upah_tawarruq = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.keuntungan_rebet) AS total')
                ->addSelect(DB::connection($cawangan['mysql'])
                ->raw('DATE_FORMAT(transaction.created_at, "%Y-%m") as tarikh'))
                ->groupBy(DB::connection($cawangan['mysql'])
                ->raw("DATE_FORMAT(transaction.created_at,'%Y%m')"))
                ->whereYear('transaction.created_at',$request->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                ->where('transaction.trans_type','!=','A')
                ->where([['trans.tarikh_bayaran','>=',$monthly_date . ' 00:00:00'],['trans.tarikh_bayaran','<=',$current->toDateString() . ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->get()->toArray();

        $variable = ['lelongupahsimpan','ansuran','tebus_arrahn','advansur','tebus_upah_tawarruq'];

        foreach($array_totalup as $array_index=>$totalup){

                foreach($variable as $index => $var)
                {
                        foreach(${$var} as $indextemp => $temp)
                        {
                                if($totalup['tarikh'] == $temp['tarikh'])
                                {
                                        $total_tebus = $array_totalup[$array_index]['keuntungan'];
                                        $total_tebus += $temp['total'];
                                        $array_totalup[$array_index]['keuntungan'] = $total_tebus;
                                        $array_totalup[$array_index]['bajetkeuntungan'] = (sizeof($bajetkeuntungan) > 0) ? $bajetkeuntungan[$array_index] : 0;
                                }
                        }
                }

                // foreach($tebus_upah_tawarruq as $indexloop=>$looptambahan)
                // {
                //         if($totalup['tarikh'] == $looptambahan['tarikh']){
                //         $total = 0;
                //         $tebusarrahntotal = (count($tebus_arrahn) < $indexloop) ? $tebus_arrahn[$indexloop]['total'] : 0;
                //         $advansurtotal = (count($advansur) < $indexloop) ? $advansur[$indexloop]['total'] ? $advansur[$indexloop]['total'] : 0 : 0;
                //         $ansurantotal = (count($ansuran) < $indexloop) ? $ansuran[$indexloop]['total'] : 0;
                //         $tebustawarruqtotal = (count($lelongupahsimpan) < $indexloop) ? $lelongupahsimpan[$indexloop]['total'] : 0;

                //         $total = $looptambahan['total'] + $tebusarrahntotal + $advansurtotal + $ansurantotal + $tebustawarruqtotal;
                //         // $total_keuntungan = $array_totalup[$array_index]['keuntungan'];
                //         $total_keuntungan = $total;
                //         $array_totalup[$array_index]['keuntungan'] = $total_keuntungan;
                //         $array_totalup[$array_index]['bajetkeuntungan'] = (sizeof($bajetkeuntungan) > 0) ? $bajetkeuntungan[$array_index] : 0;
                //         }
                // }

            $goals[0]['value'] = (sizeof($bajetkeuntungan) > 0) ? $bajetkeuntungan[$array_index] : 0;
            array_push($arrayKeuntungan,['x' => $array_totalup[$array_index]['namabulan'],'y' => $array_totalup[$array_index]['keuntungan'],'goals' => (array) $goals]);
        }
        return response()->json($arrayKeuntungan);
    }

    public function showAllGadaiToday(Request $request){

        $cawangan_all = Cawangan::on('mysql7')->get();
        $current = Carbon::now();
        $current = new Carbon();
        $harini = $current->toDateString();
        $gadaiToday = 0;
        $gadaiLastweek = 0;

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

        $monthly = Carbon::now();
        $monthly = new Carbon();

        $monthly_date = $monthly->startOfMonth()->toDateString();

        $gadailatest = Gadai::on($cawangan['mysql'])
                ->where([['t_gadai','>=',$monthly_date],['t_gadai','<=',$harini],['hargajualan','<>','NULL']])
                ->whereYear('t_gadai',$current->year)
                ->orderBy('t_gadai','asc')
                ->sum('pinjaman');

        switch($current->month){
            case 1: $bulan = 'Januari';
                    break;
            case 2: $bulan = 'Februari';
                    break;
            case 3: $bulan = 'Mac';
                    break;
            case 4: $bulan = 'April';
                    break;
            case 5: $bulan = 'Mei';
                    break;
            case 6: $bulan = 'Jun';
                    break;
            case 7: $bulan = 'Julai';
                    break;
            case 8: $bulan = 'Ogos';
                    break;
            case 9: $bulan = 'September';
                    break;
            case 10: $bulan = 'Oktober';
                    break;
            case 11: $bulan = 'November';
                    break;
            case 12: $bulan = 'Disember';
                    break;
        }


        $bajetcollection = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('bajettahunan.jenisbajet','=','Gadai')
                ->where('bajet.bulan','=',$bulan)
                ->whereYear('bajettahunan.tahun', '=', $current->year)
                ->first();

        if($bajetcollection)
        {
                $bajetharian = floatval($bajetcollection->nilaibajet) / 26;

                $cummulativegadaian = floatval($bajetcollection->nilaibajet) - floatval($gadailatest);
                $percentcum = ((floatval($gadailatest) - floatval($bajetcollection->nilaibajet)) / floatval($bajetcollection->nilaibajet)) * 100;
        }else{
                $bajetharian = 0;
                $cummulativegadaian = 0;
                $percentcum = 0;
        }



        $gadai = Gadai::on($cawangan['mysql'])->where('t_gadai','=',$harini)->sum('pinjaman');
        // $gadai_last_week = Gadai::on($cawangan['mysql'])->where('t_gadai','=',$lastweek)->sum('pinjaman');
        // $gadaiLastweek += $gadai_last_week;
        $gadaiToday += $gadai;

        $diffGadaiPercent = 0;

        if($bajetcollection)
                $diffGadaiPercent = (($gadaiToday - $bajetharian)/$bajetharian)*100;
        else
                $diffGadaiPercent = 0;

        $dataGadai = [];
        array_push($dataGadai,['gadaiToday'=>$gadaiToday,'percentDiff'=>$diffGadaiPercent,'bajetharian' => $bajetharian,'bulan' => $bulan,'percentcum' => abs(round($percentcum)),'remaining' => $cummulativegadaian]);

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

    }

    public function showAllTebusToday(Request $request){

        $cawangan_all = Cawangan::on('mysql7')->get();
        $current = Carbon::now();
        $current = new Carbon();
        $harini = $current->toDateString();
        $tebusToday = 0;
        $tebusLastWeek = 0;

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

        $monthly = Carbon::now();
        $monthly = new Carbon();


        $monthly_date = $monthly->startOfMonth()->toDateString();


        $tebuslatest = Gadai::on($cawangan['mysql'])
                ->whereYear('t_update',$current->year)
                ->where([['sttebus','!=',''],['t_update','<=',$harini],['t_update','>=',$monthly_date]])
                ->orderBy('t_update','asc')
                ->sum('bakipjm');

        switch($current->month){
            case 1: $bulan = 'Januari';
                    break;
            case 2: $bulan = 'Februari';
                    break;
            case 3: $bulan = 'Mac';
                    break;
            case 4: $bulan = 'April';
                    break;
            case 5: $bulan = 'Mei';
                    break;
            case 6: $bulan = 'Jun';
                    break;
            case 7: $bulan = 'Julai';
                    break;
            case 8: $bulan = 'Ogos';
                    break;
            case 9: $bulan = 'September';
                    break;
            case 10: $bulan = 'Oktober';
                    break;
            case 11: $bulan = 'November';
                    break;
            case 12: $bulan = 'Disember';
                    break;
        }

        $bajetcollection = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('bajettahunan.jenisbajet','=','Penebusan')
                ->where('bajet.bulan','=',$bulan)
                ->whereYear('bajettahunan.tahun', '=', $current->year)
                ->first();


        if($bajetcollection)
        {
                $bajetharian = floatval($bajetcollection->nilaibajet) / 26;

                $cummulativepenebusan = floatval($bajetcollection->nilaibajet) - floatval($tebuslatest);
                $percentcum = ((floatval($tebuslatest) - floatval($bajetcollection->nilaibajet)) / floatval($bajetcollection->nilaibajet)) * 100;
        }else{
                $bajetharian = 0;
                $cummulativepenebusan = 0;
                $percentcum = 0;
        }


        $tebus = Tebus::on($cawangan['mysql'])->where('t_tebus','=',$harini)->sum('pinjaman');
        $lelong = Lelong::on($cawangan['mysql'])->where('t_jual','=',$harini)->sum('pinjaman');

        $tebusToday = $tebus + $lelong;

        $diffTebusPercent = 0;

        if($bajetcollection)
                $diffTebusPercent = (($tebusToday - $bajetharian)/$bajetharian)*100;
        else
                $diffTebusPercent = 0;

        $dataTebus = [];
        array_push($dataTebus,['tebusToday'=>$tebusToday,'percentDiff'=>$diffTebusPercent,'bajetharian' => $bajetharian,'bulan' => $bulan,'percentcum' => abs(round($percentcum)),'remaining' => $cummulativepenebusan]);
        return response()->json($dataTebus);
    }

    public function showAllUpahToday(Request $request){

        $cawangan_all = Cawangan::on('mysql7')->get();
        $current = Carbon::now();
        $current = new Carbon();
        $harini = $current->toDateString();
        $upahToday = 0;
        $upahLastWeek = 0;

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

        $monthly = Carbon::now();
        $monthly = new Carbon();
        $monthly_date = $monthly->startOfMonth()->toDateString();

        $lelongupahsimpan = Lelong::on($cawangan['mysql'])
                    ->selectRaw('SUM(bakiupah) AS totalupahlelong')
                    ->whereYear('t_jual',$current->year)
                    ->where([['t_jual','<=',$harini],['t_jual','>=',$monthly_date]])
                    ->orderBy('t_jual','asc')
                    ->sum('bakiupah');


        $tebus = Tebus::on($cawangan['mysql'])
                    ->selectRaw('SUM(bakiupah) AS totalupahsimpan')
                    ->whereYear('t_tebus',$current->year)
                    ->where([['jenistebus','=','T'],['t_tebus','<=',$harini],['t_tebus','>=',$monthly_date]])
                    ->orWhere([['jenistebus','=','A'],['t_tebus','<=',$harini],['t_tebus','>=',$monthly_date]])
                    ->orderBy('t_tebus','asc')
                    ->sum('bakiupah');

        $advansur = Advansur::on($cawangan['mysql'])
                ->selectRaw('SUM(upahDibayar) AS total')
                ->whereYear('tarikh',$current->year)
                ->where([['tarikh','<=',$harini],['tarikh','>=',$monthly_date]])
                ->sum('upahDibayar');

        $ansuran = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.bayaran_keuntungan) AS total')
                ->whereYear('transaction.created_at',$current->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                ->where('transaction.trans_type','=','A')
                ->where([['trans.tarikh_bayaran','>=',$monthly_date . ' 00:00:00'],['trans.tarikh_bayaran','<=',$harini. ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->sum('trans.bayaran_keuntungan');


        $tebus_upah_tawarruq = Transaction::on('mysql7')
                ->selectRaw('SUM(trans.keuntungan_rebet) AS total')
                ->whereYear('transaction.created_at',$current->year)
                ->leftJoin('transaksi_keuntungan as trans', function($join)
                {
                        $join->on('transaction.norujukan', '=', 'trans.norujukan');
                        $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                })
                ->where('transaction.trans_type','!=','A')
                ->where([['trans.tarikh_bayaran','>=',$monthly_date . ' 00:00:00'],['trans.tarikh_bayaran','<=',$harini . ' 23:59:59']])
                ->where('trans.kodcaw','=',$request->kodcaw)
                ->sum('trans.keuntungan_rebet');


        $upahlatest = $lelongupahsimpan + $tebus + $ansuran + $advansur + $tebus_upah_tawarruq;

        switch($current->month){
            case 1: $bulan = 'Januari';
                    break;
            case 2: $bulan = 'Februari';
                    break;
            case 3: $bulan = 'Mac';
                    break;
            case 4: $bulan = 'April';
                    break;
            case 5: $bulan = 'Mei';
                    break;
            case 6: $bulan = 'Jun';
                    break;
            case 7: $bulan = 'Julai';
                    break;
            case 8: $bulan = 'Ogos';
                    break;
            case 9: $bulan = 'September';
                    break;
            case 10: $bulan = 'Oktober';
                    break;
            case 11: $bulan = 'November';
                    break;
            case 12: $bulan = 'Disember';
                    break;
        }


        $bajetcollection = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->where('bajettahunan.jenisbajet','=','Keuntungan')
                ->where('bajet.bulan','=',$bulan)
                ->whereYear('bajettahunan.tahun', '=', $current->year)
                ->first();

        if($bajetcollection)
        {
                $bajetharian = floatval($bajetcollection->nilaibajet) / 26;

                $cummulativekeuntungan = floatval($bajetcollection->nilaibajet) - floatval($upahlatest);
                $percentcum = ((floatval($upahlatest) - floatval($bajetcollection->nilaibajet)) / floatval($bajetcollection->nilaibajet)) * 100;
        }else{
                $bajetharian = 0;
                $cummulativekeuntungan = 0;
                $percentcum = 0;
        }


        $upah_tebus_today = Tebus::on($cawangan['mysql'])->where('t_tebus','=',$harini)->sum('bakiupah');
        $upah_today = Advansur::on($cawangan['mysql'])->where('tarikh',$harini)->sum('upahDibayar');

        $upahToday += $upah_today;

        $ansuran_today = Transaction::on('mysql7')
                        ->leftJoin('transaksi_keuntungan as trans', function($join)
                        {
                                $join->on('transaction.norujukan', '=', 'trans.norujukan');
                                $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                        })
                        ->where('transaction.trans_type','=','A')
                        ->where([['trans.tarikh_bayaran','>=',$harini . ' 00:00:00'],['trans.tarikh_bayaran','<=',$harini . ' 23:59:59']])
                        ->where('trans.kodcaw','=',$request->kodcaw)
                        ->sum('bayaran_keuntungan');

        $upah_tebus_today = Transaction::on('mysql7')
                        ->leftJoin('transaksi_keuntungan as trans', function($join)
                        {
                                $join->on('transaction.norujukan', '=', 'trans.norujukan');
                                $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
                        })
                        ->where('transaction.trans_type','!=','A')
                        ->where([['trans.tarikh_bayaran','>=',$harini . ' 00:00:00'],['trans.tarikh_bayaran','<=',$harini . ' 23:59:59']])
                        ->where('trans.kodcaw','=',$request->kodcaw)
                        ->sum('keuntungan_rebet');

        $upahToday = $upah_tebus_today + $ansuran_today;

        $diffUpah = 0;

        if($bajetcollection)
                $diffUpah = (($upahToday - $bajetharian)/$bajetharian)*100;
        else
                $diffUpah = 0;

        $upahData = [];
        array_push($upahData,['upahToday'=>$upahToday,'percentDiff'=>$diffUpah,'bajetharian' => round($bajetharian,2),'bulan' => $bulan,'percentcum' => abs(round($percentcum)),'remaining' => $cummulativekeuntungan]);
        return response()->json($upahData);
    }

    public function getpetibesiSebelumbyTarikh($kodcaw,Request $request)
    {
      $current = Carbon::now();
      $current = new Carbon();

       $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
       $vault=Vault::on($cawangan['mysql'])
               ->where('kodcaw','=',$kodcaw)
               ->where('tarikh','<',$request->tarikh)
               ->orderby('tarikh','desc')->limit(1)->get();

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

    }

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

       $gldetail=GlDetail::on($cawangan['mysql'])
                ->where('kodcaw','=',$kodcaw)
                ->where('tarikh','=',$request->tarikh)
                ->where('descpt','NOT LIKE','SERAHAN BAYAR ONLINE%')
                ->orderby('tarikh','desc')->get();

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


    public function getPanjarbyTarikh($kodcaw,Request $request)
    {
       $harini = Carbon::now();
       $harini = new Carbon;

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

       $panjar=Panjar::on($cawangan['mysql'])
                ->where('tarikh','=',$request->tarikh)
                ->get();

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

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

      $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $request->kodcaw)->first();
      $updateVault=Vault::on($cawangan['mysql'])->where('tarikh', '=', $request->tarikh)->update(array(

         'bakiawal' => $request->bakiawal,
         'keluar' => $request->keluar,
         'masuk' => $request->masuk,
         'pendahuluan' => $request->pendahuluan,
         'serahan' => $request->serahan,
         'totpanjar' => $request->panjar,
         'bakiakhir' => $request->bakiakhir,
         'bakieod' => $request->bakiakhir

      ) );

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

    public function AdminsearchSagOnline(Request $request)
    {
        $customer = TransactionOnline::on('mysql7')
        ->where('billplz_id','=', $request->billplzid)
        ->orderBy('status', 'asc')
        ->get();

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

    public function SimpanStatus(Request $request)
    {

        $transactiononline = TransactionOnline::on('mysql7')
        ->where('id', '=', $request->id)
        ->update([
            'status' => $request->status,
            'paid_at' => $request->paidat
        ]);

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

    public function SenaraiBajet(Request $request)
    {

        // $arrayBajet = ['Gadai' => [],['Penebusan' => []],['Keuntungan' =>[]]];

        // $arrayBajet = array('Gadai' => [],'Penebusan' => []);

        $bajetgroup = BajetTahunan::on('mysql7')
            ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
            ->where('bajettahunan.kodcaw','=', $request->kodcaw)
            ->whereYear('bajettahunan.tahun', '=', $request->year)
            ->groupBy('bajettahunan.jenisbajet')
            ->get();

        $bajetcollection = BajetTahunan::on('mysql7')
                ->join('bajet', 'bajettahunan.id', '=', 'bajet.bajetid')
                ->where('bajettahunan.kodcaw','=', $request->kodcaw)
                ->whereYear('bajettahunan.tahun', '=', $request->year)
                ->get();


        $arrayBajet = [];
        foreach($bajetgroup as $index=>$bg)
        {
            array_push($arrayBajet,[$bg['jenisbajet'] => []]);

            foreach($bajetcollection as $index1=>$bj)
            {
                if($bj['jenisbajet'] == key($arrayBajet[$index]))
                {
                    array_push($arrayBajet[$index][key($arrayBajet[$index])],['id' => $bj['bajetid'], 'bulan' => $bj['bulan'], 'nilaibajet' => $bj['nilaibajet'] ]);
                }
            }
        }

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

    public function CheckBajet(Request $request)
    {
        $bajet = BajetTahunan::on('mysql7')
        ->where([['kodcaw','=', $request->kodcaw],['jenisbajet','=',$request->jenisbajet]])
        ->whereYear('tahun', '=', $request->year)
        ->get();

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

    public function SimpanBajet(Request $request)
    {

        $current = Carbon::now();
        $current = new Carbon();

        $bajettahunan = new BajetTahunan();

        $bajettahunan->tahun = $request->year.'-00-00';
        $bajettahunan->jenisbajet = $request->jenisbajet;
        $bajettahunan->kodcaw = $request->kodcaw;
        $bajettahunan->save();

        foreach($request->bulan as $index=>$bulan)
        {
            $bajet = new Bajet();

            $bajet->kodcaw = $request->kodcaw;
            $bajet->bulan = $bulan['bulan'];
            $bajet->nilaibajet = $bulan['bajet'];
            $bajet->updated_by = $request->username;
            $bajet->bajetid = $bajettahunan->id;
            $bajet->save();
        }

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

    public function senaraikemaskinibajet(Request $request)
    {
        $bajet = Bajet::on('mysql7')
                ->where('bajetid','=',$request->bajetid)
                ->get();

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

    public function KemaskiniBajet(Request $request)
    {

        $bajetjanuari = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Januari')
                        ->update(['nilaibajet' => $request->bajetjanuari]);

        $bajetfebruari = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Februari')
                        ->update(['nilaibajet' => $request->bajetfebruari]);

        $bajetmarch = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Mac')
                        ->update(['nilaibajet' => $request->bajetmarch]);

        $bajetapril = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','April')
                        ->update(['nilaibajet' => $request->bajetapril]);

        $bajetmei = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Mei')
                        ->update(['nilaibajet' => $request->bajetmei]);

        $bajetjun = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Jun')
                        ->update(['nilaibajet' => $request->bajetjun]);

        $bajetjulai = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Julai')
                        ->update(['nilaibajet' => $request->bajetjulai]);

        $bajetogos = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Ogos')
                        ->update(['nilaibajet' => $request->bajetogos]);

        $bajetseptember = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','September')
                        ->update(['nilaibajet' => $request->bajetseptember]);

        $bajetoktober = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Oktober')
                        ->update(['nilaibajet' => $request->bajetoktober]);

        $bajetnovember = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','November')
                        ->update(['nilaibajet' => $request->bajetnovember]);

        $bajetdisember = Bajet::on('mysql7')
                        ->where('bajetid','=',$request->bajetid)
                        ->where('bulan','=','Disember')
                        ->update(['nilaibajet' => $request->bajetdisember]);

        return response(1);
    }

    public function SenaraiBlacklist(Request $request)
    {

        if(isset($request->search))
        {
                $blacklist = Blacklist::on('mysql7')
                ->where('nama','LIKE',"%{$request->search}%")
                ->orderBy('tarikhdaftar','desc')
                ->paginate(5);
        }else{
                $blacklist = Blacklist::on('mysql7')
                ->orderBy('tarikhdaftar','desc')
                ->paginate(5);
        }


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

    public function AddSenaraiHitam(Request $request)
    {

        $customer = Customer::on('mysql7')
                ->where('kpbaru','=', $request->nokp)
                ->orWhere('kplama','=', $request->nokp)
                ->first();

        $blacklist = Blacklist::on('mysql7')->create([
		'nosiri' => $customer['nosiri'],
                'kodcaw' => $customer['kodcaw'],
                'tarikhdaftar' => $customer['tarikhdaftar'],
                'kplama' => $customer['kplama'],
                'kpbaru' => $customer['kpbaru'],
                'nokp' => $request->nokp,
                'nama' => $customer['nama'],
                't_lahir' => $customer['t_lahir'],
                'jantina' => $customer['jantina'],
                'alamat1' => $customer['alamat1'],
                'alamat2' => $customer['alamat2'],
                'alamat3' => $customer['alamat3'],
                'alamat4' => $customer['alamat4'],
                'telefon' => $customer['telefon'],
                'nota' => $request->nota,
                'teller' => null,
                'pelulus' => null
            ]);

        return response()->json($blacklist, 201);
    }

    public function DeleteBlackList(Request $request)
    {
        $blacklist = Blacklist::where('id',$request->id)->delete();

        return response()->json($blacklist, 201);
    }


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

        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $updatetunai = Tunai::on($cawangan['mysql'])->where( [['tarikh','=', $request->tarikh],['kodlaluan','=', $request->kodlaluan] ])->
        update(array(
                'bakiawal'=>$request->bakiawal,
                'keluar'=>$request->keluar,
                'masuk'=>$request->masuk,
                'baki'=>$request->bakiakhir
        ));

        return response()->json($updatetunai, 200);

    }

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

        $cawangan_all = Cawangan::on('mysql7')->get()->toArray();

        foreach($cawangan_all as $index=>$cawangan){
                $detailslelong = Pelelong::on($cawangan['mysql'])->
                update(array(
                        'para2'=>$request->content
                ));
        }

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

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

        $cawangan_all = Cawangan::on('mysql7')->get()->toArray();

        foreach($cawangan_all as $index=>$cawangan){
                $detailslelong = Pelelong::on($cawangan['mysql'])->
                update(array(
                        'para3'=>$request->content
                ));
        }

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

    public function paginate($items, $perPage = 5, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }

    public function listoperasi()
    {
       $harini = Carbon::now();
       $harini = new Carbon;

       $cawangan_all = Cawangan::on('mysql7')->get();
       $arraykelulusan = [];

       foreach($cawangan_all as $index=>$cawangan){
           $kelulusan=Mohon::on($cawangan['mysql'])
                ->where('tarikh','=',$harini->toDateString())
                ->where('masalulus','=','')
                ->where('pelulus','=','operasi')
                ->get()->toArray();

          if(sizeof($kelulusan) != 0){
                foreach($kelulusan as $index=>$kel)
                {
                        $kelulusan[$index]['cawangan'] = $cawangan['details_caw'];
                        $kelulusan[$index]['cawangankod'] = $cawangan['kodcaw'];
                        array_push($arraykelulusan,$kelulusan[$index]);
                }
                // $arraykelulusan += $kelulusan;
                // array_push($arraykelulusan,$kelulusan);
                //   $arraykelulusan += $kelulusan;
        //       array_push($arraykelulusan,["kelulusanall" => $kelulusan,"cawangan" => $cawangan['details_caw'],"cawangankod" => $cawangan['kodcaw']]);
          }
      }

      $data = $this->paginate($arraykelulusan,3);

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

    public function listoperasikelulusan()
    {
       $harini = Carbon::now();
       $harini = new Carbon;

       $cawangan_all = Cawangan::on('mysql7')->get();
       $arraykelulusan = [];

       foreach($cawangan_all as $index=>$cawangan){
          $kelulusan=Mohon::on($cawangan['mysql'])
                ->where('peloperasi','=','operasi')
                ->where('operasi','!=','')
                ->get();

          if(sizeof($kelulusan) != 0){
              array_push($arraykelulusan,["kelulusanall" => $kelulusan,"cawangan" => $cawangan['details_caw'],"cawangankod" => $cawangan['kodcaw']]);
          }
      }

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

    public function showOneCustomerGadai($ic,$status,Request $request){
        if($status == 'belum_tebus'){
            $gadai_status = '';
        }elseif($status == 'sudah_tebus'){
            $gadai_status = 'T';
        }elseif($status == 'lelong'){
            $gadai_status = 'L';
        }

        $cawangan_all = Cawangan::on('mysql7')->get();
        $gadai_all = [];

        if(isset($request->search))
        {
                foreach($cawangan_all as $index=>$cawangan){
                        if($status == 'belum_tebus' || $status == 'sudah_tebus'){

                                if($status == 'sudah_tebus')
                                {
                                        $gadai = Gadai::on($cawangan['mysql'])
                                                ->join('tebus', 'gadai.norujukan', '=', 'tebus.norujukan')
                                                ->where([['gadai.norujukan','LIKE',"%{$request->search}%"],['gadai.sttebus','=',$gadai_status],['gadai.nokp','=',$ic]])
                                                ->orderBy('tebus.t_tebus','desc')
                                                ->get()->toArray();
                                }else{
                                        $gadai = Gadai::on($cawangan['mysql'])
                                                ->where([['norujukan','LIKE',"%{$request->search}%"],['sttebus','=',$gadai_status],['nokp','=',$ic]])
                                                ->orderBy('t_gadai','desc')
                                                ->get()->toArray();
                                }

                                if(sizeof($gadai) != 0){
                                        $gadai_all += $gadai;
                                }
                        }elseif($status == 'lelong'){
                                $gadai = Gadai::on($cawangan['mysql'])
                                ->where([['norujukan','LIKE',"%{$request->search}%"],['sttebus','=',$gadai_status],['nokp','=',$ic]])
                                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                                ->get()->toArray();
                                if(sizeof($gadai) != 0){
                                        $gadai_all += $gadai;
                                }
                        }
                }

        }else{
                foreach($cawangan_all as $index=>$cawangan){
                        if($status == 'belum_tebus' || $status == 'sudah_tebus'){

                                if($status == 'sudah_tebus')
                                {
                                        $gadai = Gadai::on($cawangan['mysql'])
                                                ->join('tebus', 'gadai.norujukan', '=', 'tebus.norujukan')
                                                ->where([['gadai.sttebus','=',$gadai_status],['gadai.nokp','=',$ic]])
                                                ->orderBy('tebus.t_tebus','desc')
                                                ->get()->toArray();
                                }else{
                                        $gadai = Gadai::on($cawangan['mysql'])
                                                ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                                                ->orderBy('t_gadai','desc')
                                                ->get()->toArray();
                                }

                                if(sizeof($gadai) != 0){
                                        $gadai_all += $gadai;
                                }
                        }elseif($status == 'lelong'){
                                $gadai = Gadai::on($cawangan['mysql'])
                                ->where([['sttebus','=',$gadai_status],['nokp','=',$ic]])
                                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                                ->get()->toArray();
                                if(sizeof($gadai) != 0){
                                        $gadai_all += $gadai;
                                }
                        }
                }
        }

        $data = $this->paginate($gadai_all);

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

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

        $timeloni = Carbon::now();
        $current = new Carbon();
        $curent_year = substr($current->year,2,2);
        $curent_month = sprintf("%02d", $current->month);
        $current_day = sprintf("%02d", $current->day);

        try {

                $transaksipermohonan = Permohonan::whereYear('tarikh_permohonan','=', $current->year)->where('kodcaw',$kodcaw)->orderBy('mohonid','desc')->first();
                $mohonid = 0;

                if($transaksipermohonan)
                {
                        $mohonid = $transaksipermohonan['mohonid'] + 1;
                }else{
                        $mohonid = 1;
                }

                $transbaru = sprintf("%04d",$mohonid);

                $permohonan = new Permohonan;
                $pengesahan = new Pengesahan;
                $status = new Status;

                $nopermohonan = 'AR' . strtoupper($kodcaw) . $curent_year . $curent_month . $current_day . '-' . $transbaru;

                $permohonan->mohonid = $mohonid;
                $permohonan->kodcaw = $kodcaw;
                $permohonan->jenismohon = $request->jenismohon;
                $permohonan->baki_petibesi = $request->bakipetibesi;
                $permohonan->amaun_mohon = $request->jumlahmohon;
                $permohonan->nama_pemohon = $request->namapemohon;
                $permohonan->jawatan_pemohon = $request->jawatanpemohon;
                $permohonan->tarikh_permohonan = $request->tarikhmohon;
                $permohonan->outstandingsemasa = $request->outstanding;
                $permohonan->nopermohonan = $nopermohonan;
                $permohonan->save();

                $pengesahan->nopermohonan = $permohonan->nopermohonan;
                $pengesahan->kodcaw = $kodcaw;
                $pengesahan->save();

                $status->nopermohonan = $permohonan->nopermohonan;
                $status->statusid = 1;
                $status->tarikhmasa = $timeloni->toDateTimeString();
                $status->save();

                return response(1);

        } catch (\Throwable $e) {
                return response($e);
        }
    }

    public function GetRekodPermohonanCawangan($kodcaw)
    {
        if($kodcaw === 'admin')
        {
                $listpermohonan = Permohonan::join('pengesahan', 'permohonan.nopermohonan', '=', 'pengesahan.nopermohonan')
                ->where('tagterima',1)
                ->orWhere('tagoperasi','=',2)
                ->orWhere('tagakaun','=',2)
                ->orWhere('tagpb','=',2)
                ->orWhere('tagdeposit','=',2)
                ->orWhere('tagprint','=',2)
                ->orWhere([['tagcit', 1],['jenismohon','bayaranbalik'],['tagakaun',1]])
                ->orderBy('tarikh_permohonan','desc')->paginate(5);

        }else{
                $listpermohonan = Permohonan::join('pengesahan', 'permohonan.nopermohonan', '=', 'pengesahan.nopermohonan')
                ->where('pengesahan.kodcaw', $kodcaw)
                ->where('tagterima',1)
                ->orWhere('tagoperasi','=',2)
                ->orWhere('tagakaun','=',2)
                ->orWhere('tagpb','=',2)
                ->orWhere('tagdeposit','=',2)
                ->orWhere('tagprint','=',2)
                ->orWhere([['tagcit', 1],['jenismohon','bayaranbalik'],['tagakaun',1]])
                ->get();

        }

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

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

        if($kodcaw === 'admin')
        {
                $listpermohonan = Permohonan::join('pengesahan', 'permohonan.nopermohonan', '=', 'pengesahan.nopermohonan')
                ->where('tagterima',0)
                ->where('tagoperasi','!=',2)
                ->where('tagakaun','!=',2)
                ->where('tagpb','!=',2)
                ->where('tagdeposit','!=',2)
                ->where('tagprint','!=',2)
                ->where(function($query){
                        $query->where('tagcit', '!=', 1)
                        ->orWhere('tagoperasi','!=',1)
                        ->orWhere('tagakaun','!=',1);
                })
                ->orderBy('tarikh_permohonan','desc')->paginate(5);

        }else{
                $listpermohonan = Permohonan::join('pengesahan', 'permohonan.nopermohonan', '=', 'pengesahan.nopermohonan')
                ->where('pengesahan.kodcaw', $kodcaw)
                ->where('tagterima',0)
                ->where('tagoperasi','!=',2)
                ->where('tagakaun','!=',2)
                ->where('tagpb','!=',2)
                ->where('tagdeposit','!=',2)
                ->where('tagprint','!=',2)
                ->where(function($query){
                        $query->where('tagcit', '!=', 1)
                        ->orWhere('tagoperasi','!=',1)
                        ->orWhere('tagakaun','!=',1);
                })
                ->get();
        }

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

    public function GetPermohonanById($kodcaw,$mohonid)
    {
        $permohonanstatus = [];
        $listpermohonan = Permohonan::join('pengesahan', 'permohonan.nopermohonan', '=', 'pengesahan.nopermohonan')
        ->where([['permohonan.kodcaw', $kodcaw],['permohonan.nopermohonan',$mohonid]])->first()->toArray();

        $status = Status::where('nopermohonan',$mohonid)->get()->toArray();

        array_push($listpermohonan,(["status" => $status]));

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

    public function GetDescriptionStatus($mohonid)
    {
        $statusarray = [];
        $statusdetails = [];
        $status = Status::join('pengesahan', 'status.nopermohonan', '=', 'pengesahan.nopermohonan')
                ->join('permohonan', 'status.nopermohonan', '=', 'permohonan.nopermohonan')
                ->where('status.nopermohonan',$mohonid)->get()->toArray();

        foreach($status as $index=>$stat)
        {
                $status_lookup = LookupStatus::where('statusid',$stat['statusid'])->first()->toArray();
                $date = date('d-m-Y',strtotime($stat['tarikhmasa']));
                $time = date('g:i a',strtotime($stat['tarikhmasa']));

                switch($stat['statusid']){
                case 1: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'nama_pemohon' => $stat['nama_pemohon'],'permohonanfiles_id' => $stat['files_permohonan_id']]);
                        break;
                case 2: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'nama_operasi' => $stat['nama_operasi'],'operasifiles_id' => $stat['files_kelope_id']]);
                        break;
                case 3: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'nama_akaun' => $stat['nama_akaun'],'akaunfiles_id' => $stat['files_kelakaun_id']]);
                        break;
                case 4: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'jumlah_diluluskan' => $stat['jumlah_diluluskan'],'pbfiles' => $stat['files_id']]);
                        break;
                case 5: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'jenisbank' => $stat['jenisbank'],'noresit' => $stat['noresit'],'jeniscit' => $stat['jeniscit'],'namasyarikat' => $stat['nama_cit']]);
                        break;
                case 6: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'nama_penerima' => $stat['nama_penerima']]);
                        break;
                case 7: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'komen' => $stat['komen_batal']]);
                        break;
                case 8: array_push($status_lookup,['tarikh' => $date, 'masa' => $time,'jenisbank' => $stat['bank_cit'],'invoicefiles' => $stat['invoicefiles_id'],'resitfiles' => $stat['resitfiles_id']]);
                        break;
                }

                array_push($statusarray,$status_lookup);
        }

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

    public function KelulusanPermohonanByOperasi(Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;
        $ar_files = new ARFiles;
        try{

                if($request->kelulusan == 'Lulus')
                {
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 2;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $ar_files->data = $request->dataimage;
                        $ar_files->type = $request->imagetype;
                        $ar_files->filename = $request->imagename;
                        $ar_files->tarikhmasa = $timeloni->toDateTimeString();
                        $ar_files->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagoperasi',0]])
                        ->update(array(
                                'tagoperasi' => 1,
                                'nama_operasi' => $request->namaoperasi,
                                'tarikh_pengesahanoperasi' => $timeloni->toDateString(),
                                'files_kelope_id' => $ar_files->id
                        ));

                }else{

                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 7;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagoperasi',0]])
                        ->update(array(
                                'tagoperasi' => 2,
                                'komen_batal' => $request->komen,
                                'nama_operasi' => $request->namaoperasi,
                                'tarikh_pengesahanoperasi' => $timeloni->toDateString()
                        ));

                }

                return response()->json($pengesahan,200);

        }catch (\Throwable $e){
                return response($e);
        }

    }


    public function KelulusanPermohonanByAkaun(Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;
        $ar_files = new ARFiles;

        try{

                if($request->kelulusan == 'Lulus')
                {
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 3;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $ar_files->data = $request->dataimage;
                        $ar_files->type = $request->imagetype;
                        $ar_files->filename = $request->imagename;
                        $ar_files->tarikhmasa = $timeloni->toDateTimeString();
                        $ar_files->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagakaun',0]])
                        ->update(array(
                                'tagakaun' => 1,
                                'nama_akaun' => $request->namaakaun,
                                'tarikh_pengesahanakaun' => $timeloni->toDateString(),
                                'files_kelakaun_id' => $ar_files->id
                        ));

                }else
                {
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 7;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagakaun',0]])
                        ->update(array(
                                'tagakaun' => 2,
                                'komen_batal' => $request->komen,
                                'nama_akaun' => $request->namaakaun,
                                'tarikh_pengesahanakaun' => $timeloni->toDateString()
                        ));
                }

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


        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function PengesahanCetakan(Request $request)
    {
        $timeloni = Carbon::now();

        try{
                $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagakaun',1]])
                ->update(array(
                        'tagprint' => 1,
                        'nama_print' => $request->namaprint,
                        'tarikh_print' => $timeloni->toDateString()
                ));

                return response()->json($pengesahan);
        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function KelulusanPermohonanByPB(Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;
        $ar_files = new ARFiles;

        try{

                if($request->kelulusan == 'Lulus')
                {
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 4;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $ar_files->data = $request->dataimage;
                        $ar_files->type = $request->imagetype;
                        $ar_files->filename = $request->imagename;
                        $ar_files->tarikhmasa = $timeloni->toDateTimeString();
                        $ar_files->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagpb',0]])
                        ->update(array(
                                'tagpb' => 1,
                                'files_id' => $ar_files->id
                        ));

                        $permohonan = Permohonan::where('nopermohonan',$request->mohonid)
                        ->update(array(
                                'tarikh_diluluskan' => $timeloni->toDateTimeString(),
                                'jumlah_diluluskan' => $request->amaun_lulus
                        ));
                }else{
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 7;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagpb',0]])
                        ->update(array(
                                'tagpb' => 2,
                                'komen_batal' => $request->komen
                        ));
                }

                return response()->json(1);


        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function DepositBank(Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;

        try{

                if($request->kelulusan == 'Lulus')
                {
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 5;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagdeposit',0]])
                        ->update(array(
                                'tagdeposit' => 1,
                                'tarikh_bankin' => $timeloni->toDateString(),
                                'jenisbank' => $request->jenisbank,
                                'noresit' => $request->noresit,
                                'jeniscit' => $request->jeniscit,
                                'nama_cit' => $request->namacit
                        ));
                }else{
                        $status->nopermohonan = $request->mohonid;
                        $status->statusid = 7;
                        $status->tarikhmasa = $timeloni->toDateTimeString();
                        $status->save();

                        $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagdeposit',0]])
                        ->update(array(
                                'tagdeposit' => 2,
                                'komen_batal' => $request->komen
                        ));
                }

                return response()->json(1);


        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function TagTerima(Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;

        try{

                $status->nopermohonan = $request->mohonid;
                $status->statusid = 6;
                $status->tarikhmasa = $timeloni->toDateTimeString();
                $status->save();

                $pengesahan = Permohonan::where([['nopermohonan',$request->mohonid],['tagterima',0]])
                ->update(array(
                        'tagterima' => 1,
                        'tarikh_terima' => $timeloni->toDateString(),
                        'nama_penerima' => $request->namapenerima
                ));

                return response()->json(1);


        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function TagCit (Request $request)
    {
        $timeloni = Carbon::now();
        $status = new Status;

        try{

                $status->nopermohonan = $request->mohonid;
                $status->statusid = 8;
                $status->tarikhmasa = $timeloni->toDateTimeString();
                $status->save();

                $ar_files = new ARFiles;
                $ar_files->data = $request->dataresit;
                $ar_files->type = $request->resittype;
                $ar_files->filename = $request->resitname;
                $ar_files->tarikhmasa = $timeloni->toDateTimeString();
                $ar_files->save();

                $ar_files2 = new ARFiles;
                $ar_files2->data = $request->datainvoice;
                $ar_files2->type = $request->invoicetype;
                $ar_files2->filename = $request->invoicename;
                $ar_files2->tarikhmasa = $timeloni->toDateTimeString();
                $ar_files2->save();

                $pengesahan = Pengesahan::where([['nopermohonan',$request->mohonid],['tagcit',0]])
                ->update(array(
                        'tagcit' => 1,
                        'resit_cit' => $request->resitcit,
                        'bank_cit' => $request->bank,
                        'resitfiles_id' => $ar_files->id,
                        'invoicefiles_id' => $ar_files2->id
                ));

                return response()->json(1);


        }catch (\Throwable $e){
                return response($e);
        }
    }

    public function downloadFile(Request $request) {
        $kp = ARFiles::where('files_id',$request->files_id)
                ->first();

        return response($kp,200);
    }

    public function rekodWTD(Request $request){

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

        //$latestbatch = SerahBaki::on($cawangan['mysql'])->where('norujukan','baru')->get()->toArray();
        //new added
        $serahBaki = SerahBaki::on($cawangan['mysql'])
    ->where('norujukan', 'baru')
    ->get();

        $allBatchNo = $serahBaki->pluck('batchno')->unique()->toArray();

        $wtddraftData = WTDDraft::on('mysql7')
                ->selectRaw("
                        batchno_serah,
                        YEAR(t_jual) as tahun,
                        GROUP_CONCAT(
                        DISTINCT MONTH(t_jual)
                        ORDER BY MONTH(t_jual)
                        SEPARATOR ','
                        ) as bulan
                ")
                ->where('kodcaw', $request->kodcaw)
                ->whereIn('batchno_serah', $allBatchNo)
                ->groupBy('batchno_serah', DB::raw('YEAR(t_jual)'))
                ->get()
                ->groupBy('batchno_serah')
                ->map(function ($rows) {
                        return $rows->map(function ($row) {
                        return [
                                'tahun' => $row->tahun,
                                'bulan' => $row->bulan
                        ];
                        })->values();
                });

        $finalData = $serahBaki->map(function ($item) use ($wtddraftData) {
                $batchno = $item->batchno;

                $tahun = null;
                $bulan = [];

                if (!empty($wtddraftData[$batchno])) {
                        // ambil tahun pertama (kebiasaannya satu tahun sahaja)
                        $tahun = $wtddraftData[$batchno][0]['tahun'];

                        // convert string "2,3,4,5" → array
                        $bulan = explode(',', $wtddraftData[$batchno][0]['bulan']);
                }

                return [
                        'batchno' => $batchno,
                        'norujukan'   => $item->norujukan,
                        'tarikh'      => $item->tarikh,
                        't_jual'      => $item->t_jual,
                        'baki'        => $item->baki,
                        't_htr_ag'    => $item->t_htr_ag,
                        'aktif'       => $item->aktif,
                        'tahun'   => $tahun,
                        'bulan'   => implode(',',$bulan),
                        // field lain kekal
                ];
        });

        $finalDataArray = $finalData->toArray();
        //end new added
        
        $batch_old = WTDDraft::on('mysql7')->select('kodcaw')->where('batchno_serah',0)->where('kodcaw',$request->kodcaw)
        ->groupBy('kodcaw')->get();

        $batch_old_noruj = WTDDraft::on('mysql7')->where('batchno_serah',0)->where('kodcaw',$request->kodcaw)->pluck('norujukan');
        $lelong_data = Lelong::on($cawangan['mysql'])->whereIn('norujukan',$batch_old_noruj)->get();
       
        foreach($batch_old as $index=>$bo)
        {
                //array_push($latestbatch,['recno' => 0,'norujukan' => 'lama','batchno' => 0,'baki' => $lelong_data->sum('baki'),'aktif' => 1]);
                array_push($finalDataArray,['recno' => 0,'norujukan' => 'lama','batchno' => 0,'baki' => $lelong_data->sum('baki'),'aktif' => 1]);

        }

        //$data = $this->paginate($latestbatch,8);
        $data = $this->paginate($finalDataArray,8);

        return response()->json($data,200);

    }

    public function rekodWTDByBatchNo($batchno,Request $request){

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

        $wtdnorujukan = WTDDraft::on('mysql7')->where('batchno_serah',$batchno)->where('kodcaw','=',$request->kodcaw)->pluck('norujukan');

        $lelong = Lelong::on($cawangan['mysql'])
        ->select('gadai.norujukan','lelong.t_lelong','gadai.pinjaman','lelong.baki','lelong.t_jual')        
        ->whereIn('lelong.norujukan',$wtdnorujukan)
        ->join('gadai','lelong.norujukan','=','gadai.norujukan')
        ->get();

        return response()->json($lelong,200);

    }

    public function rekodWTDDalamProses(Request $request){



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

        $wtdnorujukan = WTDDraft::on('mysql7')->where('batchno_serah',$request->batchno)
        ->where('kodcaw','=',$request->kodcaw)
        ->orderBy('norujukan','ASC')
        ->get();

        $pluck_norujukan = $wtdnorujukan->pluck('norujukan');
        
        
        $lelongs = Lelong::on($cawangan['mysql'])
        ->whereIn('lelong.norujukan',$pluck_norujukan)
        ->join('gadai','lelong.norujukan','=','gadai.norujukan')
        ->select('nokp', 'lelong.norujukan','lelong.t_jual','lelong.hargajual','lelong.gst_hj','lelong.pinjaman','lelong.bakiupah','lelong.cajlelong','lelong.gst_cl','lelong.cajlain','lelong.baki')
        ->orderBy('lelong.norujukan','ASC')
        ->get();
        
        $pluck_nokp = $lelongs->pluck('nokp');  
        // dd($pluck_nokp);     
        
        $customers = Customer::on('mysql7')
        ->whereIn('kpbaru', $pluck_nokp)
        ->orWhereIn('kplama', $pluck_nokp)
        ->select('nama','kpbaru','kplama')     
        ->get();            
        // dd($pluck_nokp, $customers->toArray());      
     
    
            $gadai_all_keyBy_norujukan = $lelongs->keyBy('norujukan');
           
            $gadai_all_keyBy_nokp = $gadai_all_keyBy_norujukan->keyBy('nokp');

            foreach($customers as $index=> $customer){

                if($customer->kpbaru != ''){

                        $customers[$index]['nokp'] = $customer->kpbaru;
                }

                elseif($customer->kplama != ''){

                        $customers[$index]['nokp'] = $customer->kplama;

                }

                
                
        }
        // dd($customers);

            $customer_keyBy_nokp = $customers->keyBy('nokp');
        //     dd($customer_keyBy_nokp->toArray(),$customers->toArray());
    
      

                
                foreach($lelongs as $index=>$lelong){
                        // dd($gadai_all_keyBy_nokp, $lelong->nokp,$gadai_all_keyBy_nokp[$lelong->nokp] );

                        $lelongs[$index]['customer'] = $customer_keyBy_nokp[$lelong->nokp]->toArray();
                        
                        
                        // dd($lelong->toArray());
                }

        // dd($lelongs->toArray());
            

            
       

        return response()->json($lelongs,200);

    }


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

        $current = Carbon::now();
        $current = new Carbon();

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


        $mula = explode('-', $request->mula);
        $hingga = explode('-', $request->hingga);


        $lelong = Lelong::on($cawangan['mysql'])
         ->where([['baki','>',0],['trkhtuntut',null]])
         ->whereMonth('t_jual','>=',$mula[0])
         ->whereMonth('t_jual','<=',$hingga[0])
         ->whereYear('t_jual','>=',$mula[1])
         ->whereYear('t_jual','<=',$hingga[1]);

        $lelongdetails = $lelong->get()->toArray();
        $lelongcount = $lelong->count();
        $lelongpluck = $lelong->pluck('norujukan');

        $draft = WTDDraft::on('mysql7')
                ->whereIn('norujukan',$lelongpluck)
                ->where('kodcaw',$kodcaw)
                ->whereMonth('t_jual','>=',$mula[0])
                ->whereMonth('t_jual','<=',$hingga[0])
                ->whereYear('t_jual','>=',$mula[1])
                ->whereYear('t_jual','<=',$hingga[1]);

        $draftcount = $draft->count();
        $draftpluck = $draft->pluck('norujukan');

        if($lelongcount == $draftcount)
        {
                $dummy = [];
                return response()->json($dummy,200);
        }else{
                $dif = array_diff($lelongpluck->toArray(),$draftpluck->toArray());

                $lelongbaru =  Lelong::on($cawangan['mysql'])
                ->whereIn('norujukan',$dif)
                ->get()->toArray();

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

    public function SenaraiTuntutWTD(Request $request){

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

        $norujukan = $request->norujukan;

        $lelong = Lelong::on($cawangan['mysql'])
        ->select('gadai.norujukan','lelong.t_lelong','gadai.pinjaman','lelong.baki','gadai.nokp')
        ->whereIn('lelong.norujukan',$norujukan)
        ->join('gadai','lelong.norujukan','=','gadai.norujukan')
        ->get();

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

    public function InsertDraftWTD(Request $request){

        $current = Carbon::now();
        $current = new Carbon();

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

        $norujukan = $request->norujukan;


        try{
                $lelong = Lelong::on($cawangan['mysql'])
                ->select('gadai.nokp','lelong.kodcaw','gadai.norujukan','lelong.t_jual','gadai.t_gadai','lelong.t_lelong','lelong.baki')
                ->whereIn('lelong.norujukan',$norujukan)
                ->join('gadai','lelong.norujukan','=','gadai.norujukan')
                ->get();

                $totalbaki = 0;
                $latestbatch = SerahBaki::on($cawangan['mysql'])->max('batchno');

                foreach($lelong as $lel)
                {
                        $wtddraft = new WTDDraft;
                        $wtddraft->nokp = $lel->nokp;
                        $wtddraft->kodcaw = $lel->kodcaw;
                        $wtddraft->norujukan = $lel->norujukan;
                        $wtddraft->t_jual = $lel->t_jual;
                        $wtddraft->t_gadai = $lel->t_gadai;
                        $wtddraft->t_lelong = $lel->t_lelong;
                        $wtddraft->batchno_serah = $latestbatch + 1;
                        $wtddraft->save();

                        $totalbaki += $lel->baki;
                }


                $serahbaki = SerahBaki::on($cawangan['mysql'])->create([
                        'batchno' => $latestbatch + 1,
                        'norujukan' => 'baru',
                        'hargajual' => 0.00,
                        'pinjaman' => 0.00,
                        'upah' => 0.00,
                        'cajlel' => 0.00,
                        'gst_cl' => 0.00,
                        'gst_hj' => 0.00,
                        'baki' => $totalbaki,
                        'tarikh' => $current->toDateString(),
                        'nopelanggan' => '',
                        'aktif' => 0
                     ]);


                return response()->json(['status' => 'success','batchno' => $latestbatch + 1],200);

        }catch (\Throwable $e){
                return response($e);
        }


    }

    public function RemoveDraftWTD(Request $request){

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

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

        try{
                $result1 = SerahBaki::on($cawangan['mysql'])->where('batchno',$request->batchno)->delete();
                $result2 = WTDDraft::on('mysql7')->where([['kodcaw',$request->kodcaw],['batchno_serah',$request->batchno]])->delete();

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

                return response()->json($result1,200);
        }catch (\Exception $e) {
                DB::connection('mysql7')->rollback();
                DB::connection($cawangan['mysql'])->rollback();

                return response()->json($e->getMessage(),400);
            }

    }

    public function ProsesWTD(Request $request){

        $current = Carbon::now();
        $current = new Carbon();

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

        $batchno = $request->batch;

        $selectnorujukan =  $lelong = WTDDraft::on('mysql7')
                                ->where('batchno_serah',$batchno)
                                ->pluck('norujukan');


        $lelong = Lelong::on($cawangan['mysql'])
                ->select('lelong.batchno','lelong.kodcaw','gadai.nokp','lelong.t_jual','gadai.pinjaman','gadai.nopelanggan','lelong.norujukan','gadai.bakipjm','gadai.bakiupah','lelong.cajlain','lelong.cajlelong','lelong.baki','lelong.hargajual','lelong.gst_cl')
                ->whereIn('lelong.norujukan',$selectnorujukan)
                ->join('gadai','lelong.norujukan','=','gadai.norujukan')
                ->get()->toArray();
        try{
                foreach($lelong as $lel)
                {
                        $tuntutbaki = TuntutBaki::on($cawangan['mysql'])->create([
                                'batchno' => $lel['batchno'],
                                'jenis' => "T",
                                'kodcaw' => $lel['kodcaw'],
                                'norujukan' => $lel['norujukan'],
                                'tarikh' => $current->toDateString(),
                                'prkod' => "01",
                                'teller' => "DM",
                                'bakipjm' => ($lel['bakipjm']) ? $lel['bakipjm'] : 0,
                                'bakiupah' => $lel['bakiupah'],
                                'cajlain' => '0.00',
                                'cajlelong' => $lel['cajlelong'],
                                'kodgl' => '',
                                'glcode' => '',
                                'terima' => "*",
                                'f_lulus' =>"L",
                                'jumlah' => $lel['baki'],
                                'nowakil' => 0,
                                'hargajual' => $lel['hargajual']
                        ]);

                        $wtd = WTD::on($cawangan['mysql'])->create([
                        	'norujukan' => $lel['norujukan'],
                                'tarikh' => $current->toDateString(),
                                'nokp' =>  $lel['nokp'],
                                'nopelanggan' =>  $lel['nopelanggan'],
                                'nama' => '',
                                'batchno' =>  $lel['batchno'],
                                't_jual' =>  $lel['t_jual'],
                                'hargajual' =>  $lel['hargajual'],
                                'pinjaman' =>  $lel['pinjaman'],
                                'bakiupah' =>  $lel['bakiupah'],
                                'cajlelong' =>  $lel['cajlelong'],
                                'gst_cl' => $lel['gst_cl'],
                                'baki' => $lel['baki'],
                                'rugi' => 0.00,
                                'ansrugi' => 0.00,
                                'wtd' => $lel['baki'],

                        ]);

                        $lelong=Lelong::on($cawangan['mysql'])
                        ->where('norujukan',$lel['norujukan'])
                        ->update(
                                array('trkhtuntut'=> $current->toDateString(),
                                        't_update' => $current->toDateString()));
                }

                //$serahbakiupdate = SerahBaki::on($cawangan['mysql'])->where('batchno',$batchno)->update(array('aktif' => 1,'t_jual' => $current->toDateString(),'nopelanggan' => $request->nocek));;
                $serahbakiupdate = SerahBaki::on($cawangan['mysql'])->where('batchno',$batchno)->update(array('aktif' => 1,'t_jual' => $current->toDateString(),'nopelanggan' => $request->nocek,'t_htr_ag' => $request->tarikhAG));
                
                return response()->json('success',200);

        }catch (\Throwable $e){
                return response($e);
        }



    }

    public function PenjanaanPC(Request $request){

        $timeloni = Carbon::now();
        $status = new Status;

        try{
                if($request->status == 'jana')
                {
                        $pengesahan = Permohonan::where('nopermohonan',$request->mohonid)
                        ->update(array(
                                'tagjanapc' => 1
                        ));
                }else{

                        $ar_files = new ARFiles;
                        $ar_files->data = $request->dataimage;
                        $ar_files->type = $request->imagetype;
                        $ar_files->filename = $request->imagename;
                        $ar_files->tarikhmasa = $timeloni->toDateTimeString();
                        $ar_files->save();


                        $pengesahan = Permohonan::where('nopermohonan',$request->mohonid)
                        ->update(array(
                                'tagjanapc' => 2,
                                'files_permohonan_id' => $ar_files->id
                        ));
                }


                return response()->json($pengesahan);
        }catch (\Throwable $e){
                return response($e);
        }

    }

    public function KeuntunganSebenarExport(Request $request){

        $current = Carbon::now();
        $current = new Carbon();

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

        $year = $request->year;
        $month = $request->month;

        if($request->jenistebus == 'T')
        {
                $bukanansuran_data = 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')
                // ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
                // ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
                ->whereMonth('transaksi_keuntungan.tarikh_bayaran','=',$month)
                ->whereYear('tarikh_bayaran','=',$year)
                ->where('trans.kodcaw',$request->kodcaw);

                $bukanansuran_get = $bukanansuran_data->get();
                $bukanansuran_pluck = $bukanansuran_data->pluck('trans.norujukan');

                $intersection = $bukanansuran_get->intersectByKeys(Gadai::on($cawangan['mysql'])->whereNotNull('hargajualan')->get());
                $collectionbukanansurandata = $intersection->toArray();

                return response()->json($collectionbukanansurandata,200);
        }else if($request->jenistebus == 'A'){
                $ansuran_data = 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')
                        // ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
                        // ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
                        ->whereMonth('transaksi_keuntungan.tarikh_bayaran','=',$month)
                        ->whereYear('tarikh_bayaran','=',$year)
                        ->where('trans.kodcaw',$request->kodcaw);

                $ansuran_get = $ansuran_data->get();
                $ansuran_pluck = $ansuran_data->pluck('trans.norujukan');

                $intersection = $ansuran_get->intersectByKeys(Gadai::on($cawangan['mysql'])->whereNotNull('hargajualan')->get());

                $collectionansurandata = $intersection->toArray();

                return response()->json($collectionansurandata,200);
        }else{
                $upahlelong = Lelong::on($cawangan['mysql'])
                        ->where('t_jual','>','2013-12-31')
                        ->whereMonth('t_lelong','=',$month)
                        ->whereYear('t_lelong','=',$year)
                        ->get();

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

     public function LaporanAging(Request $request){

        $current = Carbon::now();
        $current = new Carbon();

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

        if($current->month == $request->bulan)
        {
                $audit = Gadai::on($cawangan['mysql'])
                ->where(function($q) use ($current) {
                        $q->where([['tagpalsu','=',0],['t_gadai','<=',$current->toDateString()],['sttebus','=','']])
                        ->orWhere([['tagpalsu','=',0],['t_update','>',$current->toDateString()],['sttebus','!=',''],['t_gadai','<=',$current->toDateString()]]);
                });
        }else{
                if($bulan == 1){
                $audit = StokAudit1::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 2){
                $audit = StokAudit2::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 3){
                $audit = StokAudit3::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 4){
                $audit = StokAudit4::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 5){
                $audit = StokAudit5::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 6){
                $audit = StokAudit6::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 7){
                $audit = StokAudit7::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 8){
                $audit = StokAudit8::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 9){
                $audit = StokAudit9::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 10){
                $audit = StokAudit10::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 11){
                $audit = StokAudit11::on($cawangan['mysql'])->where('tahun',$tahun);
                }elseif($bulan == 12){
                $audit = StokAudit12::on($cawangan['mysql'])->where('tahun',$tahun);
                }
        }

        $jumlahrekod = $audit->count();
        $jumlahpinjaman = $audit->sum('bakipjm');

        $arraycount = [];
        $arraysum = [];
        $arrayall = [];

        for ($i = 1; $i <= 13; $i++)
        {
          ${"tempoh".$i} = clone $audit;
          if($i == 13)
          {
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where('tempoh','>',12)->count();
          }else if($i == 1){
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where([['tempoh','>',0],['tempoh','<=',1.5]])->count();
          }else if($i == 12){
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where([['tempoh','>=',$i],['tempoh','<=',$i]])->count();
          }else{
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where([['tempoh','>',$i-(0.5)],['tempoh','<=',$i+(0.5)]])->count();
          }
          ${"tempoh".$i."sum"} = ${"tempoh".$i}->sum('bakipjm');
          array_push($arraycount,${"tempoh".$i."count"});
          array_push($arraysum,${"tempoh".$i."sum"});
        }


        array_push($arrayall,['count' => $arraycount,'sum' => $arraysum]);
        if(sizeof($arrayall) == 0){
            return response()->json('failed',200);
        }else{
            return response()->json($arrayall,200);
        }
     }

     public function DashboardAging(Request $request){

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


        $current = Carbon::now();
        $current = new Carbon();

        $harini = $current->toDateString();
        $jenislaporan = $request->options;


        if($jenislaporan === 'sebenar')
        {
                $audit = Gadai::on($cawangan['mysql'])
                ->where(function ($query) use ($harini) {
                        $query->where([['tagpalsu','=',0],['t_gadai','<=',$harini],['sttebus','=','']])
                        ->orWhere([['tagpalsu','=',0],['t_update','>',$harini],['sttebus','!=',''],['t_gadai','<=',$harini]]);
                });

        }elseif($jenislaporan === 'datalelong')
        {
                $audit = Gadai::on($cawangan['mysql'])
                // ->where([['tagpalsu','=',0],['t_gadai','<=',$harini],['sttebus','=',''],['lelong_tawarruq',1]])
                // ->orWhere([['tagpalsu','=',0],['t_update','>',$harini],['sttebus','!=',''],['t_gadai','<=',$harini],['lelong_tawarruq',1]]);
                ->where(function ($query) use ($harini) {
                        $query->where([['tagpalsu','=',0],['t_gadai','<=',$harini],['sttebus','=',''],['lelong_tawarruq',1]])
                        ->orWhere([['tagpalsu','=',0],['t_update','>',$harini],['sttebus','!=',''],['t_gadai','<=',$harini],['lelong_tawarruq',1]]);
                });

        }else{
                $audit = Gadai::on($cawangan['mysql'])
                ->where(function ($query) use ($harini) {
                        $query->where([['tagpalsu','=',0],['t_gadai','<=',$harini],['sttebus','=',''],['lelong_tawarruq',0]])
                        ->orWhere([['tagpalsu','=',0],['t_update','>',$harini],['sttebus','!=',''],['t_gadai','<=',$harini],['lelong_tawarruq',0]]);
                });
        }

        $rekodaudit = $audit->get();
        $countaudit = $audit->count();
        $sumaudit = $audit->sum('bakipjm');

        $arraycount = [];
        $arraysum = [];

        for ($i = 1; $i <= 13; $i++)
        {
          ${"tempoh".$i} = clone $audit;
          if($i == 13)
          {
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where('tempoh','>',12)->count();
          }else if($i == 1){
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where([['tempoh','>',0],['tempoh','<=',1.5]])->count();
          }else{
                ${"tempoh".$i."count"} = ${"tempoh".$i}->where([['tempoh','>',$i-(0.5)],['tempoh','<=',$i+(0.5)]])->count();
          }
          ${"tempoh".$i."sum"} = ${"tempoh".$i}->sum('bakipjm');
          array_push($arraycount,${"tempoh".$i."count"});
          array_push($arraysum,${"tempoh".$i."sum"});
        }

        array_push($arraycount,$countaudit);
        array_push($arraysum,$sumaudit);

        $arrayall = ['count' => $arraycount,'sum' => $arraysum];

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


     public function Laporan_SerahPetiBesiGadai(Request $request){

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

        $current = Carbon::now();
        $current = new Carbon();

        $gadai = Gadai::on($cawangan['mysql'])
                ->where([
                    ['t_gadai','>=',$request->mula],['t_gadai','<=',$request->hingga],
                    ['cetak','=',1],['tagserah','=',1]])
                    ->orderBy('teller')
                    ->orderBy('semakbarcode')
                    ->get();

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

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

        $current = Carbon::now();
        $current = new Carbon();

        $gadai = Tebus::on($cawangan['mysql'])
                ->where([
                ['t_tebus','>=',$request->mula],['t_tebus','<=',$request->hingga]])
                ->orderBy('teller')
                ->orderBy('tagterima')
                ->get();

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

    public function laporanAuditCustomer(Request $request){

        $audit_customer = AuditCustomer::on('mysql7')
        ->where('kodcaw', $request->kodcaw)
        ->whereDate('created_at','>=', $request->mula)
        ->whereDate('created_at','<=', $request->hingga)
        ->get()
        ->toArray();

        $array_audit_old = array();
        $array_audit_new = array();
        $array_changes_audit = array();

        foreach($audit_customer as $index1=>$audit)
        {
                array_push($array_audit_old,json_decode($audit['old_data'], true));
                array_push($array_audit_new,json_decode($audit['new_data'], true));
        }

        foreach($array_audit_old as $index=>$old)
        {
                $test_old = array_diff($old[0],$array_audit_new[$index][0]);
                $test_new = array_diff($array_audit_new[$index][0],$old[0]);

                if(sizeof($test_old) != 0)
                {
                        array_push($array_changes_audit,['old' => $test_old,'new' => $test_new,'username' => $audit_customer[$index]['username'],'customer_name' => $audit_customer[$index]['customer_name'],'nokp' => $audit_customer[$index]['customer_nokp'],'tarikhmasa' => $audit_customer[$index]['created_at']]);
                }
        }

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

    public function ListBarcodeScannedOperasi(Request $request){

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

        $gadai = Gadai::on($cawangan['mysql'])
                ->where([
                    ['sttebus','=',''],
                    ['semakbarcode','<>','Lulus'],
                    ])
                    ->paginate(5);

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

    public function ListBarcodeScannedOperasi_Update(Request $request){

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

        $gadai = Gadai::on($cawangan['mysql'])
                ->where('norujukan',$request->norujukan)
                ->update(['semakbarcode'=>'Lulus']);

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

    public function PenggunaMargin(Request $request){

        
        $margin = MaxPinjaman::on('mysql7')
        ->where(function($query) {
                $query->where('user_type','=','teller')
                    ->orWhere('user_type','=','khazanah');
                })
                ->paginate(5);          
                    

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

    public function PenggunaMargin_Update(Request $request){
        

        $margin = MaxPinjaman::on('mysql7')
                ->where('id',$request->id)
                ->update(['max' => $request->max]);        

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

    

    public function BilanganPengadai(Request $request)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $request->kodcaw)->first();
    
        $gadai = Gadai::on($cawangan['mysql'])
            ->where('t_gadai', '>=', $request->mula)
            ->where('t_gadai', '<=', $request->hingga)
            ->where('sttebus', '')
            ->select('nokp')
            ->groupBy('nokp')
            ->get();
    
        $gadai_pluck_nokp = $gadai->pluck('nokp');
        $jenis = $request->jenis;
        $filter_value = $request->value ?? null;
    
        $customers = [];
    
        if ($jenis === 'pekerja') {
            $customers = Customer::on('mysql7')
                ->selectRaw('pekerjaan.keterangan, COUNT(*) AS bilangangadai')
                ->whereIn('kpbaru', $gadai_pluck_nokp)
                ->orWhereIn('kplama', $gadai_pluck_nokp)
                ->join('pekerjaan', 'customer.kodkerja', '=', 'pekerjaan.kodkerja')
                ->groupBy('pekerjaan.kodkerja')
                ->get();
    
        } elseif ($jenis === 'agama') {
            $agamaMap = [
                '01' => 'Islam',
                '02' => 'Hindu',
                '03' => 'Buddha',
                '04' => 'Kristian',
                '05' => 'Lain-lain',
                '' => 'Tiada Data',
            ];
    
            $query = Customer::on('mysql7')
                ->selectRaw('kodugama as keterangan, COUNT(*) as bilangangadai')
                ->whereIn('kpbaru', $gadai_pluck_nokp)
                ->orWhereIn('kplama', $gadai_pluck_nokp);
    
            if ($filter_value) {
                $query->where('kodugama', $filter_value); // contoh: '01'
            }
    
            $customers = $query->groupBy('kodugama')->get();
    
            foreach ($customers as $customer) {
                $customer->keterangan = $agamaMap[$customer->keterangan] ?? $customer->keterangan;
            }
    
        } elseif ($jenis === 'bangsa') {
            $bangsaMap = [
                'M' => 'Melayu',
                'C' => 'Cina',
                'I' => 'India',
                'L' => 'Lain-lain',
                '' => 'Tiada Data',
            ];
    
            $query = Customer::on('mysql7')
                ->selectRaw('bangsa as keterangan, COUNT(*) as bilangangadai')
                ->whereIn('kpbaru', $gadai_pluck_nokp)
                ->orWhereIn('kplama', $gadai_pluck_nokp);
    
            if ($filter_value) {
                $query->where('bangsa', $filter_value); // contoh: 'M'
            }
    
            $customers = $query->groupBy('bangsa')->get();
    
            foreach ($customers as $customer) {
                $customer->keterangan = $bangsaMap[$customer->keterangan] ?? $customer->keterangan;
            }
        }
    
        return response()->json($customers);
    }

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

        $current = Carbon::now();
        $current = new Carbon();

        $tarikh = new Carbon($request->tarikh);
        $year = $current->year;
        $month = $tarikh->month;

        // $get_norujukan = Gadai::on($cawangan['mysql'])
        // ->selectRaw("norujukan,CASE WHEN (YEAR(t_gadai) = YEAR(t_update) and MONTH(t_gadai) = MONTH(t_update)) THEN '1' ELSE '0' END AS result")
        // ->whereNotNull('hargajualan')
        // ->having('result','=',1)
        // ->whereYear('t_gadai','=',$year)
        // ->whereMonth('t_gadai','<=',$month)
        // ->where('sttebus','<>','')
        // ->pluck('norujukan');

        // $sum_keun = Transaction::on('mysql7')
        // ->selectRaw("trans.norujukan,SUM(CASE WHEN (transaction.trans_type) <> 'A' THEN (trans.keuntungan_rebet) ELSE 0 END) AS sum_keun,SUM(CASE WHEN (transaction.trans_type) = 'A' THEN (trans.bayaran_keuntungan) ELSE 0 END) AS sum_bayaran")
        // ->leftJoin('transaksi_keuntungan as trans', function($join)
        // {
        //     $join->on('transaction.norujukan', '=', 'trans.norujukan');
        //     $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
        // })
        // ->whereIn('trans.norujukan',$get_norujukan)->get()->toArray();

        // $sum_keuntungan = ($sum_keun) ? $sum_keun[0]['sum_keun'] : 0;
        // $sum_bayaran = ($sum_keun) ? $sum_keun[0]['sum_bayaran'] : 0;

        // /* Ansuran masuk dalam ni */

        // $collection_trans = 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.kodcaw','=',$request->kodcaw)
        // ->where('trans.trans_type','=','A')
        // ->where('transaksi_keuntungan.margin_semasa','>','0')
        // ->whereYear('transaksi_keuntungan.tarikh_bayaran','=',$year)
        // ->whereMonth('transaksi_keuntungan.tarikh_bayaran','<=',$month)
        // ->get();


        // $array_norujukan = $collection_trans->pluck('norujukan')->toArray();

        // $collection_gadai = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$array_norujukan)->where('tagbaru',1)->get();

        // $keuntungan_semasa_collection = $collection_trans->filter(function ($trans) use ($collection_gadai) {
                
        //         foreach ($collection_gadai as $gadai) {
        //                 if($gadai->norujukan === $trans->norujukan){
        //                         $t_gadai = Carbon::parse($gadai->t_gadai);
        //                         $t_bayaran = Carbon::parse($trans->tarikh_bayaran);
                                
        //                         if ($t_gadai->month !== $t_bayaran->month) {
        //                                 return false;
        //                         }
        //                 }
        //         }
        //         return true;
        // });

        // $summation_ansuran = $keuntungan_semasa_collection->sum('bayaran_keuntungan');


        // $total = $sum_keuntungan + $sum_bayaran + $summation_ansuran;
	
        $lastDayPreviousMonth = $tarikh->subMonthsNoOverflow()->endOfMonth()->toDateString();

        if(Carbon::parse($lastDayPreviousMonth)->year == Carbon::now()->year){
                $get_imbangduga = imbangdugabackup::on($cawangan['mysql'])->where('tarikh',$lastDayPreviousMonth)->first();
                $get_imbangduga = optional($get_imbangduga)->toArray() ?? [];
        }
	
        $collection_trans = Transaction::on('mysql7')
            ->leftJoin('transaksi_keuntungan as trans', function ($join) {
                $join->on('transaction.norujukan', '=', 'trans.norujukan');
                $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
            })
            ->where('transaction.kodcaw', $request->kodcaw)
            ->whereYear('transaction.created_at', '=', $year)
            ->whereMonth('transaction.created_at', '=', $month)
            ->get();

        $array_norujukan = $collection_trans->pluck('norujukan')->toArray();

        $collection_gadai = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $array_norujukan)->whereYear('t_gadai',$year)->get();

        $keuntungan_semasa_collection = $collection_trans->filter(function ($trans) use ($collection_gadai) {
            foreach ($collection_gadai as $gadai) {
                if ($gadai->norujukan === $trans->norujukan) {
                    $t_gadai = Carbon::parse($gadai->t_gadai);
                    $t_bayaran = Carbon::parse($trans->tarikh_bayaran);

                    if ($t_gadai->month !== $t_bayaran->month) {
                        return false;
                    }else{
                        return true;
                    }
                }
            }
            return false;
        });

        $total_ansuran = $keuntungan_semasa_collection->filter(function ($transaction){
            return $transaction->trans_type == 'A';
        })->sum('bayaran_keuntungan');

        $total_tebus = $keuntungan_semasa_collection->filter(function ($transaction){
            return $transaction->trans_type !== 'A';
        })->sum('keuntungan_rebet');


	$backdate_keun_sebenar = isset($get_imbangduga['keun_sebenar']) ?  $get_imbangduga['keun_sebenar'] : 0;
        $total = $total_ansuran + $total_tebus + $backdate_keun_sebenar;

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

    public function getLaporanGadaiAllCaw(Request $request){

        $cawangan_all = Cawangan::on('mysql7')->get();
        $arraygadai = [];

        foreach($cawangan_all as $index=>$cawangan){


            // gadaian
            $gadai=Gadai::on($cawangan['mysql'])
            ->where([['t_gadai','>=',$request->mula_date],['t_gadai','<=',$request->hingga_date]]);

                $jumlah_gadai = $gadai->sum('pinjaman');

                $data_gadai = $gadai->get();

                $nokp_gadai = $gadai->distinct('nokp') ;
                $jum_org_gadai = $nokp_gadai->count('nokp');

                $jum_surat_gadai = $data_gadai->count('norujukan');

            //penebusan (Tebus + Lelong + Ansuran)

            $myDateTime = DateTime::createFromFormat('Y-m-d', $request->hingga_date);
            $datez = $myDateTime->modify('+1 day')->format('Y-m-d');


            $tebus = Gadai::on($cawangan['mysql'])
                    ->where('sttebus','!=','')
                    ->where([['t_update','>=',$request->mula_date],['t_update','<=',$request->hingga_date]]);

                    $jum_tebus = $tebus->sum('bakipjm');
                    // dd($jum_tebus)  ;

            $orgtebus = Gadai::on($cawangan['mysql'])
                    ->where('sttebus','=','T')
                    ->where([['t_update','>=',$request->mula_date],['t_update','<=',$request->hingga_date]]);

                    $jum_surat_t = $orgtebus->count('norujukan');

                    $nokp_tebus = $orgtebus->distinct('nokp') ;
                    $jum_org_tebus = $nokp_tebus->count('nokp');


                    $ansuran = Transaction::on('mysql7')
                    ->leftJoin('transaksi_keuntungan', function($join)
                    {
                        $join->on('transaction.norujukan', '=', 'transaksi_keuntungan.norujukan');
                        $join->on('transaction.created_at', '=', 'transaksi_keuntungan.tarikh_bayaran');
                    })
                    ->where('trans_type','=','A')
                    ->where('transaksi_keuntungan.kodcaw','=',$cawangan['kodcaw'])
                    ->where([['tarikh_bayaran','>=',$request->mula_date],['tarikh_bayaran','<=', $datez]]);

                    $jum_ansuran = $ansuran->sum('transaksi_keuntungan.bayaran_pembiayaan');

                    $jum_penebusan = $jum_tebus + $jum_ansuran ;




            //Upah tebus (KEUNTUNGAN)

            $myDateTime = DateTime::createFromFormat('Y-m-d', $request->hingga_date);
            $datez = $myDateTime->modify('+1 day')->format('Y-m-d');


            $lelongupahsimpan = Lelong::on($cawangan['mysql'])

                                ->where([['t_jual','>=',$request->mula_date],['t_jual','<=',$request->hingga_date]]);

            $jum_lelongupahsimpan = $lelongupahsimpan->sum('bakiupah');



            $upahtebus = Tebus::on($cawangan['mysql'])
                        ->rightJoin('gadai', 'gadai.norujukan', '=', 'tebus.norujukan')
                        ->where([['tebus.jenistebus','=','T'],['gadai.hargajualan','=',NULL]])
                        ->where([['t_tebus','>=',$request->mula_date],['t_tebus','<=',$request->hingga_date]]);

            $jum_upahtebus = $upahtebus->sum('tebus.bakiupah');


            $advansur = Advansur::on($cawangan['mysql'])
                        ->where([['tarikh','>=',$request->mula_date],['tarikh','<=',$request->hingga_date]]);

            $jum_advansur = $advansur->sum('upahDibayar');



            $ansuranupah = Transaction::on('mysql7')
                            ->leftJoin('transaksi_keuntungan', function($join)
                            {
                            $join->on('transaction.norujukan', '=', 'transaksi_keuntungan.norujukan');
                            $join->on('transaction.created_at', '=', 'transaksi_keuntungan.tarikh_bayaran');
                            })
                            ->where('trans_type','=','A')
                            ->where('transaksi_keuntungan.kodcaw','=',$cawangan['kodcaw'])
                            ->where([['tarikh_bayaran','>=',$request->mula_date],['tarikh_bayaran','<=',$datez]]);

                            $jum_ansuranupah = $ansuranupah->sum('transaksi_keuntungan.bayaran_keuntungan');


            $upahtawarruq = Transaction::on('mysql7')
                                    ->leftJoin('transaksi_keuntungan', function($join)
                                    {
                                    $join->on('transaction.norujukan', '=', 'transaksi_keuntungan.norujukan');
                                    $join->on('transaction.created_at', '=', 'transaksi_keuntungan.tarikh_bayaran');
                                    })
                                    ->where('trans_type','!=','A')
                                    ->where('transaksi_keuntungan.kodcaw','=',$cawangan['kodcaw'])
                                    ->where([['tarikh_bayaran','>=',$request->mula_date],['tarikh_bayaran','<=',$datez]]);

            $jum_upahtawarruq = $upahtawarruq->sum('transaksi_keuntungan.keuntungan_rebet');


            $jumlah_upah = $jum_lelongupahsimpan + $jum_upahtebus + $jum_advansur + $jum_upahtawarruq;
            $jum_keseluruhan_upah = $jumlah_upah + $jum_ansuranupah;

            $jum_pinjaman_semasa = $jumlah_gadai - $jum_penebusan;


            //baki awal dan baki akhir

                   $myDateMonth = DateTime::createFromFormat('Y-m-d', $request->mula_date);
                   $month = $myDateMonth->modify('-1 day')->format('m');
                   // dd($month);

                   $myDateYear = DateTime::createFromFormat('Y-m-d', $request->mula_date);
                   $year = $myDateYear->format('Y');
                   // dd($year);

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

                   $rekodaudit = $audit->get();
                   $bakiawal = $audit->sum('bakipjm');
                   $bakiakhir = $bakiawal + $jumlah_gadai - $jum_penebusan;

           //pelanggan baru
            $pelanggan_baru = Customer::on('mysql7')
            ->where('kodcaw','=',$cawangan['kodcaw'])
            ->where([['tarikhdaftar','>=',$request->mula_date],['tarikhdaftar','<=',$request->hingga_date]]);

            $bil_pelanggan_baru = $pelanggan_baru->count('id');


                array_push($arraygadai,[
                "data_gadai" => $data_gadai,
                "cawangan" => $cawangan['details_caw'],
                "cawangankod" => $cawangan['kodcaw'],
                "jum_org_gadai" => $jum_org_gadai,
                "jumlah_gadai"=> $jumlah_gadai,
                "jum_surat_gadai"=>$jum_surat_gadai,
                "jum_surat_t" => $jum_surat_t,
                "jum_org_tebus" => $jum_org_tebus,
                "jum_penebusan" => $jum_penebusan,
                "jum_pinjaman_semasa" => $jum_pinjaman_semasa,
                "bil_pelanggan_baru" => $bil_pelanggan_baru,
                "jumlah_upah" => $jumlah_upah,
                "jum_ansuranupah" => $jum_ansuranupah,
                "jum_keseluruhan_upah" => $jum_keseluruhan_upah,
                "bakiawal" => $bakiawal,
                "bakiakhir" => $bakiakhir
            ]);

       }
                //    dd($jum_lelongupahsimpan, $jum_upahtebus, $jum_advansur, $jum_ansuranupah, $jum_upahtawarruq  );


        return response()->json($arraygadai,200);


    }

    public function getLaporanAkruBulan(Request $request){

        $array_akru = [];
        $cawangan = Cawangan::on('mysql7')->get();

        foreach($cawangan as $caw)
        {
                $akrunet = AkruNet::on($caw['mysql'])->where('tahun',$request->year)->get()->toArray();
                array_push($array_akru,['cawangan' => $caw['details_caw'],'akru' => $akrunet]);
        }

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

    public function LaporanOnline(Request $request){

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

        if($request->jenis == 'portal')
        {
             $online=GlDetail::on($cawangan['mysql'])
                 ->where('kodcaw','=',$request->kodcaw)
                 ->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->hingga]])
                 ->where('descpt','LIKE','SERAHAN BAYAR ONLINE%')
                 ->where('serahan','>',0)
                 ->orderby('tarikh','desc')
                 ->get();
        }else if($request->jenis == 'mobile'){

             $online=GlDetail::on($cawangan['mysql'])
                 ->where('kodcaw','=',$request->kodcaw)
                 ->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->hingga]])
                 ->where('descpt','LIKE','Serahan Mobile Payment%')
                 ->where('serahan','>',0)
                 ->orderby('tarikh','desc')
                 ->get();
        }else{
             $online=GlDetail::on($cawangan['mysql'])
                 ->where('kodcaw','=',$request->kodcaw)
                 ->where([['tarikh','>=',$request->mula],['tarikh','<=',$request->hingga]])
                 ->where('descpt','LIKE','SERAHAN LELONG ONLINE%')
                 ->where('teller','=','LELONG ONLINE')
                 ->where('serahan','>',0)
                 ->orderby('tarikh','desc')
                 ->get();
        }


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

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

        $current = new Carbon($request->tarikh);

        $daterequest = new Carbon($request->tarikh);
        $daterequest->addDays(1);

        $total = 0;

        //Untung Rugi Terkumpul Sebelum 01.12.2013
        $utgrugilama = imbangdugalama::on($cawangan['mysql']) //--masuk
            ->sum('untung_t');

        //Yuran Ahli
        $yuranTlama = imbangdugalama::on($cawangan['mysql'])
            ->sum('yuran_t');

        $yuranbaru = Customer::on('mysql7')
            ->where('tarikhdaftar','>','2013-12-31')
            ->whereYear('tarikhdaftar','<',$current->year)
            ->sum('yuranahli');

        //Caj Lelong
        $lelong = Lelong::on($cawangan['mysql']) //--masuk
            ->whereNotNull('t_jual')
            ->where('t_jual','>','2013-12-31')
            ->whereYear('t_jual','<',$current->year)
            ->sum('cajlelong');

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


        //Upah Simpan Tebus
        $upahsimpantebus = Tebus::on($cawangan['mysql']) //--masuk
            ->where('t_tebus','>','2013-12-31')
            ->whereYear('t_tebus','<',$current->year)
            ->sum('upahdibayar');

        //Upah Simpan Lelong
        $upahsimpanlelong = Lelong::on($cawangan['mysql']) //--masuk
            ->where('t_jual','>','2013-12-31')
            ->whereYear('t_jual','<','2022')
            ->sum('bakiupah');

        //Upah Simpan Advansur
        $upahsimpanansur = Advansur::on($cawangan['mysql']) //--masuk
            ->whereYear('tarikh','<',$current->year)
            ->sum('upahdibayar');

        //Upah Tawarruq

        $keuntungan_data = TransaksiKeuntungan::on('mysql7')
        ->where('transaksi_keuntungan.tarikh_bayaran' ,'<=', $daterequest)
        ->whereYear('transaksi_keuntungan.tarikh_bayaran','<','2022')
        ->where('kodcaw',$kodcaw)
        ->pluck('norujukan');

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

        $upahsimpankeuntungansebelumtawarruq = TransaksiKeuntungan::on('mysql7')
            ->where('tarikh_bayaran' ,'<=', $daterequest)
            ->whereYear('tarikh_bayaran','<','2022')
            ->whereIn('norujukan',$gadaiData)
            ->sum('bayaran_keuntungan');

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

        //GST Caj Lelong
        $gstcajlelong = Lelong::on($cawangan['mysql']) //--masuk
            ->where('t_jual','<=',$request->tarikh)
            ->whereYear('t_jual','<',$current->year)
            ->sum('gst_cl');

        //Upah Hapus Kira
        $upahhapuskira = HapusKira::on($cawangan['mysql'])
            ->where('tarikh','>','2013-12-31')
            ->whereYear('tarikh','<',$current->year)
            ->sum('bakiupah');

        $panjar1 = Panjar::on($cawangan['mysql'])
            ->whereYear('tarikh','<',$current->year)
            ->where('tag','=','1')
            ->sum('bayaran');

        $panjar2 = Panjar::on($cawangan['mysql'])
            ->whereYear('tarikh','<',$current->year)
            ->where('tag','=','2')
            ->sum('bayaran');

        $panjar3 = Panjar::on($cawangan['mysql'])
            ->whereYear('tarikh','<',$current->year)
            ->where('tag','=','3')
            ->sum('bayaran');

        $parameter = ($panjar1*-1) + ($panjar2*-1) + ($panjar3*-1);

        // $parameter = Parameter::on($cawangan['mysql']) //--masuk
        //     ->sum('sumpanjarlama');

        //Keuntungan Tawarruq Sebenar
        $keuntungansebenar = 0;
        $dateSM = '2021-04-24';

        $keuntungan_data = TransaksiKeuntungan::on('mysql7')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $request->tarikh)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', $dateSM)
                    ->whereYear('tarikh_bayaran','<','2022')
                    ->where('kodcaw',$kodcaw)
                    ->pluck('norujukan');


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

        $keuntungan = TransaksiKeuntungan::on('mysql7')->whereIn('norujukan',$gadaiData)->sum('bayaran_keuntungan');

        $keuntunganreducing_data = TransaksiKeuntungan::on('mysql7')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', '2021-06-09')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                    ->whereYear('tarikh_bayaran','<','2022')
                    ->where('kodcaw',$kodcaw)
                    ->pluck('norujukan');

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

        $keuntunganreducing = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan',$gadaiData)
            ->whereDate('tarikh_bayaran' ,'<', '2021-06-09')
            ->whereDate('tarikh_bayaran','>=', $dateSM)
            ->sum('keuntungan_rebet');

        $bukanansuran_data = 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')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('tarikh_bayaran','<','2022')
                    ->where('trans.kodcaw',$kodcaw)
                    ->pluck('transaksi_keuntungan.norujukan');

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

        $bukanansuran = TransaksiKeuntungan::on('mysql7')
                    ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
                    ->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')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('transaksi_keuntungan.tarikh_bayaran','<','2022')
                    ->sum('transaksi_keuntungan.keuntungan_rebet');

        $ansuran_data = 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')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('tarikh_bayaran','<','2022')
                    ->where('trans.kodcaw',$kodcaw)
                    ->pluck('transaksi_keuntungan.norujukan');


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

        $ansuran = TransaksiKeuntungan::on('mysql7')
            ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
            ->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')
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
            ->whereYear('transaksi_keuntungan.tarikh_bayaran','<','2022')
            ->sum('transaksi_keuntungan.bayaran_keuntungan');

        $keuntungansebenar = ($keuntungan + $keuntunganreducing + $ansuran + $bukanansuran);

        $previousYear = Carbon::parse($request->tarikh)->subYears();

        $get_norujukan = Gadai::on($cawangan['mysql'])
        ->selectRaw("norujukan,CASE WHEN (YEAR(t_gadai) = YEAR(t_update) and MONTH(t_gadai) = MONTH(t_update)) THEN '1' ELSE '0' END AS result")
        ->whereNotNull('hargajualan')->having('result','=',1)->whereYear('t_gadai','>=','2022')->whereYear('t_gadai','<=','2023')->where('sttebus','<>','')->pluck('norujukan');

        $sum_keun = Transaction::on('mysql7')
        ->selectRaw("trans.norujukan,SUM(CASE WHEN (transaction.trans_type) <> 'A' THEN (trans.keuntungan_rebet) ELSE 0 END) AS sum_keun,SUM(CASE WHEN (transaction.trans_type) = 'A' THEN (trans.bayaran_keuntungan) ELSE 0 END) AS sum_bayaran")
        ->leftJoin('transaksi_keuntungan as trans', function($join)
        {
            $join->on('transaction.norujukan', '=', 'trans.norujukan');
            $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
        })
        ->whereIn('trans.norujukan',$get_norujukan)->get()->toArray();

        $sum_keuntungan = ($sum_keun) ? $sum_keun[0]['sum_keun'] : 0;
        $sum_bayaran = ($sum_keun) ? $sum_keun[0]['sum_bayaran'] : 0;

        $total_keuntungan_sebenar =  $sum_keuntungan + $sum_bayaran;

        $backdate_keun_sebenar = 0;
        $recentDate = Carbon::now()->subYear();
        
        while ($recentDate->year > 2023) {
                $exception_case = 0;
                $lastDayOfYear = $recentDate->endOfYear()->toDateString();

                $get_imbangduga = imbangdugabackup::on($cawangan['mysql'])->where('tarikh', $lastDayOfYear)->first();
                $get_imbangduga = optional($get_imbangduga)->toArray() ?? [];
                // if(empty($get_imbangduga)){
                //         $requestData = new Request([
                //                 'tarikh' => $request->tarikh,
                //                 'kodcaw' => $kodcaw,
                //         ]);
                //         $exception_case = $this->AkruKeuntunganSebenar($requestData);
                // }

                $backdate_keun_sebenar += isset($get_imbangduga['keun_sebenar']) ? $get_imbangduga['keun_sebenar'] : 0;
                $backdate_keun_sebenar += (float) ($exception_case ?? 0);
                $recentDate->subYear()->startOfYear();
        }
        
        $total_keuntungan_sebenar = $sum_keuntungan + $sum_bayaran + $backdate_keun_sebenar;

        $available_akru = AkruNet::on($cawangan['mysql'])
                ->where('tahun','<=',$previousYear->year)
                ->sum('jumlah');

        $akru_ujrah = AkruNetPecahan::on($cawangan['mysql'])->where('tahun','<=',$previousYear->year)->sum('pend_akru_ujrah');
        $akru_1percent = AkruNetPecahan::on($cawangan['mysql'])->where('tahun','<=',$previousYear->year)->sum('pend_akru_1persen');

        $total = ($utgrugilama + $lelong + $upahsimpantebus + $upahsimpanlelong + $upahsimpanansur + $gstcajlelong + $keuntungansebenar + $upahsimpankeuntungansebelumtawarruq + $available_akru + $total_keuntungan_sebenar + $akru_ujrah + $akru_1percent) + $parameter;

        if($kodcaw == '011229')
            $total -= 45390.37;

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

    public function getTarikhTunaiSebelum($kodcaw,Request $request){
        $current = Carbon::now();
        $current = new Carbon();

         $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
         $tunai = Tunai::on($cawangan['mysql'])
                ->where([['kodcaw','=',$kodcaw],['tarikh','<',$request->tarikh],['kodlaluan','=',$request->kodlaluan]])
                 ->orderby('tarikh','desc')->limit(1)->first();

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

    public function LaporanTuntutBaki(Request $request){

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

        if($request->sort == 'tuntut'){
                $sortBy = '>';
        }else if($request->sort == 'rugi'){
                $sortBy = '<';
        }else{
                $sortBy = null;
        }
         
        if($request->jenistuntut == 'belumtuntut'){
                $batchleltuntutbaki = Lelong::on($cawangan['mysql'])
                ->selectRaw('lelong.norujukan,lelong.t_lelong as tarikhlelong,lelong.baki')
                ->leftJoin('gadai as gad', 'gad.norujukan', '=', 'lelong.norujukan')
                ->where([['lelong.t_lelong','>=',$request->mula],['lelong.t_lelong','<=',$request->hingga]])
                ->whereNotNull('gad.upah12')
                ->whereNotNull('lelong.hargajual')
                ->whereNull('lelong.trkhtuntut')
                ->when($sortBy, function ($query) use ($sortBy) {
                        return $query->where('baki',$sortBy,'0');
                }, function ($query) {
                        return $query->where('baki','!=','0');
                })
                ->get()->toArray();
        }else if($request->jenistuntut == 'sudahtuntut'){
                $batchleltuntutbaki = Lelong::on($cawangan['mysql'])
                ->selectRaw('lelong.norujukan,lelong.t_lelong as tarikhlelong,lelong.baki')
                ->leftJoin('gadai as gad', 'gad.norujukan', '=', 'lelong.norujukan')
                ->where([['lelong.t_lelong','>=',$request->mula],['lelong.t_lelong','<=',$request->hingga]])
                ->whereNotNull('gad.upah12')
                ->whereNotNull('lelong.hargajual')
                ->whereNotNull('lelong.trkhtuntut')
                ->when($sortBy, function ($query) use ($sortBy) {
                        return $query->where('baki',$sortBy,'0');
                }, function ($query) {
                        return $query->where('baki','!=','0');
                })
                ->get()->toArray();
        }else{
                $batchleltuntutbaki = Lelong::on($cawangan['mysql'])
                ->selectRaw('lelong.norujukan,lelong.t_lelong as tarikhlelong,lelong.baki')
                ->leftJoin('gadai as gad', 'gad.norujukan', '=', 'lelong.norujukan')
                ->where([['lelong.t_lelong','>=',$request->mula],['lelong.t_lelong','<=',$request->hingga]])
                ->whereNotNull('gad.upah12')
                ->whereNotNull('lelong.hargajual')
                ->when($sortBy, function ($query) use ($sortBy) {
                        return $query->where('baki',$sortBy,'0');
                }, function ($query) {
                        return $query->where('baki','!=','0');
                })
                ->get()->toArray();
        }
        
        return response()->json($batchleltuntutbaki);
    }

    public function StoreRingkasanHarian(Request $request){        
        $ringkasan = new RingkasanHarianServices;
        
        if($request->jenisgenerate == 'daily'){
                $date = $request->tarikh;
                $res = $ringkasan->StoreRingkasanHarian($date,$date,$request->zone);
        }else if($request->jenisgenerate == 'monthly'){
                $res = $ringkasan->StoreRingkasanHarian($request->mula,$request->hingga,$request->zone);
        }else{
                return response('error',400);
        }
        return response($res);
    }

    public function getRingkasanHarian(Request $request){        
        $ringkasan = new RingkasanHarianServices;
        $getData = $ringkasan->getRingkasanHarian($request->mula,$request->hingga,$request->kodcaw);

        if($getData != 'error'){
                return response($getData);
        }else{
                return response('error');
        }
    }
    public function ListPenghutang(Request $request){
        if($request->kodcaw == '010219'){
                $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
                $hutang = Penghutang::on($cawangan['mysql'])->where('tarikh','<=',$request->tarikh)->sum('hutang');
                $bakihutang = Penghutang::on($cawangan['mysql'])->where('tarikh','<=',$request->tarikh)->sum('baki_hutang');
                $array_hutang = ['hutang' => $hutang, 'bakihutang' => $bakihutang];

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

    public function SenaraiBayaranHutang(Request $request){
        if($request->kodcaw == '010219'){
                $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
                $bayaran = BayaranHutang::on($cawangan['mysql'])->where('tarikh','<=',$request->tarikh)->sum('bayaran');
                $bayaran = (float)$bayaran;
                return response()->json($bayaran);
        }
    }

    public function ListCawangan(Request $request){
        $cawangan = Cawangan::on('mysql7')->get();

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

    public function ListCawangan_Update(Request $request){
        $cawangan = Cawangan::on('mysql7')
        ->where('mid',$request->mid)
        ->update(['version' => $request->version]);

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

    public function getAccountList(Request $request){

        $cawangan = Cawangan::on('mysql7')->simplePaginate(5);
        $check = app(AccountService::class);
        $array_all = ['current_page' => $cawangan->currentPage(), 'job_ids' => []];
        foreach($cawangan as $caw){
                try{
                $jobId = Str::uuid();
                $res = dispatch(new AccountCheckJob($caw['kodcaw'], $request->month,$jobId));
                // $array_all['data'][$caw['details_caw']] = $res;
                $array_all['data'][$caw['details_caw']] = [
                        'jobId' => $jobId,
                        'status' => 'queued', 
                ];
                $array_all['job_ids'][] = $jobId;
                }catch(\Exception $e){
                        Log::error("Error processing: " . $caw['kodcaw']);
                        Log::error($e->getMessage());

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

    public function getJobStatus(Request $request)
    {
        $jobId = $request->input('jobId');

        // Get the job status and result from cache (or database)
        $status = Cache::get("job_status_{$jobId}", 'not_found');
        $result = Cache::get("job_result_{$jobId}", []);

        // Return both the status and the result
        return response()->json([
                'status' => $status,
                'result' => $status === 'completed' ? $result : null,
        ]);
    }

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

        //listing sag belum tuntut cwgn
        $sag_cwgn = collect(
        Lelong::on($cawangan['mysql'])
        ->selectRaw('norujukan')
        ->whereYear('t_jual', $request->tahun)
        ->whereNull('trkhtuntut')
        ->where('baki', '>', 0)
        ->pluck('norujukan')  // lebih bersih
        );
        
        //listing sag blocked
        $sag_online = collect(
        WTDDraft::on('mysql7')
        ->selectRaw('norujukan')
        ->where('kodcaw', '=', $request->kodcaw)
        ->pluck('norujukan')
        );
        //dd($sag_online);
        //filter sag yg tk wujud dlm wtd_draft
        $filtersag = $sag_cwgn->diff($sag_online);

        //query baru
        $tarikh_belum_tuntut = Lelong::on($cawangan['mysql'])
                ->selectRaw('
                MONTH(t_jual) as bulan, 
                SUM(pinjaman) as pembiayaan, 
                ABS(SUM(baki)) as baki, 
                COUNT(DISTINCT norujukan) as jumlah_norujukan, 
                kodcaw
                ')
                ->whereIn('norujukan', $filtersag)
                ->groupBy('bulan', 'kodcaw') 
                ->orderBy('bulan')
                ->get();

        $tarikh_belum_tuntut = $tarikh_belum_tuntut->map(function ($item) {
                $item->bulan = \Carbon\Carbon::create()->month($item->bulan)->format('F');
                return $item;
        });

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

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

        $rekod_simulasi = Lelong::on($cawangan['mysql'])
        ->join('gadai','lelong.norujukan','=','gadai.norujukan')
        ->selectRaw('ABS(lelong.baki) as baki, lelong.t_lelong, lelong.pinjaman, lelong.norujukan, gadai.nokp')
        ->whereMonth('lelong.t_jual', $request->month)
        ->whereYear('lelong.t_jual', $request->year)
        ->whereNull('lelong.trkhtuntut')
        ->where('lelong.baki', '>', 0)
        ->get();

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

        public function prosesSimulasiWTD(Request $request)
        {
        $proses = $request->input;

        // dd($proses, $cawangan);

        $baki = 0;
        $jumlahPembiayaan = 0;
        $simulasi = WTDSimulasi::max('simulasi')+1;

        foreach ($proses as $item) {
                WTDSimulasi::create([
                        'bulan' => $item['bulan'],
                        'tahun' => $item['tahun'],
                        'kodcaw' => $item['kodcaw'],
                        'jumlah_sag' => $item['jumlah_sag'],
                        'pembiayaan'=> $item['pembiayaan'],
                        'baki'=> $item['baki'],
                        'simulasi' => $simulasi,
                ]);     
                $baki += $item['baki'];
                $jumlahPembiayaan = $item['pembiayaan'];
        }      

        return response()->json(['status' => 'success','simulasi' => $simulasi,'baki' => $baki,'pinjaman' => $jumlahPembiayaan]);
        }

        public function pengesahanSimulasiWTD(Request $request)
        {
        // Decode the JSON records from the request
        $records = json_decode($request->records, true);

        // Retrieve and clean 'kodcaw' from the request
        $kodcaw = $request->kodcaw;
        $kodcaw_clean = str_replace('"', '', $kodcaw);

        // Get the database connection for the branch (cawangan)
        $cawangan = Cawangan::where('kodcaw', $kodcaw_clean)->first();

        // Check if 'Cawangan' exists
        if (!$cawangan) {
                return response()->json(['status' => 'error', 'message' => 'Invalid branch code (kodcaw).'], 404);
        }

        $cawangan_connection = $cawangan->mysql;

        // Get the latest batch number and increment it
        $latestBatch = SerahBaki::on($cawangan_connection)->max('batchno') + 1;

        // Initialize total variables
        $totalPembiayaan = 0;
        $totalBaki = 0;


        try {
                // Iterate through the records and save them to the WTDDraft table
                foreach ($records as $record) {
                // Check if 'bulan' and 'tahun' exist in the record
                if (!isset($record['bulan']) || !isset($record['tahun'])) {
                        return response()->json(['status' => 'error', 'message' => 'Missing bulan or tahun in records.'], 400);
                }
                $month = DateTime::createFromFormat('F', $record["bulan"])->format('n');


                // Query norujukan records from the database
                $query_norujukan = Lelong::on($cawangan_connection)
                        ->join('gadai', 'lelong.norujukan', '=', 'gadai.norujukan')
                        ->selectRaw('ABS(lelong.baki) as baki, lelong.t_lelong, lelong.pinjaman, lelong.norujukan, gadai.nokp, lelong.t_jual')
                        ->whereMonth('lelong.t_jual', $month)
                        ->whereYear('lelong.t_jual', $record["tahun"])
                        ->whereNull('lelong.trkhtuntut')
                        ->where('lelong.baki', '>', 0)
                        ->get();

                // Save each record to the WTDDraft table
                foreach ($query_norujukan as $query) {
                        $wtddraft = new WTDDraft();
                        $wtddraft->nokp = $query['nokp'];
                        $wtddraft->kodcaw = $kodcaw_clean;
                        $wtddraft->norujukan = $query['norujukan'];
                        $wtddraft->t_jual = $query['t_jual'];
                        $wtddraft->t_gadai = $query['t_gadai'] ?? null; // Optional: ensure 't_gadai' exists
                        $wtddraft->t_lelong = $query['t_lelong'];
                        $wtddraft->batchno_serah = $latestBatch;
                        $wtddraft->save();
                }

                // Accumulate totals
                $totalPembiayaan += $record['pembiayaan'] ?? 0;
                $totalBaki += $record['baki'] ?? 0;
                }

                // Create a new record in the SerahBaki table
                SerahBaki::on($cawangan_connection)->create([
                'norujukan' => 'baru',
                'batchno' => $latestBatch,
                'hargajual' => 0.00,
                'pinjaman' => $totalPembiayaan,
                'upah' => 0.00,
                'cajlel' => 0.00,
                'gst_cl' => 0.00,
                'gst_hj' => 0.00,
                'baki' => $totalBaki,
                'tarikh' => Carbon::now()->toDateString(),
                't_jual' => Carbon::now()->toDateString(),
                'nopelanggan' => '',
                'aktif' => 0,
                ]);

                // Return a success response with the new batch number
                return response()->json(['status' => 'success', 'batchno' => $latestBatch], 200);

        } catch (\Throwable $e) {
                // Log the error and return a failure response
                Log::error($e->getMessage());
                Log::error($e->getLine());
                return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
        }



        public function simulasiToDraft(Request $request)
        {
                $bulan = $request->bulan;

                if (!$bulan || count($bulan) === 0) {
                        return response()->json(['error' => 'Sila pilih sekurang-kurangnya satu bulan.'], 400);
                    }

                $simulasi = WTDSimulasi::whereIn('bulan', $bulan)->get();

                if ($simulasi->isEmpty()) {
                        return response()->json(['error' => 'Tiada data untuk bulan yang dipilih.'], 404);
                    }

                //     foreach ($simulasi as $data) {
                //         WTDDraft::create([
                //             'nokp' => $data->nokp ?? null,
                //             'kodcaw' => $data->kodcaw ?? null,
                //             'norujukan' => $data->norujukan ?? null,
                //             't_jual' => $data->t_jual ?? null,
                //             't_gadai' => $data->t_gadai ?? null,
                //             't_lelong' => $data->t_lelong ?? null,
                //             'batchno_serah' => $data->simulasi, // Simpan sebagai rujukan
                //         ]);
                //     }
                    
                    //dd($bulan, $simulasi);

                    return response()->json(['message' => 'Data berjaya dipindahkan ke WTD Draft!']);

        }
}
