<?php

namespace App\Http\Controllers\keuangan;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Schema;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Session;

class JurnalLainController extends Controller
{
    private $year;
    public function __construct()
    {   
        $this->middleware(function ($request, $next) {
        $url = request()->segment(1);
        $kode_group = Session::get('kode_group');
        $d_menu = DB::table("tb_menu as a")->join("tb_role as b","a.kode_menu","b.kode_menu")->where([['a.link_menu',$url],['b.kode_group',$kode_group],['b.status_role','1'],['a.active','1']])->orderBy('a.sort_menu','asc')->count();
        if(Session::get('decode') <> 1)
         {
            Session::flash('message', 'Silahkan login dengan username dan password anda.!!');
             return redirect()->to('login');
         }
         if($d_menu == 0){
            Session::flush();
            Session::flash('message', 'Anda Tidak Punya Akses ke Halaman ini.!!');
             return redirect()->to('login');
         }
        return $next($request); 
        });

        $this->year = date("Y");
    }

    function index()
    {
    	$data[] =[];

    	return view('keuangan.JurnalLainList', $data);
    }

    function JurnalLainTambah()
    {
        $id_akun = DB::table("ms_perkiraan")->where([ ["used", "=","1"] ])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
        $data['id_akun'] = array_reduce($id_akun->toArray(), function($carry, $item){
            $carry[ $item->id ] = format_akun_perkiraan($item);
            return $carry;
        });
        $jurnal_lain = DB::table("keu_jurnal_lain")->get()->toArray();
        $data['jurnal_lain'] = $this->param_data($jurnal_lain);

        return view('keuangan.JurnalLainTambah', $data);
    }

    function JurnalLainEdit($id_jurnal_lain="")
    {
		$id_akun = DB::table("ms_perkiraan")->where([ ["used", "=","1"] ])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
		$data['id_akun'] = array_reduce($id_akun->toArray(), function($carry, $item){
			$carry[ $item->id ] = format_akun_perkiraan($item);
			return $carry;
		});
        $jurnal_lain = DB::table("keu_jurnal_lain")->find($id_jurnal_lain);
        $jurnal_lain->tanggal_jurnal = date_format(date_create($jurnal_lain->tanggal_jurnal), "d/m/Y");
        $data['jurnal_lain'] = $this->param_data($jurnal_lain);
        $data['jurnal_lain_detail'] = DB::table("keu_jurnal_lain_detail")->where([["id_jurnal_lain", "=", $id_jurnal_lain]])->get();

    	return view('keuangan.JurnalLainEdit', $data);
    }

    public function dataJurnalLain()
    {
        $dataJurnalLain = DB::table("keu_jurnal_lain AS j")
                    ->selectRaw("j.*, d.total_debet, d.total_kredit")
                    ->join("a_keu_jurnal_lain AS d", "d.id_jurnal_lain", "=", "j.id")
                    ->get();
        return Datatables::of($dataJurnalLain)
                ->addColumn("aksi", function($dataJurnalLain){
                    $set_url = url('jurnal_lain/edit/'.$dataJurnalLain->id);

                    $button = "<div class='btn-group'>";
                        $button .= "<a href='".$set_url."' class='btn btn-xs btn-default'><i class='icon-pencil' onclick='btnEditJurnallain($(this))'></i> </a>";
                        $button .= "<button type='button' class='btn btn-xs btn-danger' onclick='btnDeleteJurnallain($(this))'><i class='icon-trash'></i> </button>";
                    $button .= "</div>";
                    return $button;
                })
                ->make(true);
    }

    public function simpanJurnalLain(Request $request)
    {
        $input = $request->all();

        $id_akun = $input['id_akun'];
        $id_jurnal_lain_detail = $input['id_jurnal_lain_detail'];
        $keterangan = $input['keterangan'];
        $debet = $input['debet'];
        $kredit = $input['kredit'];

        $set_tanggal_jurnal = implode("-", array_reverse(explode("/", $input['tanggal_jurnal'])));
        $data_jurnal_lain = [
                "tahun" => $this->year,
                "nomor_jurnal" => $input['nomor_jurnal'],
                "tanggal_jurnal" => $set_tanggal_jurnal,
            ];

        DB::beginTransaction();
        try {
            $id_jurnal_lain = DB::table("keu_jurnal_lain")->insertGetId($data_jurnal_lain);

            if(sizeof($id_akun) > 0){
                foreach ($id_akun as $key => $value) {
                    $detail_jurnal_lain = [
                            "id_jurnal_lain" => $id_jurnal_lain,
                            "id_akun" => $value,
                            "debet" => $debet[$key],
                            "kredit" => $kredit[$key],
                            "keterangan" => $keterangan[$key],
                        ];
                    DB::table("keu_jurnal_lain_detail")->insert($detail_jurnal_lain);
                }

            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();

        }

        return redirect( url('jurnal_lain') );
    }

    public function editJurnalLain(Request $request)
    {
        $input = $request->all();
        DB::beginTransaction();

        $id_akun = $input['id_akun'];
        $id_jurnal_lain_detail = $input['id_jurnal_lain_detail'];
        $keterangan = $input['keterangan'];
        $debet = $input['debet'];
        $kredit = $input['kredit'];
        
        try {
            if(sizeof($id_jurnal_lain_detail) > 0){
                // detail data di database
                $detail = DB::table("keu_jurnal_lain_detail")->select("id")->where([['id_jurnal_lain', '=', $input['id']]])->get();
                // hapus id yg tidak dikirim kembali
                $arr_not_in_id = array_reduce($detail->toArray(), function($carry, $item) use ($id_jurnal_lain_detail){
                    if(!in_array($item->id, $id_jurnal_lain_detail)){
                        $carry[] = $item->id;
                    }
                    return $carry;
                });

                if(sizeof($arr_not_in_id) > 0){
                    DB::table("keu_jurnal_lain_detail")->whereIn("id", $arr_not_in_id)->delete();
                }

                foreach ($id_jurnal_lain_detail as $key => $value) {
                    $detail_transaksi = [
                            "id_akun" => $id_akun[$key],
                            "debet" => $debet[$key],
                            "kredit" => $kredit[$key],
                            "keterangan" => $keterangan[$key],
                        ];

                    if($value!="" | $value!=0){ // update
                        DB::table("keu_jurnal_lain_detail")->where([['id', "=", $value]])->update($detail_transaksi);
                    }else{ // tambahkan detail
                        $detail_transaksi['id_jurnal_lain'] = $input['id'];
                        DB::table("keu_jurnal_lain_detail")->insert($detail_transaksi);
                    }
                }
            }else{

            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
        }

        return redirect( url('jurnal_lain/edit/'.$input['id']) );
    }

    public function hapusJurnalLain(Request $request)
    {
        $input = $request->all();
        DB::beginTransaction();

        try {
            DB::table('keu_jurnal_lain_detail')->where(['id_jurnal_lain'=>$input['id']])->delete();
            DB::table('keu_jurnal_lain')->where($input)->delete();

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
        }
    }

    public function param_data($data=[])
    {
        $jl = Schema::getColumnListing("keu_jurnal_lain");
        $result = array_reduce($jl, function($carry, $item){
            $carry[ $item ] = "";
            return $carry;
        });

        if(is_array($data) && sizeof($data)>0){
            foreach ($jl as $key => $value) {
                $result[ $value ] = $data[ $value ];
            }
        }else if($data!=null){
            foreach ($jl as $key => $value) {
                $result[ $value ] = $data->$value;
            }
        }

        return $result;
    }
}
