<?php

namespace App\Http\Controllers;

use App\Customer;
use App\BatchLel;
use App\Pelelong;
use App\Daerah;
use App\Poskod;
use App\Negeri;
use App\Lelong;
use App\Transaction;
use App\Cawangan;
use App\Gadai;
use App\TuntutBaki;
use App\WTD;
use App\GlCode;
use App\imbangdugalama;
use App\AnsRugi;
use App\SerahBaki;
use App\Tebus;
use App\Advansur;
use App\LelTebus;
use App\LelMarhun;
use App\Tunai;
use App\Audit;
use App\GlDetail;
use App\Pembeli;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Services\RingkasanHarianServices;
use App\Services\OnePercentServices;
use App\Services\MasterServices;
use App\Support\v2\Calculation;
use Illuminate\Support\Facades\Validator;


use Log;
use DB;
    use Carbon\Carbon;

class LelongController extends Controller
{

    public function showAllLelongs()
    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $lelong_all = [];
        foreach ($cawangan_all as $index => $cawangan){
            $lelong = Lelong::on($cawangan['mysql'])->get();
            if(sizeof($lelong) != 0){
                array_push($lelong_all,$lelong);
            }
        }
        return response()->json($lelong_all);
    }

    public function showAllLelongByCawangan($kodcaw)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong = Lelong::on($cawangan['mysql'])->get();
        return response()->json($lelong);
    }

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

        $lelong = Lelong::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->get();

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

    public function showBakiLelong($noic,$jenislelong, $kodcaw, Request $request)

    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $bakilelongtotal = 0;
        $rugilelongtotal = 0;
        $current = Carbon::now();
        $current = new Carbon();

        if($jenislelong == 'baki')
        {
        foreach($cawangan_all as $index=>$cawangan){
            $bakilelong = Gadai::on($cawangan['mysql'])
            ->where([['gadai.sttebus','=', 'L'],['gadai.nokp','=',$noic],['lelong.baki','not like', '-%']])
            ->whereNull('lelong.trkhtuntut')
            ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->sum('baki');

                    if($bakilelong != 0){
                        $bakilelongtotal += $bakilelong;
                    }
        }


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

        }

        else if($jenislelong == 'rugi')
        {
            foreach($cawangan_all as $index=>$cawangan){
                $rugilelong = Gadai::on($cawangan['mysql'])
                ->where([['gadai.sttebus','=', 'L'],['gadai.nokp','=',$noic],['lelong.baki','like', '-%']])
                ->whereNull('lelong.trkhtuntut')
                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                        ->sum('baki');

                        if($rugilelong != 0){
                            $rugilelongtotal += $rugilelong;
                        }
            }

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

    }

    public function showBakiLelongEachCawangan($kodcaw,$noic,$jenislelong)
    {
        $cawangan_all = Cawangan::on('mysql7')->get();
        $bakilelongtotal = 0;
        $rugilelongtotal = 0;

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

        if($jenislelong == 'baki')
        {
            $bakilelong = Gadai::on($cawangan['mysql'])
            ->where([['gadai.sttebus','=', 'L'],['gadai.nokp','=',$noic],['lelong.baki','not like', '-%']])
            ->whereNull('lelong.trkhtuntut')
            ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->sum('baki');

                    if($bakilelong != 0){
                        $bakilelongtotal += $bakilelong;
                    }


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

        }

        else if($jenislelong == 'rugi')
        {
                $rugilelong = Gadai::on($cawangan['mysql'])
                ->where([['gadai.sttebus','=', 'L'],['gadai.nokp','=',$noic],['lelong.baki','like', '-%']])
                ->whereNull('lelong.trkhtuntut')
                ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                        ->sum('baki');

                        if($rugilelong != 0){
                            $rugilelongtotal += $rugilelong;
                        }


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

    }

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

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


        // $bakilelonglama = imbangdugalama::on($cawangan['mysql'])
        //     ->sum('baki_lelong');

        // $rugilelonglama = imbangdugalama::on($cawangan['mysql'])
        //     ->sum('rugi_lelong');


        if($kodcaw == 'KB2')
        {
            if($request->tarikh <= '2021-02-25')
            {
                $bakilelong = Lelong::on($cawangan['mysql'])
                ->where('t_jual','<=',$request->tarikh)
                ->where(function($query) use ($tarikhbaru){
                    $query->whereNull('trkhtuntut')
                        ->orWhere('trkhtuntut','>',$tarikhbaru);
                })
                ->where('baki','>=',0)
                ->sum('baki');
            }else{
                $bakilelong = Lelong::on($cawangan['mysql'])
                ->where('t_jual','<=',$request->tarikh)
                ->where(function($query) use ($tarikhbaru){
                    $query->whereNull('trkhtuntut')
                        ->orWhere('trkhtuntut','>',$tarikhbaru);
                })
                ->where('baki','>=',0)
                ->sum('baki');
            }
        }else{
            $bakilelong = Lelong::on($cawangan['mysql'])
            ->where('t_jual','<=',$request->tarikh)
            ->where(function($query) use ($tarikhbaru){
                $query->whereNull('trkhtuntut')
                    ->orWhere('trkhtuntut','>',$tarikhbaru);
            })
            ->where('baki','>=',0)
            ->sum('baki');
        }

        $ansrugi = AnsRugi::on($cawangan['mysql'])
            ->sum('bayaran');

        $rugilelong = Lelong::on($cawangan['mysql'])
            ->where('t_jual','<=',$request->tarikh)
            ->where(function($query) use ($tarikhbaru)
            {
                $query->whereNull('trkhtuntut')
                    ->orWhere('trkhtuntut','>',$tarikhbaru);
            })
            ->where('baki','<',0)
            ->sum('baki');

        $rugitotal=$rugilelong + $ansrugi;


       if($kodcaw == '010617')
            $rugitotal -= 6.1;

        if($kodcaw == '011229'){
            $rugitotal -= 919.7;
        }

        if($kodcaw == '011412')
            $rugitotal -= 7248.4;

        if($kodcaw == '020303')
        {
            $rugitotal += 0.01;
        }

        if($kodcaw === 'ARP'){
            $rugitotal += 119;
        }


        $arraylelong = ['bakilelong' => $bakilelong, 'rugilelong' => $rugitotal];

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

    public function BakiLelongCalculationLejer($kodcaw,Request $request)
    {
        $cas_lelong = 0;
        $jumlah_lelong = 0;
        $baki_lelong = 0;
        $rugi_lelong = 0;

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


        $bakilelong = Lelong::on($cawangan['mysql'])
            ->where('trkhtuntut','>=',$request->mula)
            ->where('trkhtuntut','<=',$request->hingga)
            ->where('baki','>=',0)
            ->sum('baki');

        $rugilelong = Lelong::on($cawangan['mysql'])
            ->where('trkhtuntut','>=',$request->mula)
            ->where('trkhtuntut','<=',$request->hingga)
            ->where('baki','<',0)
            ->sum('baki');

        $data_lelong = Lelong::on($cawangan['mysql'])->where([['t_jual','>=',$request->mula],['t_jual','<=',$request->hingga]])->get();

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

        $arraylelong = ['bakilelong' => $bakilelong, 'rugilelong' => abs($rugilelong), 'baki' => $baki_lelong, 'rugi' => $rugi_lelong, 'jumlahlelong' => $jumlah_lelong, 'caslelong' => $cas_lelong];

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

    public function BilAkanDilelong($noic)
    {
        $cawangan_all = Cawangan::on('mysql7')->get();

        $akanlelongarray = [];

        foreach($cawangan_all as $index=>$cawangan){
            $akanlelong = Gadai::on($cawangan['mysql'])
            ->where([['sttebus','=', ''],['nokp','=',$noic],['hargajual','=', 0]])
            ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->get();

                    if(sizeof($akanlelong) != 0){
                        array_push($akanlelongarray,$akanlelong);
                    }
        }

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



    public function create(Request $request)
    {
        $lelong = Lelong::create($request->all());

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

    public function update($id, Request $request)
    {
        $lelong = Lelong::findOrFail($id);
        $lelong->update($request->all());

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

    public function delete($id)
    {
        Lelong::findOrFail($id)->delete();
        return response('Deleted Successfully', 200);
    }


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

        $lelong = Lelong::on($cawangan['mysql'])
                ->where('t_lelong','=',$tarikh)
                ->whereNotNull('t_jual')
                ->leftJoin('pembeli', 'pembeli.nopembeli', '=', 'Lelong.nopembeli')
                ->orderBy('t_lelong')
                ->get();

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

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

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

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

        $tuntutbaki = TuntutBaki::on($cawangan['mysql'])->create([
            'batchno' => $request->batchno,
            'jenis' => $request->jenis,
            'kodcaw' => $kodcaw,
            'norujukan' => $request->norujukan,
            'tarikh' => $current->toDateString(),
            'prkod' => "01",
            'teller' => $request->teller,
            'bakipjm' => $request->bakipjm,
            'bakiupah' => $request->bakiupah,
            'cajlain' => $request->cajlain,
            'cajlelong' => $request->cajlelong,
            'kodgl' => "1000/013",
            'glcode' => "1000/010",
            'terima' => "*",
            'f_lulus' => "L",
            'jumlah' => $request->jumlah,
            'nowakil' => $request->nowakil,
            'hargajual' => $request->hargajual
        ]);

        $audit = new Audit();
        $audit->norujukan = $request->norujukan;
        $audit->users = $request->teller;
        $audit->actions = "Tuntut Baki Lelong";
        $audit->new_data = null;
        $audit->kodcaw = $request->kodcaw;
        $audit->created_at =  $current;
        $audit->updated_at =  $current;
        $audit->save();

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

    public function updatetagtbaki($kodcaw,$norujukan){

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

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

        $gadai=Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->update(
                        array('tagtbaki'=> 0));

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


        if($gadai == 1 && $lelong == 1)
        {
            return response('Berjaya', 200);
        }else{
            return response('Gagal', 200);
        }

    }

    public function showTuntutBaki($kodcaw){

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

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

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

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

    public function showTuntutBakiTarikh($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)
            ->get();

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

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

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

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

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

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

    public function resitLelong(Request $request, $kodcaw,$norujukan){

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

        $lelong = Lelong::on($cawangan['mysql'])
        ->select('gadai.nokp','tuntutbaki.batchno','tuntutbaki.nowakil','tuntutbaki.tarikh','tuntutbaki.bakipjm','tuntutbaki.bakiupah','tuntutbaki.recno','lelong.t_lelong','tuntutbaki.norujukan','tuntutbaki.hargajual','tuntutbaki.jumlah','tuntutbaki.cajlelong','lelong.pinjaman')
        ->where('lelong.norujukan','=',$norujukan)
        ->whereNotNull('lelong.trkhtuntut')
        ->join('tuntutbaki', 'tuntutbaki.norujukan', '=', 'lelong.norujukan')
        ->join('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->orderBy('tuntutbaki.tarikh')
        ->first();

        $customerinfo = Customer::on('mysql7')
        ->select('nama','kpbaru','teller')
        ->where('kpbaru', $lelong['nokp'])
        ->orWhere('kplama', $lelong['nokp'])
        ->first();

        $arraycustomer = ['nama' => $customerinfo['nama'],'teller' => $customerinfo['teller'],'kpbaru' => $customerinfo['kpbaru'],'nokp' => $lelong['nokp'],'batchno' => $lelong['batchno'],'nowakil' => $lelong['nowakil'],'tarikh' => $lelong['tarikh'],'bakipjm' => $lelong['bakipjm'],'bakiupah' => $lelong['bakiupah'],'recno' => $lelong['recno'],'t_lelong' => $lelong['t_lelong'],'norujukan' => $lelong['norujukan'],'hargajual' => $lelong['hargajual'],'jumlah' => $lelong['jumlah'],'cajlelong' => $lelong['cajlelong'],'pinjaman' => $lelong['pinjaman']];

        $audit = new Audit();
        $audit->norujukan = $norujukan;
        $audit->users = $request->name;
        // $audit->users = $arraycustomer['teller'];
        $audit->actions = "Cetak Resit Lelong";
        $audit->new_data = null;
        $audit->kodcaw = $kodcaw;
        $audit->created_at =  $current;
        $audit->updated_at =  $current;
        $audit->save();

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

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


       $wtd = WTD::on($cawangan['mysql'])
            ->where('tarikh','<=', $request->tarikh)
            ->sum('wtd');

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

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


       $wtd = WTD::on($cawangan['mysql'])
            ->where('tarikh','>=', $request->mula)
            ->where('tarikh','<=', $request->hingga)
            ->sum('wtd');

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

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


       $serahbaki = SerahBaki::on($cawangan['mysql'])
            ->where([['tarikh','<=', $request->tarikh],['aktif',1]])
            ->sum('baki');

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

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

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


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

        $cajlelong = Lelong::on($cawangan['mysql'])
        ->whereNotNull('t_jual')
        ->where([['t_jual','<=', $request->tarikh],['t_jual','>','2014-12-31']])
        ->whereYear('t_jual','=',$current->year)
        ->sum('cajlelong');

        if($kodcaw === '011232' && $current->year < 2023)
            $cajlelong +=122.5;

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

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

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

        $cajlelong = Lelong::on($cawangan['mysql'])
        ->whereNotNull('t_jual')
        ->where([['t_jual','<=', $request->mula],['t_jual','>=',$request->hingga]])
        ->sum('cajlelong');

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

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

        $cajperkhidmatan = GlCode::on($cawangan['mysql'])
        ->where('glcode','=','7000/500')
        ->sum('amaun');

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

    public function LelonganHarini($kodcaw)
    {
        $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','=', $current->toDateString())
	->where('teller','LIKE','LELONG')
        ->sum('hargajual');

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

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

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

        if($cawangan['tagarrahnbid'] == 1){
            if(env('APP_ENV') != 'production'){
                $link = 'http://niklah.arrahn.com.my/api/portalApi';
            }else{
                $link = 'https://adminbid-kopkb.erahn.com.my/api/portalApi';
            }

            $lelong = Http::withOptions(['verify' => true])->get($link,[
                'norujukan' => $request->norujukan
            ])->json();
            $lelong = ($lelong != null) ? $lelong['lelong'] : [];
            if( $lelong == null )
            {
                $lelong = Lelong::on($cawangan['mysql'])
                ->where('norujukan', '=', $request->norujukan)
                ->first();
            }
        }else{
            $lelong = Lelong::on($cawangan['mysql'])
            ->where('norujukan', '=', $request->norujukan)
            //->where('t_lelong', '<=', $current->toDateString())
            ->first();
        }

        if($lelong)
        {
            $date_lelong = new Carbon($lelong['t_lelong']);
            $current_date = new Carbon($current->toDateString());

            if($lelong['t_lelong'] >= $current->toDateString())
            {
                $diff = $date_lelong->diffInDays($current_date);
            }else{
                $diff = $date_lelong->diffInDays($current_date);
                $diff = -$diff;
            }

            if($diff <= 2)
            {
                return response(1);
            }else{
                return response(0);
            }
        }else{
            return response(0);
        }
    }

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

        if ($cawangan['tagarrahnbid'] == 0){
            $lelong = Http::withOptions(['verify' => true])->get(config('app_parameter.api_arrahnbid').'portalApi',[
                'norujukan' => $request->norujukan
            ])->json();
            $lelong = ($lelong != null) ? $lelong['lelong'] : [];
            if( $lelong == null )
            {
                $lelong = Lelong::on($cawangan['mysql'])
                ->where('norujukan', '=', $request->norujukan)
                ->first();
            }
        }

        else{

            $lelong = Lelong::on($cawangan['mysql'])
            ->where('norujukan', '=', $request->norujukan)
            ->select('norujukan', 't_lelong')
            ->first();
        }

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

    public function keluarLelong(Request $request){
        $current = Carbon::now();
        $current = new Carbon();
        if($request->zone == 'all'){
            $cawangan_all = Cawangan::on('mysql7')->get();
        }else{
            $cawangan_all = Cawangan::on('mysql7')->where('zone',$request->zone)->get();
        }

        foreach($cawangan_all as $index=>$cawangan){
            $list_tebus_today = Tebus::on($cawangan['mysql'])->where('t_tebus',$current->toDateString())->pluck('norujukan')->toArray();
            $list_advansur_today = Advansur::on($cawangan['mysql'])->where('tarikh',$current->toDateString())->pluck('norujukan')->toArray();

            $gadai_tebus = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$list_tebus_today)->update([
                'taglel' => 0
            ]);
            $gadai_advansur = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$list_advansur_today)->update([
                'sttebus' => '',
                'taglel' => 0
            ]);
            $lelong_tebus = Lelong::on($cawangan['mysql'])->whereIn('norujukan',$list_tebus_today)->get();
            foreach($lelong_tebus as $index=>$tebus_lelong){
                $tebus_detail = Tebus::on($cawangan['mysql'])->where('norujukan',$tebus_lelong['norujukan'])->first();

                $lel_tebus = LelTebus::on($cawangan['mysql'])->create([
                    'tarikh' => $current->toDateString(),
                    'teller' => $tebus_detail['teller'],
                    'norujukan' => $tebus_lelong['norujukan'],
                    'batch_no' => $tebus_lelong['batchno'],
                    'nilai_marhun' => $tebus_lelong['nilaimarhun'],
                    'pinjaman' => $tebus_lelong['pinjaman'],
                    'upah' => $tebus_detail['bakiupah'],
                    'jbg' => $tebus_detail['jbg'],
                    'jenis_tebus' => 'T',
                ]);
            }
            $lelong_marhun_tebus = LelMarhun::on($cawangan['mysql'])->whereIn('norujukan',$list_tebus_today)->delete();
            $lelong_marhun_adv = LelMarhun::on($cawangan['mysql'])->whereIn('norujukan',$list_advansur_today)->delete();
            $lelong_tebus = Lelong::on($cawangan['mysql'])->whereIn('norujukan',$list_tebus_today)->delete();
            $lelong_advansur = Lelong::on($cawangan['mysql'])->whereIn('norujukan',$list_advansur_today)->delete();
        }

        return response()->json('successful');
    }

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

        if($cawangan['tagarrahnbid'] == 1)
        {
            $lelong = Http::withOptions(['verify' => true])->get(config('app_parameter.api_arrahnbid').'portalApi',['norujukan' => $request->norujukan])->json();
            $lelong = ($lelong != null) ? $lelong['lelong'] : [];
        }else{
            $lelong = Lelong::on($cawangan['mysql'])->where([['norujukan',$request->norujukan]])->first();
        }

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

    public function updateJBGLelong(Request $request){
        if($request->zone == 'all'){
            $cawangan_all = Cawangan::on('mysql7')->get();
        }else{
            $cawangan_all = Cawangan::on('mysql7')->where('zone',$request->zone)->get();
        }

        foreach($cawangan_all as $index=>$cawangan){
            $lelongList = Lelong::on($cawangan['mysql'])->where([['t_jual',null],['hargajual',0.00]])->get();

            foreach($lelongList as $index=>$lelongData){
                $gadaiData = Gadai::on($cawangan['mysql'])->where('norujukan',$lelongData['norujukan'])->first();
                $tarikh_gadai = Carbon::parse($gadaiData['t_gadai']. ' 00:00:00');
                $current = Carbon::now();

                $tahun_gadai = $tarikh_gadai->year;
                $bulan_gadai = $tarikh_gadai->month;
                $hari_gadai = $tarikh_gadai->day;

                $tahun_semasa = $current->year;
                $bulan_semasa = $current->month;
                $hari_semasa = $current->day;

                if($hari_semasa >= $hari_gadai){
                    $beza_hari = $hari_semasa - $hari_gadai + 1;
                }else if($hari_semasa < $hari_gadai){
                    $bulan_semasa = $bulan_semasa - 1;
                    $beza_hari = ($hari_semasa + 30) - $hari_gadai + 1;
                }

                $extensivemonth_gadai = 0;

                if($beza_hari >= 1 && $beza_hari <= 15){
                    $extensivemonth_gadai = 0.5;
                }else if($beza_hari >= 16){
                    $extensivemonth_gadai = 1;
                }else{
                    $extensivemonth_gadai = 0;
                }

                $beza_tahun = $tahun_semasa - $tahun_gadai;

                $beza_bulan = ($bulan_semasa + ($beza_tahun * 12)) - $bulan_gadai;

                $tempoh_gadai = $beza_bulan + $extensivemonth_gadai;

                $lelong = Lelong::on($cawangan['mysql'])->where('norujukan',$lelongData['norujukan'])->update([
                    'jbg' => $tempoh_gadai
                ]);
            }
        }
    }

    public function getSenaraiLelongAktif($kodcaw,$fasa){
        $current = Carbon::now();
        $current = new Carbon();

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

        if($fasa == 'fasa1')
        {
            $lelong = Lelong::on($cawangan['mysql'])
                ->selectRaw('count(*) as total, batchno,t_lelong')
                ->where('t_lelong','>=',$current->toDateString())
                ->where('fasa', 0)
                ->whereNull('t_jual')
                ->orderBy('t_lelong','desc')
                ->groupBy('batchno')
                ->get();
        }else{
            $lelong = Lelong::on($cawangan['mysql'])
                ->selectRaw('count(*) as total, batchno,t_lelong')
                ->where('t_lelong','>=',$current->toDateString())
                ->where('fasa', 2)
                ->whereNull('t_jual')
                ->orderBy('t_lelong','desc')
                ->groupBy('batchno')
                ->get();
        }


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

    public function getSenaraiBatchNoAktif($kodcaw,$fasa,Request $request){

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

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

        if($fasa == 'fasa1')
        {
            $lelong = Lelong::on($cawangan['mysql'])
                ->select('lelong.t_lelong','lelong.norujukan','gadai.jbg','gadai.nokp','gadai.pinjaman','gadai.bakiupah')
                ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
                // ->leftJoin('customer', 'customer.kpbaru', '=', 'gadai.nokp')
                ->where('batchno','=',$request->batchno)
                ->where('fasa',0)
                ->orderBy('gadai.t_gadai','asc')
                ->orderBy('gadai.sirig','asc')
                ->where('gadai.taglel','=', 1);
        }else{
            $lelong = Lelong::on($cawangan['mysql'])
                ->select('lelong.t_lelong','lelong.norujukan','gadai.jbg','gadai.nokp','gadai.pinjaman','gadai.bakiupah')
                ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
                // ->leftJoin('customer', 'customer.kpbaru', '=', 'gadai.nokp')
                ->where('batchno','=',$request->batchno)
                ->where('fasa',2)
                ->orderBy('gadai.t_gadai','asc')
                ->orderBy('gadai.sirig','asc')
                ->where('gadai.taglel','=', 1);
        }


        $batchlel = BatchLel::on($cawangan['mysql'])
                    ->where('batchno','=',$request->batchno)
                    ->first();

        $lelonglist = $lelong->get();

        foreach($lelonglist as $index=>$lel)
        {
            $ansuran = Transaction::on('mysql7')
                    ->where('norujukan','=', $lel['norujukan'])
                    ->where([['trans_type','=','A'],['kodcaw','=',$kodcaw]])
                    ->sum('duit_masuk');

            $customer = Customer::on('mysql7')
                    ->select('nama','telefon','telefon2','alamat1','alamat2','poskod','koddaerah')
                    ->where('kpbaru','=',$lel['nokp'])
                    ->orWhere('kplama','=',$lel['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' . $lel['nokp']);

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

            array_push($arraylelong,['poskod'=>$customer['poskod'],'negeri' => $negeri['negeri'],'daerah' => $daerah['namadaerah'],'alamat' => $customer['alamat1'],'alamat2' => $customer['alamat2'],'masa' => $batchlel['masadari'],'tarikhlelong' => $lel['t_lelong'],'nama' => $customer['nama'], 'telefon1' => $customer['telefon'], 'telefon2' => $customer['telefon2'], 'norujukan' => $lel['norujukan'], 'JBG' => $lel['jbg'], 'IC' => $lel['nokp'], 'Pembiayaan' => $lel['pinjaman'], 'upah6' => $lel['bakiupah'], 'bayaran' => $ansuran]);
        }

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

    public function DetailsNotisLelong($kodcaw){

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

        $detailslelong = Pelelong::on($cawangan['mysql'])->get();

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

    public function keluarLelongTawarruq(Request $request){
        if($request->zone == 'all'){
            $cawangan_all = Cawangan::on('mysql7')->get();
        }else{
            $cawangan_all = Cawangan::on('mysql7')->where('zone',$request->zone)->get();
        }

        foreach($cawangan_all as $index=>$cawangan){
            $list_lelong = Lelong::on($cawangan['mysql'])->where('t_jual',null)->pluck('norujukan')->toArray();

            $gadai_lelong = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$list_lelong)->where('lelong_tawarruq',0)->where('tempoh','<=',10.5)->pluck('norujukan')->toArray();

            $delete_lelong = Lelong::on($cawangan['mysql'])->whereIn('norujukan',$gadai_lelong)->delete();

            $update_gadai = Gadai::on($cawangan['mysql'])->whereIn('norujukan',$gadai_lelong)->update(['taglel'=>0]);
        }
    }

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

        $arraybatch = [];

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

        $batchleltuntutbaki = BatchLel::on($cawangan['mysql'])
            ->selectRaw('count(lel.norujukan) as bilangan,batchlel.batchno as batchno,lel.t_lelong as tarikhlelong')
            ->leftJoin('lelong as lel', 'lel.batchno', '=', 'batchlel.batchno')
            ->leftJoin('gadai as gad', 'gad.norujukan', '=', 'lel.norujukan')
            ->whereNotNull('gad.upah12')
            ->whereNotNull('lel.hargajual')
            ->whereNull('lel.trkhtuntut')
            ->where('lel.baki','>',0)
            ->groupBy('batchlel.batchno')
            ->get()->toArray();

        $batchlelrugi = BatchLel::on($cawangan['mysql'])
            ->selectRaw('count(lel.norujukan) as bilangan,batchlel.batchno as batchno,lel.t_lelong as tarikhlelong')
            ->leftJoin('lelong as lel', 'lel.batchno', '=', 'batchlel.batchno')
            ->leftJoin('gadai as gad', 'gad.norujukan', '=', 'lel.norujukan')
            ->whereNotNull('gad.upah12')
            ->whereNotNull('lel.hargajual')
            ->whereNull('lel.trkhtuntut')
            ->where('lel.baki','<',0)
            ->groupBy('batchlel.batchno')
            ->get()->toArray();

        $batchnosama = [];
        if(sizeof($batchleltuntutbaki) > 0 && sizeof($batchlelrugi) > 0)
        {
            foreach($batchleltuntutbaki as $index=>$bl)
            {
                foreach($batchlelrugi as $index=>$rl)
                {
                    if($bl['batchno'] == $rl['batchno'])
                    {
                        array_push($arraybatch,['batchno' => $bl['batchno'], 'bilangantuntutbaki' => $bl['bilangan'], 'bilanganrugi' => $rl['bilangan'],'tarikhlelong' => $bl['tarikhlelong']]);
                        array_push($batchnosama,$bl['batchno']);
                    }
                }

            }

        }

        $countsama = 0;
        foreach($batchleltuntutbaki as $index=>$bl)
        {

            if($batchnosama)
            {
                $dif=array_intersect($bl,$batchnosama);

                if(!$dif)
                {
                    array_push($arraybatch,['batchno' => $bl['batchno'], 'bilangantuntutbaki' => $bl['bilangan'], 'bilanganrugi' => 0,'tarikhlelong' => $bl['tarikhlelong']]);
                }
            }

        }

        foreach($batchlelrugi as $index=>$br)
        {

            if($batchnosama)
            {
                $dif=array_intersect($br,$batchnosama);

                if(!$dif)
                {
                    array_push($arraybatch,['batchno' => $br['batchno'], 'bilangantuntutbaki' => 0, 'bilanganrugi' => $br['bilangan'],'tarikhlelong' => $br['tarikhlelong']]);
                }
            }

        }

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

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

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

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

        $bulanlepas = $current->subMonth()->toDateString();

        if($request->jenis == 'tuntutbaki')
        {
            $lelong = Lelong::on($cawangan['mysql'])
            ->select('lelong.t_lelong','lelong.norujukan','gadai.nokp','gadai.bakipjm','lelong.bakiupah','lelong.t_jual','lelong.cajlelong','lelong.baki','lelong.cajlain','lelong.gst_hj','lelong.gst_cl','lelong.hargajual')
            ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
            ->where('baki','>',0)
            ->where('batchno',$request->batchno)
            ->whereNotNull('t_jual')
            ->whereNull('trkhtuntut')
            ->orderBy('gadai.t_gadai','asc')
            ->orderBy('gadai.sirig','asc')
            ->where('gadai.taglel','=', 1);
        }else{
            $lelong = Lelong::on($cawangan['mysql'])
            ->select('lelong.t_lelong','lelong.norujukan','gadai.nokp','gadai.bakipjm','lelong.bakiupah','lelong.t_jual','lelong.cajlelong','lelong.baki','lelong.cajlain','lelong.gst_hj','lelong.gst_cl','lelong.hargajual')
            ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
            ->where('baki','<',0)
            ->where('batchno',$request->batchno)
            ->whereNotNull('t_jual')
            ->whereNull('trkhtuntut')
            ->orderBy('gadai.t_gadai','asc')
            ->orderBy('gadai.sirig','asc')
            ->where('gadai.taglel','=', 1);
        }

        $lelonglist = $lelong->get();

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

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

            $daerah = Daerah::on('mysql7')
                    ->where('koddaerah','=',$poskod['koddaerah'])
                    ->first();

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

            array_push($arraylelong,['poskod'=>$customer['poskod'],'negeri' => $negeri['negeri'],'daerah' => $daerah['namadaerah'],'alamat' => $customer['alamat1'],'alamat2' => $customer['alamat2'],'tarikhlelong' => $lel['t_lelong'],'nama' => $customer['nama'], 'telefon1' => $customer['telefon'], 'telefon2' => $customer['telefon2'], 'norujukan' => $lel['norujukan'], 't_jual' => $lel['t_jual'], 'IC' => $lel['nokp'], 'bakipjm' => $lel['bakipjm'], 'bakiupah' => $lel['bakiupah'],'cajlelong' => $lel['cajlelong'],'baki' => $lel['baki'],'cajlain' => $lel['cajlain'],'gst_hj' => $lel['gst_hj'],'gst_cl' => $lel['gst_cl'],'hargajual' => $lel['hargajual']]);
        }

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

    public function exportLelong(Request $request)
    {
        $currentDate = Carbon::now()->toDateString();

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

        if (!$cawangan) {
            Log::error("Export Lelong gagal: cawangan tidak ditemui", ['kodcaw' => $request->kodcaw]);
            return response()->json(['error' => 'Cawangan tidak ditemui'], 404);
        }

        Log::info("Mula Export Lelong", [
            'kodcaw' => $cawangan->kodcaw,
            'nama_cawangan' => $cawangan->details_caw,
        ]);

        // --- Step 1: Batch (Cegah duplicate) ---
        $batchlel = BatchLel::on($cawangan['mysql'])
            ->where('kodcaw', $request->kodcaw)
            ->whereDate('tarikh', $request->tarikh)
            ->where('masadari', $request->masadari)
            ->where('masahingga', $request->masahingga)
            ->first();

        if (!$batchlel) {
            $lastBatchNo = BatchLel::on($cawangan['mysql'])->max('batchno') ?? 0;
            $newBatchNo = $lastBatchNo + 1;

            $batchlel = BatchLel::on($cawangan['mysql'])->create([
                'kodcaw' => $request->kodcaw,
                'batchno' => $newBatchNo,
                'tarikh' => $request->tarikh,
                'tarikh2' => $request->tarikh,
                't_daftar' => $currentDate,
                'masadari' => $request->masadari,
                'masahingga' => $request->masahingga
            ]);

            Log::info("Batch baru dicipta", ['batchno' => $newBatchNo]);
        } else {
            $newBatchNo = $batchlel->batchno;
            Log::info("Batch sedia ada digunakan", ['batchno' => $newBatchNo]);
        }

        // --- Step 2: Siri Lelong Terakhir ---
        $lastSiriLelong = Lelong::on($cawangan['mysql'])->max('sirilel') ?? 0;
        $lelong_arr = [];

        // --- Step 3: Cegah duplicate Lelong ---
        $existingNorujukan = Lelong::on($cawangan['mysql'])
            ->whereIn('norujukan', collect($request->lelongbid)->pluck('norujukan'))
            ->pluck('norujukan')
            ->toArray();

        foreach ($request->lelongbid as $index) {
            if (in_array($index['norujukan'], $existingNorujukan)) {
                Log::warning("Skip Lelong duplicate", ['norujukan' => $index['norujukan']]);
                continue;
            }

            // --- Step 4: Semak / cipta pembeli ---
            $no_pembeli = Pembeli::on($cawangan['mysql'])
                ->where('nokp', $index['user_details']['nokp'])
                ->value('nopembeli');

            if (!$no_pembeli) {
                $last_no_pembeli = Pembeli::on($cawangan['mysql'])
                    ->max('nopembeli') ?? 0;
                $no_pembeli = $last_no_pembeli + 1;

                Pembeli::on($cawangan['mysql'])->create([
                    'nopembeli' => $no_pembeli,
                    'nokp' => $index['user_details']['nokp'],
                    'nama' => $index['user_details']['name'],
                    'alamat1' => $index['user_details']['alamat'],
                    'telefon' => $index['user_details']['notelbimbit'],
                ]);
            }

            // --- Step 5: Update gadai ---
            Gadai::on($cawangan['mysql'])
                ->where('norujukan', $index['norujukan'])
                ->update([
                    'sttebus' => "L",
                    't_update' => $request->tarikh
                ]);

            // --- Step 6: Simpan data Lelong ---
            $lelong_arr[] = [
                'batchno' => $newBatchNo,
                'sirilel' => ++$lastSiriLelong,
                'kodcaw' => $index['kodcaw'],
                'norujukan' => $index['norujukan'],
                't_lelong' => $request->tarikh,
                'hargaasas' => $index['hargaasas'],
                'hargajual' => $index['hargajual'],
                'glcode' => "1000/010",
                't_jual' => $index['t_jual'],
                'nopembeli' => $no_pembeli,
                'jbg' => $index['jbg'],
                'kadarupah' => $index['kadarupah'],
                'upahsimpan' => $index['upahsimpan'],
                'ansuran' => $index['ansuran'],
                'nilaimarhun' => $index['nilaimarhun'],
                'nilaimarhuns' => $index['nmarhuns'],
                'pinjaman' => $index['pinjaman'],
                'bakiupah' => $index['bakiupah'],
                'cajlelong' => $index['cajlelong'],
                'baki' => $index['baki'],
                'teller' => $index['teller'],
                'prkod' => "01",
                'kodgl' => "1000/013",
                'berat' => $index['berat'],
                'marhun' => $index['marhun'],
                'fasa' => $index['fasa'],
                'ujrah' => $index['ujrah'],
                'onepercent' => $index['onepercent'],
                'tagujrah' => $index['tagujrah'],
            ];
        }

        if ($lelong_arr) {
            Lelong::on($cawangan['mysql'])->insert($lelong_arr);
            Log::info("Berjaya simpan lelong baru", ['total' => count($lelong_arr)]);
        }

        // --- Step 7: LELMARHUN (cegah duplicate) ---
        if ($request->lelongbidmarhun) {
            $existingMarhun = LelMarhun::on($cawangan['mysql'])
                ->whereIn('norujukan', collect($request->lelongbidmarhun)->pluck('norujukan'))
                ->pluck('norujukan')
                ->toArray();

            $lelmarhun_arr = collect($request->lelongbidmarhun)
                ->reject(fn($data) => in_array($data['norujukan'], $existingMarhun))
                ->map(function ($data) use ($request, $newBatchNo) {
                    return [
                        'kodcaw' => $request->kodcaw,
                        'norujukan' => $data['norujukan'],
                        'bil' => $data['bil'],
                        'marhun' => $data['marhun'],
                        'nota' => $data['nota'],
                        'karat' => $data['karat'],
                        'berat' => $data['berat'],
                        'harga' => $data['harga'],
                        'n_marhun' => $data['n_marhun'],
                        'hargaasas' => $data['hargaasas'],
                        'batch_no' => $newBatchNo
                    ];
                })
                ->toArray();

            if ($lelmarhun_arr) {
                LelMarhun::on($cawangan['mysql'])->insert($lelmarhun_arr);
                Log::info("LelMarhun baru disimpan", ['total' => count($lelmarhun_arr)]);
            }
        }

        // --- Step 8: GL dan Tunai (check duplicate descpt) ---
        if ($request->tunai > 0) {
            $existsTunai = Tunai::on($cawangan['mysql'])
                ->where('kodcaw', $request->kodcaw)
                ->where('tarikh', $request->tarikh)
                ->where('kodlaluan', 'LELONG')
                ->exists();

            if (!$existsTunai) {
                Tunai::on($cawangan['mysql'])->create([
                    'tarikh' => $request->tarikh,
                    'kodcaw' => $request->kodcaw,
                    'kodlaluan' => "LELONG",
                    'masuk' => $request->tunai,
                    'baki' => $request->tunai,
                ]);
                Log::info("Rekod Tunai lelong dimasukkan");
            } else {
                Log::warning("Skip Tunai duplicate");
            }
        }

        $glDescs = [
            'SERAHAN LELONG ONLINE' => $request->gldetail,
            'SERAHAN LELONG CDM' => $request->gldetailcdm,
        ];

        foreach ($glDescs as $desc => $amount) {
            if ($amount > 0) {
                $existsGl = GlDetail::on($cawangan['mysql'])
                    ->where('kodcaw', $request->kodcaw)
                    ->where('tarikh', $request->tarikh)
                    ->where('descpt', 'like', "%{$desc}%")
                    ->exists();

                if (!$existsGl) {
                    GlDetail::on($cawangan['mysql'])->create([
                        'kodcaw' => $request->kodcaw,
                        'tarikh' => $request->tarikh,
                        'dtacct' => "1000/010",
                        'ktacct' => "1000/020",
                        'descpt' => "{$desc}, {$request->tarikh}",
                        'amaun' => $amount,
                        'teller' => "LELONG ONLINE",
                        'serahan' => $amount,
                    ]);
                    Log::info("Rekod GL dimasukkan", ['desc' => $desc]);
                } else {
                    Log::warning("Skip GL duplicate", ['desc' => $desc]);
                }
            }
        }

        // --- Step 9: Log Akhir ---
        Log::info('Berjaya Export Cawangan:', [
            'kodcaw' => $cawangan->kodcaw,
            'nama_cawangan' => $cawangan->details_caw,
            'batch_baru' => $newBatchNo,
            'total_lelong' => count($lelong_arr),
        ]);

        return response()->json(['status' => 'success']);
    }

    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 getLaporanGadaiRangeDatebyTeller($kodcaw,Request $request){
        // dd($request->all());
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $gadai_data = Gadai::on($cawangan['mysql'])->select('t_gadai','norujukan','nokp','semakbarcode','masa','berat','nilaimarhun','pinjaman','upah12','percentpinj','teller','nokp')
        ->where('t_gadai','>=',$request->mula)
        ->where('t_gadai','<=',$request->akhir)
        ->whereIn('teller', $request->teller)
        ->orderBy('t_gadai')
        ->orderBy('teller','desc')
        ->orderBy('sirig')
        ->get();
        $groupbyteller = $gadai_data->groupBy('teller');

        $gadai = [];

            foreach($groupbyteller as $index=>$gadaiData){
                $total_pembiayaan = $gadaiData->sum('pinjaman');
                $total_gadai = $gadaiData->count('norujukan');
                array_push($gadai,[
                    "total_pembiayaan"=> $total_pembiayaan,
                    "total_gadai"=> $total_gadai,
                    "kodcaw"=> $kodcaw,
                    "teller"=> $index,
                ]);
            }

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


    public function getLaporanTebusRangeDatebyTeller($kodcaw,Request $request){
        // dd($request->all());
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $tebus_data = Tebus::on($cawangan['mysql'])
        ->select('tebus.t_tebus', 'gad.t_gadai','gad.hargajualan','gad.bakihargajualan','gad.bakipjm as gadaibakipjm','tebus.nilaimarhun','tebus.tagterima', 'tebus.teller','tebus.jenistebus','tebus.pinjaman','tebus.bakiupah','tebus.bakipjm','gad.norujukan','gad.nokp','tebus.jbg')
        ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
        ->where('t_tebus','>=',$request->mula)
        ->where('t_tebus','<=',$request->akhir)
        ->whereIn('tebus.teller', $request->teller)
        ->orderBy('tebus.teller')
        ->orderBy('tebus.sirit')
        ->get();
        $groupbyteller = $tebus_data->groupBy('teller');


        $tebus = [];

            foreach($groupbyteller as $index=>$tebusData){
                $total_penebusan = $tebusData->sum('pinjaman');
                $total_tebus = $tebusData->count('norujukan');
                array_push($tebus,[
                    "total_penebusan"=> $total_penebusan,
                    "total_tebus"=> $total_tebus,
                    "teller"=> $index,
                ]);
            }

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

    public function getLaporanGadaiRangeDatebyPenilai($kodcaw,Request $request){
        // dd($request->all());
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $gadai_data = Gadai::on($cawangan['mysql'])->select('t_gadai','norujukan','nokp','semakbarcode','masa','berat','nilaimarhun','pinjaman','upah12','percentpinj','penilai','nokp')
        ->where('t_gadai','>=',$request->mula)
        ->where('t_gadai','<=',$request->akhir)
        // ->whereIn('penilai', $request->penilai)
        ->orderBy('t_gadai')
        ->orderBy('penilai')
        ->orderBy('sirig')
        ->get();
        // dd($gadai_data);
        $groupbypenilai = $gadai_data->groupBy('penilai');

        $gadai = [];

            foreach($groupbypenilai as $index=>$gadaiData){
                $total_pembiayaan = $gadaiData->sum('pinjaman');
                $total_gadai = $gadaiData->count('norujukan');
                array_push($gadai,[
                    "total_pembiayaan"=> $total_pembiayaan,
                    "total_gadai"=> $total_gadai,
                    "kodcaw"=> $kodcaw,
                    "penilai"=> $index,
                ]);
            }

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

    public function showAllLelongByCawanganBatchno($kodcaw)
    {
        $item = ['PMT', 'batu', 'permata'];

        // Semak kewujudan cawangan dulu
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $kodcaw)->first();
        if (!$cawangan) {
            return response()->json(['error' => 'Cawangan tidak dijumpai.'], 404);
        }

        // Ambil data lelong
        $lelong_data = Lelong::on($cawangan['mysql'])
            ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
            ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
            ->whereNull('upah12')
            ->where(function ($query) use ($item) {
                foreach ($item as $i) {
                    $query->orWhere('lelmarhun.nota', 'like', '%' . $i . '%');
                }
            })
            ->orderBy('lelong.t_lelong', 'asc')
            ->select(
                'lelong.t_lelong',
                'gadai.t_gadai',
                'gadai.nokp',
                'lelong.pinjaman',
                'lelong.baki',
                'lelong.batchno',
                'lelong.norujukan'
            )
            ->distinct()
            ->get();

        // Group by batch number
        $groupbybatch = $lelong_data->groupBy('batchno');
        $lelong = [];

        foreach ($groupbybatch as $batchno => $lelongData) {
            $total_pembiayaan = $lelongData->sum('pinjaman');
            $total_lelong = $lelongData->count();
            $t_lelong = optional($lelongData->first())->t_lelong; // elak error kalau kosong

            $lelong[] = [
                't_lelong'          => $t_lelong,
                'batchno'           => $batchno,
                'total_pembiayaan'  => $total_pembiayaan,
                'total_lelong'      => $total_lelong,
                'kodcaw'            => $kodcaw,
            ];
        }
        return response()->json($lelong);
    }

    public function showAllLelongByCawanganbyBatchno($kodcaw,$batchno)
    {
        $item = array('PMT','batu','permata');
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong_data = Lelong::on($cawangan['mysql'])
        ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
        ->where('batchno',$batchno)
        ->whereNull('upah12')
        // ->where('lelong.marhun', 'like', '%PMT%')
        // ->orWhere('lelong.marhun', 'like', '%batu%')
        // ->orWhere('lelong.marhun', 'like', '%permata%')
        ->Where(function ($query) use($item) {
            for ($i = 0; $i < count($item); $i++){
               $query->orwhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
            }
        })
        ->orderBy('lelong.t_lelong','asc')
        ->select('lelong.t_lelong','gadai.t_gadai','gadai.nokp','lelong.pinjaman','lelong.baki','lelong.batchno','lelong.norujukan')
        ->where('batchno',$batchno)
        ->whereNull('upah12')
        ->distinct()
        ->get();
        // dd($lelong_data);
        $lelong = [];
        foreach($lelong_data as $index=>$lelongData){
            // dd($lelongData->norujukan);
            $lelmarhun = LelMarhun::on($cawangan['mysql'])
            ->where('norujukan',$lelongData['norujukan'])
            ->where('batch_no',$batchno)
            // ->Where('nota', 'like', '%PMT%')
            ->Where(function ($query) use($item) {
                for ($i = 0; $i < count($item); $i++){
                   $query->orwhere('nota', 'like',  '%' . $item[$i] .'%');
                }
            })
            ->get();
            // dd($lelmarhun->norujukan);
            array_push($lelong,[
                "norujukan"=>  $lelongData->norujukan,
                "nokp"=>  $lelongData->nokp,
                "t_gadai"=>  $lelongData->t_gadai,
                "t_lelong"=>  $lelongData->t_lelong,
                "pinjaman"=>  $lelongData->pinjaman,
                "baki"=>  $lelongData->baki,
                "listmarhun"=> $lelmarhun,
                "kodcaw"=> $kodcaw,
                "kuantiti"=> $lelmarhun->count('norujukan'),
            ]);
            // dd($lelong);
        }


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

    public function showAllLelongByCawanganbyBatchnoall($kodcaw)
    {
        $item = array('PMT','batu','permata');
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong_data = Lelong::on($cawangan['mysql'])
        ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
        ->whereNull('upah12')
        // ->where('lelmarhun.nota', 'like', '%PMT%')
        // ->orWhere('lelmarhun.nota', 'like', '%batu%')
        // ->orWhere('lelmarhun.nota', 'like', '%permata%')
        ->where(function ($query) use($item) {
            for ($i = 0; $i < count($item); $i++){
               $query->orWhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
            }
        })
        ->select('lelong.batchno','lelong.t_lelong','gadai.t_gadai','gadai.nokp','lelong.pinjaman','lelong.baki','lelong.batchno','lelong.norujukan','gadai.marhun')
        ->orderBy('lelong.t_lelong')
        ->whereNull('upah12')
        ->distinct()
        ->get();
        // dd($lelong_data);
        $lelong = [];
        foreach($lelong_data as $index=>$lelongData){

            // dd($lelongData->norujukan);
            $lelmarhun = LelMarhun::on($cawangan['mysql'])
            ->where('norujukan',$lelongData['norujukan'])
            // ->where('batch_no',$lelongData['batchno'])
            // ->where('nota', 'like', '%PMT%')
            // ->orWhere('nota', 'like', '%batu%')
            ->where(function ($query) use($item) {
                for ($i = 0; $i < count($item); $i++){
                   $query->orWhere('nota', 'like',  '%' . $item[$i] .'%');
                }
            })
            ->where('norujukan',$lelongData['norujukan'])
            ->where('batch_no',$lelongData['batchno'])
            ->distinct()
            ->get();

            array_push($lelong,[
                "batchno"=>  $lelongData->batchno,
                "norujukan"=>  $lelongData->norujukan,
                "nokp"=>  $lelongData->nokp,
                "t_gadai"=>  $lelongData->t_gadai,
                "t_lelong"=>  $lelongData->t_lelong,
                "pinjaman"=>  $lelongData->pinjaman,
                "baki"=>  $lelongData->baki,
                "listmarhun"=> $lelmarhun,
                "kodcaw"=> $kodcaw,
                "kuantiti"=> $lelmarhun->count('norujukan'),
                "marhungadai"=> $lelongData->marhun,
            ]);
            // dd($lelong);
        }


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

    public function showAllLelongByCawanganbyBatchnoallT($kodcaw)
    {
        $item = array('PMT','batu','permata');
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong_data = Lelong::on($cawangan['mysql'])
        ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
        ->whereNotNull('upah12')
        // ->where('lelmarhun.nota', 'like', '%PMT%')
        // ->orWhere('lelmarhun.nota', 'like', '%batu%')
        // ->orWhere('lelmarhun.nota', 'like', '%permata%')
        ->Where(function ($query) use($item) {
            for ($i = 0; $i < count($item); $i++){
               $query->orwhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
            }
        })
        ->select('lelong.batchno','lelong.t_lelong','gadai.t_gadai','gadai.nokp','lelong.pinjaman','lelong.baki','lelong.batchno','lelong.norujukan','gadai.marhun')
        ->orderBy('lelong.t_lelong')
        ->whereNotNull('upah12')
        ->distinct()
        ->get();
        // dd($lelong_data);
        $lelong = [];
        foreach($lelong_data as $index=>$lelongData){

            $lelmarhun = LelMarhun::on($cawangan['mysql'])
            ->where('norujukan',$lelongData['norujukan'])
            ->where('batch_no',$lelongData['batchno'])
            // ->where('nota', 'like', '%PMT%')
            // ->orWhere('nota', 'like', '%batu%')
            // ->orWhere('nota', 'like', '%permata%')
            ->Where(function ($query) use($item) {
                for ($i = 0; $i < count($item); $i++){
                   $query->orwhere('nota', 'like',  '%' . $item[$i] .'%');
                }
            })
            ->where('batch_no',$lelongData['batchno'])
            ->where('norujukan',$lelongData['norujukan'])
            ->distinct()
            ->get();
            // dd($lelmarhun->norujukan);
            array_push($lelong,[
                "batchno"=>  $lelongData->batchno,
                "norujukan"=>  $lelongData->norujukan,
                "nokp"=>  $lelongData->nokp,
                "t_gadai"=>  $lelongData->t_gadai,
                "t_lelong"=>  $lelongData->t_lelong,
                "pinjaman"=>  $lelongData->pinjaman,
                "baki"=>  $lelongData->baki,
                "listmarhun"=> $lelmarhun,
                "kodcaw"=> $kodcaw,
                "kuantiti"=> $lelmarhun->count('norujukan'),
                "marhungadai"=> $lelongData->marhun,
            ]);
            // dd($lelong);
        }


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

    public function showAllLelongByCawanganBatchnoT($kodcaw)
    {
        $item = array('PMT','batu','permata');
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong_data = Lelong::on($cawangan['mysql'])
        ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
        ->whereNotNull('upah12')
        // ->where('lelmarhun.nota', 'like', '%PMT%')
        // ->orWhere('lelmarhun.nota', 'like', '%batu%')
        // ->orWhere('lelmarhun.nota', 'like', '%permata%')
        ->Where(function ($query) use($item) {
            for ($i = 0; $i < count($item); $i++){
               $query->orwhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
            }
        })
        ->orderBy('lelong.t_lelong','asc')
        ->select('lelong.t_lelong','gadai.t_gadai','gadai.nokp','lelong.pinjaman','lelong.baki','lelong.batchno','lelong.norujukan')
        ->whereNotNull('upah12')
        ->distinct()
        ->get();
        // dd($lelong_data);
        $groupbybatch = $lelong_data->groupBy('batchno');
        $lelong = [];

        foreach($groupbybatch as $index=>$lelongData){
            $total_pembiayaan = $lelongData->sum('pinjaman');
            // dd($total_pembiayaan);
            $total_lelong = $lelongData->count('norujukan');
            array_push($lelong,[
                // "upah12"=>  $lelongData->upah12,
                "t_lelong"=>  $lelongData->groupBy('t_lelong'),
                "batchno"=>  $index,
                "total_pembiayaan"=> $total_pembiayaan,
                "total_lelong"=> $total_lelong,
                "kodcaw"=> $kodcaw,
            ]);
            // dd($lelong);
        }
        return response()->json($lelong);
    }

    public function showAllLelongByCawanganbyBatchnoT($kodcaw,$batchno)
    {
        $item = array('PMT','batu','permata');
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $lelong_data = Lelong::on($cawangan['mysql'])
        ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
        ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
        ->where('batchno',$batchno)
        ->whereNotNull('upah12')
        // ->where('lelmarhun.nota', 'like', '%PMT%')
        // ->orWhere('lelmarhun.nota', 'like', '%batu%')
        // ->orWhere('lelmarhun.nota', 'like', '%permata%')
        ->Where(function ($query) use($item) {
            for ($i = 0; $i < count($item); $i++){
               $query->orwhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
            }
        })
        ->orderBy('lelong.t_lelong','asc')
        ->select('lelong.t_lelong','gadai.t_gadai','gadai.nokp','lelong.pinjaman','lelong.baki','lelong.batchno','lelong.norujukan')
        ->where('batchno',$batchno)
        ->whereNotNull('upah12')
        ->distinct()
        ->get();
        // dd($lelong_data);
        $lelong = [];
        foreach($lelong_data as $index=>$lelongData){
            // dd($lelongData->norujukan);
            $lelmarhun = LelMarhun::on($cawangan['mysql'])
            ->where('norujukan',$lelongData['norujukan'])
            ->where('batch_no',$batchno)
            // ->where('nota', 'like', '%PMT%')
            // ->orWhere('nota', 'like', '%batu%')
            // ->orWhere('nota', 'like', '%permata%')
            ->Where(function ($query) use($item) {
                for ($i = 0; $i < count($item); $i++){
                   $query->orwhere('lelmarhun.nota', 'like',  '%' . $item[$i] .'%');
                }
            })
            ->where('batch_no',$batchno)
            ->where('norujukan',$lelongData['norujukan'])
            ->distinct()
            ->get();
            // dd($lelmarhun->norujukan);
            array_push($lelong,[
                "upah12"=>  $lelongData->upah12,
                "norujukan"=>  $lelongData->norujukan,
                "nokp"=>  $lelongData->nokp,
                "t_gadai"=>  $lelongData->t_gadai,
                "t_lelong"=>  $lelongData->t_lelong,
                "pinjaman"=>  $lelongData->pinjaman,
                "baki"=>  $lelongData->baki,
                "listmarhun"=> $lelmarhun,
                "kodcaw"=> $kodcaw,
                "kuantiti"=> $lelmarhun->count('norujukan'),
            ]);
            // dd($lelong);
        }


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


    public function kiraupahUjrahOnePercent($kodcaw,$norujukan){
        $onepercentservices = new OnePercentServices();

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

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }

        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];
        $array_upah = $onepercentservices->kiraanKeuntunganSebenar($gadai_data['pinjaman'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['percentpinj']);
        $ujrah = $bilang_bln * $array_upah['ujrah'];
        $onepercent = $bilang_bln * $array_upah['onepercent'];
        $onepercent_semasa = $onepercent;
        $ujrah_semasa = $ujrah;

        return ['ujrah' => $ujrah_semasa, 'onepercent' => $onepercent_semasa];
    }

    // public function kiraupahUjrahOnePercentRebate($kodcaw,$norujukan){
    //     // $onepercentservices = new OnePercentServices();
    //     $onepercentservices = new Calculation();

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

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

    //         if($gadai_data['tempoh'] >= 12.0){
    //         $tempoh = 12;
    //     }else{
    //         $tempoh = $gadai_data['tempoh'];
    //     }

    //     $bilang_bln = $tempoh - $gadai_data['tempohbayar'];
    //     $array_upah = $onepercentservices->kiraanKeuntunganRebet($gadai_data['bakipjm'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['margin_semasa']);
    //     $ujrah_semasa = $onepercentservices->getRoundedMethod($bilang_bln * $array_upah['ujrah']);
    //     $onepercent_semasa = $onepercentservices->getRoundedMethod($bilang_bln * $array_upah['onepercent']);

    //     return ['ujrah' => $ujrah_semasa, 'onepercent' => $onepercent_semasa];
    // }

    public function kiraupahUjrahOnePercentRebate($kodcaw,$norujukan){
        // $master = new MasterServices($kodcaw);
        // $response = $master->kiraupahUjrahOnePercentRebate($kodcaw,$norujukan);

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

        $onepercentservices = new Calculation();

        // $cawangan = $kodcaw;

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        if($gadai_data['tempoh'] >= 12.0){
            $tempoh = 12;
        }else{
            $tempoh = $gadai_data['tempoh'];
        }

        $bilang_bln = $tempoh - $gadai_data['tempohbayar'];
        $array_upah = $onepercentservices->kiraanKeuntunganRebet($gadai_data['bakipjm'],$gadai_data['nilaimarhun'],$gadai_data['kadarupah'],$gadai_data['margin_semasa']);
        // $ujrah_rounded = $onepercentservices->getRoundedMethod($array_upah['ujrah']);
        // $keuntungan_rounded = $onepercentservices->getRoundedMethod($array_upah['onepercent']);
        $ujrah = $bilang_bln * $array_upah['ujrah'];
        $onepercent = $bilang_bln * $array_upah['onepercent'];
        $ujrah = $onepercentservices->getRoundedMethod($ujrah);
        $onepercent = $onepercentservices->getRoundedMethod($onepercent);

        return ['ujrah' => $ujrah, 'onepercent' => $onepercent];
    }

    public function upahTawarruqByTarikh(Request $request){
        $master = new MasterServices($request->kodcaw);
        $response = $master->kiraupahTawarruqByTarikh($request->kodcaw,$request->norujukan,$request->tarikh,$request);

        return $response;
    }


    public function showTuntutBakiRangeDate($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->mula)
            ->where('tarikh','<=',$request->akhir)
            ->get();

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

    public function LaporanLelong(Request $request)
    {
        // Validate required input
        $validator = Validator::make($request->all(), [
            'kodcaw' => 'required|string',
            'tarikhmula' => 'required|date',
            'tarikhhingga' => 'required|date|after_or_equal:tarikhmula',
            'batchno' => 'nullable|string'
        ]);
        
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 400);
        }
        

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

        if (!$cawangan) {
            return response()->json(['error' => 'Invalid kodcaw'], 403);
        }

        // Query lelong data
        $lelong_query = Lelong::on($cawangan['mysql'])
            ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
            ->join('lelmarhun', 'lelmarhun.norujukan', '=', 'lelong.norujukan')
            ->join('pembeli', 'pembeli.nopembeli', '=', 'lelong.nopembeli')
            ->whereBetween('lelong.t_lelong', [$request->tarikhmula, $request->tarikhhingga]);

        // Optional: Filter by batch number
        if ($request->has('batchno') && !empty($request->batchno)) {
            $lelong_query->where('lelong.batchno', $request->batchno);
        }
        // Select required fields
        $lelong_data = $lelong_query->select(
            'lelong.batchno', 'lelong.t_lelong', 'gadai.t_gadai', 'gadai.nokp', 'lelong.pinjaman', 
            'lelong.baki', 'lelong.norujukan', 'gadai.marhun', 'lelong.nilaimarhun', 
            'lelong.bakiupah', 'lelong.cajlelong', 'lelong.hargajual', 'lelong.hargaasas', 
            'pembeli.nama', 'pembeli.nokp AS nokppembeli', 'lelong.tagujrah', 'lelong.ujrah', 
            'lelong.onepercent', 'lelong.teller'
        )
        ->distinct()
        ->orderByRaw("
        SUBSTRING_INDEX(SUBSTRING_INDEX(lelong.norujukan, '-', 1), '^[A-Za-z]+', -1),
        CAST(SUBSTRING_INDEX(lelong.norujukan, '-', -1) AS UNSIGNED)
        ")
        ->get();
        // dd($lelong_data);

        // If no data found, return a message
        if ($lelong_data->isEmpty()) {
            return response()->json([
                'message' => 'Tiada lelongan dalam tarikh dipilih.',
                'data' => [],
                'totals' => [
                    'total_pinjaman' => 0,
                    'total_nilaimarhun' => 0,
                    'total_keuntungan' => 0,
                    'total_onepercent' => 0,
                    'total_ujrah' => 0,
                    'total_cajlelong' => 0,
                    'total_hargajual' => 0,
                    'total_baki' => 0,
                    'total_hargaasas' => 0
                ]
            ]);
        }

        // Calculate totals safely (prevent null values)
        $totals = [
            'total_pinjaman' => $lelong_data->sum(fn($item) => $item->pinjaman ?? 0),
            'total_nilaimarhun' => $lelong_data->sum(fn($item) => $item->nilaimarhun ?? 0),
            'total_keuntungan' => $lelong_data->sum(fn($item) => $item->bakiupah ?? 0),
            'total_onepercent' => $lelong_data->sum(fn($item) => $item->onepercent ?? 0),
            'total_ujrah' => $lelong_data->sum(fn($item) => $item->ujrah ?? 0),
            'total_cajlelong' => $lelong_data->sum(fn($item) => $item->cajlelong ?? 0),
            'total_hargajual' => $lelong_data->sum(fn($item) => $item->hargajual ?? 0),
            'total_baki' => $lelong_data->sum(fn($item) => $item->baki ?? 0),
            'total_hargaasas' => $lelong_data->sum(fn($item) => $item->hargaasas ?? 0)
        ];
       
        $tarikh_lelongs = $lelong_data->pluck('t_lelong')->first(); // Get first date

        // Return JSON response
        return response()->json([
            'data' => $lelong_data,
            'totals' => $totals,
            'tarikh_lelong' => $tarikh_lelongs 
        ]);
    }


    public function LookupBatchLel($kodcaw,Request $request)
    {
        $harini = Carbon::now();
        $harini = new Carbon;
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        
        $batchlel = BatchLel::on($cawangan['mysql'])
        ->select('batchno','tarikh')
        ->when($kodcaw, function ($query, $kodcaw) {
            return $query->where('kodcaw', $kodcaw);
        })
        ->orderBy('tarikh', 'DESC')
        ->get();
        
        return response()->json($batchlel);

    }
    

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

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

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

            $belumtuntutbaki = Lelong::on($cawangan['mysql'])
                ->select('lelong.t_jual','lelong.norujukan','lelong.baki','gadai.nokp','gadai.pinjaman','lelong.bakiupah','lelong.cajlelong','lelong.hargajual','lelong.hargaasas','lelong.nilaimarhun')
                ->leftJoin('gadai', 'gadai.norujukan', '=', 'lelong.norujukan')
                ->where('t_jual','>=',$request->mula)
                ->where('t_jual','<=',$request->akhir)
                ->where('baki','>',0)
                ->whereNull('trkhtuntut');
        
        $belumtuntut = $belumtuntutbaki->get();

        $arrayblm = [];
        foreach($belumtuntut as $index=>$blm)
        {
            $customer = Customer::on('mysql7')
                    ->select('nama','telefon','telefon2','alamat1','alamat2','poskod','koddaerah')
                    ->where('kpbaru','=',$blm['nokp'])
                    ->orWhere('kplama','=',$blm['nokp'])
                    ->first();
            array_push($arrayblm,['nama'=>$customer['nama'],'nokp'=>$blm['nokp'],'norujukan'=>$blm['norujukan'],'t_jual'=>$blm['t_jual'],'hargajual'=>$blm['hargajual'],'pinjaman'=>$blm['pinjaman'],'bakiupah'=>$blm['bakiupah'],'cajlelong'=>$blm['cajlelong'],'baki'=>$blm['baki'],'hargaasas'=>$blm['hargaasas'],'nilaimarhun'=>$blm['nilaimarhun']]);
            
        }

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

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

        $date = $request->tarikh;

        $rugiLelong = TuntutBaki::on($cawangan['mysql'])
                    ->whereDate('tarikh', $date)
                    ->where('jumlah', '<', 0)
                    ->where('teller','=', $request->kodlaluan)
                    ->sum('jumlah');

        $bakiLelong = TuntutBaki::on($cawangan['mysql'])
                    ->whereDate('tarikh', $date)
                    ->where('jumlah', '>', 0)
                    ->where('teller','=', $request->kodlaluan)
                    ->sum('jumlah');
        
        return response()->json([
                'tarikh' => $date,
                'cawangan' => $kodcaw,
                'rugi_lelong' => $rugiLelong,
                'baki_lelong' => $bakiLelong
            ], 200);
    }

}
