<?php

namespace App\Services\Reports;

use App\Advansur;
use App\Cawangan;
use App\Customer;
use App\Denominasi;
use App\Gadai;
use App\GlDetail;
use App\imbangdugalama;
use App\Lelong;
use App\Panjar;
use App\Tebus;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\Tunai;
use App\TuntutBaki;
use App\Vault;
use Carbon\Carbon;
use Illuminate\Support\Str;

class RingkasanHarianService
{
    private $kodCawangan;
    private $connectionCawangan;
    private $startDate;
    private $endDate;

    public function __construct($kodCawangan, $request)
    {
        $this->kodCawangan = $kodCawangan;
        $this->connectionCawangan = Cawangan::on('mysql7')->where('kodcaw', $kodCawangan)->first()->mysql;
        $this->startDate = $request->startDate;
        $this->endDate = $request->endDate;
    }

    public function getLaporanCawangan()
    {

        $laporan_harian = [];

        $total_gadai = Gadai::on($this->connectionCawangan)->whereDate('t_gadai', '>=', $this->startDate)->whereDate('t_gadai', '<=', $this->endDate)->sum('pinjaman');
        $bayaranonline = $this->getSumBayaranOnline();
        $bilbayaranonline = $this->getTotalBayaranOnline();
        $total_ansuran = $this->getSumAnsuranNotOnline();
        $total_ansuranonline = $this->getSumAnsuranOnline();
        $bilangan_gadai = Gadai::on($this->connectionCawangan)->whereDate('t_gadai', '>=', $this->startDate)->whereDate('t_gadai', '<=', $this->endDate)->where('pinjaman', '>', 0)->count();
        $bilangan_tebus = Tebus::on($this->connectionCawangan)->whereDate('t_tebus', '>=', $this->startDate)->whereDate('t_tebus', '<=', $this->endDate)->count();
        $bilangan_ansuran = $this->getTotalAnsuranNotOnline();
        $bilangan_ansuranonline = $this->getTotalAnsuranOnline();
        $bilangan_customer_baru = $this->getBilanganCustomerBaru();
        $bayar_baki_lelong = $this->getBayarBakiLelong();
        $bayar_rugi_lelong = $this->getBayarRugiLelong();
        $gadai_70 = $this->getGadaiSumPinjamanPercentLessThan(70);
        $gadai_75 = $this->getGadaiSumPinjamanPercentRange(70, 75);
        $gadai_80 = $this->getGadaiSumPinjamanPercentRange(75, 80);
        $total_gadaian = floatval($gadai_70) + floatval($gadai_75) + floatval($gadai_80);
        $nilaimarhun_70 = $this->getGadaiSumNilaiMarhunPercentLessThan(70);
        $nilaimarhun_75 = $this->getGadaiSumNilaiMarhunPercentRange(70, 75);
        $nilaimarhun_80 = $this->getGadaiSumNilaiMarhunPercentRange(75, 80);
        $total_nm = floatval($nilaimarhun_70) + floatval($nilaimarhun_75) + floatval($nilaimarhun_80);
        $bilangan_70 = $this->getGadaiCountPercentLessThan(70);
        $bilangan_75 = $this->getGadaiCountPercentRange(70, 75);
        $bilangan_80 = $this->getGadaiCountPercentRange(75, 80);
        $total_bilangan = floatval($bilangan_70) + floatval($bilangan_75) + floatval($bilangan_80);
        $panjar_harian = Panjar::on($this->connectionCawangan)->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)->sum('bayaran');
        $panjar_bulanan = $this->getPanjarBulanan();
        $panjar_tahunan = $this->getPanjarTahunan();
        $bilangan_lelong = Lelong::on($this->connectionCawangan)->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)->count();
        $data_lelong = $this->getDataLelong();
        $cas_lelong = $data_lelong['cas_lelong'];
        $jumlah_lelong = $data_lelong['jumlah_lelong'];
        $baki_lelong = $data_lelong['baki_lelong'];
        $rugi_lelong = $data_lelong['rugi_lelong'];
        $total_keuntungan_kaunter = $this->getTotalKeuntunganKaunter();
        $total_keuntungan_online = $this->getTotalKeuntunganOnline();
        $total_bayaran_online = $this->getTotalSumBayaranOnline();
        $bil_total_bayaran_online = $this->getBilTotalBayaranOnline();
        $petibesi_sistem = Vault::on($this->connectionCawangan)->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)->sum('bakiakhir');
        $petibesi_deno = Denominasi::on($this->connectionCawangan)->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)->sum('txtjumlah');
        $total_stok_audit = $this->getTotalStokAudit();
        $stokauditpembiayaan = $total_stok_audit['stokAuditPembiayaan'];
        $stokauditnilaimarhun = $total_stok_audit['stokAuditNilaiMarhun'];
        $stokauditcount = $total_stok_audit['stokAuditCount'];
        $petibesiimbangduga = $this->getPetiBesiImbangDuga();
        $outstandingimbangduga = $this->getOutstandingImbangDuga();
        $rekodpinj = $this->getRekodKoopSumPinjaman();
        $rekodpinjnm = $this->getRekodKoopSumNilaiMarhun();
        $rekodpinjbil = $this->getRekodKoopCount();
        $totalpenebusan = $this->getTotalPenebusan();
        $rekodtawarruq = $this->getPinjamanRekodTawarruq();
        $rekodtawarruqnilaimarhun = $this->getNilaiMarhunRekodTawarruq();
        $rekodtawarruqbil = $this->getBilanganRekodTawarruq();
        $bayaranpendahuluan = $this->getBayaranPendahuluan();
        $upahsimpankaunter = $this->getUpahSimpanKaunter();
        $keuntungansebenarkaunter = $this->getKeuntunganSebenarKaunter();
        $serahanbayaranOnline = $this->getSerahanBayaranOnline();
        $totalSerahan = $this->getTotalSerahan();
        $totalPendahuluan = $this->getTotalPendahuluan();
        $getOnePercentSimpanKaunter = $this->getOnePercentSimpanKaunter();
        $getUjrahSimpanKaunter = $this->getUjrahSimpanKaunter();
        $getOnepercentSebenarKaunter = $this->getOnepercentSebenarKaunter();
        $getUjrahSebenarKaunter = $this->getUjrahSebenarKaunter();
        $getTotalOnePercentOnline = $this->getTotalOnePercentOnline();
        $getTotalUjrahOnline = $this->getTotalUjrahOnline();
        $getUpahSimpanKaunterLama = $this->getUpahSimpanKaunterLama();
        $getKeuntunganSebenarKaunterLama = $this->getKeuntunganSebenarKaunterLama();
        $getTotalKeuntunganOnlineLama = $this->getTotalKeuntunganOnlineLama();

        array_push($laporan_harian, [
            'total_gadai' => $total_gadai,
            'total_tebus' => $totalpenebusan,
            'total_ansuran' => $total_ansuran,
            'total_ansuranonline' => $total_ansuranonline,
            'bilangan_gadai' => $bilangan_gadai,
            'bilangan_tebus' => $bilangan_tebus,
            'bilangan_ansuran' => $bilangan_ansuran,
            'bilangan_ansuranonline' => $bilangan_ansuranonline,
            'bilangan_customer_baru' => $bilangan_customer_baru,
            'bayar_baki_lelong' => $bayar_baki_lelong,
            'bayar_rugi_lelong' => $bayar_rugi_lelong,
            'gadai_70' => $gadai_70,
            'gadai_75' => $gadai_75,
            'gadai_80' => $gadai_80,
            'total_gadaian' => $total_gadaian,
            'nilaimarhun_70' => $nilaimarhun_70,
            'nilaimarhun_75' => $nilaimarhun_75,
            'nilaimarhun_80' => $nilaimarhun_80,
            'total_nm' => $total_nm,
            'bilangan_70' => $bilangan_70,
            'bilangan_75' => $bilangan_75,
            'bilangan_80' => $bilangan_80,
            'total_bilangan' => $total_bilangan,
            'panjar_harian' => $panjar_harian,
            'panjar_bulanan' => $panjar_bulanan,
            'panjar_tahunan' => $panjar_tahunan,
            'bilangan_lelong' => $bilangan_lelong,
            'cas_lelong' => $cas_lelong,
            'jumlah_lelong' => $jumlah_lelong,
            'baki_lelong' => $baki_lelong,
            'rugi_lelong' => $rugi_lelong,
            'total_keuntungan_kaunter' => $total_keuntungan_kaunter,
            'total_keuntungan_online' => $total_keuntungan_online,
            'totalbayaranonline' => $total_bayaran_online,
            'biltotalbayaranonline' => $bil_total_bayaran_online,
            'petibesi_sistem' => $petibesi_sistem,
            'petibesi_deno' => $petibesi_deno,
            'stokauditpembiayaan' => $stokauditpembiayaan,
            'stokauditnilaimarhun' => $stokauditnilaimarhun,
            'stokauditcount' => $stokauditcount,
            'petibesiimbangduga' => $petibesiimbangduga,
            'outstandingimbangduga' => $outstandingimbangduga,
            'rekodpinj' => $rekodpinj,
            'rekodpinjnm' => $rekodpinjnm,
            'rekodpinjbil' => $rekodpinjbil,
            'rekodpemb' => $rekodtawarruq,
            'rekodpembnm' => $rekodtawarruqnilaimarhun,
            'rekodpembbil' => $rekodtawarruqbil,
            'bayaranpend' => $bayaranpendahuluan,
            'upahsimpankaunter' => $upahsimpankaunter,
            'keuntungansebenarkaunter' => $keuntungansebenarkaunter,
            'totalserahan' => $totalSerahan,
            'serahanbayaranOnline' => $serahanbayaranOnline,
            'totalpendahuluan' => $totalPendahuluan,
            'onePercentSimpanKaunter' => $getOnePercentSimpanKaunter,
            'ujrahSimpanKaunter' => $getUjrahSimpanKaunter,
            'onepercentSebenarKaunter' => $getOnepercentSebenarKaunter,
            'ujrahSebenarKaunter' => $getUjrahSebenarKaunter,
            'totalOnePercentOnline' => $getTotalOnePercentOnline,
            'totalUjrahOnline' => $getTotalUjrahOnline,
            'upahSimpanKaunterLama' => $getUpahSimpanKaunterLama,
            'keuntunganSebenarKaunterLama' => $getKeuntunganSebenarKaunterLama,
            'totalKeuntunganOnlineLama' => $getTotalKeuntunganOnlineLama,
        ]);

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

    private function getTotalPenebusan()
    {
        $tebus = Tebus::on($this->connectionCawangan)
            ->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')
            ->whereDate('tebus.t_tebus', '>=', $this->startDate)->whereDate('tebus.t_tebus', '<=', $this->endDate)
            ->get();

        $pembiayaanlelong = Lelong::on($this->connectionCawangan)
            ->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)
            ->sum('pinjaman');

        $totalpenebusan = 0;

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

        //Lelongan Pembiayaan
        return $totalpenebusan += $pembiayaanlelong;
    }

    private function getAnsuranQuery()
    {
        $sum_ansuran_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) >= ?', [$this->startDate])
            ->whereRaw('DATE(transaksi_keuntungan.tarikh_bayaran) <= ?', [$this->endDate])
            ->where([['trans.trans_type', '=', 'A'], ['trans.kodcaw', '=', $this->kodCawangan]]);

        return $sum_ansuran_query;

    }

    private function getSumAnsuranOnline()
    {
        $sum_ansuran = $this->getAnsuranQuery($this->kodCawangan)
            ->where('teller', '=', 'online')
            ->sum('transaksi_keuntungan.bayaran_pembiayaan');

        return $sum_ansuran;
    }

    private function getTotalAnsuranOnline()
    {
        $sum_ansuran = $this->getAnsuranQuery($this->kodCawangan)
            ->where('teller', '=', 'online')
            ->count();

        return $sum_ansuran;
    }

    private function getSumAnsuranNotOnline()
    {
        $sum_ansuran = $this->getAnsuranQuery($this->kodCawangan)
            ->where('teller', '<>', 'online')
            ->sum('transaksi_keuntungan.bayaran_pembiayaan');

        return $sum_ansuran;
    }

    private function getTotalAnsuranNotOnline()
    {
        $sum_ansuran = $this->getAnsuranQuery($this->kodCawangan)
            ->where('teller', '<>', 'online')
            ->count();

        return $sum_ansuran;
    }

    private function getBilanganCustomerBaru()
    {
        $totalCustomer = Customer::on('mysql7')->where([
            ['tarikhdaftar', '>=', $this->startDate],
            ['tarikhdaftar', '<=', $this->endDate],
            ['kodcaw', $this->kodCawangan],
        ])->count();

        return $totalCustomer;

    }

    // Public method that calls the private method
    public function getCustomerSummary()
    {
        return $this->getBilanganCustomerBaru(); // Access the private method here
    }

    private function getBayarRugiLelong()
    {
        $bayarRugiLelong = TuntutBaki::on($this->connectionCawangan)
            ->whereDate('tarikh', '>=', $this->startDate)
            ->whereDate('tarikh', '<=', $this->endDate)
            ->where('jumlah', '<', 0)
            ->sum('jumlah');

        return $bayarRugiLelong;
    }

    private function getBayarBakiLelong()
    {
        $bayarBakiLelong = TuntutBaki::on($this->connectionCawangan)
            ->whereDate('tarikh', '>=', $this->startDate)
            ->whereDate('tarikh', '<=', $this->endDate)
            ->where('jumlah', '>', 0)
            ->sum('jumlah');

        return $bayarBakiLelong;
    }

    private function getBayaranOnlineQuery()
    {
        $bayaranOnlineQuery = Transaction::on('mysql7')
            ->whereDate('created_at', '>=', $this->startDate)
            ->whereDate('created_at', '<=', $this->endDate)
            ->where('teller', '=', 'Online')
            ->where('kodcaw', $this->kodCawangan);

        return $bayaranOnlineQuery;
    }

    private function getSumBayaranOnline()
    {
        return $this->getBayaranOnlineQuery($this->kodCawangan)->sum('duit_masuk');
    }

    private function getTotalBayaranOnline()
    {
        return $this->getBayaranOnlineQuery($this->kodCawangan)->count();
    }

    private function getGadaiPercentLessThan($percentage)
    {
        return Gadai::on($this->connectionCawangan)
            ->where([
                ['t_gadai', '>=', $this->startDate],
                ['t_gadai', '<=', $this->endDate],
                ['percentpinj', '<=', $percentage],
            ]);
    }

    private function getGadaiSumPinjamanPercentLessThan($percentage)
    {
        return $this->getGadaiPercentLessThan($percentage)->sum('pinjaman');
    }

    private function getGadaiPercentRange($percentage_from, $percentage_to)
    {
        return Gadai::on($this->connectionCawangan)
            ->where([
                ['t_gadai', '>=', $this->startDate],
                ['t_gadai', '<=', $this->endDate],
                ['percentpinj', '>', $percentage_from],
                ['percentpinj', '<=', $percentage_to],
            ]);
    }

    private function getGadaiSumPinjamanPercentRange($percentage_from, $percentage_to)
    {
        return $this->getGadaiPercentRange($percentage_from, $percentage_to)->sum('pinjaman');
    }

    private function getGadaiSumNilaiMarhunPercentLessThan($percentage)
    {
        return $this->getGadaiPercentLessThan($percentage)->sum('nilaimarhun');
    }

    private function getGadaiSumNilaiMarhunPercentRange($percentage_from, $percentage_to)
    {
        return $this->getGadaiPercentRange($percentage_from, $percentage_to)->sum('nilaimarhun');
    }

    private function getGadaiCountPercentLessThan($percentage)
    {
        return $this->getGadaiPercentLessThan($percentage)->count();
    }

    private function getGadaiCountPercentRange($percentage_from, $percentage_to)
    {
        return $this->getGadaiPercentRange($percentage_from, $percentage_to)->count();
    }

    private function getDataLelong()
    {

        $data_lelong_query = Lelong::on($this->connectionCawangan)->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate);

        $data_lelong_untung = (clone $data_lelong_query)->where('baki', '>=', 0)
            ->selectRaw('
                        sum(cajlelong) as cajLelong,
                        sum(hargajual) as jumlahLelong,
                        sum(baki) as bakiLelong
                    ')
            ->first();

        $data_lelong_rugi = (clone $data_lelong_query)->where('baki', '<', 0)
            ->selectRaw('
                        sum(cajlelong) as cajLelong,
                        sum(hargajual) as jumlahLelong,
                        abs(sum(baki)) as rugiLelong
                    ')
            ->first();


        return [
            'cas_lelong' => $data_lelong_untung->cajLelong + $data_lelong_rugi->cajLelong,
            'jumlah_lelong' => $data_lelong_untung->jumlahLelong + $data_lelong_rugi->jumlahLelong,
            'baki_lelong' => $data_lelong_untung->bakiLelong ?? 0,
            'rugi_lelong' => $data_lelong_rugi->rugiLelong ?? 0,
        ];

    }

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->whereIn('trans.norujukan', $gadaiDataOnline)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('bayaran_keuntungan');

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataOnline)
            ->whereDate('tarikh_bayaran', '>=', $this->startDate)->whereDate('tarikh_bayaran', '<=', $this->endDate);

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

        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

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

        $upahsimpanonline = $upahansurOnline;
        $total_keuntungan_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        return floatval($total_keuntungan_online);

    }

    private function getTotalKeuntunganOnlineLama()
    {
        $total_keuntunganansuran_data_online = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('transaksi_keuntungan.margin_semasa', '=' ,0.00)
            ->where('trans.kodcaw', $this->kodCawangan)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->where('transaksi_keuntungan.margin_semasa', '=' ,0.00)
            ->whereIn('trans.norujukan', $gadaiDataOnline)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('bayaran_keuntungan');

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataOnline)
            ->where('margin_semasa', '=' ,0.00)
            ->whereDate('tarikh_bayaran', '>=', $this->startDate)->whereDate('tarikh_bayaran', '<=', $this->endDate);

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

        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

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

        $upahsimpanonline = $upahansurOnline;
        $total_keuntungan_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        return floatval($total_keuntungan_online);

    }

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->whereIn('trans.norujukan', $gadaiDataOnline)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('onepercent');

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataOnline)
            ->whereDate('tarikh_bayaran', '>=', $this->startDate)->whereDate('tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->sum('onepercent_rebet');

        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

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

        $upahsimpanonline = $upahansurOnline;
        $total_onepercent_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        return floatval($total_onepercent_online);

    }

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->whereIn('trans.norujukan', $gadaiDataOnline)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('ujrah');

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataOnline)
            ->whereDate('tarikh_bayaran', '>=', $this->startDate)->whereDate('tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganbukanansuran_online = $keuntunganbukanansuran_online_query->sum('ujrah_rebet');

        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

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

        $upahsimpanonline = $upahansurOnline;
        $total_ujrah_online = floatval($upahsimpanonline) + floatval($keuntungansebenaronline);

        return floatval($total_ujrah_online);

    }

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '=', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->whereIn('trans.norujukan', $gadaiDataOnline)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_keuntunganansuran_online = $keuntunganansuran_online_query->sum('bayaran_keuntungan');

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

        $gadaiDataOnline = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganbukanansuran_data_online)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganbukanansuran_online_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataOnline)
            ->whereDate('tarikh_bayaran', '>=', $this->startDate)->whereDate('tarikh_bayaran', '<=', $this->endDate);

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

        $keuntungansebenaronline = $total_keuntunganansuran_online + $total_keuntunganbukanansuran_online;

        $upahSimpanKaunter = $this->getUpahSimpanKaunter();
        $keuntunganSebenar = $this->getKeuntunganSebenarKaunter();
        $totalKeuntunganSebenar = $upahSimpanKaunter + $keuntunganSebenar;

        return floatval($totalKeuntunganSebenar);
    }

    private function getUpahAnsurOnlineQuery()
    {
        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

        return $upahansurOnlineQuery;

    }

    private function getUpahAnsuranOnline()
    {
        $upahansurOnline = $this->getUpahAnsurOnlineQuery()->sum('upahdibayar');
        return floatval($upahansurOnline);
    }

    private function getUpahAnsuranOnlineTotal()
    {
        return $this->getUpahAnsurOnlineQuery()->count();
    }

    private function getTotalSumBayaranOnline()
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $this->kodCawangan);
        return floatval($this->getSumBayaranOnline($this->kodCawangan)) + floatval($this->getUpahAnsuranOnline());
    }

    private function getTotalStokAudit()
    {

        $stokaudit = Gadai::on($this->connectionCawangan)
            ->where(function ($query) {
                $query->where('tagpalsu', '=', 0)
                    ->where([['t_gadai', '<=', $this->endDate], ['sttebus', '=', '']])
                    ->orWhere([['t_update', '>', $this->startDate], ['sttebus', '!=', ''], ['t_gadai', '<=', $this->endDate]]);
            });

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

        $totalstokaudit_from_pinjaman = (clone $stokaudit)->whereNull('hargajualan')
            ->sum('pinjaman');

        $totalstokaudit_from_baki_pinjaman = (clone $stokaudit)->whereNotNull('hargajualan')
            ->sum('bakipjm');

        return [
            'stokAuditPembiayaan' => $totalstokaudit_from_pinjaman + $totalstokaudit_from_baki_pinjaman,
            'stokAuditNilaiMarhun' => $stokauditnilaimarhun,
            'stokAuditCount' => $stokauditcount,
        ];
    }

    private function getPetiBesiImbangDuga()
    {

        $totalbakiakhirtunai = 0;

        $vault = Vault::on($this->connectionCawangan)
            ->where('kodcaw', '=', $this->kodCawangan)
            ->where('tarikh', '<=', $this->endDate)
            ->orderby('tarikh', 'desc')->first();

        $tunai = Tunai::on($this->connectionCawangan)
            ->where('kodcaw', '=', $this->kodCawangan)
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate);

        $total = $tunai->sum('baki');

        $totalBakiAkhirTunai = $vault['bakiakhir'] ?? 0;

        if ($total != 0) {
            $totalBakiAkhirTunai = $vault['bakiakhir'] + $total;
        }

        return $totalBakiAkhirTunai;
    }

    private function getTarikhTawarruq()
    {

        $tarikhTawarruq = [
            'KB2' => '2021-04-13',
            'WCY' => '2021-05-04',
            '1STOP' => '2021-05-09',
            '020301' => '2021-05-18',
            'ALS' => '2021-05-24',
            'WB' => '2021-05-24',
            'APM' => '2021-06-08',
            'ARM' => '2021-06-08',
            '020306' => '2021-06-08',
            '010311' => '2021-06-13',
            'GC' => '2021-06-13',
            'JLI' => '2021-06-13',
            '010621' => '2021-06-15',
            'ARP' => '2021-06-15',
            '010621' => '2021-06-21',
            '010136' => '2021-06-20',
            '011235' => '2021-06-21',
            '011227' => '2021-06-21',
            '010620' => '2021-06-21',
            '010617' => '2021-06-21',
            '010915' => '2021-06-22',
            '011228' => '2021-06-22',
            '010219' => '2021-06-22',
            '011229' => '2021-06-22',
            '011230' => '2021-06-23',
            '011013' => '2021-06-23',
            '011412' => '2021-06-23',
            '011234' => '2021-06-28',
            '020303' => '2021-06-29',
            '010618' => '2021-06-29',
            '011231' => '2021-06-23',
            '011232' => '2021-06-28',
            '011233' => '2021-06-28',
        ];

        $defaultDate = '2021-01-01'; 
        return $tarikhTawarruq[Str::upper($this->kodCawangan)] ?? $defaultDate;
    }

    private function getOutstandingImbangDuga()
    {
        $rekodKoop = $this->getRekodKoopSumPinjaman();
        $rekodTawarruq = $this->getPinjamanRekodTawarruq();
        $bayaranPendahuluan = $this->getBayaranPendahuluan();

        $outstandingImbangDuga = $rekodKoop + $rekodTawarruq - $bayaranPendahuluan;

        return $outstandingImbangDuga;
    }

    private function getRekodKoopQuery()
    {
        $tarikhTawarruq = $this->getTarikhTawarruq();
        $rekodkoopquery = Gadai::on($this->connectionCawangan)
            ->where('tagpalsu', '=', 0)
            ->where([['t_gadai', '<=', $tarikhTawarruq], ['sttebus', '=', '']])
            ->orWhere([['sttebus', '!=', ''], ['t_update', '>', $this->endDate], ['t_gadai', '<=', $tarikhTawarruq]]);

        return $rekodkoopquery;
    }

    private function getRekodKoopSumPinjaman()
    {
        return floatval($this->getRekodKoopQuery()->sum('pinjaman'));

    }

    private function getRekodKoopSumNilaiMarhun()
    {
        return floatval($this->getRekodKoopQuery()->sum('nilaimarhun'));
    }

    private function getRekodKoopCount()
    {
        return floatval($this->getRekodKoopQuery()->count());
    }

    private function getRekodTawarruqQuery()
    {

        $rekodtawarruqquery = Gadai::on($this->connectionCawangan)
            ->where('tagpalsu', '=', 0)
            ->where([['t_gadai', '<=', $this->startDate], ['hargajualan', '<>', 'NULL'], ['sttebus', '=', '']])
            ->orWhere([['t_update', '>', $this->endDate], ['sttebus', '!=', ''], ['t_gadai', '<=', $this->startDate], ['hargajualan', '<>', 'null']]);

        return $rekodtawarruqquery;
    }

    private function getPinjamanRekodTawarruq()
    {
        if ($this->startDate < '2021-04-13') {
            return null;
        }

        $rekodtawarruq = $this->getRekodTawarruqQuery()->sum('pinjaman');
        return floatval($rekodtawarruq);
    }

    private function getNilaiMarhunRekodTawarruq()
    {
        $rekodtawarruqnilaimarhun = $this->getRekodTawarruqQuery()->sum('nilaimarhun');
        return floatval($rekodtawarruqnilaimarhun);
    }

    private function getBilanganRekodTawarruq()
    {
        $rekodtawarruqbil = $this->getRekodTawarruqQuery()->count();
        return floatval($rekodtawarruqbil);
    }

    private function getBayaranPendahuluan()
    {
        $daterequest = new Carbon($this->startDate);
        $daterequest->addDays(1);

        $bayaranpendahuluan_data = TransaksiKeuntungan::on('mysql7')
            ->where('tarikh_bayaran', '<=', $daterequest)
            ->where('kodcaw', $this->kodCawangan)
            ->pluck('norujukan');

        $gadaiData = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $bayaranpendahuluan_data)
            ->where([['sttebus', ''], ['hargajualan', '<>', 'null']])
            ->orWhere([['sttebus', '!=', ''], ['t_update', '>', $this->endDate], ['hargajualan', '<>', 'null']])
            ->pluck('norujukan');

        $bayaranpendahuluan = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiData)
            ->where('tarikh_bayaran', '<=', $daterequest)
            ->sum('bayaran_pembiayaan');

        return floatval($bayaranpendahuluan);
    }

    private function getUpahSimpanKaunter()
    {
        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')

            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');

        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataKaunter);

        $keuntungan_kaunter = $keuntungan_kaunter_query->sum('bayaran_keuntungan');

        $upahtebus = Tebus::on($this->connectionCawangan)
            ->whereDate('t_tebus', '>=', $this->startDate)->whereDate('t_tebus', '<=', $this->endDate)
            ->sum('upahdibayar');

        $upahlelong = Lelong::on($this->connectionCawangan)
            ->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)
            ->sum('bakiupah');

        $upahansurKaunter = Advansur::on($this->connectionCawangan)
            ->where('teller', '<>', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)
            ->sum('upahdibayar');

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type', '!=', 'A')
            ->where('trans.teller', '<>', 'Online')
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.kodcaw', '=', $this->kodCawangan);

        $total_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('keuntungan_rebet');

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

        return floatval($upahsimpankaunter);
    }

    private function getOnePercentSimpanKaunter()
    {
        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')

            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');

        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataKaunter);

        $keuntungan_onepercent = $keuntungan_kaunter_query->sum('onepercent_rebet');

        // $onepercenttebus = Tebus::on($this->connectionCawangan)
        //     ->whereDate('t_tebus', '>=', $this->startDate)->whereDate('t_tebus', '<=', $this->endDate)
        //     ->sum('onepercent');


        $onepercentlelong = Lelong::on($this->connectionCawangan)
            ->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)
            ->sum('onepercent');

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type', '!=', 'A')
            ->where('trans.teller', '<>', 'Online')
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.kodcaw', '=', $this->kodCawangan);

        $total_keuntungan_onepercent_bukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('onepercent_rebet');

        $upahsimpanonepercent = $keuntungan_onepercent + $onepercentlelong + $total_keuntungan_onepercent_bukanansuran_kaunter;

        return floatval($upahsimpanonepercent);
    }

    private function getUjrahSimpanKaunter()
    {
        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')

            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');

        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataKaunter);

        $keuntungan_ujrah = $keuntungan_kaunter_query->sum('ujrah_rebet');


        // $ujrahtebus = Tebus::on($this->connectionCawangan)
        //     ->whereDate('t_tebus', '>=', $this->startDate)->whereDate('t_tebus', '<=', $this->endDate)
        //     ->sum('ujrah');


        $ujrahlelong = Lelong::on($this->connectionCawangan)
            ->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)
            ->sum('ujrah');

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type', '!=', 'A')
            ->where('trans.teller', '<>', 'Online')
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.kodcaw', '=', $this->kodCawangan);

        $total_keuntungan_onepercent_bukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('ujrah_rebet');

        $upahsimpanujrah = $keuntungan_ujrah + $ujrahlelong + $total_keuntungan_onepercent_bukanansuran_kaunter;

        return floatval($upahsimpanujrah);
    }

    private function getUpahSimpanKaunterLama()
    {
        $keuntungan_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')

            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $keuntungan_data_kaunter)->whereNull('hargajualan')->pluck('norujukan');
        
        $keuntungan_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->whereIn('norujukan', $gadaiDataKaunter)
            ->where('margin_semasa', '=' ,0.00);

        $keuntungan_kaunter = $keuntungan_kaunter_query->sum('bayaran_keuntungan');

        // $upahtebus = Tebus::on($this->connectionCawangan)
        //     ->whereDate('t_tebus', '>=', $this->startDate)->whereDate('t_tebus', '<=', $this->endDate)
        //     ->sum('upahdibayar');

        $upahlelong = Lelong::on($this->connectionCawangan)
            ->whereDate('t_jual', '>=', $this->startDate)->whereDate('t_jual', '<=', $this->endDate)
            ->sum('bakiupah');

      

        $total_keuntunganbukanansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.trans_type', '!=', 'A')
            ->where('trans.teller', '<>', 'Online')
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.kodcaw', '=', $this->kodCawangan)
            ->where('transaksi_keuntungan.margin_semasa', '=' ,0.00);
            

        $total_keuntunganbukanansuran_kaunter = $total_keuntunganbukanansuran_data_kaunter->sum('keuntungan_rebet');

        $upahsimpankaunterlama = $keuntungan_kaunter + $upahlelong + $total_keuntunganbukanansuran_kaunter;

        return floatval($upahsimpankaunterlama);
    }

    private function getKeuntunganSebenarKaunter()
    {
        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->whereIn('transaksi_keuntungan.norujukan', $gadaiDataKaunter)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

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

        $keuntungansebenarkaunter = $total_keuntunganansuran_kaunter;

        return floatval($keuntungansebenarkaunter);
    }

    private function getKeuntunganSebenarKaunterLama()
    {
        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->where('transaksi_keuntungan.margin_semasa', '=' ,0.00)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $keuntunganansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->whereIn('transaksi_keuntungan.norujukan', $gadaiDataKaunter)
            ->where('transaksi_keuntungan.margin_semasa', '=' ,0.00)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

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

        $keuntungansebenarkaunter = $total_keuntunganansuran_kaunter;

        return floatval($keuntungansebenarkaunter);
    }

    private function getOnepercentSebenarKaunter()
    {
        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $onepercentansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->whereIn('transaksi_keuntungan.norujukan', $gadaiDataKaunter)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_onepercent_ansuran_kaunter = $onepercentansuran_kaunter_query->sum('onepercent');

        $onepercentsebenarkaunter = $total_onepercent_ansuran_kaunter;

        return floatval($onepercentsebenarkaunter);
    }

    private function getUjrahSebenarKaunter()
    {
        $total_keuntunganansuran_data_kaunter = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->whereDate('trans.created_at', '>=', $this->startDate)->whereDate('trans.created_at', '<=', $this->endDate)
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->where('trans.kodcaw', $this->kodCawangan)
            ->pluck('transaksi_keuntungan.norujukan');

        $gadaiDataKaunter = Gadai::on($this->connectionCawangan)->whereIn('norujukan', $total_keuntunganansuran_data_kaunter)->whereNotNull('hargajualan')->pluck('norujukan');

        $ujrahansuran_kaunter_query = TransaksiKeuntungan::on('mysql7')
            ->leftJoin('transaction as trans', function ($join) {
                $join->on('transaksi_keuntungan.norujukan', '=', 'trans.norujukan');
                $join->on('transaksi_keuntungan.tarikh_bayaran', '=', 'trans.created_at');
            })
            ->where('trans.teller', '<>', 'Online')
            ->where('trans.trans_type', '=', 'A')
            ->whereIn('transaksi_keuntungan.norujukan', $gadaiDataKaunter)
            ->whereDate('transaksi_keuntungan.tarikh_bayaran', '>=', $this->startDate)->whereDate('transaksi_keuntungan.tarikh_bayaran', '<=', $this->endDate);

        $total_ujrah_ansuran_kaunter = $ujrahansuran_kaunter_query->sum('ujrah');

        $ujrahsebenarkaunter = $total_ujrah_ansuran_kaunter;

        return floatval($ujrahsebenarkaunter);
    }

    public function getSerahanBayaranOnline()
    {
        $serahanpkb = '1000/020';

        $serahanbayaranOnline = GlDetail::on($this->connectionCawangan)
            ->where('ktacct', '=', $serahanpkb)
            ->where('descpt', 'like', 'SERAHAN BAYAR ONLINE%')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)
            ->where('tarikh', '>', '2021-03-24')
            ->sum('serahan');

        return floatval($serahanbayaranOnline);

    }

    private function getTotalSerahan()
    {

        $serahanpkb = '1000/020';
        $serahanjmc = '1000/026';

        $serahanpkbTawarruq = GlDetail::on($this->connectionCawangan)
            ->where('ktacct', '=', $serahanpkb)
            ->where('descpt', 'not like', 'SERAHAN BAYAR ONLINE%')
            ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)
            ->where('tarikh', '>', '2021-03-24')
            ->sum('serahan');

        $specificCawangan = [
            'KB2',
            'WCY',
            '1STOP',
            'ARM',
            'APM',
            '010621',
            '010915',
        ];

        $kodCawangan = strtoupper($this->kodCawangan);

        if (in_array($kodCawangan, $specificCawangan)) {

            $tarikhMulaTawarruq = '2013-12-31';

            $serahanpkb = GlDetail::on($this->connectionCawangan)
                ->where('dtacct', '=', $serahanpkb)
                ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)
                ->where('tarikh', '>', $tarikhMulaTawarruq)
                ->sum('amaun');

            $serahanJMC = GlDetail::on($this->connectionCawangan)
                ->where('dtacct', '=', $serahanjmc)
                ->whereDate('tarikh', '>=', $this->startDate)->whereDate('tarikh', '<=', $this->endDate)
                ->where('tarikh', '>', $tarikhMulaTawarruq)
                ->sum('amaun');

            $totalSerahan = 0;

            if ($this->startDate <= $tarikhMulaTawarruq) {
                $serahanpkblama = imbangdugalama::on($this->connectionCawangan)
                    ->sum('serahan_pkb');

                $serahanjmclama = imbangdugalama::on($this->connectionCawangan)
                    ->sum('serahan_jmc');

                $totaljmc = $serahanJMC + $serahanjmclama;
                $totalpkb = $serahanpkb + $serahanpkblama;

                $totalserahan = $serahanpkbTawarruq + $totaljmc + $totalpkb;

            } else {

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

            return floatval($totalSerahan);
        }

        return floatval($serahanpkbTawarruq);

    }

    private function getTotalPendahuluan()
    {
        $pendahuluanpkb = '7000/102';

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

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

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

        if ($this->startDate <= '2013-12-31') {
            $pendahuluanpkblama = imbangdugalama::on($this->connectionCawangan)
                ->sum('pendahuluan_pkb');

            $pendahuluanjmclama = imbangdugalama::on($this->connectionCawangan)
                ->sum('pendahuluan_jmc');

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

        } else {

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

        return floatval($totalpendahuluan);

    }

    function getBilTotalBayaranOnline()
    {

        $bayaranonlinequery = Transaction::on('mysql7')
            ->whereDate('created_at', '>=', $this->startDate)
            ->whereDate('created_at', '<=', $this->endDate)
            ->where('teller', '=', 'Online')->where('kodcaw', $this->kodCawangan);

        $bilbayaranonline = $bayaranonlinequery->count();

        $upahansurOnlineQuery = Advansur::on($this->connectionCawangan)
            ->where('teller', '=', 'Online')
            ->whereDate('tarikh', '>=', $this->startDate)
            ->whereDate('tarikh', '<=', $this->endDate);

        $bilupahansurOnline = $upahansurOnlineQuery->count();

        $biltotalbayaranonline = $bilbayaranonline + $bilupahansurOnline;

        return $biltotalbayaranonline;
    }

    private function getPanjarBulanan()
    {
        $getFirstDayOfMonthByDate = function ($date) {
            return Carbon::parse($date)->firstOfMonth();
        };

        // range start from first day of month of startDate to endDate
        $panjar = Panjar::on($this->connectionCawangan)
            ->where([
                ['tarikh', '>=', $getFirstDayOfMonthByDate($this->startDate)],
                ['tarikh', '<=', $this->endDate],
            ])
            ->sum('bayaran');

        return $panjar;
    }

    private function getPanjarTahunan()
    {
        $getFirstDayOfYearByDate = function ($date) {
            return Carbon::parse($date)->firstOfYear();
        };

        // range start from first day of year of startDate to endDate
        $panjar = Panjar::on($this->connectionCawangan)
            ->where([
                ['tarikh', '<=', $this->endDate],
                ['tarikh', '>=', $getFirstDayOfYearByDate($this->startDate)],
            ])
            ->sum('bayaran');

        return $panjar;
    }

    public function getLaporanCawanganKPI()
    {

        $laporan_harian = [];

        $total_gadai = Gadai::on($this->connectionCawangan)->whereDate('t_gadai', '>=', $this->startDate)->whereDate('t_gadai', '<=', $this->endDate)->sum('pinjaman');
        $bilangan_gadai = Gadai::on($this->connectionCawangan)->whereDate('t_gadai', '>=', $this->startDate)->whereDate('t_gadai', '<=', $this->endDate)->where('pinjaman', '>', 0)->count();
        $bilangan_customer_baru = $this->getBilanganCustomerBaru();
        $total_keuntungan_online = $this->getTotalKeuntunganOnline();
        $upahsimpankaunter = $this->getUpahSimpanKaunter();
        $keuntungansebenarkaunter = $this->getKeuntunganSebenarKaunter();
        $totalpenebusan = $this->getTotalPenebusan();

        array_push($laporan_harian, [
            'total_gadai' => $total_gadai,
            'bilangan_gadai' => $bilangan_gadai,
            'bilangan_customer_baru' => $bilangan_customer_baru,
            'total_keuntungan_online' => $total_keuntungan_online,
            'upahsimpankaunter' => $upahsimpankaunter,
            'keuntungansebenarkaunter' => $keuntungansebenarkaunter,
            'total_tebus' => $totalpenebusan,
        ]);

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