<?php

namespace App\Http\Controllers;

use App\Gadai;
use App\Marhun;
use App\Cawangan;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\Advansur;
use App\Tebus;
use App\InOutMar;
use App\Wakil;
use App\imbangdugalama;
use App\Customer;
use App\Lelong;
use App\HapusKira;
use App\Parameter;
use App\Panjar;
use App\HargaEmas;
use App\Moratorium;
use App\Audit;
use App\LookupWakil;

use App\StokAudit1;
use App\StokAudit2;
use App\StokAudit3;
use App\StokAudit4;
use App\StokAudit5;
use App\StokAudit6;
use App\StokAudit7;
use App\StokAudit8;
use App\StokAudit9;
use App\StokAudit10;
use App\StokAudit11;
use App\StokAudit12;

use App\AkruNet;
use App\Services\MasterServices;
use App\WakilSurat;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Log;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class TebusController extends Controller
{
    public function tebusTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $tagbaru = Gadai::on($cawangan['mysql'])->where('norujukan',$norujukan)->pluck('tagbaru');
        $jeniskeuntungan = ($tagbaru[0] == 0) ? 'asal' : 'onepercent';
        $master = new MasterServices($kodcaw);
        $response = $master->tebusTawarruq($kodcaw,$norujukan,$jeniskeuntungan);

        return $response;
    }

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

        return $response;
    }

    public function kiraupahTawarruq($kodcaw,$norujukan,$jeniskeuntungan){
        $master = new MasterServices($kodcaw);
        $response = $master->kiraUpahTawarruq($kodcaw,$norujukan,$jeniskeuntungan);

        return $response;
    }

    public function kiraUpahRebet($kodcaw,$norujukan,Request $request){
        $jeniskeuntungan = ($request->jeniskeuntungan == 'onepercent') ? 'onepercent' : 'asal';
        $master = new MasterServices($kodcaw);
        $response = $master->kiraupahRebet($kodcaw,$norujukan,$jeniskeuntungan);

        return $response;
    }

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

        return $response;
    }

    public function upahTawarruq($kodcaw,$norujukan,Request $request){
        $jeniskeuntungan = ($request->jeniskeuntungan == 'onepercent') ? 'onepercent' : 'asal';
        $master = new MasterServices($kodcaw);
        $response = $master->upahTawarruq($kodcaw,$norujukan,$jeniskeuntungan);

        return $response;
    }

    public function upahRebetTawarruq($kodcaw,$norujukan,Request $request){
        $jeniskeuntungan = ($request->jeniskeuntungan == 'onepercent') ? 'onepercent' : 'asal';
        $master = new MasterServices($kodcaw);
        $response = $master->upahRebetTawarruq($kodcaw,$norujukan,$jeniskeuntungan);

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

    public function getMoratorium(){
        $bln_mora = Moratorium::first();

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

    public function updateMoratorium(Request $request){

    }

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

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

    function rebetselepastawarruq($kodcaw,$norujukan,$jeniskeuntungan){
        $master = new MasterServices($kodcaw);
        $response = $master->rebetselepastawarruq($kodcaw,$norujukan);

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

    public function getLaporanTebus($kodcaw,$tarikh){
        $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','tebus.ujrah','tebus.onepercent','gad.tagbaru')
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
               // ->join('online_arrahn.customer as cust', function($join)
               // {
               //     $join->on('gad.nokp', '=', 'cust.kpbaru');
               //     $join->orOn('gad.nokp', '=', 'cust.kplama');
               // })
               // ->join('online_arrahn.transaksi_keuntungan as trans','tebus.norujukan','=','trans.norujukan')
                ->where('tebus.t_tebus','=',$tarikh)
                ->groupBy('tebus.norujukan')
                ->orderBy('tebus.teller')
                ->orderBy('tebus.sirit')
                ->get();

	    $tebus = [];
        if($tebus_data){
            foreach($tebus_data as $index=>$tebusData){
                $customer_info = Customer::on('mysql7')->where('kplama','=',$tebusData['nokp'])->orWhere('kpbaru','=',$tebusData['nokp'])->first();

                $trans = TransaksiKeuntungan::on('mysql7')->where('norujukan',$tebusData['norujukan'])->orderBy('tarikh_bayaran','desc')->first();
                array_push($tebus,[
                    "t_tebus"=>$tebusData['t_tebus'],
                    "t_gadai"=>$tebusData['t_gadai'],
                    "hargajualan"=>$tebusData['hargajualan'],
                    "bakihargajualan"=>$tebusData['bakihargajualan'],
                    "gadaibakipjm"=>$tebusData['gadaibakipjm'],
                    "tarikh_bayaran"=>$trans['tarikh_bayaran'],
                    "nilaimarhun"=>$tebusData['nilaimarhun'],
                    "tagterima"=>$tebusData['tagterima'],
                    "teller"=>$tebusData['teller'],
                    "jenistebus"=>$tebusData['jenistebus'],
                    "pinjaman"=>$tebusData['pinjaman'],
                    "bakiupah"=>$tebusData['bakiupah'],
                    "bakipjm"=>$tebusData['bakipjm'],
                    "norujukan"=>$tebusData['norujukan'],
                    "nama"=>$customer_info['nama'],
                    "nokp"=>$tebusData['nokp'],
                    "jbg"=>$tebusData['jbg'],
                    "ujrah"=>$trans['ujrah_rebet'],
                    "onepercent"=>$trans['onepercent_rebet']

                ]);
            }
        }

        usort($tebus, function ($a, $b) {
            $compare_teller = strcmp($a['teller'], $b['teller']);

            if ($compare_teller === 0) {
                return strcmp($a['t_tebus'], $b['t_tebus']);
            }

            return $compare_teller;
        });

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


    public function getLaporanTebusUjrah($kodcaw, Request $request){
        $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',
        'tebus.ujrah',
        'tebus.onepercent',
        'gad.tagbaru'
    )
    ->join('gadai as gad', 'gad.norujukan', '=', 'tebus.norujukan')
    ->where('tebus.t_tebus', '>=', $request->mula)
    ->where('tebus.t_tebus', '<=', $request->akhir)
    ->groupBy('tebus.norujukan')
    ->orderBy('tebus.teller')
    ->orderBy('tebus.sirit')
    ->get();

	    $tebus = [];
        if($tebus_data){
            foreach($tebus_data as $index=>$tebusData){
                $customer_info = Customer::on('mysql7')->where('kplama','=',$tebusData['nokp'])->orWhere('kpbaru','=',$tebusData['nokp'])->first();

                $trans = TransaksiKeuntungan::on('mysql7')->where('norujukan',$tebusData['norujukan'])->orderBy('tarikh_bayaran','desc')->first();
                array_push($tebus,[
                    "t_tebus"=>$tebusData['t_tebus'],
                    "t_gadai"=>$tebusData['t_gadai'],
                    "hargajualan"=>$tebusData['hargajualan'],
                    "bakihargajualan"=>$tebusData['bakihargajualan'],
                    "gadaibakipjm"=>$tebusData['gadaibakipjm'],
                    "tarikh_bayaran"=>$trans['tarikh_bayaran'],
                    "nilaimarhun"=>$tebusData['nilaimarhun'],
                    "tagterima"=>$tebusData['tagterima'],
                    "teller"=>$tebusData['teller'],
                    "jenistebus"=>$tebusData['jenistebus'],
                    "pinjaman"=>$tebusData['pinjaman'],
                    "bakiupah"=>$tebusData['bakiupah'],
                    "bakipjm"=>$tebusData['bakipjm'],
                    "norujukan"=>$tebusData['norujukan'],
                    "nama"=>$customer_info['nama'],
                    "nokp"=>$tebusData['nokp'],
                    "jbg"=>$tebusData['jbg'],
                    "ujrah"=>$trans['ujrah_rebet'],
                    "onepercent"=>$trans['onepercent_rebet'],
                    "tagbaru"=>$tebusData['tagbaru']

                ]);
            }
        }

        usort($tebus, function ($a, $b) {
            $compare_teller = strcmp($a['teller'], $b['teller']);

            if ($compare_teller === 0) {
                $compare_tebus = strcmp($a['t_tebus'], $b['t_tebus']);

                if ($compare_tebus === 0) {
                    return $a['tarikh_bayaran'] <=> $b['tarikh_bayaran'];
                }

                return $compare_tebus;
            }

            return $compare_teller;
        });

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

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

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

        $tebusarrahn = Tebus::on($cawangan['mysql'])
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('t_tebus','=',$request->tarikh)
                ->whereNull('hargajualan');

        $totalpenebusanarrahn = $tebusarrahn->sum('tebus.pinjaman');
        $bilpenebusanarrahn = $tebusarrahn->count();
        $totalkeuntunganarrahn = $tebusarrahn->sum('tebus.bakiupah');
        $totalujraharrahn = $tebusarrahn->sum('tebus.ujrah');
        $totalonepercentarrahn = $tebusarrahn->sum('tebus.onepercent');


        $tebustawarruq = Tebus::on($cawangan['mysql'])
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('t_tebus','=',$request->tarikh)
                ->whereNotNull('hargajualan');

        $tebustawarruqansuran = Tebus::on($cawangan['mysql'])
        ->select('tebus.bakiupah','tebus.norujukan')
        ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
        ->where('t_tebus','=',$request->tarikh)
        ->whereNotNull('hargajualan')
        ->where('hargajualan','<>','bakihargajualan');

        // dd($tebustawarruqansuran);

        // $totalpenebusantawarruq = ($tebustawarruq->sum('tebus.pinjaman') - $tebustawarruqansuran->sum('gad.pinjaman')) + $tebustawarruqansuran->sum('gad.bakipjm');
        $totalpenebusantawarruq = $tebustawarruq->sum('tebus.pinjaman');
        $bilpenebusantawarruq = $tebustawarruq->count();
        $totalrebatetawarruq = $tebustawarruq->sum('tebus.rebate');
        $totalkeuntungantawarruq = $tebustawarruq->sum('tebus.bakiupah');
        $totalujrahtawarruq = $tebustawarruq->sum('tebus.ujrah');
        $totalonepercenttawarruq = $tebustawarruq->sum('tebus.onepercent');



        // dd($totalkeuntunganarrahn,$totalkeuntungantawarruq);

        $array_penebusan = [
                            'bilarrahn' => $bilpenebusanarrahn,
                            'totalarrahn' => $totalpenebusanarrahn,
                            'keuntunganarrahn' => $totalkeuntunganarrahn,
                            'ujraharrahn' => $totalujraharrahn,
                            'onepercentarrahn' => $totalonepercentarrahn,

                            'biltawarruq' => $bilpenebusantawarruq,
                            'totaltawarruq' => $totalpenebusantawarruq,
                            'totalrebate' => $totalrebatetawarruq,
                            'keuntungantawarruq' => $totalkeuntungantawarruq,
                            'ujrahtawarruq' => $totalujrahtawarruq,
                            'onepercenttawarruq' => $totalonepercenttawarruq
                        ];

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

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

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

        $tebusarrahn = Tebus::on($cawangan['mysql'])
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('tebus.t_tebus','>=',$request->mula)
                ->where('tebus.t_tebus','<=',$request->akhir)
                ->whereNull('hargajualan');

        $totalpenebusanarrahn = $tebusarrahn->sum('tebus.pinjaman');
        $bilpenebusanarrahn = $tebusarrahn->count();
        $totalkeuntunganarrahn = $tebusarrahn->sum('tebus.bakiupah');
        $totalujraharrahn = $tebusarrahn->sum('tebus.ujrah');
        $totalonepercentarrahn = $tebusarrahn->sum('tebus.onepercent');


        $tebustawarruq = Tebus::on($cawangan['mysql'])
                ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
                ->where('tebus.t_tebus','>=',$request->mula)
                ->where('tebus.t_tebus','<=',$request->akhir)
                ->whereNotNull('hargajualan');

        $tebustawarruqansuran = Tebus::on($cawangan['mysql'])
        ->select('tebus.bakiupah','tebus.norujukan')
        ->join('gadai as gad','gad.norujukan','=','tebus.norujukan')
        ->where('tebus.t_tebus','>=',$request->mula)
        ->where('tebus.t_tebus','<=',$request->akhir)
        ->whereNotNull('hargajualan')
        ->where('gad.tagbaru','=',1)
        ->where('hargajualan','<>','bakihargajualan');

        // dd($tebustawarruqansuran);

        // $totalpenebusantawarruq = ($tebustawarruq->sum('tebus.pinjaman') - $tebustawarruqansuran->sum('gad.pinjaman')) + $tebustawarruqansuran->sum('gad.bakipjm');
        $totalpenebusantawarruq = $tebustawarruq->sum('tebus.pinjaman');
        $bilpenebusantawarruq = $tebustawarruq->count();
        $totalrebatetawarruq = $tebustawarruq->sum('tebus.rebate');
        $totalkeuntungantawarruq = $tebustawarruq->sum('tebus.bakiupah');
        $totalujrahtawarruq = $tebustawarruq->sum('tebus.ujrah');
        $totalonepercenttawarruq = $tebustawarruq->sum('tebus.onepercent');



        // dd($totalkeuntunganarrahn,$totalkeuntungantawarruq);

        $array_penebusan = [
                            'bilarrahn' => $bilpenebusanarrahn,
                            'totalarrahn' => $totalpenebusanarrahn,
                            'keuntunganarrahn' => $totalkeuntunganarrahn,
                            'ujraharrahn' => $totalujraharrahn,
                            'onepercentarrahn' => $totalonepercentarrahn,

                            'biltawarruq' => $bilpenebusantawarruq,
                            'totaltawarruq' => $totalpenebusantawarruq,
                            'totalrebate' => $totalrebatetawarruq,
                            'keuntungantawarruq' => $totalkeuntungantawarruq,
                            'ujrahtawarruq' => $totalujrahtawarruq,
                            'onepercenttawarruq' => $totalonepercenttawarruq
                        ];

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

    public function listPenebusanBaru($kodcaw){

        $current = Carbon::now();
        $current = new Carbon();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $gadai = Tebus::on($cawangan['mysql'])
                    ->where([['t_tebus','=',$current->toDateString()],['tagterima','=',0]])
                    ->get();

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

    }

    public function listSerahKhazanah($kodcaw){

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

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

        $gadai = Tebus::on($cawangan['mysql'])
        ->where([['t_tebus','=',$current->toDateString()],['tagterima','=',1]])
        ->get();
        return response()->json($gadai);

    }

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

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $dahscan = Tebus::on($cawangan['mysql'])->where([['norujukan','=',$norujukan],['tagterima',1]])->first();

        if($dahscan){
            return response()->json('scanned');
        }else{
            $available_tebus = Tebus::on($cawangan['mysql'])->where('norujukan',$norujukan)->first();
            if($available_tebus)
            {
                $update_inoutmar = Tebus::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
                    'tagterima' => 1
                ));

                $audit = new Audit();
                $audit->users = $request->nama;
                $audit->actions = "Khazanah Scan Barcode Tebus";
                $audit->norujukan = $norujukan;
                $audit->kodcaw = $kodcaw;
                $audit->created_at = $current;
                $audit->updated_at = $current;
                $audit->save();

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

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

        $rekod_gadaian = Tebus::on($cawangan['mysql'])->where('norujukan','=',$request->norujukan)->first();

        if($rekod_gadaian['tagterima'] == 1){
            return response()->json('true');
        }else{
            return response()->json('false');
        }
    }

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

        $wakil = Wakil::on($cawangan['mysql'])
        ->orderBy('nowakil','desc')
        ->get();

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

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

        $wakil = Wakil::on($cawangan['mysql'])
        ->orderBy('nowakil','desc')
        ->first();

        if(!$wakil){
           return response(0);
        }

        if($wakil['nowakil'])
            return response($wakil['nowakil']);
        else
            return response(0);
    }

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

        if($status == 'hubungan')
        {
            $wakil = Wakil::on($cawangan['mysql'])
                ->where('hubungan','=',$request->hubungan)
                ->get();
        }else{
            $wakil = [];
        }


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

    public function LookupWakil()
    {
        $lookupwakil = LookupWakil::on('mysql7')->get();

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


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

        $wakil = Wakil::on($cawangan['mysql'])
        ->where('nokp','=',$icno)
        ->get();

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

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

        $wakil = Wakil::on($cawangan['mysql'])
        ->where('nowakil','=',$nowakil)
        ->get();

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

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

        $wakil_surat = WakilSurat::on($cawangan['mysql'])->where('norujukan', $norujukan)->select('no_surat')->first();

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

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

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

        $wakil_create = Wakil::on($cawangan['mysql'])->create([

            'kodcaw' => $kodcaw,
            'nopelanggan' => $request->nopelanggan,
            'nowakil' => $request->nowakil,
            'nama' => $request->nama,
            'nokp' => $icno,
            'hubungan' => $request->hubungan,
            'alamat1' => $request->alamat,
            'telefon' => $request->telefon,
            'teller' => $request->teller,
            'nota' => $request->nota
        ]);

        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = "Daftar Wakil";
        $audit->new_data = json_encode($wakil_create);
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();
       
        return response()->json($wakil_create ,201);
    }

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

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

        $wakil = $request->nowakil;

        $update_wakil = Tebus::on($cawangan['mysql'])->where('norujukan','=',$request->norujukan)->update(array(
            "nowakil" => $wakil
        ));

        // $audit = new Audit();
        // $audit->users = $request->teller;
        // $audit->actions = "Ubah Wakil";
        // $audit->new_data = json_encode($update_wakil);
        // $audit->kodcaw = $kodcaw;
        // $audit->created_at = $current;
        // $audit->updated_at = $current;
        // $audit->save();

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

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

        $listtebus = Tebus::on($cawangan['mysql'])
            ->where('norujukan', $request->norujukan)
            ->get();
       
        foreach ($listtebus as $tebus) {
            // Cari transaction padan berdasarkan norujukan dan trans_type = 'A'
            $transaction = \DB::connection('mysql7')
                ->table('transaction')
                ->where('norujukan', $tebus->norujukan)
                ->whereIn('trans_type', ['T', 'AT'])
                ->first();

            // Jika wujud, cari transaksi_keuntungan yang padan ikut tarikh
            if ($transaction) {
                $createdDate = Carbon::parse($transaction->created_at)->toDateString();

                $keuntungan = \DB::connection('mysql7')
                    ->table('transaksi_keuntungan')
                    ->where('norujukan', $tebus->norujukan)
                    ->whereDate('tarikh_bayaran', $createdDate)
                    ->first();

                if ($transaction->trans_type == 'T') {
                    $tebus->bayaran_keuntungan = number_format($keuntungan->keuntungan_rebet ?? 0, 2);
                } elseif ($transaction->trans_type == 'AT') {
                    $tebus->bayaran_keuntungan = number_format($keuntungan->bayaran_keuntungan ?? 0, 2);
                }

                $tebus->bayaran_pembiayaan = number_format($keuntungan->bayaran_pembiayaan  ?? 0, 2);
                $tebus->duit_masuk = number_format($transaction->duit_masuk  ?? 0, 2);
                $tebus->trans_type = $transaction->trans_type ?? null;
            } else {
                $tebus->bayaran_keuntungan = null;
                $tebus->bayaran_pembiayaan = null;
                $tebus->duit_masuk = null; 
            }
        }

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

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

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

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

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

        $listadvansur = Advansur::on($cawangan['mysql'])
        ->where('norujukan','=',$norujukan)
        ->orderBy('tarikh','desc')
        ->first();

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

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

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

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

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

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

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

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

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

        $listadvansur = Advansur::on($cawangan['mysql'])
        ->where('tarikh','>=',$request->mula)
        ->where('tarikh','<=',$request->akhir)
        ->orderBy('teller')
        ->orderBy('tarikh','asc')
        ->get();

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

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

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

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

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

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

    }

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

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

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

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

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

        $countadvansurkaunter = $listadvansurkaunter->count();
        $totaladvansurkaunter = $listadvansurkaunter->sum('upahdibayar');

        $countadvansuronline = $listadvansuronline->count();
        $totaladvansuronline = $listadvansuronline->sum('upahdibayar');

        $arrayadvansur = ['bilkaunter' => $countadvansurkaunter, 'totalkaunter' => $totaladvansurkaunter,'bilonline' => $countadvansuronline, 'totalonline' => $totaladvansuronline];

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

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

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

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

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

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

        $countadvansurkaunter = $listadvansurkaunter->count();
        $totaladvansurkaunter = $listadvansurkaunter->sum('upahdibayar');

        $countadvansuronline = $listadvansuronline->count();
        $totaladvansuronline = $listadvansuronline->sum('upahdibayar');

        $arrayadvansur = ['bilkaunter' => $countadvansurkaunter,
                          'totalkaunter' => $totaladvansurkaunter,
                          'bilonline' => $countadvansuronline,
                          'totalonline' => $totaladvansuronline];

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

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

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

        $listadvansur = Advansur::on($cawangan['mysql'])
            ->where('teller','=',$request->kodlaluan)
            ->where('tarikh','=',$current->toDateString())
            ->sum('upahdibayar');

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

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

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

        $create_advansur = Advansur::on($cawangan['mysql'])->create([
            'tarikh'=> $current->toDateString(),
            'noresit'=> 0,
            'norujukan' => $request->norujukan,
            'nopelanggan' => $request->nopelanggan,
            'nilaimarhun' => $request->nilaimarhun,
            'pinjaman' => $request->pinjaman,
            'kadarupah' => $request->kadarupah,
            'glcode' => $request->glcode,
            'upahsebenar' => $request->upahsebenar,
            'upahDibayar' => $request->upahdibayar,
            'teller' => $request->teller,
            'prkod' => $request->prkod,
            'jbg' => $request->jbg,
            'nowakil' => $request->nowakil,
            'hubungan' => $request->hubungan,
            'status' => 0,
            'historygadaian' => $request->historygadaian
        ]);

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

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

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

        $total = 0;
        $keuntunganselepastawarruq = 0;
        $keuntungansebelumtawarruq = 0;

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

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

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

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

        // //Keuntungan Selepas Tawarruq
        // $keuntungan_data = TransaksiKeuntungan::on('mysql7')
        //     // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
        //     ->where('transaksi_keuntungan.tarikh_bayaran' ,'<=', $daterequest)
        //     ->whereYear('transaksi_keuntungan.tarikh_bayaran','=',$current->year)
        //     // ->whereNull('db2.hargajualan')
        //     // ->sum('bayaran_keuntungan');
        //     ->get();

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


        $upahtebus = Tebus::on($cawangan['mysql'])
            ->where([['t_tebus','<=',$request->tarikh],['t_tebus','>','2013-12-31']])
            ->whereYear('t_tebus','=',$current->year)
            ->sum('upahdibayar');

        $upahlelong = Lelong::on($cawangan['mysql'])
            ->where([['t_jual','<=',$request->tarikh],['t_jual','>','2013-12-31'],['t_jual','<=','2022-07-24']])
            ->whereYear('t_jual','=',$current->year)
            ->sum('bakiupah');

        $upahansur = Advansur::on($cawangan['mysql'])
            ->where('tarikh','<=',$request->tarikh)
            ->whereYear('tarikh','=',$current->year)
            ->sum('upahdibayar');


        $keuntungansebelumtawarruq = $upahtebus + $upahlelong + $upahansur;

        $total = $keuntungansebelumtawarruq + $keuntungan;

        if($kodcaw === '011232')
        {
            $total +=623.5;
        }

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

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

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

        $total = 0;
        $keuntunganselepastawarruq = 0;
        $keuntungansebelumtawarruq = 0;

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

        //Keuntungan Selepas Tawarruq
        $keuntungan_data = TransaksiKeuntungan::on('mysql7')
            // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
            // ->whereYear('transaksi_keuntungan.tarikh_bayaran','=',$current->year)
            // ->whereNull('db2.hargajualan')
            // ->sum('bayaran_keuntungan');
            // ->get();
            ->pluck('norujukan');

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

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

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

        $upahtebus = Tebus::on($cawangan['mysql'])
            ->where([['t_tebus','>=',$request->mula],['t_tebus','<=',$request->hingga],['t_tebus','>','2013-12-31']])
            // ->whereYear('t_tebus','=',$current->year)
            ->sum('upahdibayar');

        $upahlelong = Lelong::on($cawangan['mysql'])
            ->where([['t_jual','>=',$request->mula],['t_jual','<=',$request->hingga],['t_jual','>','2013-12-31'],['t_jual','<=','2022-07-24']])
            // ->whereYear('t_jual','=',$current->year)
            ->sum('bakiupah');

        $upahansur = Advansur::on($cawangan['mysql'])
            ->where('tarikh','>=',$request->mula)
            ->where('tarikh','<=',$request->hingga)
            // ->whereYear('tarikh','=',$current->year)
            ->sum('upahdibayar');


        $keuntungansebelumtawarruq = $upahtebus + $upahlelong + $upahansur;

        // $keuntunganselepastawarruq = $keuntunganselepastawarruqupah;

        // $total = $keuntungansebelumtawarruq + $keuntunganselepastawarruq;

        $total = $keuntungansebelumtawarruq + $keuntungan;

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

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

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

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

        $total = 0;

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

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

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

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

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


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

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

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

        //Upah Tawarruq

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

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

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

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

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

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

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

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

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

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

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

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

        if($request->tarikh < '2021-06-09')
        {
            $keuntungan_data = TransaksiKeuntungan::on('mysql7')
                ->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $request->tarikh)
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', $dateSM)
                ->whereYear('tarikh_bayaran','<',$current->year)
                ->where('kodcaw',$kodcaw)
                ->pluck('norujukan');

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

            $keuntungan = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran', '<=', $request->tarikh)
                ->whereDate('tarikh_bayaran' ,'<', $dateSM)
                ->whereYear('tarikh_bayaran','<',$current->year)
                ->sum('bayaran_keuntungan');

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

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

            $keuntunganreducing = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran' ,'<=', $request->tarikh)
                ->whereDate('tarikh_bayaran','>=', $dateSM)
                ->whereYear('tarikh_bayaran','<',$current->year)
                ->sum('keuntungan_rebet');

            $keuntungansebenar = ($keuntungan + $keuntunganreducing);


        }else{

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


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

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

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

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

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

        $bukanansuran_data = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','!=','A')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('tarikh_bayaran','<',$current->year)
                    ->where('trans.kodcaw',$kodcaw)
                    ->pluck('transaksi_keuntungan.norujukan');

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

        $bukanansuran = TransaksiKeuntungan::on('mysql7')
                    ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','!=','A')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('transaksi_keuntungan.tarikh_bayaran','<',$current->year)
                    ->sum('transaksi_keuntungan.keuntungan_rebet');

        $ansuran_data = TransaksiKeuntungan::on('mysql7')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','=','A')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                    ->whereYear('tarikh_bayaran','<',$current->year)
                    ->where('trans.kodcaw',$kodcaw)
                    ->pluck('transaksi_keuntungan.norujukan');

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

        $ansuran = TransaksiKeuntungan::on('mysql7')
            ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
            ->leftJoin('transaction as trans', function($join)
            {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type','=','A')
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
            ->whereYear('transaksi_keuntungan.tarikh_bayaran','<',$current->year)
            ->sum('transaksi_keuntungan.bayaran_keuntungan');


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

        }
        // dd($keuntungansebenar);

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

        // dd($utgrugilama,$lelong,$upahsimpantebus,$upahsimpanlelong,$upahsimpanansur,$gstcajlelong,$parameter);

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


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

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

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

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

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

        // $datetawarruq = new Carbon('2021-04-14');
        $daterequest = new Carbon($request->tarikh);
        $daterequest->addDays(1);

        $dateSM = '2021-04-24';

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

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

        if($request->tarikh < '2021-06-09')
        {
            $keuntungan_data = TransaksiKeuntungan::on('mysql7')
                // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                ->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $request->tarikh)
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', $dateSM)
                ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                ->where('kodcaw',$request->kodcaw)
                // ->whereNotNull('db2.hargajualan')
                // ->sum('bayaran_keuntungan');
                ->pluck('norujukan');

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

            $keuntungan = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran', '<=', $request->tarikh)
                ->whereDate('tarikh_bayaran' ,'<', $dateSM)
                ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                ->sum('bayaran_keuntungan');

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

            $keuntunganreducing_data = TransaksiKeuntungan::on('mysql7')
                // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                ->where('kodcaw',$request->kodcaw)
                // ->whereNotNull('db2.hargajualan')
                // ->sum('keuntungan_rebet');
                // ->get();
                ->pluck('norujukan');

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

            $keuntunganreducing = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran' ,'<=', $request->tarikh)
                ->whereDate('tarikh_bayaran','>=', $dateSM)
                ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                ->sum('keuntungan_rebet');

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

            $total = ($keuntungan + $keuntunganreducing);


        }else{

        //ps. Fix sementara je ni.
        if($cawangan['zone'] == 1){

            $keuntungan = TransaksiKeuntungan::on('mysql7')
                            ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $request->tarikh)
                            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', $dateSM)
                            ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                            ->where('transaksi_keuntungan.kodcaw',$request->kodcaw)
                            ->whereNotNull('db2.hargajualan')
                            ->sum('keuntungan_rebet');

            $keuntunganreducing = TransaksiKeuntungan::on('mysql7')
                        ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', '2021-06-09')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                        ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                        ->where('transaksi_keuntungan.kodcaw',$request->kodcaw)
                        ->whereNotNull('db2.hargajualan')
                        ->sum('keuntungan_rebet');

            $bukanansuran = TransaksiKeuntungan::on('mysql7')
                        ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->where('trans.trans_type','!=','A')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                        // ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                        ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                        ->where('trans.kodcaw',$request->kodcaw)
                        ->whereNotNull('db2.hargajualan')
                        ->sum('keuntungan_rebet');

            $ansuran = TransaksiKeuntungan::on('mysql7')
                        ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->where('trans.trans_type','=','A')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                        // ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                        ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                        ->where('trans.kodcaw',$request->kodcaw)
                        ->whereNotNull('db2.hargajualan')
                        ->sum('bayaran_keuntungan');

        }else{
            $keuntungan_data = TransaksiKeuntungan::on('mysql7')
            // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $request->tarikh)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', $dateSM)
            ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
            ->where('kodcaw',$request->kodcaw)
            // ->whereNotNull('db2.hargajualan')
            // ->sum('bayaran_keuntungan');
            // ->get();
            ->pluck('norujukan');

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

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

            $keuntunganreducing_data = TransaksiKeuntungan::on('mysql7')
                        // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<', '2021-06-09')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                        ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                        ->where('kodcaw',$request->kodcaw)
                        // ->whereNotNull('db2.hargajualan')
                        // ->sum('keuntungan_rebet');
                        // ->get();
                        ->pluck('norujukan');

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

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

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

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

            $bukanansuran = TransaksiKeuntungan::on('mysql7')
                        ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->where('trans.trans_type','!=','A')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                        ->whereYear('transaksi_keuntungan.tarikh_bayaran','=',$tarikhyear->year)
                        ->sum('transaksi_keuntungan.keuntungan_rebet');

            $ansuran_data = TransaksiKeuntungan::on('mysql7')
                        // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                        ->leftJoin('transaction as trans', function($join)
                        {
                            $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                            $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                        })
                        ->where('trans.trans_type','=','A')
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                        ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                        // ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $dateSM)
                        ->whereYear('tarikh_bayaran','=',$tarikhyear->year)
                        ->where('trans.kodcaw',$request->kodcaw)
                        // ->whereNotNull('db2.hargajualan')
                        // ->sum('bayaran_keuntungan');
                        // ->get();
                        ->pluck('transaksi_keuntungan.norujukan');

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

            $ansuran = TransaksiKeuntungan::on('mysql7')
                ->whereIn('transaksi_keuntungan.norujukan',$gadaiData)
                ->leftJoin('transaction as trans', function($join)
                {
                    $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                    $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                })
                ->where('trans.trans_type','=','A')
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->tarikh)
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', '2021-06-09')
                ->whereYear('transaksi_keuntungan.tarikh_bayaran','=',$tarikhyear->year)
                ->sum('transaksi_keuntungan.bayaran_keuntungan');

        }


        $upahlelong = Lelong::on($cawangan['mysql'])
        ->where([['t_jual','<=',$request->tarikh],['t_jual','>','2022-07-24']])
        ->whereYear('t_jual','=',$tarikhyear->year)
        ->sum('bakiupah');


        $total = ($keuntungan + $keuntunganreducing + $ansuran + $bukanansuran + $upahlelong);

        }

        return response($total);
    }

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

        // $datetawarruq = new Carbon('2021-04-14');
        $daterequest = new Carbon($request->tarikh);
        $daterequest->addDays(1);

        $dateSM = '2021-04-24';

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


	if($request->hingga < '2021-06-01')
        {

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


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

            $keuntungan = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran', '<=', $request->hingga)
                ->whereDate('tarikh_bayaran', '>=', $request->mula)
                ->whereDate('tarikh_bayaran' ,'<', $dateSM)
                // ->whereYear('tarikh_bayaran','=',$current->year)
                ->sum('bayaran_keuntungan');

            $keuntunganreducing_data = TransaksiKeuntungan::on('mysql7')
                ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
                ->whereDate('transaksi_keuntungan.tarikh_bayaran','>=', $request->mula)
                // ->whereYear('tarikh_bayaran','=',$current->year)
                ->where('kodcaw',$request->kodcaw)
                ->pluck('norujukan');

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

            $keuntunganreducing = TransaksiKeuntungan::on('mysql7')
                ->whereIn('norujukan',$gadaiData)
                ->whereDate('tarikh_bayaran' ,'<=', $request->hingga)
                ->whereDate('tarikh_bayaran','>=', $request->mula)
                // ->whereYear('tarikh_bayaran','=',$current->year)
                ->sum('keuntungan_rebet');

            $total = ($keuntungan + $keuntunganreducing);

        }else{
        $bukanansuran_data = TransaksiKeuntungan::on('mysql7')
                    // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','!=','A')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
                    ->whereYear('tarikh_bayaran','=',$current->year)
                    ->where('trans.kodcaw',$request->kodcaw)
                    ->where('transaksi_keuntungan.margin_semasa',0)
                    // ->whereNotNull('db2.hargajualan')
                    // ->sum('keuntungan_rebet');
                    ->get();

        $bukanansuran = 0;
        if($bukanansuran_data){
            foreach($bukanansuran_data as $index=>$bukanansuranData){
                $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$bukanansuranData['norujukan']],['hargajualan','<>',null],['tagbaru',0]])->first();
                if($gadaiData){
                    $bukanansuran += $bukanansuranData['keuntungan_rebet'];
                }
            }
        }

        $ansuran_data = TransaksiKeuntungan::on('mysql7')
                    // ->join($cawangan['db_name'].'.gadai as db2','transaksi_keuntungan.norujukan','=','db2.norujukan')
                    ->leftJoin('transaction as trans', function($join)
                    {
                        $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                        $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
                    })
                    ->where('trans.trans_type','=','A')
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'>=', $request->mula)
                    ->whereDate('transaksi_keuntungan.tarikh_bayaran' ,'<=', $request->hingga)
                    ->whereYear('tarikh_bayaran','=',$current->year)
                    ->where('trans.kodcaw',$request->kodcaw)
                    ->where('transaksi_keuntungan.margin_semasa',0)
                    // ->whereNotNull('db2.hargajualan')
                    // ->sum('bayaran_keuntungan');
                    ->get();

        $ansuran = 0;
        if($ansuran_data){
            foreach($ansuran_data as $index=>$ansuranData){
                $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$ansuranData['norujukan']],['hargajualan','<>',null],['tagbaru',0]])->first();
                if($gadaiData){
                    $ansuran += $ansuranData['bayaran_keuntungan'];
                }
            }
        }

        $upahlelong = Lelong::on($cawangan['mysql'])
        ->where([['t_jual','>=',$request->mula],['t_jual','<=',$request->hingga],['t_jual','>','2022-07-24']])
        ->whereYear('t_jual','=',$current->year)
        ->sum('bakiupah');

	    $total = ($ansuran + $bukanansuran + $upahlelong);
	}

        return response($total);
    }

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

        $rebet = Tebus::on($cawangan['mysql'])
                ->join('gadai as db2','tebus.norujukan','=','db2.norujukan')
                // ->where('tebus.t_tebus','>','2021-04-13')
                ->where('tebus.t_tebus','<=',$request->tarikh)
                ->where('db2.hargajualan','>','0') // tambahan 2021-05-07
                ->whereNotNull('db2.hargajualan')
                ->sum('rebate');

        return response($rebet);
    }

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

        $rebet = Tebus::on($cawangan['mysql'])
                ->join('gadai as db2','tebus.norujukan','=','db2.norujukan')
                ->where('tebus.t_tebus','>=',$request->mula)
                ->where('tebus.t_tebus','<=',$request->hingga)
                ->where('db2.hargajualan','>','0')
                ->whereNotNull('db2.hargajualan')
                ->sum('rebate');

        return response($rebet);
    }

    public function getUpahLamaToday($kodcaw,$norujukan)
    {
        $current = Carbon::now();
        $current = new Carbon();

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

        $listadvansur = Advansur::on($cawangan['mysql'])
            ->where('norujukan','=',$norujukan)
            ->where('tarikh','=',$current->toDateString())
            ->orderBy('tarikh','desc')
            ->get();

        if(sizeof($listadvansur) > 0)
            return response(1);
        else
            return response(0);
    }

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

        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $data_ansuran = Advansur::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();
        $removed = Advansur::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->delete();

        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = "Hapus Upah";
        $audit->norujukan = $norujukan;
        $audit->old_data = $data_ansuran;
        $audit->kodcaw = $kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();

        if($removed)
            return response(1);
        else
            return response(0);
    }



    public function calculationKeuntunganPenggadai($kodcaw,Request $request)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $determine_past = new Carbon($request->tarikh);
        $date = new Carbon($request->tarikh);
        $date_sekarang = clone $date;
        $month_sebelum = $date->subMonth()->format('m');
        $month_sekarang = $date_sekarang->format('m');
        $year_generate = $date_sekarang->format('Y');

        if($determine_past->isToday())
        {
            $audit_now = Gadai::on($cawangan['mysql'])
                ->select(DB::raw('sum(tunggakan) as "akru",
                sum(tunggakanujrah) as "akruujrah",
                sum(tunggakanonepercent) as "akruonepercent"'))
                ->where([['tagpalsu','=',0],['t_gadai','<=',$request->tarikh],['sttebus','=','']])
                ->orWhere([['tagpalsu','=',0],['t_update','>',$request->tarikh],['sttebus','!=',''],['t_gadai','<=',$request->tarikh]])
                ->orderBy('t_gadai', 'ASC')
                ->orderBy('sirig', 'ASC')->first();

            $totaltunggakan_now = $audit_now['akru'] + $audit_now['akruujrah'] + $audit_now['akruonepercent'];
        }else{

            $result_audit_backdate = $this->StokAuditGenerateTerakru($month_sekarang,$cawangan,$year_generate);
            $totaltunggakan_now = $result_audit_backdate->selectRaw('SUM(upahblmbyar) + SUM(ujrah) + SUM(utgonepercent) as total_sum')->first();
            $totaltunggakan_now = $totaltunggakan_now['total_sum'];
        }

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

    }

    public function StokAuditGenerateTerakru($Month = null, $cawangan = [], $year_generate = null) : Object{
        switch($Month){
            case '01': return $audit_backdate = StokAudit1::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '02': return $audit_backdate = StokAudit2::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '03': return $audit_backdate = StokAudit3::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '04': return $audit_backdate = StokAudit4::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '05': return $audit_backdate = StokAudit5::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '06': return $audit_backdate = StokAudit6::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '07': return $audit_backdate = StokAudit7::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '08': return $audit_backdate = StokAudit8::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '09': return $audit_backdate = StokAudit9::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '10': return $audit_backdate = StokAudit10::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '11': return $audit_backdate = StokAudit11::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
            case '12': return $audit_backdate = StokAudit12::on($cawangan['mysql'])->where('tahun',$year_generate);
                        break;
        }
    }

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

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

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

        $date_sebelum = clone $date;
        $determine_past = new Carbon($request->tarikh);
        $date_sebelum = $date_sebelum->firstOfMonth();
        $month_sebelum = $date_sebelum->subMonth()->format('m');
        $month_sekarang = $date->format('m');
        $year_generate = $date->format('Y');
        $haripertama = $date->firstOfMonth();
        $haripertama_extension = $haripertama->toDateString();
        $datenow = new Carbon($request->tarikh);
        $year = $current->year;
        $month = $tarikh->month;


        $intmonth_sebelum = (int)$month_sebelum;
        $intmonth_sekarang = (int)$month_sekarang;

        $latest_month_akrunet = AkruNet::on($cawangan['mysql'])
        ->where('tahun','=',$year_generate)
        ->latest('bulan')->first();

        if($year_generate == 2022 && $intmonth_sebelum > 4)
        {
            $result_audit_backdate = $this->StokAuditGenerateTerakru($month_sebelum,$cawangan,$year_generate);
        }else if($year_generate > 2022 && $intmonth_sekarang == 1){
            $previousYear = Carbon::now()->subYears(1);
            $result_audit_backdate = $this->StokAuditGenerateTerakru('12',$cawangan,$previousYear->year);
        }else{
            $result_audit_backdate = $this->StokAuditGenerateTerakru($month_sebelum,$cawangan,$year_generate);
        }

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

        // $sum_keun_tebus = Transaction::on('mysql7')
        //     ->leftJoin('transaksi_keuntungan as trans', function($join)
        //     {
        //             $join->on('transaction.norujukan', '=', 'trans.norujukan');
        //             $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
        //     })
        //     ->whereIn('trans.norujukan',$get_norujukan)
        //     ->where('transaction.trans_type','<>','A')
        //     ->where('trans.margin_semasa','=',0) //3.80
        //     ->sum('keuntungan_rebet');

        // $sum_keun_ansuran = Transaction::on('mysql7')
        //     ->leftJoin('transaksi_keuntungan as trans', function($join)
        //     {
        //             $join->on('transaction.norujukan', '=', 'trans.norujukan');
        //             $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
        //     })
        //     ->whereIn('trans.norujukan',$get_norujukan)
        //     ->where('transaction.trans_type','A')
        //     ->where('trans.margin_semasa','=',0)
        //     ->sum('bayaran_keuntungan');

        // $total = $sum_keun_tebus + $sum_keun_ansuran;

        $total = $this->calculateKeuntunganSemasa($tarikh,$request->kodcaw);

        if(!$determine_past->isToday()){
            $calculate_month = (int)$month_sekarang - $latest_month_akrunet->bulan;

            if($calculate_month > 1){
                return 'ERR_MONTH_SEBELUM';
            }else if($calculate_month == 1){
                $jumlahakru = AkruNet::on($cawangan['mysql'])
                ->sum('jumlah');
            }else if($calculate_month < 0){
                $jumlahakru = AkruNet::on($cawangan['mysql'])
                ->where('bulan','<=',$intmonth_sekarang)
                ->where('tahun',$year)
                ->sum('jumlah');

                return response()->json($jumlahakru);
            }else if($calculate_month == 0)
            {
                $jumlahakru = AkruNet::on($cawangan['mysql'])
                ->where('bulan','<',$intmonth_sekarang)
                ->sum('jumlah');
            }
        }else{
            $calculate_month = 0;

            $jumlahakru = AkruNet::on($cawangan['mysql'])
            ->where('bulan','<',$intmonth_sekarang)
            ->where('tahun', $current->year)
            ->sum('jumlah');
        }


        if($determine_past->isToday())
        {
            $audit_now = Gadai::on($cawangan['mysql'])
            ->where([['tagpalsu','=',0],['t_gadai','<=',$request->tarikh],['sttebus','=','']])
            ->orWhere([['tagpalsu','=',0],['t_update','>',$request->tarikh],['sttebus','!=',''],['t_gadai','<=',$request->tarikh]])
            ->orderBy('t_gadai', 'ASC')
            ->orderBy('sirig', 'ASC');

            $totaltunggakan_now = $audit_now->sum('tunggakan');
            $totaltunggakan_sebelum = $result_audit_backdate->sum('upahblmbyar');

            $request_dibina = new \Illuminate\Http\Request([
                    'mula' => $haripertama_extension,
                    'hingga' => $datenow->toDateString(),
                    'kodcaw' => $request->kodcaw,
                ]);

            // $calculation_keuntungan_sebenar = $this->untungrugicalculationLejer($request->kodcaw,$request_dibina);
            // $upah_diterima = $calculation_keuntungan_sebenar->getContent();
            $upah_diterima = $total;
            $calculation = $totaltunggakan_sebelum - $upah_diterima;
            $accrual_net = $totaltunggakan_now - $calculation;

            if($calculate_month <= 1){
                $available_akru = AkruNet::on($cawangan['mysql'])
                ->where('bulan', (int)$month_sekarang)
                ->where('tahun', $current->year)
                ->get()->toArray();

                if(sizeof($available_akru) == 0)
                {
                    $akrunet = new AkruNet();
                    $akrunet->setConnection($cawangan['mysql']);
                    $akrunet->tahun = $current->year;
                    $akrunet->bulan = $tarikh->month;
                    $akrunet->jumlah = ($accrual_net);
                    $akrunet->save();
                }else{
                    if($available_akru[0]['jumlah'] !== ($accrual_net))
                    {
                        AkruNet::on($cawangan['mysql'])->where('bulan','=',(int)$month_sekarang)->where('tahun',$current->year)
                        ->update(['jumlah' => ($accrual_net)]);
                    }

                }
            }

		//dd($jumlahakru,$accrual_net,$total);
            $total_accrual_net = $jumlahakru + ($accrual_net);

        }else{


            $result_audit_stated = $this->StokAuditGenerateTerakru($month_sekarang,$cawangan,$year_generate);

            $totaltunggakan_now = $result_audit_stated->sum('upahblmbyar');
            $totaltunggakan_sebelum = $result_audit_backdate->sum('upahblmbyar');

            $request_dibina = new \Illuminate\Http\Request([
                    'mula' => $haripertama_extension,
                    'hingga' => $date->endOfMonth()->toDateString(),
                    'kodcaw' => $request->kodcaw,
                ]);

            $calculation_keuntungan_sebenar = $this->untungrugicalculationLejer($request->kodcaw,$request_dibina);
            $calculation_upahsimpan = $this->calculationKeuntunganSebenarLejer($request->kodcaw,$request_dibina);

            $upah_diterima = $calculation_keuntungan_sebenar->getContent() + $calculation_upahsimpan->getContent();
            $calculation = $totaltunggakan_sebelum - $upah_diterima;
            $accrual_net = $totaltunggakan_now - $calculation;

            if($calculate_month <= 1){
                $available_akru = AkruNet::on($cawangan['mysql'])
                ->where('bulan', (int)$month_sekarang)
                ->get()->toArray();

                if(sizeof($available_akru) == 0)
                {
                    $akrunet = new AkruNet();
                    $akrunet->setConnection($cawangan['mysql']);
                    $akrunet->tahun = $current->year;
                    $akrunet->bulan = $tarikh->month;
                    $akrunet->jumlah = ($accrual_net - $total);
                    $akrunet->save();
                }
            }

            $total_accrual_net = $jumlahakru + ($accrual_net - $total);
        }

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

    private function calculateKeuntunganSemasa($currentDate,$kodcaw)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $firstMonth = (clone $currentDate)->firstOfMonth();
        $lastMonth = (clone $currentDate)->endOfMonth();
        /* Start Keuntungan Semasa Calculation */

        $collection_trans = Transaction::on('mysql7')
        ->leftJoin('transaksi_keuntungan as trans', function ($join) {
            $join->on('transaction.norujukan', '=', 'trans.norujukan');
            $join->on('transaction.created_at', '=', 'trans.tarikh_bayaran');
        })
        ->where('transaction.kodcaw', $kodcaw)
        ->whereYear('transaction.created_at', '=', $currentDate->year)
        ->whereMonth('transaction.created_at', '=', $currentDate->month)
        ->get();


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

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

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

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

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

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

        /* Keuntungan Lelong */
        $upahlelong = Lelong::on($cawangan['mysql'])
            ->where([['tagujrah','0'],['t_jual', '>=', $firstMonth], ['t_jual', '<=', $lastMonth], ['t_jual', '>', '2022-07-24']])
            ->whereYear('t_jual', '=', $currentDate->year)
            ->sum('bakiupah');

        $total_keuntungan_semasa = ($total_ansuran + $total_tebus + $upahlelong);

        /* End Keuntungan Semasa Calculation */
        return $total_keuntungan_semasa;
    }

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

        return $response;
    }

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

        return $response;
    }

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

        return $response;
    }

    public function showOneTebusbyRujukanAndCawangan($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$kodcaw)->first();
        $tebus = Tebus::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->get();

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


}
