<?php

namespace App\Services\Transaction;

use App\Audit;
use App\Gadai;
use App\Tunai;
use App\Transaction;
use App\TransaksiKeuntungan;
use App\Cawangan;
use App\Mohon;
use App\Mohonid;
use App\TransaksiGadai;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AnsuranServices
{

    /*
        //////////////
        /// NOTED ///
        ////////////

        1. Pembaharuan untuk Hapus Ansuran.

    */
    
    
    protected $cawangan = 'KB2';

    public function __construct($kodcaw){
        $this->cawangan = $kodcaw;
    }

    public function delete(Request $request): String{
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$this->cawangan)->first();
        $tarikh_request = new Carbon($request->tarikh);
        $tarikh = Carbon::now();
        $harisemasa = $tarikh->toDateString();

        $audit = new Audit();
        $audit->users = $request->teller;
        $audit->actions = 'Hapus Ansuran';
        $audit->norujukan = $request->norujukan;
        $audit->new_data = '';

        if($harisemasa !== $tarikh_request->toDateString()){
            Log::debug('Date mismatch: ' . $harisemasa . ' vs ' . $tarikh_request->toDateString());
            return 'date not equal';
        }
        $transaction_gadai = TransaksiGadai::on('mysql7')->where('id',$request->tg_id)->first();
        $transaction = Transaction::on('mysql7')->where('id',$transaction_gadai['transaction_id'])->first();

        if($transaction['teller'] != $request->teller){
            return 'wrong teller';
        }

        $audit->old_data = $transaction_gadai;
        

        try{
            DB::connection('mysql7')->transaction(function () use($cawangan,$request,$harisemasa,$transaction,$transaction_gadai,$audit){

                try{
                    DB::connection($cawangan['mysql'])->transaction(function () use($cawangan,$request,$transaction_gadai,$harisemasa,$transaction){

                        Gadai::on($cawangan['mysql'])->where('norujukan',$request->norujukan)->update(array(
                            'percentpinj' => $transaction_gadai['percentpinj'],
                            'bakipjm' => $transaction_gadai['bakipjm'],
                            'tempoh' => $transaction_gadai['tempoh'],
                            't_update' => $transaction_gadai['t_update'],
                            'bakihargajualan' => $transaction_gadai['bakihargajualan'],
                            'tempohbayar' => $transaction_gadai['tempohbayar'],
                            'lelong_tawarruq' => $transaction_gadai['lelong_tawarruq'],
                            'margin_semasa' => $transaction_gadai['margin_semasa'],
                            'tunggakanujrah' => $transaction_gadai['tunggakanujrah'],
                            'tunggakanonepercent' => $transaction_gadai['tunggakanonepercent'],
                        ));

                        $tunai = Tunai::on($cawangan['mysql'])->where('kodlaluan',$request->teller)->where('tarikh',$harisemasa)->first();


                        $total = $tunai['masuk'] - $transaction['duit_masuk'];
                        $bakiakhir = $tunai['bakiawal'] - $tunai['keluar'] + $total + $tunai['tambah'] - $tunai['serahan'];


                        Tunai::on($cawangan['mysql'])->where('tarikh',$harisemasa)->where('kodlaluan',$request->teller)->update(['masuk' => $total,'baki' => $bakiakhir]);
                        
                    });
                }catch(\Exception $e){
                    DB::connection('mysql7')->rollBack();
                    Log::debug($e->getMessage());
                    return  'error';
                }

                Transaction::on('mysql7')->where('id',$transaction_gadai['transaction_id'])->delete();
                TransaksiKeuntungan::on('mysql7')->where('id',$transaction_gadai['transaksiupah_id'])->delete();

                TransaksiGadai::on('mysql7')->where('id',$request->tg_id)->update(array(
                    'softDelete' => 1,
                ));

                $gadai_updated = Gadai::on($cawangan['mysql'])
                                ->select('percentpinj','bakipjm','tempoh','t_update','bakihargajualan','tempohbayar','lelong_tawarruq','margin_semasa','tunggakanujrah','tunggakanonepercent')
                                ->where('norujukan',$request->norujukan)->first();

                $tarikh_audit = Carbon::now();
                $audit->new_data = $gadai_updated;
                $audit->kodcaw = $this->cawangan;
                $audit->created_at = $tarikh_audit;
                $audit->updated_at = $tarikh_audit;
                $audit->save();


                return 'success';

            });
        }catch(\Exception $error){
            DB::connection($cawangan['mysql'])->rollBack();
            DB::connection('mysql7')->rollBack();
            Log::debug($error->getMessage());
            return  'error';
        }
        
        return 'success';
    }

    public function getLatestAdvanceWithoutDelete(Request $request){
        $tarikh = Carbon::now();

        $latest = TransaksiGadai::on('mysql7')->whereDate('created_at',$tarikh->toDateString())->where('norujukan',$request->norujukan)->where('softDelete',0)->latest()->first();

        return $latest;
    }

    public function getApprovalFromOperation(Request $request){
        $tarikh = Carbon::now();
        $cawangan = Cawangan::on('mysql7')->where('kodcaw','=',$this->cawangan)->first();

        $latest = Mohon::on($cawangan['mysql'])
            ->whereDate('tarikh',$tarikh->toDateString())
            ->where('teller',$request->teller)
            ->where('masalulus','=','')
            ->where('operasi','=','')
            ->where('status','Hapus Ansuran')
            ->latest('tarikh')
            ->first();

        return $latest;
    }


}
