<?php

namespace App\Services\Miscellaneous;

use App\Audit;
use App\Cawangan;
use App\Denominasi;
use App\DenoPanjar;
use App\Panjar;
use App\Vault;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PanjarServices
{

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

        1. tak buat lgi untuk perubatan. just untuk buat yang panjar biasa.

    */
    
    
    protected $cawangan = 'KB2';
    protected $namelist_deno = [
        'bd1' => 100,'bd5' => 500,'bd10' => 1000,'bd20' => 1000,'bd50' => 5000,'bd100' => 5000,
        'txtsen1' => 0.01,'txtsen5' => 0.05,'txtsen10' => 0.10,'txtsen20' => 0.20,'txtsen50' => 0.50,
        'txtring1' => 1,'txtring5' => 5,'txtring10' => 10,'txtring20' => 20,'txtring50' => 50,
        'txtring100' => 100,'txtring1000' => 1000,        
    ];

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

    private function calculation_denominasi($array_deno = [],$denominasi = [],$jenis_panjar){

        if(empty($array_deno) && empty($denominasi)){
            return empty($array_deno);
            return 'no data';
        }

        if($jenis_panjar != 'masuk' && $jenis_panjar != 'keluar') return 'no data';

        $records = [];
        foreach($this->namelist_deno as $deno => $value){
            $total_deno = 0;$total = 0;
            $total_deno = ($jenis_panjar == 'masuk') ? $denominasi[$deno] += intval($array_deno[$deno]) : $denominasi[$deno] -= intval($array_deno[$deno]);
            $total = ($total_deno * $value);

            $records[$deno] = [
                'keping' => $total_deno,
                'jumlah' => $total
            ];
        }

        /* total Keping */
        $total_keping =  array_sum(array_column($records, 'jumlah'));

        /* Total Bundle */
        $filteredKeys = array_filter(array_keys($records), function($key) {
            return strpos($key, 'bd') !== false;
        });
      
        $filteredRecords = array_filter($records, function($record,$key) use ($filteredKeys) {
            return in_array($key, $filteredKeys);
        }, ARRAY_FILTER_USE_BOTH);

        $total_bundle = array_sum(array_column($filteredRecords, 'jumlah'));
        
        return [
            'deno' => $records,
            'total' => $total_keping,
            'total_bundle' => $total_bundle,
            'total_all' => ($total_keping + $total_bundle),
        ];
    }

    private function checkModal($jenismodal){
        switch ($jenismodal) {
            case "selenggara":
                $kategori = "Baiki dan Selenggara";
                $tag = 2;
               break;
            case "keraian":
                $kategori = "Keraian & Promosi";
                $tag = 3;
               break;
            case "belanjaam":
                $kategori = "Belanja AM";
                $tag = 1;
               break;
            case "perubatan":
                $kategori = "Belanja AM - Perubatan";
                $tag = 1;
               break;
            case "dapur":
                $kategori = "Belanja AM - Barangan Dapur";
                $tag = 1;
               break;
            case "pos":
                $kategori = "Belanja AM - Postage";
                $tag = 1;
               break;
          }

          return ['kategori' => $kategori, 'tag' => $tag];
    }

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

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $this->cawangan)->first();
        $denominasi = Denominasi::on($cawangan['mysql'])->latest('tarikh')->first();
        $panjar = Panjar::on($cawangan['mysql'])->latest('tarikh')->where('nobaucer', $request->nobaucer)->first();
        $vault = Vault::on($cawangan['mysql'])->latest('tarikh')->first();
        $deno_panjar = DenoPanjar::on('mysql7')->where('kodcaw', $this->cawangan)->where('recno', $request->recno)->latest('tarikh','masa')->first();
        try{
            if (!$panjar) throw new \Exception('Custom Exception: Panjar Does Not Exist!');
            if (!$denominasi) throw new \Exception('Custom Exception: Denominasi Does Not Exist!');
            if (!$vault) throw new \Exception('Custom Exception: Vault Does Not Exist!');
            if (!$deno_panjar) throw new \Exception('Custom Exception: Denominasi Panjar Does Not Exist!');
            
            return DB::transaction(function () use ($cawangan,$deno_panjar,$panjar,$denominasi,$current,$vault) {

                $return_data = $this->calculation_denominasi($deno_panjar,$denominasi,'masuk');
                if($return_data == 'no data') throw new \Exception('Custom Exception: Denominasi Panjar Not Return Data');

                Denominasi::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()]])->update(array(
                    'bd1' => $return_data['deno']['bd1']['keping'],
                    'b1'=> $return_data['deno']['bd1']['jumlah'],
                    'bd5'=> $return_data['deno']['bd5']['keping'],
                    'b5'=> $return_data['deno']['bd5']['keping'],
                    'bd10'=> $return_data['deno']['bd10']['keping'],
                    'b10'=> $return_data['deno']['bd10']['jumlah'],
                    'bd20'=> $return_data['deno']['bd20']['keping'],
                    'b20'=> $return_data['deno']['bd20']['jumlah'],
                    'bd50'=> $return_data['deno']['bd50']['keping'],
                    'b50'=> $return_data['deno']['bd50']['jumlah'],
                    'bd100'=> $return_data['deno']['bd100']['keping'],
                    'b100'=> $return_data['deno']['bd100']['jumlah'],
                    'txtring1'=> $return_data['deno']['txtring1']['keping'],
                    'k1'=> $return_data['deno']['txtring1']['jumlah'],
                    'txtring5'=> $return_data['deno']['txtring5']['keping'],
                    'k5'=> $return_data['deno']['txtring5']['jumlah'],
                    'txtsen1'=> $return_data['deno']['txtsen1']['keping'],
                    'k01'=> $return_data['deno']['txtsen1']['jumlah'],
                    'txtsen5'=> $return_data['deno']['txtsen5']['keping'],
                    'k05'=> $return_data['deno']['txtsen5']['jumlah'],
                    'txtsen10'=> $return_data['deno']['txtsen10']['keping'],
                    'k010'=> $return_data['deno']['txtsen10']['jumlah'],
                    'txtsen20'=> $return_data['deno']['txtsen20']['keping'],
                    'k020'=> $return_data['deno']['txtsen20']['jumlah'],
                    'txtsen50'=> $return_data['deno']['txtsen50']['keping'],
                    'k050'=> $return_data['deno']['txtsen50']['jumlah'],
                    'txtring10'=> $return_data['deno']['txtring10']['keping'],
                    'k10'=> $return_data['deno']['txtring10']['jumlah'],
                    'txtring20'=> $return_data['deno']['txtring20']['keping'],
                    'k20'=> $return_data['deno']['txtring20']['jumlah'],
                    'txtring50'=> $return_data['deno']['txtring50']['keping'],
                    'k50'=> $return_data['deno']['txtring50']['jumlah'],
                    'txtring100'=> $return_data['deno']['txtring100']['keping'],
                    'k100'=> $return_data['deno']['txtring100']['jumlah'],
                    'txtring1000'=> $return_data['deno']['txtring1000']['keping'],
                    'k1000'=> $return_data['deno']['txtring1000']['jumlah'],
                    'jumlahbundle'=> $return_data['total_bundle'],
                    'txtjumlah'=> $return_data['total_all'],
                    'jumlahkeping' => $return_data['total']
                ) );

                $totalpanjar = ($vault['totpanjar'] - $deno_panjar['serahan']);
                $bakiakhir = ($vault['bakiawal'] - $vault['keluar'] + $vault['masuk'] + $vault['pendahuluan'] - $vault['serahan'] - $totalpanjar);

                if($bakiakhir <= 0) throw new \Exception('Custom Exception: Amaun Baki Akhir Cannot Be Zero');
                if($totalpanjar < 0) throw new \Exception('Custom Exception: Amaun Panjar Cannot Be Zero');

                Vault::on($cawangan['mysql'])->where('kodcaw','=', $cawangan['kodcaw'])->where('tarikh','=',$current->toDateString())->update(array(
                    'totpanjar' => $totalpanjar,
                    'bakiakhir'=>$bakiakhir,
                    'bakieod'=>$bakiakhir
                 ));

                $audit = new Audit();
                $audit->users = $panjar['tuntutoleh'];
                $audit->actions = "Hapus Perbelanjaan";
                $audit->new_data = $panjar;
                $audit->kodcaw = $this->cawangan;
                $audit->created_at = $current;
                $audit->updated_at = $current;
                $audit->save();

                DenoPanjar::on('mysql7')->where('kodcaw', $this->cawangan)->where('recno', $panjar['recno'])->latest('tarikh','masa')->delete();
                Panjar::on($cawangan['mysql'])->where('recno',$panjar['recno'])->delete();

                $totalperubatan = floatval($this->getPerubatanAmount($panjar['tuntutoleh']));

                return $array_response = [
                    'result' => 'success',
                    'data' => 1,
                    'totalperubatan' => $totalperubatan,
                    'tuntutoleh' => $panjar['tuntutoleh'],
                    'jenis' => ($panjar['kategori'] == 'Belanja AM - Perubatan') ? 'perubatan' : 'none'
                 ]; 

            });
        }catch(\Exception $e){
            $array_response = [
                'result' => 'error',
                'data' => $e->getMessage()
            ];
            Log::error('Exception: ' . $e->getMessage());
            return $array_response;
        }
    }

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

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $this->cawangan)->first();
        $denominasi = Denominasi::on($cawangan['mysql'])->latest('tarikh')->first();
        $vault = Vault::on($cawangan['mysql'])->latest('tarikh')->first();
        try{
            if (!$denominasi) throw new \Exception('Custom Exception: Denominasi Does Not Exist!');
            if (!$vault) throw new \Exception('Custom Exception: Vault Does Not Exist!');
            
            return $response =  DB::transaction(function () use ($cawangan,$denominasi,$current,$vault,$request) {

                $myDateTime = DateTime::createFromFormat('Y-m-d', $request->tarikhbil);
                $tarikhbil = $myDateTime->format('dmY');
                $tagmodal = $this->checkModal($request->jenismodal);
                $panjar = Panjar::on($cawangan['mysql'])
                ->create([ 
                    'tarikh'=> $current->toDateString(),
                    'deskripsi'=> $request->deskripsi,
                    'bayaran' => $request->bayaran,
                    'tag' => $tagmodal['tag'],
                    'kategori' => $tagmodal['kategori'],
                    'id' => $request->kodlaluan,
                    'bakiperubatan' => 0,
                    'nobaucer' => $request->baucer,
                    'nobil' => $tarikhbil,
                    'tuntutoleh' => $request->tuntutan
                ]);

                $denopanjar = DenoPanjar::on('mysql7')->create([ 
                    'tarikh' => $current->toDateString(),
                    'masa' => $current->toTimeString(),
                    'kodcaw' => $this->cawangan,
                    'kodlaluan' => $request->kodlaluan,
                    'serahan' => $request->bayaran,
                    'bd1' => 0,
                    'bd5' => 0,
                    'bd10' => 0,
                    'bd20' => 0,
                    'bd50' => 0,
                    'bd100' => 0,
                    'txtring1' => $request->ambilanring1,
                    'txtring5' => $request->ambilanring5,
                    'txtring10' => $request->ambilanring10,
                    'txtring20' => $request->ambilanring20,
                    'txtring50' => $request->ambilanring50,
                    'txtring100' => $request->ambilanring100,
                    'txtring1000' => 0,
                    'txtsen1' => $request->ambilansen1,
                    'txtsen5' => $request->ambilansen5,
                    'txtsen10' => $request->ambilansen10,
                    'txtsen20' => $request->ambilansen20,
                    'txtsen50' => $request->ambilansen50,
                    'jenis' =>$request->jenismodal,
                    'recno' =>$panjar['id'],
                    'update' => '0'
                ]);

                $return_data = $this->calculation_denominasi($denopanjar,$denominasi,'keluar');
                if($return_data == 'no data') throw new \Exception('Custom Exception: Denominasi Panjar Not Return Data');

                Denominasi::on($cawangan['mysql'])->where([['tarikh','=',$current->toDateString()]])->update(array(
                    'bd1' => $return_data['deno']['bd1']['keping'],
                    'b1'=> $return_data['deno']['bd1']['jumlah'],
                    'bd5'=> $return_data['deno']['bd5']['keping'],
                    'b5'=> $return_data['deno']['bd5']['keping'],
                    'bd10'=> $return_data['deno']['bd10']['keping'],
                    'b10'=> $return_data['deno']['bd10']['jumlah'],
                    'bd20'=> $return_data['deno']['bd20']['keping'],
                    'b20'=> $return_data['deno']['bd20']['jumlah'],
                    'bd50'=> $return_data['deno']['bd50']['keping'],
                    'b50'=> $return_data['deno']['bd50']['jumlah'],
                    'bd100'=> $return_data['deno']['bd100']['keping'],
                    'b100'=> $return_data['deno']['bd100']['jumlah'],
                    'txtring1'=> $return_data['deno']['txtring1']['keping'],
                    'k1'=> $return_data['deno']['txtring1']['jumlah'],
                    'txtring5'=> $return_data['deno']['txtring5']['keping'],
                    'k5'=> $return_data['deno']['txtring5']['jumlah'],
                    'txtsen1'=> $return_data['deno']['txtsen1']['keping'],
                    'k01'=> $return_data['deno']['txtsen1']['jumlah'],
                    'txtsen5'=> $return_data['deno']['txtsen5']['keping'],
                    'k05'=> $return_data['deno']['txtsen5']['jumlah'],
                    'txtsen10'=> $return_data['deno']['txtsen10']['keping'],
                    'k010'=> $return_data['deno']['txtsen10']['jumlah'],
                    'txtsen20'=> $return_data['deno']['txtsen20']['keping'],
                    'k020'=> $return_data['deno']['txtsen20']['jumlah'],
                    'txtsen50'=> $return_data['deno']['txtsen50']['keping'],
                    'k050'=> $return_data['deno']['txtsen50']['jumlah'],
                    'txtring10'=> $return_data['deno']['txtring10']['keping'],
                    'k10'=> $return_data['deno']['txtring10']['jumlah'],
                    'txtring20'=> $return_data['deno']['txtring20']['keping'],
                    'k20'=> $return_data['deno']['txtring20']['jumlah'],
                    'txtring50'=> $return_data['deno']['txtring50']['keping'],
                    'k50'=> $return_data['deno']['txtring50']['jumlah'],
                    'txtring100'=> $return_data['deno']['txtring100']['keping'],
                    'k100'=> $return_data['deno']['txtring100']['jumlah'],
                    'txtring1000'=> $return_data['deno']['txtring1000']['keping'],
                    'k1000'=> $return_data['deno']['txtring1000']['jumlah'],
                    'jumlahbundle'=> $return_data['total_bundle'],
                    'txtjumlah'=> $return_data['total_all'],
                    'jumlahkeping' => $return_data['total']
                ) );

                $totalpanjar = ($vault['totpanjar'] + $denopanjar['serahan']);
                $bakiakhir = ($vault['bakiawal'] - $vault['keluar'] + $vault['masuk'] + $vault['pendahuluan'] - $vault['serahan'] - $totalpanjar);

                if($bakiakhir <= 0) throw new \Exception('Custom Exception: Amaun Baki Akhir Cannot Be Zero');
                if($totalpanjar < 0) throw new \Exception('Custom Exception: Amaun Panjar Cannot Be Zero');

                Vault::on($cawangan['mysql'])->where('kodcaw','=', $cawangan['kodcaw'])->where('tarikh','=',$current->toDateString())->update(array(
                    'totpanjar' => $totalpanjar,
                    'bakiakhir'=>$bakiakhir,
                    'bakieod'=>$bakiakhir
                 ));

                $audit = new Audit();
                $audit->users = $panjar['tuntutoleh'];
                $audit->actions = "Daftar Perbelanjaan";
                $audit->new_data = $panjar;
                $audit->kodcaw = $this->cawangan;
                $audit->created_at = $current;
                $audit->updated_at = $current;
                $audit->save();

                $totalperubatan = $this->getPerubatanAmount($request->tuntutan);

                $array_response = [
                    'result' => 'success',
                    'data' => 1,
                    'totalperubatan' => $totalperubatan,
                ];
                return $array_response;

            });
        }catch(\Exception $e){
            $array_response = [
                'result' => 'error',
                'data' => $e->getMessage()
            ];
            Log::error('Exception: ' . $e->getMessage());
            return $array_response;
        }

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

    public function getPerubatanAmount($tuntutanoleh){
        $current = Carbon::now();

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $this->cawangan)->first();
        $panjar = Panjar::on($cawangan['mysql'])->whereYear('tarikh',$current->year)->where('kategori','Belanja AM - Perubatan')->where('tuntutoleh',$tuntutanoleh)->sum('bayaran');
        
        return $panjar;
    }
}
