<?php

namespace App\Http\Controllers;

use App\Gadai;
use App\Marhun;
use App\Cawangan;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\TransactionOnline;
use App\batalGadai;
use App\TuntutBaki;
use App\AnsRugi;
use App\Lelong;
use App\WTD;
use App\HapusKira;
use App\Tebus;
use App\Vault;
use App\Tunai;
use App\Komuditi;
use App\KawalanStokLama;
use App\KawalanStok;
use App\KadarUpah;
use App\Moratorium;
use App\Audit;
use App\Customer;
use App\KomuditiPurchase;
use App\KomuditiTransaksi;
use App\Advansur;
use App\BlastWasap;
use App\Notis;
use App\CawanganNotis;
use App\NotisPeringatan;
use App\Jobs\WhatsappPelangganSAGLAMA;
use App\Jobs\SMSPelangganSAGLAMA;
use Illuminate\Http\Request;
use App\CawanganDetail;
use App\BlastSMS;
use App\Jobs\ARCCWhatsappPelangganSAGLAMAbysag;
use App\Jobs\ARCCSMSPelangganSAGLAMAbysag;
use App\Services\MasterServices;
use App\Daerah;
use App\Poskod;
use App\Negeri;
use App\NotisJbg;
use App\NotJbg;
use App\CawanganNotisJbg;
use Log;

use App\Services\OnePercentServices;

use Illuminate\Support\Facades\DB;

use Carbon\Carbon;

class CallCenterController extends Controller
{
    public function showAllCawangans(Request $request)
    {
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $checkcawangannotis = Cawangan::on('mysql7')
        // ->whereNotExists(function($query) use($daritempoh,$hinggatempoh)
        // {
        //     $query->select(DB::raw(1))
        //     ->from('cawangan_notis')
        //          ->whereRaw('cawangan_notis.kodcaw = arrahn_master_db.kodcaw')
        //           ->where('daritempoh','=',$daritempoh)
        //           ->where('hinggatempoh','=',$hinggatempoh);
        // } )
        ->orderBy('details_caw','ASC')->get();
        // dd($checkcawangannotis);
        return response()->json($checkcawangannotis);
    }
    public function datagadai($kodcaw,Request $request)
    {
        // dd($request->all(), $kodcaw);
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $datagadai = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['tempoh','>=',$daritempoh],['tempoh','<=',$hinggatempoh],['sttebus','=',''],['taglel','=',0],['tagnotis','=',0]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC');
            // ->get();
        // dd($datagadai);
        $arraynorujukan = $datagadai->pluck('norujukan')->toArray();
        $rekodgadai = $datagadai->get();
       
        $totalrekod = $datagadai->count('norujukan');
        $totalberat = $datagadai->sum('berat');
        $totalnilaimarhun = $datagadai->sum('nilaimarhun');
        $totalpinjaman = $datagadai->sum('pinjaman');
        $totalbakipjm = $datagadai->sum('bakipjm');
        $totaltunggakan = $datagadai->sum('tunggakan');

        $arrayrekod = ['rekod' => $rekodgadai, 'totalsag' => $totalrekod,'totalberat' => $totalberat,'totalnilaimarhun' =>  $totalnilaimarhun,'totalpembiayaan'=>$totalpinjaman,'totalbakipjm'=>$totalbakipjm,'totaltunggakan'=>$totaltunggakan];
        // dd($arrayrekod);
        return response()->json($arrayrekod,200);
    }
    
    public function insertdatagadai($kodcaw,Request $request)
    {
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;
        $notisid = $request->notisid;
        $currentDate = Carbon::now();
        // $currentDate = $currentDate->toDateString();
        $tarikh_notis = $currentDate->toDateString();
        $sag_cawangans = [];
        $bil_surat = 0;
        // dd($kodcaw);
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

        // $notis = Notis::create([
        //     'tarikh_notis' => $tarikh_notis,
        //     'daritempoh' => $daritempoh,
        //     'hinggatempoh' => $hinggatempoh,
        //     'sts_notis' => 1,
        //     'peringatan' => 1
        // ]);

        $datagadai = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['tempoh','>=',$daritempoh],['tempoh','<=',$hinggatempoh],['sttebus','=',''],['taglel','=',0],['tagnotis','=',0]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC');
            // ->get();

           
            array_push($sag_cawangans,['data'=>$datagadai->get()]);
            // dd($sag_cawangans);

            foreach($sag_cawangans as $index=>$cawnotis){

                $caw_notis = new CawanganNotis;
                $caw_notis->notis_id = $notisid;
                $caw_notis->kodcaw = $kodcaw;
                $caw_notis->peringatan = 1;
                $caw_notis->daritempoh = $daritempoh;
                $caw_notis->hinggatempoh = $hinggatempoh;
                $caw_notis->status = 1;
                $caw_notis->save();
                

                $suratcaw = $cawnotis['data'];

                $notis_peringatan_arr = [];
                $now = Carbon::now();
                foreach($suratcaw as $surat)
                {
                    $notis_to_be_inserted = new NotisPeringatan();
                    $notis_to_be_inserted->notis_id = $notisid;
                    $notis_to_be_inserted->tarikh_notis = $tarikh_notis;
                    $notis_to_be_inserted->kodcaw = $kodcaw;
                    $notis_to_be_inserted->norujukan = $surat->norujukan;
                    $notis_to_be_inserted->nokp = $surat->nokp;
                    $notis_to_be_inserted->jbg = $surat->tempoh;
                    $notis_to_be_inserted->kadarupah = $surat->kadarupah;
                    $notis_to_be_inserted->nilaimarhun = $surat->nilaimarhun;
                    $notis_to_be_inserted->pinjaman = $surat->bakipjm;
                    $notis_to_be_inserted->bakiupah = $surat->bakiupah;
                    $notis_to_be_inserted->berat = $surat->berat;
                    $notis_to_be_inserted->marhun = $surat->marhun;
                    $notis_to_be_inserted->percent = $surat->percentpinj;
                    $notis_to_be_inserted->peringatan = '1';
                    $notis_peringatan_arr[] = $notis_to_be_inserted->attributesToArray();

                    //updatetagnotisdlmgadai
                    $updateTagNotis = Gadai::on($cawangan['mysql'])->where('norujukan',$surat->norujukan)->update([
                        'tagnotis'=> 1
                    ]);
                }

                $notis_peringatan_collection = collect($notis_peringatan_arr);

                NotisPeringatan::insert($notis_peringatan_arr);
        }
        return response()->json("success");
    }

    public function getbatchnotis(Request $request)
    {

        $currentDate = Carbon::now();
        $tarikh_notis = $currentDate->toDateString();
        $daritempoh = $request->daritempoh;
        $hinggatempoh = $request->hinggatempoh;

        $notis = Notis::create([
            'tarikh_notis' => $tarikh_notis,
            'daritempoh' => $daritempoh,
            'hinggatempoh' => $hinggatempoh,
            'sts_notis' => 1,
            'peringatan' => 1
        ]);

        $batchnotis = Notis::on('mysql7')->orderBy('id','desc')->first()->id;

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

    }

    public function senarainotisperingatan()
    {
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        // $batchnotis = Notis::on('mysql7')->get();
        // return response()->json($batchnotis);
        $batchnotis = Notis::on('mysql7')
        ->get();
        $cawnotis_all = [];
        foreach ($batchnotis as $index => $cawangan){
            $idnotis = $cawangan['id'];
            $tarikh_notis = $cawangan['tarikh_notis'];
            $daritempoh = $cawangan['daritempoh'];
            $notis = CawanganNotis::on('mysql7')
            ->join('notisperingatan', 'notisperingatan.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notisperingatan.notis_id',$cawangan['id'])
            ->where('notisperingatan.peringatan','1')
            ->distinct()
            ->get();
            $totalsag = $notis->count('norujukan'); 
            if(sizeof($notis) != 0){
                array_push($cawnotis_all,['id' => $idnotis, 'tarikh_notis' => $tarikh_notis, 'daritempoh' => $daritempoh,'totalsag' => $totalsag, 'detail' => $notis]);
            }
        }
        return response()->json($cawnotis_all);
    }

    public function getcawnotis($notisid)
    {
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        $batchnotis = Notis::on('mysql7')->where('id',$notisid)->get();
        $cawangan_all = Cawangan::on('mysql7')->get();
        $cawnotis_all = [];
        foreach ($batchnotis as $index => $cawangan){
            $notis = CawanganNotis::on('mysql7')
            ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notis_id',$notisid)
            ->get();
            foreach ($notis as $index1 => $bil){
                $notisperingatanall = NotisPeringatan::on('mysql7')
                ->where('notis_id',$notisid)
                ->where('kodcaw',$bil['kodcaw'])
                ->get();

                $notisperingatan = NotisPeringatan::on('mysql7')
                ->where('notis_id',$notisid)
                ->where('kodcaw',$bil['kodcaw'])
                ->where('peringatan',1)
                ->get();

                $notisperingatankedua = NotisPeringatan::on('mysql7')
                ->where('notis_id',$notisid)
                ->where('kodcaw',$bil['kodcaw'])
                ->where('peringatan',2)
                ->get();
                // dd($notisperingatan);

                $totalsag = $notisperingatanall->count('norujukan'); 
                $bakitotalsag = $notisperingatan->count('norujukan'); 
                $bakitotalsagkedua = $notisperingatankedua->count('norujukan'); 
                $notis[$index1]['totalsag'] = $totalsag;
                $notis[$index1]['bakitotalsag'] = $bakitotalsag;
                $notis[$index1]['bakitotalsagkedua'] = $bakitotalsagkedua;
                // dd($bil['kodcaw'],$totalsag);
            }

            if(sizeof($notis) != 0){
                array_push($cawnotis_all,$notis);
            }
        }
        return response()->json($cawnotis_all);
    }

    public function getcawnotisbycaw(Request $request)
    {
        $notisid = $request->notisid;
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        $batchnotis = Notis::on('mysql7')->where('id',$notisid)->get();
        $cawangan_all = Cawangan::on('mysql7')->get();
        $cawnotis_all = [];

        $notis = CawanganNotis::on('mysql7')
            ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notis_id',$notisid)->get();

        foreach ($notis as $index => $cawangan){
            // dd($cawangan['kodcaw']);
                // dd($cawangan);
                $notisbycaw = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$cawangan['kodcaw'])
                ->where('notisperingatan.peringatan','=', 1)
                ->distinct()
                ->get();

                $notisbycawall = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$cawangan['kodcaw'])
                // ->where('notisperingatan.peringatan','=', 1)
                ->distinct()
                ->get();
                // dd($notisbycaw);

                $totalsag = $notisbycaw->count('norujukan');
                $totalsagall = $notisbycawall->count('norujukan');
                $totalbakipjm = $notisbycaw->sum('pinjaman');

            // if(sizeof($notis) != 0){
                array_push($cawnotis_all,['namacaw' => $notis, 'detailbycaw' => $notisbycaw,'totalsag' =>$totalsag,'totalsagall' =>$totalsagall,'totalbakipjm' =>$totalbakipjm]);
            // }
        }
        return response()->json($cawnotis_all);
    }

    public function bycawnotisperingatan($kodcaw,$notisid)
    {
        $cawnotis_all = [];
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $notisbycaw = NotisPeringatan::on('mysql7')
        ->where('notisperingatan.notis_id',$notisid)
        ->where('notisperingatan.kodcaw',$kodcaw)
        ->where('notisperingatan.peringatan', '=', 1)
        ->distinct()
        ->get();

        $notisbycawarray = $notisbycaw->toArray();

        foreach($notisbycawarray as $index=>$cal){
            $customer =  Customer::where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();

            $datagadai =  Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$cal['norujukan'])
            ->first();
            // dd( $datagadai);

            if($datagadai->tagbaru == '0'){
                $keuntungan = 'asal';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraUpahTawarruq($kodcaw,$cal['norujukan'],$jeniskeuntungan);
            }elseif($datagadai->tagbaru == '1'){
                $keuntungan = 'onepercent';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraupahUjrahOnePercent($kodcaw,$cal['norujukan']);
            }
            
            $notisbycawarray[$index]['namacust'] = $customer;
            $notisbycawarray[$index]['datagadai'] = $datagadai;
            $notisbycawarray[$index]['keuntungan'] = $response;
        }

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

    public function blastwasapbysag(Request $request)
    {
        // dd($request->all());
        $current = Carbon::now();
        $current = new Carbon();
        $kodcaw = $request->kodcaw;
        $notisid = $request->notisid;

        $namapengguna = $request->namapengguna;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $cawangan_detail = CawanganDetail::on($cawangan['mysql'])->first();
        $caw_name = $cawangan->details_caw;
        $nofoncaw = $cawangan_detail->notel;

        $statusblast =  CawanganNotis::where('notis_id','=',$notisid)
        ->where('kodcaw','=',$kodcaw)
        ->first();
        if($statusblast->status == '1'){

                $notisbycaw = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)->where('notisperingatan.kodcaw',$kodcaw)
                ->distinct()
                ->get();

                $arraynorujukan = $notisbycaw->pluck('norujukan')->toArray();
                
                $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
                ->get();
                $gadai_all_groupby_nokp = $notisbycaw->groupBy('nokp');

                foreach($gadainokp as $index1=>$cal){
                    if($gadai_all_groupby_nokp[$cal->nokp]){
                        $gadainokp[$index1]['gadai'] = $gadai_all_groupby_nokp[$cal->nokp];
                    }
                    $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
                    ->orWhere('kplama','=',$cal['nokp'])
                    ->first();
                    $nokp=$cal['nokp'];
                    // dd($customer);
                            if($customer->telefon != 'null'){
                                $telefon=$customer->telefon;
                                    //log auditrail
                                    $audit = new Audit();
                                    $audit->users = $namapengguna;
                                    $audit->actions = 'ARCC Blast Whatsapp & SMS: Notis ID'.$notisid;
                                    $audit->norujukan = $cal->norujukan;
                                    $audit->new_data = $customer->telefon;
                                    $audit->old_data = $nokp;
                                    $audit->kodcaw = $kodcaw;
                                    $audit->created_at = $current;
                                    $audit->updated_at = $current;
                                    $audit->save();

                                    $today = $current->toDateString();  
                                    $harini = date('Y-m-d',strtotime($today)); 

                                    //update tarikh dlm table notisperingatan
                                        $updatenotis=NotisPeringatan::on('mysql7')
                                        ->where('norujukan','=', $cal->norujukan)
                                        ->update(
                                            array('tarikhnotis1'=> $harini));

                                dispatch(new ARCCWhatsappPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq,$namapengguna));
                                dispatch(new ARCCSMSPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq,$namapengguna));
                            }
                }

                $updatestatusnotis=CawanganNotis::on('mysql7')
                ->where('notis_id','=', $notisid)
                ->where('kodcaw','=', $kodcaw)
                ->update(
                array('status'=> 2));

                return response()->json('success');
            }
            else{
                return response()->json('failed');
            }

    }

    public function cariannotispertama($kodcaw,Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $today = $current->toDateString();
        $time = strtotime($today);
        $monthscoming = date("Y-m-d", strtotime("+1 month", $time));

       
        $fasa = $request->fasa;
        // dd($fasa);
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        if($fasa == 1){
           
            $datagadai = Gadai::on($cawangan['mysql'])
                ->where([['t_matang','<=',$monthscoming],['lelong_tawarruq','=',1],['tempoh','>=',5],['tempoh','<=',7],['tagpalsu','=',0],['sttebus','=',''],['taglel','=',0],['tagnotis','=',0]])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC');
                // ->get();      
                // dd($datagadai);    

            }elseif($fasa == 2){
                $datagadai = Gadai::on($cawangan['mysql'])
                ->where([['t_matang1','<=',$monthscoming],['lelong_tawarruq','=',0],['tempoh','>=',11],['tagpalsu','=',0],['sttebus','=',''],['taglel','=',0],['tagnotis','=',0]])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC');
                // ->get(); 
            }
            
            $arraynorujukan = $datagadai->pluck('norujukan')->toArray();
            $rekodgadai = $datagadai->get();
            // dd($rekodgadai);
       
        $totalrekod = $datagadai->count('norujukan');
        $totalberat = $datagadai->sum('berat');
        $totalnilaimarhun = $datagadai->sum('nilaimarhun');
        $totalpinjaman = $datagadai->sum('pinjaman');
        $totalbakipjm = $datagadai->sum('bakipjm');
        $totaltunggakan = $datagadai->sum('tunggakan');

        $arrayrekod = ['rekod' => $rekodgadai, 'totalsag' => $totalrekod,'totalberat' => $totalberat,'totalnilaimarhun' =>  $totalnilaimarhun,'totalpembiayaan'=>$totalpinjaman,'totalbakipjm'=>$totalbakipjm,'totaltunggakan'=>$totaltunggakan];
        // dd($arrayrekod);
        return response()->json($arrayrekod,200);
    }

    public function insertnotispertama($kodcaw,Request $request)
    {
        $fasa = $request->fasa;
        $notisid = $request->notisid;
        $current = Carbon::now();
        $current = new Carbon();
        $today = $current->toDateString();
        $tarikh_notis = $current->toDateString();
        $time = strtotime($today);
        $monthscoming = date("Y-m-d", strtotime("+1 month", $time));

        $sag_cawangans = [];
        $bil_surat = 0;
        // dd($kodcaw);
        if($kodcaw){
            $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
            if($fasa == 1){
                $datagadai = Gadai::on($cawangan['mysql'])
                ->where([['t_matang','<=',$monthscoming],['lelong_tawarruq','=',1],['tempoh','>=',5],['tempoh','<=',7],['tagpalsu','=',0],['sttebus','=',''],['taglel','=',0],['tagnotis','=',0]])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC');
            }elseif($fasa == 2){
                $datagadai = Gadai::on($cawangan['mysql'])
                ->where([['t_matang1','<=',$monthscoming],['lelong_tawarruq','=',0],['tempoh','>=',11],['tagpalsu','=',0],['sttebus','=',''],['taglel','=',0]])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC');
            }
            array_push($sag_cawangans,['data'=>$datagadai->get()]);
                // dd($sag_cawangans);

                foreach($sag_cawangans as $index=>$cawnotis){

                    if($fasa == 1){
                        $caw_notis = new CawanganNotis;
                        $caw_notis->notis_id = $notisid;
                        $caw_notis->kodcaw = $kodcaw;
                        $caw_notis->peringatan = 1;
                        $caw_notis->daritempoh = 5;
                        $caw_notis->hinggatempoh = 7;
                        $caw_notis->status = 1;
                        $caw_notis->save();

                    }elseif($fasa == 2){
                        $caw_notis = new CawanganNotis;
                        $caw_notis->notis_id = $notisid;
                        $caw_notis->kodcaw = $kodcaw;
                        $caw_notis->peringatan = 1;
                        $caw_notis->daritempoh = 11;
                        $caw_notis->hinggatempoh = 12;
                        $caw_notis->status = 1;
                        $caw_notis->save();

                    }
                    
                    

                    $suratcaw = $cawnotis['data'];

                    $notis_peringatan_arr = [];
                    $now = Carbon::now();
                    foreach($suratcaw as $surat)
                    {
                        $notis_to_be_inserted = new NotisPeringatan();
                        $notis_to_be_inserted->notis_id = $notisid;
                        $notis_to_be_inserted->tarikh_notis = $tarikh_notis;
                        $notis_to_be_inserted->kodcaw = $kodcaw;
                        $notis_to_be_inserted->norujukan = $surat->norujukan;
                        $notis_to_be_inserted->nokp = $surat->nokp;
                        $notis_to_be_inserted->jbg = $surat->tempoh;
                        $notis_to_be_inserted->kadarupah = $surat->kadarupah;
                        $notis_to_be_inserted->nilaimarhun = $surat->nilaimarhun;
                        $notis_to_be_inserted->pinjaman = $surat->bakipjm;
                        $notis_to_be_inserted->bakiupah = $surat->bakiupah;
                        $notis_to_be_inserted->berat = $surat->berat;
                        $notis_to_be_inserted->marhun = $surat->marhun;
                        $notis_to_be_inserted->percent = $surat->percentpinj;
                        $notis_to_be_inserted->peringatan = '1';
                        $notis_to_be_inserted->tmatang = $surat->t_matang;
                        $notis_to_be_inserted->tmatang1 = $surat->t_matang1;
                        $notis_to_be_inserted->fasa = $fasa;
                        $notis_peringatan_arr[] = $notis_to_be_inserted->attributesToArray();

                        //updatetagnotisdlmgadai
                        $updateTagNotis = Gadai::on($cawangan['mysql'])->where('norujukan',$surat->norujukan)->update([
                            'tagnotis'=> 1
                        ]);
                    }

                    $notis_peringatan_collection = collect($notis_peringatan_arr);

                    NotisPeringatan::insert($notis_peringatan_arr);
            }
        }
        return response()->json("success");
    }

    public function getbatchnotispertama(Request $request)
    {

        $currentDate = Carbon::now();
        $tarikh_notis = $currentDate->toDateString();
        $fasa = $request->fasa;
        // $hinggatempoh = $request->hinggatempoh;
        if($fasa == 1){
            $notis = Notis::create([
                'tarikh_notis' => $tarikh_notis,
                'daritempoh' => 5,
                'hinggatempoh' => 7,
                'sts_notis' => 1,
                'peringatan' => 1
            ]);
        }elseif($fasa == 2){
            $notis = Notis::create([
                'tarikh_notis' => $tarikh_notis,
                'daritempoh' => 11,
                'hinggatempoh' => 12,
                'sts_notis' => 1,
                'peringatan' => 1
            ]);
        }

        $batchnotis = Notis::on('mysql7')->orderBy('id','desc')->first()->id;

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

    }
    

    public function kemaskininotisperingatan(Request $request)
    {
        // dd($request->all());
        $notisid = $request->notisid;
        $current = Carbon::now();
        $current = new Carbon();
       
        $kodcaw = $request->kodcaw;
        $notisid = $request->notisid;

        $cawnotis_all = [];

        $notis = CawanganNotis::on('mysql7')
            ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notis_id',$notisid)
            ->where('cawangan_notis.kodcaw','=', $kodcaw)
            ->get();
        
        foreach ($notis as $index => $cawangan){
                $notisbycaw = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$cawangan['kodcaw'])
                ->distinct()
                ->get();
                foreach($notisbycaw as $index=> $notis){
                    // dd($notis['tarikhnotis1']);
                    $checkgadai = Gadai::on($cawangan['mysql'])
                    ->where([['norujukan','=',$notis['norujukan']]])
                    ->first();

                    if($checkgadai->sttebus == 'T' || $checkgadai->sttebus == 'L'){
                        $updatelistnotis=NotisPeringatan::on('mysql7')
                        ->where('norujukan','=', $notis['norujukan'])
                        ->where('notis_id','=', $notisid)
                        ->where('kodcaw','=', $kodcaw)
                        ->delete();
                         //save log audit
                         $audit = new Audit();
                         $audit->users = $request->kodlaluan;
                         $audit->actions = 'Keluar Tebus';
                         $audit->norujukan = $notis['norujukan'];
                         $audit->kodcaw = $kodcaw;
                         $audit->created_at = $current;
                         $audit->updated_at = $current;
                         $audit->save();

                    }elseif($checkgadai->sttebus == ''){
                        $telahbayar = $checkgadai->hargajualan - $checkgadai->bakihargajualan;
                        $upah6bln_raw = $checkgadai->bakiupah - 0.5;
                        
                        if($checkgadai->lelong_tawarruq == '1'){ //fasa1
                            if(bcdiv($telahbayar,1,1) >= bcdiv($upah6bln_raw,1,1)){
                                    //deletelist
                                    $updatelistnotis=NotisPeringatan::on('mysql7')
                                    ->where('norujukan','=', $notis['norujukan'])
                                    ->where('notis_id','=', $notisid)
                                    ->where('kodcaw','=', $kodcaw)
                                    ->delete();
                                    //update tagnotis
                                    $updatedata = Gadai::on($cawangan['mysql'])
                                    ->where('norujukan',$notis['norujukan'])
                                    ->update([
                                        'tagnotis'=> '0'
                                    ]);
                                    //save log audit
                                    $audit = new Audit();
                                    $audit->users = $request->kodlaluan;
                                    $audit->actions = 'Keluar Notis';
                                    $audit->norujukan = $notis['norujukan'];
                                    $audit->kodcaw = $kodcaw;
                                    $audit->created_at = $current;
                                    $audit->updated_at = $current;
                                    $audit->save();
                            }else{
                                if($checkgadai->tagbaru == '0'){
                                    // dd($notis['norujukan']);
                                    $keuntungan = 'asal';
                                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                                    $master = new MasterServices($kodcaw);
                                    $response = $master->kiraUpahTawarruq($kodcaw,$notis['norujukan'],$jeniskeuntungan);
                                }elseif($checkgadai->tagbaru == '1'){
                                    $keuntungan = 'onepercent';
                                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                                    $master = new MasterServices($kodcaw);
                                    $response = $master->kiraupahUjrahOnePercent($kodcaw,$notis['norujukan']);
                                }
                            
                                $updatedata = NotisPeringatan::on('mysql7')
                                ->where('norujukan',$notis['norujukan'])
                                ->where('notis_id','=', $notisid)
                                ->where('kodcaw','=', $kodcaw)
                                ->update([
                                    'jbg'=> $checkgadai->tempoh,
                                    'pinjaman'=> $checkgadai->bakipjm,
                                    'bakiupah'=> $response
                                ]);
                            }                            
                        }elseif($checkgadai->lelong_tawarruq == '0'){ //fasa2             
                                if($checkgadai->tagbaru == '0'){
                                    // dd($notis['norujukan']);
                                    $keuntungan = 'asal';
                                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                                    $master = new MasterServices($kodcaw);
                                    $response = $master->kiraUpahTawarruq($kodcaw,$notis['norujukan'],$jeniskeuntungan);
                                }elseif($checkgadai->tagbaru == '1'){
                                    $keuntungan = 'onepercent';
                                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                                    $master = new MasterServices($kodcaw);
                                    $response = $master->kiraupahUjrahOnePercent($kodcaw,$notis['norujukan']);
                                }
                            
                                $updatedata = NotisPeringatan::on('mysql7')
                                ->where('norujukan',$notis['norujukan'])
                                ->where('notis_id','=', $notisid)
                                ->where('kodcaw','=', $kodcaw)
                                ->update([
                                    'jbg'=> $checkgadai->tempoh,
                                    'pinjaman'=> $checkgadai->bakipjm,
                                    'bakiupah'=> $response
                                ]);
                            }
                    }
                }
            }
            return response()->json("success");
    }

    public function cariannotiskedua(Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $today = $current->toDateString();
        $fasa = $request->fasa;
        // dd($fasa);
        if($fasa == 1){
            // dd(true);
            $listnotis = NotisPeringatan::on('mysql7')
                    ->where('peringatan', 1)
                    ->where('tarikhnotis1','<>', NULL)
                    ->get();
            foreach($listnotis as $index=> $notis){
                $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$notis['kodcaw'])->first();
                $detail = Gadai::on($cawangan['mysql'])
                ->where([['norujukan','=',$notis['norujukan']]])
                ->first();
                $tarikhmatang = Carbon::parse($detail['t_matang']);
                
                if($detail['lelong_tawarruq'] == 1){
                    $t_perlunotis = ($tarikhmatang->subDays(14))->format('Y-m-d');
                    if($t_perlunotis <= $today){
                        $updatedata = NotisPeringatan::on('mysql7')
                            ->where('norujukan',$notis['norujukan'])
                            ->where('notis_id','=', $notis['notis_id'])
                            ->where('kodcaw','=', $notis['kodcaw'])
                            ->update([
                                'peringatan'=> 2
                            ]);}
                }
            }
        }elseif($fasa == 2){ //sag tamat kontrak
            $listnotis = NotisPeringatan::on('mysql7')
            ->where('peringatan', 1)
            ->where('tarikhnotis1','<>', NULL)
            ->get();
            // dd($listnotis);
            foreach($listnotis as $index=> $notis){
                // dd($notis['tmatang1']);
                $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$notis['kodcaw'])->first();
                $detail = Gadai::on($cawangan['mysql'])
                ->where([['norujukan','=',$notis['norujukan']]])
                ->first();
                $tarikhmatang1 = Carbon::parse($notis['tmatang1']);
                // dd($notis['tmatang1']);
                if($detail['lelong_tawarruq'] == 0){
                    $t_perlunotis = ($tarikhmatang1->subDays(14))->format('Y-m-d');
                    // dd($t_perlunotis, $today);
                    if($t_perlunotis <= $today){
                        $updatedata = NotisPeringatan::on('mysql7')
                            ->where('norujukan',$notis['norujukan'])
                            ->where('notis_id','=', $notis['notis_id'])
                            ->where('kodcaw','=', $notis['kodcaw'])
                            ->update([
                                'peringatan'=> 2
                            ]);}
                }
            }
        }

        $arrayrekod = ['rekod' => $detail];
        return response()->json($arrayrekod,200);
    }

    public function getcawnotiskeduabycaw(Request $request)
    {
        $notisid = $request->notisid;
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        $batchnotis = Notis::on('mysql7')->where('id',$notisid)->get();
        $cawangan_all = Cawangan::on('mysql7')->get();
        $cawnotis_all = [];

        $notis = CawanganNotis::on('mysql7')
            ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notis_id',$notisid)->get();

        foreach ($notis as $index => $cawangan){
            // dd($cawangan['kodcaw']);
                // dd($cawangan);
                $notisbycaw = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$cawangan['kodcaw'])
                ->where('notisperingatan.peringatan','2')
                ->distinct()
                ->get();
                // dd($notisbycaw);

                $notisbycawall = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$cawangan['kodcaw'])
                // ->where('notisperingatan.peringatan','=', 1)
                ->distinct()
                ->get();

                $totalsag = $notisbycaw->count('norujukan');
                $totalsagall = $notisbycawall->count('norujukan');
                $totalbakipjm = $notisbycaw->sum('pinjaman');

            // if(sizeof($notis) != 0){
                array_push($cawnotis_all,['namacaw' => $notis, 'detailbycaw' => $notisbycaw,'totalsag' =>$totalsag,'totalsagall' =>$totalsagall,'totalbakipjm' =>$totalbakipjm]);
            // }
        }
        return response()->json($cawnotis_all);
    }

    public function bycawnotisperingatankedua($kodcaw,$notisid)
    {
        $cawnotis_all = [];
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $notisbycaw = NotisPeringatan::on('mysql7')
        ->where('notisperingatan.notis_id',$notisid)
        ->where('notisperingatan.kodcaw',$kodcaw)
        ->where('notisperingatan.peringatan',2)
        ->distinct()
        ->get();

        $notisbycawarray = $notisbycaw->toArray();

        foreach($notisbycawarray as $index=>$cal){
            $customer =  Customer::where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();

            $datagadai =  Gadai::on($cawangan['mysql'])
            ->where('norujukan','=',$cal['norujukan'])
            ->first();
            // dd( $datagadai);

            if($datagadai->tagbaru == '0'){
                $keuntungan = 'asal';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraUpahTawarruq($kodcaw,$cal['norujukan'],$jeniskeuntungan);
            }elseif($datagadai->tagbaru == '1'){
                $keuntungan = 'onepercent';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraupahUjrahOnePercent($kodcaw,$cal['norujukan']);
            }
            
            $notisbycawarray[$index]['namacust'] = $customer;
            $notisbycawarray[$index]['datagadai'] = $datagadai;
            $notisbycawarray[$index]['keuntungan'] = $response;
        }

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

    public function getfasa(Request $request){
        
        $fasa = NotisPeringatan::on('mysql7')
        ->where('kodcaw','=',$request->kodcaw)
        ->where('notis_id','=',$request->notisid)
        ->where('peringatan','=',2)
        ->first();

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

    public function getdatanotiskedua($kodcaw,$notisid,$fasa,Request $request){

        $current = Carbon::now();
        $current = new Carbon();
        $arraynotiskedua = [];

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

        if($fasa == 'fasa1')
        {
            $notisbycaw = NotisPeringatan::on('mysql7')
            ->where('notisperingatan.notis_id',$notisid)
            ->where('notisperingatan.kodcaw',$kodcaw)
            ->where('notisperingatan.peringatan',2)
            ->where('notisperingatan.fasa',1)
            ->where('notisperingatan.tagsurat', NULL);
        }else{
            $notisbycaw = NotisPeringatan::on('mysql7')
            ->where('notisperingatan.notis_id',$notisid)
            ->where('notisperingatan.kodcaw',$kodcaw)
            ->where('notisperingatan.peringatan',2)
            ->where('notisperingatan.fasa',2)
            ->where('notisperingatan.tagsurat', NULL);
        }


        $notislist = $notisbycaw->get();

        foreach($notislist as $index=>$not)
        {
            $gadai = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=', $not['norujukan'])
                    ->first();
                    // dd($gadai);
             if($gadai->tagbaru == '0'){
                $keuntungan = 'asal';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraUpahTawarruq($kodcaw,$not['norujukan'],$jeniskeuntungan);
            }elseif($gadai->tagbaru == '1'){
                $keuntungan = 'onepercent';
                $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                $master = new MasterServices($kodcaw);
                $response = $master->kiraupahUjrahOnePercent($kodcaw,$not['norujukan']);
            }

            $customer = Customer::on('mysql7')
                    ->select('nama','telefon','telefon2','alamat1','alamat2','poskod','koddaerah')
                    ->where('kpbaru','=',$not['nokp'])
                    ->orWhere('kplama','=',$not['nokp'])
                    ->first();

            $poskod = Poskod::on('mysql7')
                    ->where('poskod','=',$customer['poskod'])
                    ->first();

                if($poskod)
                        $daerah = Daerah::on('mysql7')
                                ->where('koddaerah','=',$poskod['koddaerah'])
                                ->first();
                else
                    Log::debug('poskod tiada' . $not['nokp']);

                $negeri = Negeri::on('mysql7')
                    ->where('kodnegeri','=',$poskod['kodnegeri'])
                    ->first();

                $updatetagsurat=NotisPeringatan::on('mysql7')
                ->where('norujukan','=', $not['norujukan'])
                ->update(
                    array('tagsurat'=> 1));

            array_push($arraynotiskedua,['poskod'=>$customer['poskod'],
            'negeri' => $negeri['negeri'],
            'daerah' => $daerah['namadaerah'],
            'alamat' => $customer['alamat1'],
            'alamat2' => $customer['alamat2'],
            'nama' => $customer['nama'],
            'telefon1' => $customer['telefon'], 
            'telefon2' => $customer['telefon2'], 
            'norujukan' => $gadai['norujukan'], 
            'tempoh' => $gadai['tempoh'], 
            'nokp' => $gadai['nokp'], 
            'pinjaman' => $gadai['bakipjm'], 
            'keuntungan' => $response,
            'tmatang' => $gadai['t_matang'],
            'tmatang1' => $gadai['t_matang1'],
            'tagbaru' => $gadai['tagbaru'],
            'leltawarruq' => $gadai['lelong_tawarruq']]);
        }

       

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

    public function blastwasapbysagkedua(Request $request)
    {
        // dd($request->all());
        $current = Carbon::now();
        $current = new Carbon();
        $kodcaw = $request->kodcaw;
        $notisid = $request->notisid;

        $namapengguna = $request->namapengguna;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$request->kodcaw)->first();
        $cawangan_detail = CawanganDetail::on($cawangan['mysql'])->first();
        $caw_name = $cawangan->details_caw;
        $nofoncaw = $cawangan_detail->notel;

        $statusblast =  CawanganNotis::where('notis_id','=',$notisid)
        ->where('kodcaw','=',$kodcaw)
        ->first();
        // dd($statusblast);
        // if($statusblast->status == '2'){

                $notisbycaw = NotisPeringatan::on('mysql7')
                ->where('notisperingatan.notis_id',$notisid)
                ->where('notisperingatan.kodcaw',$kodcaw)
                ->where('notisperingatan.peringatan',2)
                ->where('notisperingatan.tarikhnotis2','=', NULL)
                ->distinct()
                ->get();
                $notisbycawarray = $notisbycaw->toArray();
                // dd($notisbycaw);
                if(empty($notisbycawarray)){
                    // dd(false);
                    return response()->json('failed');
                }else{
                    // dd(true);
                    $arraynorujukan = $notisbycaw->pluck('norujukan')->toArray();
                    
                    $gadainokp = Gadai::on($cawangan['mysql'])->whereIn('norujukan', $arraynorujukan)
                    ->get();
                    $gadai_all_groupby_nokp = $notisbycaw->groupBy('nokp');

                    foreach($gadainokp as $index1=>$cal){
                        if($gadai_all_groupby_nokp[$cal->nokp]){
                            $gadainokp[$index1]['gadai'] = $gadai_all_groupby_nokp[$cal->nokp];
                        }
                        $customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp'])
                        ->orWhere('kplama','=',$cal['nokp'])
                        ->first();
                        $nokp=$cal['nokp'];
                        // dd($customer);
                                if($customer->telefon != 'null'){
                                    $telefon=$customer->telefon;
                                        //log auditrail
                                        $audit = new Audit();
                                        $audit->users = $namapengguna;
                                        $audit->actions = 'ARCC Blast Whatsapp & SMS: Notis ID'.$notisid;
                                        $audit->norujukan = $cal->norujukan;
                                        $audit->new_data = $customer->telefon;
                                        $audit->old_data = $nokp;
                                        $audit->kodcaw = $kodcaw;
                                        $audit->created_at = $current;
                                        $audit->updated_at = $current;
                                        $audit->save();

                                        $today = $current->toDateString();  
                                        $harini = date('Y-m-d',strtotime($today)); 

                                        //update tarikh dlm table notisperingatan
                                            $updatenotis=NotisPeringatan::on('mysql7')
                                            ->where('norujukan','=', $cal->norujukan)
                                            ->update(
                                                array('tarikhnotis2'=> $harini));

                                    dispatch(new ARCCWhatsappPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq,$namapengguna));
                                    dispatch(new ARCCSMSPelangganSAGLAMAbysag($nokp,$customer->telefon,$caw_name,$nofoncaw,$kodcaw,$cal->norujukan,$cal->tempoh,$cal->t_matang,$cal->t_matang1,$cal->lelong_tawarruq,$namapengguna));
                                }
                    }
                    return response()->json('success');
                }       
    }   

   //carian untuk notis jbg
   public function getJbgGadai($kodcaw,Request $request)
   {
       // return 1;
       //$kodcaw = $request->kodcaw;
       $jbgmula = $request->jbgmula;
       $jbghingga = $request->jbghingga;

       // dd($jbghingga, $jbgmula);
       $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
       $gadaian = Gadai::on($cawangan['mysql'])
           ->where([['tagpalsu','=',0],['tempoh','>=',$jbgmula],['tempoh','<=',$jbghingga],['sttebus','=',''],['taglel','=',0]])
           ->orderBy('t_gadai', 'ASC')
           ->orderBy('sirig', 'ASC');

           $arraynorujukan = $gadaian->pluck('norujukan')->toArray();
           $rekodgadai = $gadaian->get();
      
           $totalrekod = $gadaian->count('norujukan');
           $totalberat = $gadaian->sum('berat');
           $totalnilaimarhun = $gadaian->sum('nilaimarhun');
           $totalpinjaman = $gadaian->sum('pinjaman');
           $totalbakipjm = $gadaian->sum('bakipjm');
           $totaltunggakan = $gadaian->sum('tunggakan');
   
           $arrayrekod = ['rekod' => $rekodgadai, 'totalsag' => $totalrekod,'totalberat' => $totalberat,'totalnilaimarhun' =>  $totalnilaimarhun,'totalpembiayaan'=>$totalpinjaman,'totalbakipjm'=>$totalbakipjm,'totaltunggakan'=>$totaltunggakan];
            //dd($arrayrekod);
           return response()->json($arrayrekod,200);
   }

   public function getbatchnotisjbg(Request $request){
       $currentDate = Carbon::now();
       $tarikh_daftar = $currentDate->toDateString();
       $jbgmula = $request->jbgmula;
       $jbghingga = $request->jbghingga;

       $notis = NotJbg::create([
           'tarikh_notjbg' => $tarikh_daftar,
           'daritempoh' => $jbgmula,
           'hinggatempoh' => $jbghingga,
           'sts_notis' => 1,
           'notiskali' => 1
       ]);

       $batchnotis = NotJbg::on('mysql7')->orderBy('id','desc')->first()->id;

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

   public function insertdatagadaijbg($kodcaw,Request $request)
   {
       $jbgmula = $request->jbgmula;
       $jbghingga = $request->jbghingga;
       $notisid = $request->notisid;
       $currentDate = Carbon::now();
       // $currentDate = $currentDate->toDateString();
       $tarikh_daftar = $currentDate->toDateString();
       $sag_cawangans = [];
       $bil_surat = 0;
       // dd($kodcaw);
       $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();

       $datagadaijbg = Gadai::on($cawangan['mysql'])
           ->where([['tagpalsu','=',0],['tempoh','>=',$jbgmula],['tempoh','<=',$jbghingga],['sttebus','=',''],['taglel','=',0]])
           ->orderBy('t_gadai', 'ASC')
           ->orderBy('sirig', 'ASC');
           // ->get();
           array_push($sag_cawangans,['data'=>$datagadaijbg->get()]);
            //dd($sag_cawangans);

           foreach($sag_cawangans as $index=>$cawnotis){
               // dd($cawnotis);
               $caw_notis = new CawanganNotisJbg;
               $caw_notis->notjbg_id = $notisid;
               $caw_notis->kodcaw = $kodcaw;
               $caw_notis->notiskali = 1;
               $caw_notis->daritempoh = $jbgmula;
               $caw_notis->hinggatempoh = $jbghingga;
               $caw_notis->status = 1;
               $caw_notis->save();
               //dd($caw_notis);
               $notiscaw = $cawnotis['data'];

               $notis_jbg_arr = [];
               $now = Carbon::now();
               foreach($notiscaw as $call)
               {
                   $notis_to_be_inserted = new NotisJbg();
                   $notis_to_be_inserted->notjbg_id = $notisid;
                   $notis_to_be_inserted->tarikh_daftar = $tarikh_daftar;
                   $notis_to_be_inserted->kodcaw = $kodcaw;
                   $notis_to_be_inserted->norujukan = $call->norujukan;
                   $notis_to_be_inserted->nokp = $call->nokp;
                   $notis_to_be_inserted->jbg = $call->tempoh;
                   $notis_to_be_inserted->kadarupah = $call->kadarupah;
                   $notis_to_be_inserted->nilaimarhun = $call->nilaimarhun;
                   $notis_to_be_inserted->pinjaman = $call->bakipjm;
                   $notis_to_be_inserted->bakiupah = $call->bakiupah;
                   $notis_to_be_inserted->berat = $call->berat;
                   $notis_to_be_inserted->marhun = $call->marhun;
                   $notis_to_be_inserted->percentpinj = $call->percentpinj;
                   $notis_to_be_inserted->notiskali = '1';
                   $notis_jbg_arr[] = $notis_to_be_inserted->attributesToArray();
               }

               $notis_jbg_collection = collect($notis_jbg_arr);

               NotisJbg::insert($notis_jbg_arr);
       }
       return response()->json("success");
   }

   public function senarainotisjbg()
   {
       $current = Carbon::now();
       $current = new Carbon();

       $arraybatch = [];
       $batchnotis = NotJbg::on('mysql7')->get();
       // $cawangan_all = Cawangan::on('mysql7')->get();
       // $cawnotis_all = [];
       // foreach ($batchnotis as $index => $cawangan){
       //     $notis = CawanganNotis::on('mysql7')->get();
       //     if(sizeof($notis) != 0){
       //         array_push($cawnotis_all,$notis);
       //     }
       // }
       return response()->json($batchnotis);
   }

   public function getcawnotisjbg($notisid)
   {
       $current = Carbon::now();
       $current = new Carbon();

       $arraybatch = [];
       $batchnotisjbg = NotJbg::on('mysql7')->where('id',$notisid)->get();
       $cawangan_all = Cawangan::on('mysql7')->get();
       $cawnotisjbg_all = [];
       foreach ($batchnotisjbg as $index => $cawangan){
           $notis = CawanganNotisJbg::on('mysql7')
           ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notisjbg.kodcaw')
           ->where('cawangan_notisjbg.notjbg_id',$notisid)->get();
           if(sizeof($notis) != 0){
               array_push($cawnotisjbg_all,$notis);
           }
       }
       return response()->json($cawnotisjbg_all);
   }

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

       $kodcaw = $request->kodcaw;
       $notisid = $request->notisid;
       $cawnotis_all = [];

       $arraybatch = [];
       $batchnotis = CawanganNotisJbg::on('mysql7')
       ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notisjbg.kodcaw')
       ->where('cawangan_notisjbg.notjbg_id',$notisid)->get();
     
       foreach ($batchnotis as $index => $cawangan){
           $notis = NotisJbg::on('mysql7')
           ->where('notisjbg.notjbg_id',$notisid)
           ->where('notisjbg.kodcaw',$cawangan['kodcaw'])
           ->distinct()
           ->get();

           $totalsagjbg = $notis->count('norujukan');

           //$batchnotis [$index]['totalsag'] = $notis->count('norujukan');
            //dd($totalsagjbg);
           // if(sizeof($notis) != 0){
               array_push($cawnotis_all,['namacaw'=>$batchnotis, 'detailbycaw' => $notis, 'totalsagjbg' =>$totalsagjbg]);
           // }
       }
       // dd($cawnotis_all);

       // $arrayrekod = ['rekod' => $cawnotis_all,'totalsagjbg' =>$totalsagjbg];
       return response()->json($cawnotis_all);
   }

   public function bycawnotisjbg($kodcaw,$notisid)
   {
       $cawnotis_all = [];

       $notisjbgbycaw = NotisJbg::on('mysql7')
       ->where('notisjbg.notjbg_id',$notisid)->where('notisjbg.kodcaw',$kodcaw)
       ->distinct()
       ->get();

       $notisjbgbycawarray = $notisjbgbycaw->toArray();

       foreach($notisjbgbycawarray as $index=>$cal){
           $customer =  Customer::where('kpbaru','=',$cal['nokp'])
           ->orWhere('kplama','=',$cal['nokp'])
           ->first();

           $notisjbgbycawarray[$index]['namacust'] = $customer;
       }

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

   public function bysagnotisjbg($kodcaw,$notisid,$id)
   {
       $notissag = NotisJbg::on('mysql7')
       //->join('customer','customer.kplama','||','customer.kpbaru','=','notisjbg.nokp')
       ->where('notisjbg.notjbg_id',$notisid)->where('notisjbg.kodcaw',$kodcaw)->where('notisjbg.id',$id)
       ->first();

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

   public function bysagnotisjbgCustomer($kodcaw,$notisid,$id)
    {
        $notissag = NotisJbg::on('mysql7')
        //->join('customer','customer.kplama','||','customer.kpbaru','=','notisjbg.nokp')
        ->where('notisjbg.notjbg_id',$notisid)->where('notisjbg.kodcaw',$kodcaw)->where('notisjbg.id',$id)
        ->first();

        $nokp = $notissag['nokp'];
        // $notissagbyjbgarray = $notissagbyjbg->toArray();

        // foreach($notissagbyjbgarray as $index=>$cal){
            $cust_info =  Customer::where('kpbaru','=',$notissag['nokp'])
            ->orWhere('kplama','=',$notissag['nokp'])
            ->first();

        //     $notissagbyjbgarray[$index]['namacust'] = $customer;
        // }

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

    public function bycawnotisjbg2($kodcaw,$notisid)
    {
        $cawnotis_all = [];
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $notisjbgbycaw = NotisPeringatan::on('mysql7')
        ->where('notisperingatan.notis_id',$notisid)->where('notisperingatan.kodcaw',$kodcaw)
        ->where('notisperingatan.peringatan',2)
        //->distinct() //asal
        ->orderBy('nokp')
        ->get(); //asal
   
        $arraynorujukan = $notisjbgbycaw->pluck('norujukan')->toArray(); //asal
     
        $notisnokp = NotisPeringatan::whereIn('norujukan', $arraynorujukan)
        ->where('notisperingatan.peringatan',2)
        ->select('nokp')
        ->groupBy('nokp')
        ->get(); // asal

        foreach($notisnokp as $index=>$cal){    //asal      
            //$customer =  Customer::on('mysql7')->where('kpbaru','=',$cal['nokp']) //asal
            $customer =  Customer::where('kpbaru','=',$cal['nokp'])
            ->orWhere('kplama','=',$cal['nokp'])
            ->first();

            //$listnotis = NotisPeringatan::on('mysql7')->whereIn('norujukan', $arraynorujukan) //asal
            $listnotis = NotisPeringatan::whereIn('norujukan', $arraynorujukan)
            ->where('nokp','=',$cal['nokp'])
            ->get();

            $listsag = Gadai::on($cawangan['mysql'])
            ->whereIn('norujukan', $arraynorujukan)
            ->where('nokp','=',$cal['nokp'])
            ->get();

            foreach($listsag as $index2=>$sag){
                if($sag['tagbaru'] == '0'){
                    $keuntungan = 'asal';
                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                    $master = new MasterServices($kodcaw);
                    $response = $master->kiraUpahTawarruq($kodcaw,$sag['norujukan'],$jeniskeuntungan);
                    //dd($response);
                }elseif($sag['tagbaru'] == '1'){
                    $keuntungan = 'onepercent';
                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                    $master = new MasterServices($kodcaw);
                    $response = $master->kiraupahUjrahOnePercent($kodcaw,$sag['norujukan']);
                }

                 $listsag[$index2]['keuntungan'] = $response;
            }
                       
            $notisnokp[$index]['info'] = $customer;
            $notisnokp[$index]['listsag'] = $listsag;
            $notisnokp[$index]['listnotis'] = $listnotis;
                  
        }

        $totalrekod = $notisjbgbycaw->sum('pinjaman');
        $totalberat = $notisjbgbycaw->sum('berat');
        $totalnilaimarhun = $notisjbgbycaw->sum('nilaimarhun');
        $totalpinjaman = $notisjbgbycaw->sum('pinjaman');
        $totalbakipjm = $notisjbgbycaw->sum('bakipjm');
        $totaltunggakan = $notisjbgbycaw->sum('tunggakan');

        $arrayrekod = ['rekod' => $notisnokp, 'total' => $totalrekod,'totalberat' => $totalberat,'totalnilaimarhun' =>  $totalnilaimarhun,'totalpinjaman'=>$totalpinjaman,'totalbakipjm'=>$totalbakipjm,'totaltunggakan'=>$totaltunggakan];
        // dd($arrayrekod);
        return response()->json($arrayrekod,200);
    }

    public function bysagnotisjbg2($kodcaw,$notisid,$nokp)
    {
        $cawnotis_all = [];
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $notisjbgbycaw = NotisPeringatan::on('mysql7')
        ->where('notisperingatan.notis_id',$notisid)->where('notisperingatan.kodcaw',$kodcaw)
        ->where('nokp',$nokp)
        ->where('notisperingatan.peringatan',2)
        ->distinct()
        ->get();
        
        $arraynorujukan = $notisjbgbycaw->pluck('norujukan')->toArray();
        $notisnokp = NotisPeringatan::on('mysql7')->whereIn('norujukan', $arraynorujukan)
        ->where('notisperingatan.peringatan',2)
        ->select('nokp')
        ->groupBy('nokp')
        ->get();
        
        // dd($notisnokp);
        foreach($notisnokp as $index1=>$cal){           

            $listnotis = NotisPeringatan::on('mysql7')->whereIn('norujukan', $arraynorujukan)
            // ->where('nokp','=',$cal['nokp'])
            ->where('nokp', 'like', '%'.$cal['nokp'].'%')
            ->where('notisperingatan.peringatan',2)
            ->get();

            $listsag = Gadai::on($cawangan['mysql'])
            ->whereIn('norujukan', $arraynorujukan)
            ->where('nokp','=',$cal['nokp'])
            ->get();

            foreach($listsag as $index11=>$sag){
                if($sag['tagbaru'] == '0'){
                    $keuntungan = 'asal';
                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                    $master = new MasterServices($kodcaw);
                    $response = $master->kiraUpahTawarruq($kodcaw,$sag['norujukan'],$jeniskeuntungan);
                    //dd($response);
                }elseif($sag['tagbaru'] == '1'){
                    $keuntungan = 'onepercent';
                    $jeniskeuntungan = ($keuntungan == 'onepercent') ? 'onepercent' : 'asal';
                    $master = new MasterServices($kodcaw);
                    $response = $master->kiraupahUjrahOnePercent($kodcaw,$sag['norujukan']);
                }

                 $listsag[$index11]['keuntungan'] = $response;
            }
                       
            $notisnokp[$index1]['listsag'] = $listsag;
            $notisnokp[$index1]['listnotis'] = $listnotis;
                  
        }

        $getstatusremark = NotisPeringatan::on('mysql7')->where('nokp', $nokp)
        //->whereIn('norujukan', $arraynorujukan)
        ->where('notis_id',$notisid)
        ->where('notisperingatan.peringatan',2)
        // ->select('statuscall,remark1')
         ->groupBy('nokp')
        ->get();
        
        $arrayrekod = ['rekodnotis' => $notisnokp, 'getstatusremark' => $getstatusremark];
        // dd($arrayrekod);
        return response()->json($arrayrekod,200);
    }

    public function bysagnotisjbgCustomer2($kodcaw,$notisid,$nokp)
    {
        $notissag = NotisPeringatan::on('mysql7')
        //->join('customer','customer.kplama','||','customer.kpbaru','=','notisjbg.nokp')
        ->where('notis_id',$notisid)->where('kodcaw',$kodcaw)->where('nokp',$nokp)
        ->where('peringatan',2)
        ->first();

        $nokp = $notissag['nokp'];
        // $notissagbyjbgarray = $notissagbyjbg->toArray();

        // foreach($notissagbyjbgarray as $index=>$cal){
            $cust_info =  Customer::where('kpbaru','=',$notissag['nokp'])
            ->orWhere('kplama','=',$notissag['nokp'])
            ->first();

        //     $notissagbyjbgarray[$index]['namacust'] = $customer;
        // }

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

    public function getcawnotiskemaskini($notisid)
    {
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        $batchnotis = Notis::on('mysql7')->where('id',$notisid)->get();
        $cawangan_all = Cawangan::on('mysql7')->get();
        $cawnotis_all = [];
        foreach ($batchnotis as $index => $cawangan){
            $notis = CawanganNotis::on('mysql7')
            ->join('arrahn_master_db', 'arrahn_master_db.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notis_id',$notisid)->get();
        }
        return response()->json($notis);
    }

    public function updatecall($kodcaw,$notisid,$nokp, Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();
        $harini = $current->toDateString();
        $cawnotis_all = [];
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $notiscall = NotisPeringatan::on('mysql7')
        ->where('notisperingatan.notis_id',$notisid)->where('notisperingatan.kodcaw',$kodcaw)
        ->where('nokp',$nokp)
        //->where('notisperingatan.peringatan',2)
        ->distinct()
        ->get();
        
        $arraynorujukan = $notiscall->pluck('norujukan')->toArray();

        $updateNotisCall = NotisPeringatan::on('mysql7')
        ->where('nokp', $nokp)
        ->where('notis_id', $notisid)->update([
            'tarikhcall1'=> $harini,
            'remark1'=> $request->nota,
            'statuscall'=> $request->statuscall,
            'caller'=>$request->caller
        ]);   

        return response()->json('success');

    }

        public function senarainotisperingatankedua()
        {
        $current = Carbon::now();
        $current = new Carbon();

        $arraybatch = [];
        // $batchnotis = Notis::on('mysql7')->get();
        // return response()->json($batchnotis);
        $batchnotis = Notis::on('mysql7')
        // ->join('cawangan_notis', 'cawangan_notis.notis_id', '=', 'notis.id')
        // ->distinct()
        ->get();
        // $cawangan_all = Cawangan::on('mysql7')->get();
        $cawnotis_all = [];
        foreach ($batchnotis as $index => $cawangan){
            $idnotis = $cawangan['id'];
            $tarikh_notis = $cawangan['tarikh_notis'];
            $daritempoh = $cawangan['daritempoh'];
            $notis = CawanganNotis::on('mysql7')
            ->join('notisperingatan', 'notisperingatan.kodcaw', '=', 'cawangan_notis.kodcaw')
            ->where('notisperingatan.notis_id',$cawangan['id'])
            // ->where('cawangan_notis.kodcaw',$cawangan['kodcaw'])
            ->where('notisperingatan.peringatan','2')
            ->distinct()
            ->get();

            $totalsag = $notis->count('norujukan'); 
            if(sizeof($notis) != 0){
                array_push($cawnotis_all,['id' => $idnotis, 'tarikh_notis' => $tarikh_notis, 'daritempoh' => $daritempoh,'totalsag' => $totalsag, 'detail' => $notis]);
            }
        }
        return response()->json($cawnotis_all);
    }

    public function rekodgadai(Request $request)
    {
        $nokp = $request->nokp;
        $kodcaw = $request->kodcaw;
        // Dapatkan maklumat cawangan
        $cawangan = Cawangan::on('mysql7')
            ->where('kodcaw', $kodcaw)
            ->first();

        if (!$cawangan || empty($cawangan->mysql)) {
            return response()->json([
                'status'  => false,
                'message' => 'Cawangan tidak dijumpai atau konfigurasi DB tidak lengkap',
                'data'    => []
            ], 404);
        }

        try {
            // Query rekod gadai dari DB cawangan yang betul
            $gadai = Gadai::on($cawangan->mysql)
                ->where('nokp', $nokp)
                ->get();

            return response()->json([
                'status'  => !$gadai->isEmpty(),
                'message' => $gadai->isEmpty() ? 'Tiada rekod gadai' : 'Rekod gadai dijumpai',
                'data'    => $gadai
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => 'Ralat semasa ambil data: ' . $e->getMessage(),
                'data'    => []
            ], 500);
        }
    }

   public function rekodgadaiBatch(Request $request)
{
    $nokpList = $request->input('nokp_list', []);
    $kodcaw   = $request->input('kodcaw');

    if (empty($nokpList) || empty($kodcaw)) {
        return response()->json([
            'status'  => false,
            'message' => 'Parameter tidak lengkap',
            'data'    => []
        ], 400);
    }

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

    if (!$cawangan || empty($cawangan->mysql)) {
        return response()->json([
            'status'  => false,
            'message' => 'Cawangan tidak dijumpai',
            'data'    => []
        ], 404);
    }

    try {
        $gadai = Gadai::on($cawangan->mysql)
            ->whereIn('nokp', $nokpList)
            ->get();

        return response()->json([
            'status'  => !$gadai->isEmpty(),
            'message' => $gadai->isEmpty() ? 'Tiada rekod gadai' : 'Rekod gadai dijumpai',
            'data'    => $gadai
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status'  => false,
            'message' => 'Ralat semasa ambil data: ' . $e->getMessage(),
            'data'    => []
        ], 500);
    }
}





    public function customerUpdate($nokp,Request $request){
        $poskod = Poskod::on('mysql7')->where('poskod','=',$request->poskod)->first();
        $customer_update = Customer::on('mysql7')
        ->where('kplama','=',$nokp)
        ->orWhere('kpbaru','=',$nokp)
        ->update(array(
            'nota_arcc'=>$request->nota_arcc,
        ));

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


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

        DB::connection('mysql7')->beginTransaction();

        try{
            $poskod = Poskod::on('mysql7')->where('poskod','=',$request->poskod)->first();

            $customer_info = DB::connection('mysql7')->table('customer')
            ->select('kodcaw','kodkerja','nota_pekerjaan','nota_arcc','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','poskod')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->get()->toArray();


            $old_data = json_encode($customer_info);

            $customer_update = Customer::on('mysql7')
            ->where('kplama','=',$nokp)
            ->orWhere('kpbaru','=',$nokp)
            ->update(array(
                'nota_arcc' => $request->nota_arcc, 
            ));

            if($customer_update)
            {
                $customer_info_new = DB::connection('mysql7')->table('customer')
                ->select('kodcaw','kodkerja','nota_pekerjaan','nota_arcc','tarikhdaftar','nopelanggan','kpbaru','kplama','nama','t_lahir','jantina','alamat1','poskod')
                ->where('kplama','=',$nokp)
                ->orWhere('kpbaru','=',$nokp)
                ->get()->toArray();

                $new_data = json_encode($customer_info_new);

                $audit_customer = DB::connection('mysql7')
                ->table('audit_customer')
                ->insert([
                    'username' => $request->namateller,
                    'old_data' => $old_data,
                    'new_data' => $new_data,
                    'kodcaw' => $customer_info[0]->kodcaw,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString(),
                    'customer_name' => $customer_info[0]->nama,
                    'customer_nokp' => $nokp,
                ]);
            }

            DB::connection('mysql7')->commit();

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

        }catch (\Exception $e) {
            DB::connection('mysql7')->rollback();
            return response()->json($e->getMessage(),400);

        }
    }

}