<?php

namespace App\Http\Controllers;

use App\Advansur;
use App\Audit;
use App\Cawangan;
use App\Gadai;
use App\GlDetail;
use App\Http\Controllers\TebusController as TebusController;
use App\Lelong;
use App\Services\Loggers\OnlineTransactionLoggerService;
use App\Services\OnePercentServices;
use App\Support\v2\Calculation;
use App\Support\v2\GadaiV2 as Version2Gadai;
use App\Transaction;
use App\TransactionOnline;
use App\TransactionOnlineStatus;
use App\TransaksiKeuntungan;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TransactionOnlineController extends Controller
{
    public function getTransactionOnline(Request $request)
    {
        $transactionOnline = TransactionOnline::on('mysql7')->where('norujukan',$request->norujukan)->where('billplz_id', $request->billplz_id)->first();
        return response()->json($transactionOnline);
    }

    public function getListTransactionOnlineQuery(Request $request)
    {
        
        if($request->filled('billId')){
            
            $transactionOnline = TransactionOnline::on('mysql7')
                ->where('billplz_id', $request->billId)
                ->get();
                
    
            return response()->json($transactionOnline);
        }

        $date = $request->date ? $request->date : Carbon::now()->toDateString();
        
        $transactionOnline = TransactionOnline::on('mysql7')
            ->whereDate('tarikh', $date)
            ->when($request->filled('status'), function ($query) use ($request) {
                return $query->where('status', $request->status);
            })
            ->get();

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

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

        $nosiri = TransactionOnline::on('mysql7')->where('tarikh', '=', $current->toDateString())->orderBy('nosiri', 'desc')->first();

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

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

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

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

        $transactionData = [
            'nokp' => $request->nokp,
            'reference_no' => $request->reference_no,
            'nosiri' => $request->nosiri,
            'billplz_id' => $request->billplz_id,
            'norujukan' => $request->norujukan,
            'kodcaw' => $request->kodcaw,
            'total_payment' => $request->total_payment,
            'tarikh' => $current->toDateString(),
            'masa' => $current->toTimeString(),
            'customer_name' => $request->customer_name,
            'tempohbayar' => $sag['tempoh'],
            'jenisbayaran' => $request->jenisbayaran ? $request->jenisbayaran : 'A',
        ];
        
        
        try {
            $transaction = TransactionOnline::on('mysql7')->create($transactionData);
            OnlineTransactionLoggerService::logsAfterDBTransaction($transaction->billplz_id, TransactionOnlineStatus::INITIALIZED_TRANSACTION, $transaction, $transactionData);
        } catch (\Exception $e) {
            OnlineTransactionLoggerService::logsAfterDBTransaction($transaction->billplz_id, TransactionOnlineStatus::INITIALIZED_TRANSACTION, $transactionData, $e->getMessage());
            throw $e;
        }
        

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

    public function updateStatus(Request $request)
    {
        $transaction = TransactionOnline::on('mysql7')->where('billplz_id', '=', $request->billplz_id)->update(array(
            'status' => $request->status,
            'paid_at' => $request->paid_at,
        ));

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

    public function updateTransactionOnline()
    {
        $transactions = TransactionOnline::on('mysql7')->where([['status', '=', 'PAID'], ['update_status', 0]])->get();
        $current = Carbon::now();
        $current = new Carbon();

        $checkTime = $this->checkTime();

        if($checkTime == 'rejected'){
            return response()->json('rejected-time');
        }

        foreach ($transactions as $index => $transaction) {
            $cawangan = Cawangan::on('mysql7')
                ->where('kodcaw', '=', $transaction['kodcaw'])   
                ->first();
            $gadai_data = Gadai::on($cawangan['mysql'])->where([['norujukan', $transaction['norujukan']], ['nokp', $transaction['nokp']]])->first();
            if ($transaction->jenisbayaran == 'A') {
                if ($gadai_data['hargajualan'] > 0) {
                    $response = $this->updateGadaiMarhunOnline($transaction['kodcaw'], $transaction['norujukan'], $transaction['total_payment'], $transaction['paid_at'], $transaction['tempohbayar'], $transaction['billplz_id']);
                } else {
                    $this->createAdvansur($transaction['kodcaw'], $transaction['norujukan'], $transaction['total_payment'], $transaction['paid_at']);
                }
            }

            $glDetailData = [
                'kodcaw' => $transaction['kodcaw'],
                'tarikh' => Carbon::parse($transaction['paid_at'])->format('Y-m-d'),
                'dtacct' => '1000/010',
                'ktacct' => '1000/020',
                'descpt' => 'SERAHAN BAYAR ONLINE - ' . $transaction['norujukan'],
                'serahan' => $transaction['total_payment'],
                'teller' => 'ONLINE',
                'date_created' => $current
            ];

            try {
                $glDetail = GlDetail::on($cawangan['mysql'])->create($glDetailData);
                OnlineTransactionLoggerService::logsAfterDBTransaction($transaction->billplz_id, TransactionOnlineStatus::CRONJOB_REGISTER_GLDETAIL, $glDetail, $glDetailData);
            } catch (\Exception $e) {
                OnlineTransactionLoggerService::logsAfterDBTransaction($transaction->billplz_id, TransactionOnlineStatus::CRONJOB_REGISTER_GLDETAIL, $glDetail, $e->getMessage());
                throw $e;
            }

            $transactionOnlineData = [
                'update_status' => 1,
                'update_serahan' => 1,
            ];

            try {
                $transactionOnline = TransactionOnline::on('mysql7')->where([['norujukan', $transaction['norujukan']], ['billplz_id', $transaction['billplz_id']]])->update($transactionOnlineData);
                OnlineTransactionLoggerService::logsAfterDBTransaction($transaction['billplz_id'], TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_ONLINE, $transactionOnlineData, $transactionOnline);
            } catch (\Exception $e) {
                OnlineTransactionLoggerService::logsAfterDBTransaction($transaction['billplz_id'], TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_ONLINE, $transactionOnlineData, $e->getMessage());
                throw $e;
            }
        }

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

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

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

        $bilang_bln = $tempohbayar - $gadai_data['tempohbayar'];

        $upahsemasa_raw = $bilang_bln * (($gadai_data['kadarupah'] / 100) * $gadai_data['pinjaman']);

        $upah_semasa_round = number_format($upahsemasa_raw, 2);
        $upah_semasa = substr($upah_semasa_round, 0, -1);
        if (strpos($upah_semasa, ',')) {
            $upah_semasa = str_replace(',', '', $upah_semasa);
        }
        // $upah_semasa = floatval(preg_replace('/[^\d.]/', '', $upah_semasa));
        return $upah_semasa;
    }

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

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

        $bilang_bln = $tempohbayar - $gadai_data['tempohbayar'];

        $upahrebet_raw = $bilang_bln * (($gadai_data['kadarupah'] / 100) * $gadai_data['bakipjm']);

        $upah_rebet_round = number_format($upahrebet_raw, 2);
        $upah_rebet = substr($upah_rebet_round, 0, -1);
        if (strpos($upah_rebet, ',')) {
            $upah_rebet = str_replace(',', '', $upah_rebet);
        }
        // $upah_rebet = floatval(preg_replace('/[^\d.]/', '', $upah_rebet));

        return $upah_rebet;
    }

    // public function updateGadaiMarhunKaunter($kodcaw,$norujukan,$bayaran,$paid_at,$tempohbayar){
    //     $current = Carbon::now();
    //     $current = new Carbon();

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

    //     if($tempohbayar == 0.0){
    //         $tempohbayar = $gadai['tempoh'];
    //     }

    //     $upahsemasa = $this->kiraupahTawarruq($kodcaw,$norujukan,$tempohbayar);
    //     $upahrebet = $this->kiraUpahRebet($kodcaw,$norujukan,$tempohbayar);

    //     $total_bayaran_prev = Transaction::on('mysql7')->where([['norujukan','=',$norujukan],['trans_type','=','A']])->sum('duit_masuk');

    //     $total_bayaran_semasa = $total_bayaran_prev + $bayaran;

    //     if($total_bayaran_semasa >= $gadai['bakiupah']){
    //         $lelong_tawarruq = 0;
    //     }else{
    //         $lelong_tawarruq = 1;
    //     }
    //     $onepercent = new OnePercentServices();

    //     $old_data = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->first();
    //     $margin_semasa = ($gadai['bakipjm'] / $gadai['nilaimarhun']) * 100;
    //     $keuntungan = $onepercent->kiraanKeuntunganSebenar($gadai['bakipjm'],$gadai['nilaimarhun'],$gadai['kadarupah'],$margin_semasa);
    //     $ujrahasal = $onepercent->kiraanUjrahSebenar($gadai['nilaimarhun'],$gadai['kadarupah'],$gadai['margin_semasa']);

    //     if($gadai['tagbaru'] == 1){
    //         $upah_semasa = $keuntungan;
    //     }

    //     $baki_hargajualan = $gadai['bakihargajualan'] - $bayaran;

    //     $baki_bayaran = $bayaran - $upahsemasa;
    //     //$baki_bayaran = $bayaran - $upah_semasa;

    //     $baki_pinjaman = $gadai['bakipjm'] - $baki_bayaran;

    //     $margin_semasa = ($gadai['bakipjm'] / $gadai['nilaimarhun']) * 100;

    //     $keuntungan = $onepercent->kiraanKeuntunganSebenar($gadai['bakipjm'],$gadai['nilaimarhun'],$gadai['kadarupah'],$margin_semasa);
    //     $ujrahasal = $onepercent->kiraanUjrahSebenar($gadai['nilaimarhun'],$gadai['kadarupah'],$gadai['margin_semasa']);

    //     $onepercentasal = $gadai['pinjaman'] * (1/100);

    //     try {

    //         DB::connection('mysql7')->transaction(function () use($onepercentasal,$ujrahasal,$keuntungan,$norujukan,$gadai,$kodcaw,$current,$baki_hargajualan,$upahsemasa,$baki_bayaran,$upahrebet,$cawangan,$old_data,$baki_pinjaman,$lelong_tawarruq,$margin_semasa,$bayaran,$upah_semasa) {

    //             $transaction = Transaction::on('mysql7')->create([
    //                 'trans_type' => 'A',
    //                 'norujukan' => $norujukan,
    //                 'nokp' => $gadai['nokp'],
    //                 'teller' => 'Online',
    //                 'kodcaw' => $kodcaw,
    //                 'duit_masuk' => $bayaran,
    //                 'created_at' => $current,
    //                 'bakiharga' => $baki_hargajualan,
    //             ]);

    //             if($gadai['tempoh'] >= 12.0){
    //                 $tempoh = 12;
    //             }else{
    //                 $tempoh = $gadai['tempoh'];
    //             }
    //             $bilang_bln = $tempoh - $gadai['tempohbayar'];

    //                 $transaction_upah = TransaksiKeuntungan::on('mysql7')->create([
    //                 'norujukan' => $norujukan,
    //                 'bayaran_keuntungan' => $upahsemasa,
    //                 'bayaran_pembiayaan' => $baki_bayaran,
    //                 'keuntungan_rebet'=> $upahrebet,
    //                 'tarikh_bayaran'=> $current,
    //                 'kodcaw'=> $kodcaw,
    //                 'ujrah' => ($keuntungan['ujrah'] * $bilang_bln),
    //                 'ujrah_rebet' => ($ujrahasal*$bilang_bln),
    //                 'onepercent' => ($onepercentasal * $bilang_bln),
    //                 'onepercent_rebet' => ($keuntungan['onepercent'] * $bilang_bln),
    //                 'tempoh' => $gadai['tempoh'],
    //                 'beza_tempoh' => $bilang_bln,
    //                 'margin_semasa' => $margin_semasa,
    //                 ]);
    //

    //             DB::connection($cawangan['mysql'])->transaction(function () use($cawangan,$baki_pinjaman,$current,$norujukan,$gadai,$baki_hargajualan,$lelong_tawarruq,$margin_semasa){

    //                 $margin_updated = ($baki_pinjaman / $gadai['nilaimarhun']) * 100;

    //                 $update_gadai = Gadai::on($cawangan['mysql'])->where('norujukan','=',$norujukan)->update(array(
    //                     'bakipjm' => $baki_pinjaman,
    //                     'jbg' => 0,
    //                     't_update' => $current->toDateString(),
    //                     'bakihargajualan' => $baki_hargajualan,
    //                     'tempohbayar' => $gadai['tempoh'],
    //                     'lelong_tawarruq' => $lelong_tawarruq,
    //                     'margin_semasa' => $margin_updated,
    //                 ));
    //             });

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

    //             $audit = new Audit();
    //             $audit->users = 'Online';
    //             $audit->actions = 'Bayaran Ansuran';
    //             $audit->norujukan = $norujukan;
    //             $audit->new_data = $new_data;
    //             $audit->old_data = $old_data;
    //             $audit->kodcaw = $kodcaw;
    //             $audit->created_at = $current;
    //             $audit->updated_at = $current;
    //             $audit->save();

    //             if(!$transaction || !$transaction_upah) {
    //                 throw new \Exception('One of the database operations failed.');
    //             }

    //             DB::commit();

    //         });
    //     }catch(\Exception $e){
    //         Log::error("Transaction failed: " . $e->getMessage());
    //         return response()->json("Transaction failed: " . $e->getMessage(),500);
    //     }

    //     return response()->json("success",200);
    // }

    public function updateGadaiMarhunOnline($kodcaw, $norujukan, $bayaran, $paid_at, $tempohbayar, $bill_id)
    {
        $current = Carbon::now();
        $current = new Carbon();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();
        $gadai = Gadai::on($cawangan['mysql'])->where('norujukan', '=', $norujukan)->first();

        if ($tempohbayar == 0.0) {
            $tempohbayar = $gadai['tempoh'];
        }

        $upahrebet = $this->kiraUpahRebet($kodcaw, $norujukan, $tempohbayar);

        $total_bayaran_prev = Transaction::on('mysql7')->where([['norujukan', '=', $norujukan], ['trans_type', '=', 'A']])->sum('duit_masuk');

        $total_bayaran_semasa = $total_bayaran_prev + $bayaran;

        if ($total_bayaran_semasa >= $gadai['bakiupah']) {
            $lelong_tawarruq = 0;
        } else {
            $lelong_tawarruq = 1;
        }
        $onepercent = new OnePercentServices();

        $old_data = Gadai::on($cawangan['mysql'])->where('norujukan', '=', $norujukan)->first();
        $margin_semasa = ($gadai['bakipjm'] / $gadai['nilaimarhun']) * 100;

        $baki_hargajualan = $gadai['bakihargajualan'] - $bayaran;

        $margin_semasa = ($gadai['bakipjm'] / $gadai['nilaimarhun']) * 100;

        try {

            DB::connection('mysql7')->transaction(function () use ($norujukan, $gadai, $kodcaw, $current, $baki_hargajualan, $cawangan, $old_data, $lelong_tawarruq, $margin_semasa, $bayaran, $tempohbayar, $bill_id, $paid_at) {

                $data = [
                    'trans_type' => 'A',
                    'norujukan' => $norujukan,
                    'nokp' => $gadai['nokp'],
                    'teller' => 'Online',
                    'kodcaw' => $kodcaw,
                    'duit_masuk' => $bayaran,
                    'created_at' => $paid_at,
                    'bakiharga' => $baki_hargajualan,
                ];

                try {
                    $transaction = Transaction::on('mysql7')->create($data);
                    OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSACTION, $data, $transaction);
                } catch (\Exception $e) {
                    OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSACTION, $data, $e->getMessage());
                    throw $e;
                }

                if ($gadai['tempoh'] >= 12.0) {
                    $tempoh = 12;
                } else {
                    $tempoh = $gadai['tempoh'];
                }
                $bilang_bln = $tempoh - $gadai['tempohbayar'];

                if ($gadai['tagbaru'] == 0) {
                    $upahsemasa = $this->kiraupahTawarruq($kodcaw, $norujukan, $tempohbayar);
                    $baki_bayaran = $bayaran - $upahsemasa;
                    $upahsemasa = $this->kiraupahTawarruq($kodcaw, $norujukan, $tempohbayar);
                    $upahrebet = $this->kiraUpahRebet($kodcaw, $norujukan, $tempohbayar);

                    $dataTransactionUpah = [
                        'norujukan' => $norujukan,
                        'bayaran_keuntungan' => $upahsemasa,
                        'bayaran_pembiayaan' => $baki_bayaran,
                        'keuntungan_rebet' => $upahrebet,
                        'tarikh_bayaran' => $current,
                        'kodcaw' => $kodcaw,
                        'ujrah' => 0,
                        'ujrah_rebet' => 0,
                        'onepercent' => 0,
                        'onepercent_rebet' => 0,
                        'tempoh' => 0,
                        'beza_tempoh' => 0,
                        'margin_semasa' => 0,
                        'tarikh_bayaran' => $paid_at,
                    ];

                    try {
                        $transaction_upah = TransaksiKeuntungan::on('mysql7')->create($dataTransactionUpah);
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_KEUNTUNGAN, $dataTransactionUpah, $transaction_upah);
                    } catch (\Exception $e) {
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_KEUNTUNGAN, $dataTransactionUpah, $e->getMessage());
                        throw $e;
                    }

                } else {

                    $onepercent = new OnePercentServices();
                    $keuntungan = $onepercent->kiraanKeuntunganRebet($gadai['bakipjm'], $gadai['nilaimarhun'], $gadai['kadarupah'], $gadai['margin_semasa']);
                    $ujrahasal = $onepercent->kiraanUjrahSebenar($gadai['nilaimarhun'], $gadai['kadarupah'], $gadai['percentpinj']);
                    $onepercentasal = $gadai['pinjaman'] * (1 / 100);

                    $gadaionepercent = new Version2Gadai($kodcaw, $cawangan);

                    $upahsemasa = $gadaionepercent->kiraupahOnePercent($norujukan);
                    $upahrebet = $gadaionepercent->kiraUpahRebet($norujukan);
                    $baki_bayaran = $bayaran - $upahsemasa;

                    $ujrah_calculation = $this->getUjrah($kodcaw, $norujukan);

                    $onepercent = new Calculation();
                    $ujrahasal = $onepercent->getRoundedMethod($ujrahasal);
                    $onepercentasal = $onepercent->getRoundedMethod($onepercentasal);
                    $ujrah = $onepercent->getRoundedMethod($ujrahasal * $bilang_bln);
                    $ujrah_rebate = $onepercent->getRoundedMethod($keuntungan['ujrah'] * $bilang_bln);
                    $keun = $onepercent->getRoundedMethod($onepercentasal * $bilang_bln);
                    $keuntungan_rebate = $onepercent->getRoundedMethod($keuntungan['onepercent'] * $bilang_bln);

                    $dataTransactionUpah = [
                        'norujukan' => $norujukan,
                        'bayaran_keuntungan' => $upahsemasa,
                        'bayaran_pembiayaan' => $baki_bayaran,
                        'keuntungan_rebet' => $upahrebet,
                        'tarikh_bayaran' => $current,
                        'kodcaw' => $kodcaw,
                        'ujrah' => $ujrah,
                        'ujrah_rebet' => $ujrah_rebate,
                        'onepercent' => $keun,
                        'onepercent_rebet' => $keuntungan_rebate,
                        'tempoh' => $gadai['tempoh'],
                        'beza_tempoh' => $bilang_bln,
                        'margin_semasa' => $margin_semasa,
                        'tarikh_bayaran' => $paid_at,
                    ];

                    try {
                        $transaction_upah = TransaksiKeuntungan::on('mysql7')->create($dataTransactionUpah);
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_KEUNTUNGAN, $dataTransactionUpah, $transaction_upah);
                    } catch (\Exception $e) {
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_TRANSAKSI_KEUNTUNGAN, $dataTransactionUpah, $e->getMessage());
                        throw $e;
                    }
                }

                $baki_pinjaman = $gadai['bakipjm'] - $baki_bayaran;
                DB::connection($cawangan['mysql'])->transaction(function () use ($cawangan, $baki_pinjaman, $current, $norujukan, $gadai, $baki_hargajualan, $lelong_tawarruq, $margin_semasa, $bill_id) {

                    $margin_updated = ($baki_pinjaman / $gadai['nilaimarhun']) * 100;

                    $updateGadaiData = [
                        'bakipjm' => $baki_pinjaman,
                        'jbg' => 0,
                        't_update' => $current->toDateString(),
                        'bakihargajualan' => $baki_hargajualan,
                        'tempohbayar' => $gadai['tempoh'],
                        'lelong_tawarruq' => $lelong_tawarruq,
                        'margin_semasa' => $margin_updated,
                    ];

                    try {
                        $update_gadai = Gadai::on($cawangan['mysql'])->where('norujukan', '=', $norujukan)->update($updateGadaiData);
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_GADAI, $updateGadaiData, $update_gadai);
                    } catch (\Exception $e) {
                        OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_UPDATE_GADAI, $updateGadaiData, $e->getMessage());
                        throw $e;
                    }

                });

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

                $auditData = [
                    'users' => 'Online',
                    'actions' => 'Bayaran Ansuran',
                    'norujukan' => $norujukan,
                    'new_data' => $new_data,
                    'old_data' => $old_data,
                    'kodcaw' => $kodcaw,
                    'created_at' => $current,
                    'updated_at' => $current,
                ];

                try {
                    $audit = Audit::create($auditData);
                    OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_REGISTER_AUDIT, $auditData, $audit);
                } catch (\Exception $e) {
                    OnlineTransactionLoggerService::logsAfterDBTransaction($bill_id, TransactionOnlineStatus::CRONJOB_REGISTER_AUDIT, $auditData, $e->getMessage());
                    throw $e;
                }

                if (!$transaction || !$transaction_upah) {
                    throw new \Exception('One of the database operations failed.');
                }

                DB::commit();
            });
        } catch (\Exception $e) {
            Log::error("Transaction failed: " . $e->getMessage());
            return response()->json("Transaction failed: " . $e->getMessage(), 500);
        }

        return response()->json("success", 200);
    }

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

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

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

        $create_advansur = Advansur::on($cawangan['mysql'])->create([
            'tarikh' => Carbon::parse($paid_at)->toDateString(),
            'noresit' => 0,
            'norujukan' => $norujukan,
            'nopelanggan' => $gadai['nopelanggan'],
            'nilaimarhun' => $gadai['nilaimarhun'],
            'pinjaman' => $gadai['pinjaman'],
            'kadarupah' => $gadai['kadarupah'],
            'glcode' => "1000/010",
            'upahsebenar' => $bayaran,
            'upahDibayar' => $bayaran,
            'teller' => 'Online',
            'prkod' => $gadai['prkod'],
            'jbg' => $gadai['tempoh'],
            'nowakil' => 0,
            'hubungan' => 0,
            'status' => 0,
            'historygadaian' => $norujukan,
        ]);

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

    public function getTransactionOnlineLogin(Request $request)
    {
        $transactionOnline = TransactionOnline::on('mysql7')->where('billplz_id', $request->billplz_id)->get();

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

    public function searchSAGOnline(Request $request)
    {

        $current = Carbon::now();
        $current = new Carbon();
        $boolmasa = false;
        $transaction_online = TransactionOnline::on('mysql7')->where([['norujukan', $request->norujukan], ['status', 'PAID'], ['update_status', 0], ['tarikh', $current->toDateString()]])->first();

        $transaction_masa = TransactionOnline::on('mysql7')->where([['norujukan', $request->norujukan], ['status', 'NOT PAID'], ['tarikh', $current->toDateString()]])
            ->orderBy('masa', 'desc')->first();

        if ($transaction_masa) {
            $carbonmasa = new Carbon($transaction_masa['masa']);
            $carbonmasaexpired = new Carbon($transaction_masa['masa']);
            $carbonmasaexpired->addMinutes(10);

            $boolmasa = ($carbonmasaexpired->greaterThanOrEqualTo($current) && $carbonmasa->lessThanOrEqualTo($current)) ? true : false;
        }

        if ($transaction_online || $boolmasa) {
            return response()->json(true);
        } else {
            return response()->json(false);
        }
    }

    public function getListUnsuccessful()
    {
        $list = TransactionOnline::on('mysql7')->where('status', 'NOT PAID')->orderBy('id', 'desc')->take(10)->get();

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

    public function updateUnsuccessfulTransaction(Request $request)
    {
        $transaction = TransactionOnline::on('mysql7')->where('billplz_id', '=', $request->billplz_id)->update(array(
            'status' => $request->status,
            'paid_at' => $request->paid_at,
        ));

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

    public function CustomerInfo(Request $request)
    {

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

        foreach ($cawangan_all as $index => $cawangan) {
            $gadai = Gadai::on($cawangan['mysql'])
                ->where([['sttebus', '=', ''], ['taglel', 0], ['nokp', '=', $request->ic]])
                ->orderBy('t_gadai', 'desc')
                ->get()->toArray();
            //dd($gadai, $cawangan);
            if (sizeof($gadai) != 0) {
                foreach ($gadai as $gad) {

                    if ($gad['tagbaru'] == 1) {
                        $jenis = 'onepercent';
                    } else {
                        $jenis = 'asal';
                    }

                    $array_utg = new \Illuminate\Http\Request([
                        'jeniskeuntungan' => $jenis,
                    ]);

                    $result = (new TebusController)->upahTawarruq($gad['kodcaw'], $gad['norujukan'], $array_utg);

                    if ($jenis == 'onepercent') {
                        $gad['keuntungan'] = $result['pendapatan'];
                    } else {
                        $gad['keuntungan'] = $result;
                    }
                    array_push($gadai_all, $gad);
                }
            }

            if ($cawangan['tagarrahnbid'] == 1) {
                $akanlelong = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus', '=', ''], ['taglel', 1], ['nokp', '=', $request->ic]])
                    ->get()->toArray();
            } else {
                $akanlelong = Gadai::on($cawangan['mysql'])
                    ->where([['sttebus', '=', ''], ['taglel', 1], ['nokp', '=', $request->ic]])
                    ->rightJoin('lelong', 'gadai.norujukan', '=', 'lelong.norujukan')
                    ->get()->toArray();
            }

            if (sizeof($akanlelong) != 0) {
                foreach ($akanlelong as $lelong) {

                    if ($lelong['tagbaru'] == 1) {
                        $jenis = 'onepercent';
                    } else {
                        $jenis = 'asal';
                    }

                    $array_utg = new \Illuminate\Http\Request([
                        'jeniskeuntungan' => $jenis,
                    ]);

                    $result = (new TebusController)->kiraupahTawarruq($lelong['kodcaw'], $lelong['norujukan'], $array_utg);
                    $lelong['keuntungan'] = $result;
                    array_push($akanlelongarray, $lelong);
                }
            }
        }

        return response()->json(
            array(
                'gadai' => $gadai_all,
                'lelong' => $akanlelongarray,
            ),
            200
        );
    }

    public function updateTagPortal(Request $request)
    {
        $transaction = TransactionOnline::on('mysql7')->where('billplz_id', '=', $request->billplz_id)->update(array(
            'tagportal' => 1,
        ));

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

    public function getUjrah($kodcaw, $norujukan)
    {
        try {

            $gadai = (new GadaiController())->showOneGadaibyRujukanAndCawangan($kodcaw, $norujukan)
                ->getData()[0];

            $jenis_keuntungan = $gadai->tagbaru === 1 ? 'onepercent' : 'asal';

            $request_upah_tawarruq = new Request(['jeniskeuntungan' => $jenis_keuntungan]);
            $request_upah_rebet_tawarruq = new Request(['jeniskeuntungan' => $jenis_keuntungan]);

            $upah_tawarruq = (new TebusController())->upahTawarruq($kodcaw, $norujukan, $request_upah_tawarruq);
            $upah_rebet_tawarruq = (new TebusController())->upahRebetTawarruq($kodcaw, $norujukan, $request_upah_rebet_tawarruq);

            if ($jenis_keuntungan === 'onepercent') {
                $ujrah_sebenar = (float) $upah_tawarruq['ujrah'];
                $ujrah_rebet = $ujrah_sebenar - (float) $upah_rebet_tawarruq['ujrah'];

                return [
                    'ujrah_sebenar' => $ujrah_sebenar,
                    'ujrah_rebet' => $ujrah_rebet,
                ];
            }

            return [
                'ujrah_sebenar' => (float) $upah_tawarruq,
                'ujrah_rebet' => (float) $upah_rebet_tawarruq,
            ];
        } catch (\Throwable $th) {
            Log::error($th);
            return $th;
        }
    }

    private function checkTime(){
        $current = Carbon::now();

        $startRange1 = Carbon::today()->setTime(19, 0);
        $endRange1 = Carbon::today()->setTime(19, 30);
    
        $startRange2 = Carbon::today()->setTime(23, 0);
        $endRange2 = Carbon::today()->setTime(23, 30);
    
        if ($current->between($startRange1, $endRange1) || $current->between($startRange2, $endRange2)) {
            return 'rejected';
        }
    }

    public function CustomerInfoLelong(Request $request){
        $cawangan_all = Cawangan::on('mysql7')->get();
        $totalBakiLelong = 0;
        $totalRugiLelong = 0;

        foreach ($cawangan_all as $index => $cawangan) {
        $gadai = Gadai::on($cawangan['mysql'])
                ->where('nokp', '=', $request->ic)
                ->where('sttebus','=','L')
                ->orderBy('t_gadai', 'desc')
                ->get()->toArray();

            if (sizeof($gadai) != 0) {
                foreach ($gadai as $gad) {
                    $bakilelong = Lelong::on($cawangan['mysql'])
                    ->where(function($query) {
                        $query->whereNull('trkhtuntut')
                              ->orWhere('trkhtuntut', '=', '');
                    })
                    ->where('norujukan', '=' ,$gad['norujukan'])
                    ->where('baki', '>=', 0)
                    ->sum('baki');

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

                    $totalBakiLelong += $bakilelong;
                    $totalRugiLelong += $rugilelong;
                }
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Data retrieved successfully',
            'data' => [
                'bakilelong' => $totalBakiLelong,
                'rugilelong' => $totalRugiLelong,
            ]
        ], 200);
    }
}
