<?php

namespace App\Http\Controllers\keuangan;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Yajra\Datatables\Datatables;
use DB;
use CodeGenerator;
use App\Perkiraan;
use App\Rekanan;
use App\KasbonRekanan;
use App\KasbonRekananBayar;
use App\KasbonRekananBayarTransaksi;
use Illuminate\Support\Facades\Session;

class PiutangRekananController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    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); 
        });
    }

    public function index()
    {
        //
        return redirect(url('piutang_pegawai'));
    }

    public function kasbon_rekanan()
    {
        $dataKasbonRekanan = DB::table("view_kasbon_rekanan_bayar")->orderByRaw("tanggal_transaksi DESC")->get();
        return Datatables::of($dataKasbonRekanan)
                ->editColumn("tanggal_transaksi", function($dataKasbonPegawai){
                    return date_db($dataKasbonPegawai->tanggal_transaksi, true, 2);
                })
                ->editColumn("nomor_transaksi", function($dataKasbonRekanan)
                {
                    return "<a href='".url('piutang_rekanan/daftar_bayar_tagihan/'.$dataKasbonRekanan->id)."'>".$dataKasbonRekanan->nomor_transaksi."</a>";
                })
                ->addColumn("pembayaran", function($dataKasbonRekanan){
                    return $dataKasbonRekanan->total_bayar;
                })
                ->addColumn("status", function($dataKasbonRekanan){
                    $kasbon = $dataKasbonRekanan->nominal;
                    $pembayaran = $dataKasbonRekanan->total_bayar;

                    $total_bayar = $pembayaran;
                    if($total_bayar == 0){
                        $status = 0;
                    }else if($total_bayar < $kasbon){
                        $status = 1;
                    }else if($total_bayar > $kasbon){
                        $status = 3;
                    }else{
                        $status = 2;
                    }
                    return status_bayar($status);
                })
                ->addColumn("aksi", function($dataKasbonRekanan){
                    $kasbon = $dataKasbonRekanan->nominal;
                    $pembayaran = $dataKasbonRekanan->total_bayar;
                    $sisa_kasbon = $kasbon-$pembayaran;
                    $button = "<div class='btn-group'>";
                        if($pembayaran <= 0):
                            $button .= "<a href='".url("piutang_rekanan/".$dataKasbonRekanan->id."/edit")."' class='btn btn-sm btn-default'><i class='fa fa-pencil'></i></a>";
                            $button .= "<button type='button' class='btn btn-sm btn-danger' onclick='btnDeleteKasbonRekanan($(this))'><i class='fa fa-trash'></i></button>";
                        endif;

                        if($sisa_kasbon > 0 ):
                            $button .= "<a href='".url("piutang_rekanan/".$dataKasbonRekanan->id."/bayar")."' class='btn btn-sm btn-success'><i class='fa fa-money'></i></a>";
                        endif;

                        $button .= "<button type='button' class='btn btn-sm btn-info' onclick='btnCetakKasbonRekanan($(this))'><i class='fa fa-print'></i></button>";
                    $button .= "</div>";
                    return $button;
                })
                ->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $akun = dataAkunKasBank();
        $data['akun'] = setOptionSelectAkunValue($akun->toArray());

        // $rekanan = Rekanan::with(['dataKelompok'])->get();
        // $rekanan = DB::table("ms_rekanan_kelompok")->get();
        $query = DB::table("view_ms_makelar")->orderByRaw("id_kelompok, id_rekanan")->get();
        $data['dataRekanan'] = array_reduce($query->toArray(), function($carry, $item){
            $carry[ $item->id_kelompok."|".$item->id_rekanan ] = $item->nama." ( ".$item->keterangan." )";
            return $carry;
        });
        $data['lokasi_produksi'] = DB::table("ms_lokasi_produksi")->get();

        $data['method'] = "POST";

        return view("keuangan.rekanan.PiutangRekananAdd", $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $input = $request->all();
        // dd($input);
        $exp_rekanan = explode("|", $input['id_rekanan']);
        $id_kelompok = $exp_rekanan[0];
        $id_rekanan = $exp_rekanan[1];
        $dataKasbonRekanan = [
                "lokasi"=>$input['lokasi'],
                "id_kelompok"=>$id_kelompok,
                "id_rekanan"=>$id_rekanan,
                "nomor_transaksi"=>$input['nomor_transaksi'],
                "tanggal_transaksi"=>date_db($input['tanggal_transaksi']),
                "dari_akun"=>$input['dari_akun'],
                "tipe_dari_akun"=>$input['tipe_dari_akun'],
                "nominal"=>$input['nominal'],
                "keterangan"=>$input['keterangan'],
            ];
        DB::beginTransaction();
        try {
            $dataKasbonRekanan['user_id_create'] = Session::get("kode_user");
            $dataKasbonRekanan['user_id_update'] = Session::get("kode_user");
            KasbonRekanan::insert($dataKasbonRekanan);

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

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $akun = Perkiraan::whereIn("parent", [3, 7])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
        $data['akun'] = setOptionSelectAkunValue($akun->toArray());

        // $rekanan = Rekanan::with(['dataKelompok'])->get();
        $query = DB::table("view_ms_makelar")->orderByRaw("id_kelompok, id_rekanan")->get();
        $data['dataRekanan'] = array_reduce($query->toArray(), function($carry, $item){
            $carry[ $item->id_kelompok."|".$item->id_rekanan ] = $item->nama." ( ".$item->keterangan." )";
            return $carry;
        });
        $data['lokasi_produksi'] = DB::table("ms_lokasi_produksi")->get();

        $data['method'] = "PUT";
        $data['kasbon'] = KasbonRekanan::with(['dataRekanan'])->find($id);
        // dd($data);

        return view("keuangan.rekanan.PiutangRekananAdd", $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $input = $request->all();
        // dd($input);
        $exp_rekanan = explode("|", $input['id_rekanan']);
        $id_kelompok = $exp_rekanan[0];
        $id_rekanan = $exp_rekanan[1];
        $dataKasbonRekanan = [
                "lokasi"=>$input['lokasi'],
                "id_kelompok"=>$id_kelompok,
                "id_rekanan"=>$id_rekanan,
                "nomor_transaksi"=>$input['nomor_transaksi'],
                "tanggal_transaksi"=>date_db($input['tanggal_transaksi']),
                "dari_akun"=>$input['dari_akun'],
                "nominal"=>$input['nominal'],
                "keterangan"=>$input['keterangan'],
            ];

        DB::beginTransaction();
        try {
            $dataKasbonRekanan['user_id_update'] = Session::get("kode_user");
            KasbonRekanan::where([['id', '=', $id]])->update($dataKasbonRekanan);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
        }
        
        return redirect(url('piutang_pegawai'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {            
            
            $detailBayar = KasbonRekananBayar::where(["id_kasbon_rekanan"=>$id]);

            if ($detailBayar->count() > 0) {
                $id_transaksi_bayar = $detailBayar->first()->id_transaksi_bayar;

                $detailBayar2 = KasbonRekananBayar::where(["id_transaksi_bayar"=>$id_transaksi_bayar])->get();

                if(sizeof($detailBayar2->toArray())<1){
                    KasbonRekananBayarTransaksi::find($id_transaksi_bayar)->delete();
                }

                $detailBayar->delete();
            }

            KasbonRekanan::find($id)->delete();

            DB::commit();
            $arr = ['status' => '1'];
        } catch (Exception $e) {
            DB::rollBack();
            $arr = ['status' => '0'];
        }

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

    public function kasbon_cetak(Request $request, $id_kasbon)
    {
        $input = $request->all();
        require('fpdf181/Mc_table.php');
        $data['judul'] = "KASBON REKANAN";
        $data['kasbon'] = DB::table("view_kasbon_rekanan_bayar")->where([ ["id", "=", $id_kasbon] ])->first();
        $data['kasbon']->nama_penerima = $data['kasbon']->nama_rekanan;
        $html = view('keuangan.KasbonPegawaiRekananCetak', $data);
        return response($html)->header('Content-Type', 'application/pdf');
    }

    public function cetak_bukti_kasbon_bayar(Request $request, $id_transaksi_bayar)
    {
        $input = $request->all();
        $data['transaksi_bayar'] = KasbonRekananBayarTransaksi::with(['detailTransaksi'])->where([ ['id', '=', $id_transaksi_bayar] ])->first();

        $data['label_cv'] = isset($input['label_cv']) ? $input['label_cv'] : "false";
        $data['tanggal_cetak']= isset($input['tanggal_cetak']) ? tgl_full($input['tanggal_cetak'], 98) : tgl_full(date("d-m-Y"), 98);
        $data['bukti'] = 'MASUK';
        $data['judul'] = 'Bukti Pembayaran Kasbon '.$data['transaksi_bayar']->nomor_transaksi;

        if($input['uk_kertas']==1){
            $html = view('keuangan.rekanan.CetakBuktiKasbonKecil')->with('data',$data);
        }else if($input['uk_kertas']==2){
            $html = view('keuangan.rekanan.CetakBuktiKasbon')->with('data',$data);
        }
        
        require('fpdf181/Mc_table.php');
        return response($html)->header('Content-Type', 'application/pdf');
    }

    public function bayar_piutang_rekanan(Request $request, $id)
    {
        $input = $request->all();
        if (isset($input['edit']) && $input['edit'] == "true") {
            $akun = Perkiraan::whereIn("parent", [3, 7])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
            $data['akunTerima'] = setOptionSelectAkunValue($akun->toArray());

            $data['rekananById'] = DB::table("view_kasbon_rekanan_bayar")->where([["id", "=", $id]])->first();

            $data['kasbonBayar'] = DB::table('keu_kasbon_rekanan_bayar as kpb')
                                    ->join('keu_kasbon_rekanan_transaksi_bayar as kptb', 'kptb.id', 'kpb.id_transaksi_bayar')
                                    ->where('kpb.id', $input['idbayar'])
                                    ->select('kpb.id', 'kpb.id_transaksi_bayar', 'kpb.id_akun', 'kptb.no_transaksi_bayar', 'kpb.tgl_bayar')
                                    ->first();

            $data['kasbonByIdRekanan'] = DB::table('keu_kasbon_rekanan_bayar as kpb')
                                        ->join('keu_kasbon_rekanan_transaksi_bayar as kptb', 'kptb.id', 'kpb.id_transaksi_bayar')
                                        ->join('keu_kasbon_rekanan as kp', 'kp.id', 'kpb.id_kasbon_rekanan')
                                        ->join('view_kasbon_rekanan_bayar as vkpb', 'vkpb.id', 'kp.id')
                                        ->where('kpb.id', '=', $input['idbayar'])
                                        ->selectRaw('
                                            vkpb.nominal,
                                            vkpb.total_bayar,
                                            vkpb.tanggal_transaksi,
                                            vkpb.nomor_transaksi,
                                            vkpb.keterangan,
                                            kpb.jum_bayar as jumlah_bayar,
                                            vkpb.nominal,
                                            vkpb.id
                                        ')
                                        ->get();
        } else {
            $akun = Perkiraan::whereIn("parent", [3, 7])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
            $data['akunTerima'] = setOptionSelectAkunValue($akun->toArray());

            $data['rekananById'] = DB::table("view_kasbon_rekanan_bayar")->where([["id", "=", $id]])->first();
            $data['kasbonByIdRekanan'] = DB::table("view_kasbon_rekanan_bayar")->where([["id_rekanan", "=", $data['rekananById']->id_rekanan], ['id', "<>", $id]])->get();
        }
        // dd($data);
        return view("keuangan.rekanan.PiutangRekananBayar", $data);
    }

    public function simpan_bayar_kasbon(Request $request)
    {
        $input = $request->all();
        if ($input['id_transaksi_bayar'] != "") {
            DB::beginTransaction();
            try{
                $dataTransaksiBayar = [
                        "lokasi"=>Session::get('id_lokasi') == "" ? 1 : Session::get('id_lokasi'),
                        "user_id_update"=>Session::get("kode_user"),
                        "no_transaksi_bayar"=>$input['no_transaksi_bayar'],
                        "tanggal_bayar"=>date_db($input['tgl_bayar']),
                        "updated_at"=>date('Y-m-d H:i:s')
                    ];

                DB::table("keu_kasbon_rekanan_transaksi_bayar")->where('id', '=', $input['id_transaksi_bayar'])->update($dataTransaksiBayar);

                $id_kasbon = $input['detail_kasbon']['id_kasbon'];
                $nominal_bayar = $input['detail_kasbon']['nominal_bayar'];

                foreach ($id_kasbon as $key => $value) {
                    if($nominal_bayar[$key]==0 || $nominal_bayar[$key]=="") continue;
                    $dataBayar = [
                            "id_transaksi_bayar"=>$input['id_transaksi_bayar'],
                            "id_kasbon_rekanan"=>$value,
                            "id_akun"=>$input['id_akun'],
                            "tgl_bayar"=>date_db($input['tgl_bayar']),
                            "jum_bayar"=>$nominal_bayar[$key],
                            "tipe_id_akun"=>"D",
                        ];
                    DB::table("keu_kasbon_rekanan_bayar")->where('id', $input['id_bayar'])->update($dataBayar);
                }
                DB::commit();
            }catch(Exception $e){
                DB::rollBack();
            }
        } else {
            DB::beginTransaction();
            $dataTransaksiBayar = [
                    "lokasi"=>Session::get('id_lokasi') == "" ? 1 : Session::get('id_lokasi'),
                    "user_id_create"=>1,
                    "user_id_update"=>1,
                    "no_transaksi_bayar"=>$input['no_transaksi_bayar'],
                    "tanggal_bayar"=>date_db($input['tgl_bayar']),
                ];

            try {
                $id_transaksi = DB::table("keu_kasbon_rekanan_transaksi_bayar")->insertGetId($dataTransaksiBayar);

                $id_kasbon = $input['detail_kasbon']['id_kasbon'];
                $nominal_bayar = $input['detail_kasbon']['nominal_bayar'];

                foreach ($id_kasbon as $key => $value) {
                    if($nominal_bayar[$key]==0 || $nominal_bayar[$key]=="") continue;
                    $dataBayar = [
                            "id_transaksi_bayar"=>$id_transaksi,
                            "id_kasbon_rekanan"=>$value,
                            "id_akun"=>$input['id_akun'],
                            "tgl_bayar"=>date_db($input['tgl_bayar']),
                            "jum_bayar"=>$nominal_bayar[$key],
                            "tipe_id_akun"=>"D",
                        ];
                    DB::table("keu_kasbon_rekanan_bayar")->insert($dataBayar);
                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }
        }

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

    // daftar tagihan bayar piutang_pegawai
    public function daftar_bayar_tagihan($id)
    {
        $data['piutang'] = DB::table('view_kasbon_rekanan_bayar')->where(['id'=>$id])->first();
        // dd($data['piutang']);
        
        return view("keuangan.rekanan.PiutangRekananDaftarBayar", $data);
    }

    public function tabel_daftar_bayar($id)
    {
        DB::enableQueryLog();
        $data = KasbonRekananBayar::with(['dataTransaksiBayar', 'dataPerkiraan'])->where([ ['id_kasbon_rekanan', '=', $id] ])->get();
        return Datatables::of($data)
                ->addColumn("akun_bayar", function($data){
                    return format_akun_perkiraan($data->dataPerkiraan);
                })
                ->addColumn("tgl_bayar", function($data){
                    return date_db($data->tgl_bayar, true);
                })
                ->addColumn("aksi", function($data){
                    $button = "<div class='btn-group'>";
                        $button .= "<a href='".url('piutang_rekanan/'.$data->id_kasbon_rekanan.'/bayar?edit=true&idbayar='.$data->id)."' class='btn btn-xs btn-primary' title='Edit'><i class='fa fa-pencil'></i></a>";
                        $button .= "<button type='button' class='btn btn-xs btn-danger' onclick='btnHapusDetailBayar($(this))'><i class='fa fa-trash'></i></button>";
                        $button .= "<button type='button' class='btn btn-xs btn-success' onclick='btnPrintBuktiTransaksi($(this))' data-href='".url("piutang_rekanan/cetak_bukti_kasbon_bayar/".$data->id_transaksi_bayar)."'><i class='fa fa-print'></i></button>";
                    $button .= "</div>";
                    return $button;
                })
                ->make(true);
    }

    public function delete_detail_bayar(Request $request)
    {
        $input = $request->all();
        DB::beginTransaction();
        try {
            
            $detailBayar = KasbonRekananBayar::where(["id"=>$input['id']]);
            $id_transaksi_bayar = $detailBayar->first()->id_transaksi_bayar;
            
            $detailBayar->delete();

            $detailBayar2 = KasbonRekananBayar::where(["id_transaksi_bayar"=>$id_transaksi_bayar])->get();
            if(sizeof($detailBayar2->toArray())<1){
                KasbonRekananBayarTransaksi::find($id_transaksi_bayar)->delete();
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
        }
    }
    // end : daftar tagihan bayar piutang_pegawai

    public function get_nomor_kasbon(Request $request)
    {
        $input = $request->all();
        $tanggal = explode("/", $input['tanggal_transaksi']);
        if($input['id']!=""){
            $kasbon = KasbonRekanan::find($input['id']);
            // if($kasbon->nomor_transaksi==""){
            //     $kasbon = KasbonRekanan::whereRaw("YEAR(tanggal_transaksi)=$tanggal[2] AND MONTH(tanggal_transaksi)=$tanggal[1]")->max("nomor_transaksi");
            //     if($kasbon==0){
            //         $kasbon = substr($tanggal[2], -2).$tanggal[1].sprintf("%04d", 0);
            //     }
            //     $result = [
            //             "nomor_transaksi"=>$kasbon+1,
            //         ];
            // }else{
            //     $result = [
            //             "nomor_transaksi"=>$kasbon->nomor_transaksi,
            //         ];   
            // }
            $result = [
                        "nomor_transaksi"=>$kasbon->nomor_transaksi,
                    ];
        }else{
            // $kasbon = KasbonRekanan::whereRaw("YEAR(tanggal_transaksi)=$tanggal[2] AND MONTH(tanggal_transaksi)=$tanggal[1]")->max("nomor_transaksi");
            // if($kasbon==0){
            //     $kasbon = substr($tanggal[2], -2).$tanggal[1].sprintf("%04d", 0);
            // }
            // $result = [
            //         "nomor_transaksi"=>$kasbon+1,
            //     ];
            $kasbon = CodeGenerator::numberOfTransaction('keu_kasbon_rekanan', 'nomor_transaksi', 3, 4, 4, 'KR', 'kas_bon');
            $result = [
                    "nomor_transaksi"=>$kasbon,
                ];
        }
        return response()->json($result);
    }

    public function lapPiutangKaryawanCetak(Request $request)
    {
        require('fpdf181/Mc_table.php');
        $input = $request->all();
        $tgl_awal = date_db($input['tanggal_awal']);
        $tgl_akhir = date_db($input['tanggal_akhir']);
        $rekanan = explode("|", $input['rekanan']);
        if ($rekanan[1] == "0") {
            // id_kelompok
            $nama_rekanan = null;
            $kasbon = DB::table('jurnal_kasbon as jk')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'jk.id_ref')
                    ->where('jk.jenis_kasbon', 2)
                    ->where('jk.tanggal_ref', '<', $tgl_awal)
                    ->where('kr.id_kelompok', '=', $rekanan[0])
                    ->select('jk.tipe_transaksi', 'jk.nominal')
                    ->get();

            $kasbon_bayar = DB::table('jurnal_penerimaan_pembayaran_kasbon as jppk')
                    ->join('keu_kasbon_rekanan_bayar as krb', 'krb.id', 'jppk.id_ref')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'krb.id_kasbon_rekanan')
                    ->where('jppk.jenis_kasbon', 2)
                    ->where('jppk.tanggal_ref', '<', $tgl_awal)
                    ->where('kr.id_kelompok', '=', $rekanan[0])
                    ->select('jppk.tipe_transaksi', 'jppk.nominal')
                    ->get();

            $lap_kasbon = DB::table('jurnal_kasbon as jk')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'jk.id_ref')
                    ->where('jk.jenis_kasbon', 2)
                    ->whereBetween('jk.tanggal_ref', [$tgl_awal, $tgl_akhir])
                    ->where('kr.id_kelompok', '=', $rekanan[0])
                    ->select('jk.tipe_transaksi', 'jk.nominal', 'jk.keterangan', 'jk.tanggal_ref', 'jk.nomor_ref')
                    ->get();

            $lap_kasbon_bayar = DB::table('jurnal_penerimaan_pembayaran_kasbon as jppk')
                    ->join('keu_kasbon_rekanan_bayar as krb', 'krb.id', 'jppk.id_ref')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'krb.id_kasbon_rekanan')
                    ->where('jppk.jenis_kasbon', 2)
                    ->whereBetween('jppk.tanggal_ref', [$tgl_awal, $tgl_akhir])
                    ->where('kr.id_kelompok', '=', $rekanan[0])
                    ->select('jppk.tipe_transaksi', 'jppk.nominal', 'jppk.tanggal_ref', 'jppk.nomor_ref')
                    ->get();
        } else {
            // id_rekanan
            $nama_rekanan = DB::table('ms_rekanan')->where('id_rekanan', $rekanan[1])->select('nama')->first()->nama;
            $kasbon = DB::table('jurnal_kasbon as jk')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'jk.id_ref')
                    ->where('jk.jenis_kasbon', 2)
                    ->where('jk.tanggal_ref', '<', $tgl_awal)
                    ->where('kr.id_rekanan', '=', $rekanan[1])
                    ->select('jk.tipe_transaksi', 'jk.nominal')
                    ->get();

            $kasbon_bayar = DB::table('jurnal_penerimaan_pembayaran_kasbon as jppk')
                    ->join('keu_kasbon_rekanan_bayar as krb', 'krb.id', 'jppk.id_ref')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'krb.id_kasbon_rekanan')
                    ->where('jppk.jenis_kasbon', 2)
                    ->where('jppk.tanggal_ref', '<', $tgl_awal)
                    ->where('kr.id_rekanan', '=', $rekanan[1])
                    ->select('jppk.tipe_transaksi', 'jppk.nominal')
                    ->get();

            $lap_kasbon = DB::table('jurnal_kasbon as jk')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'jk.id_ref')
                    ->where('jk.jenis_kasbon', 2)
                    ->whereBetween('jk.tanggal_ref', [$tgl_awal, $tgl_akhir])
                    ->where('kr.id_rekanan', '=', $rekanan[1])
                    ->select('jk.tipe_transaksi', 'jk.nominal', 'jk.keterangan', 'jk.tanggal_ref', 'jk.nomor_ref')
                    ->get();

            $lap_kasbon_bayar = DB::table('jurnal_penerimaan_pembayaran_kasbon as jppk')
                    ->join('keu_kasbon_rekanan_bayar as krb', 'krb.id', 'jppk.id_ref')
                    ->join('keu_kasbon_rekanan as kr', 'kr.id', 'krb.id_kasbon_rekanan')
                    ->where('jppk.jenis_kasbon', 2)
                    ->whereBetween('jppk.tanggal_ref', [$tgl_awal, $tgl_akhir])
                    ->where('kr.id_rekanan', '=', $rekanan[1])
                    ->select('jppk.tipe_transaksi', 'jppk.nominal', 'jppk.tanggal_ref', 'jppk.nomor_ref')
                    ->get();
        }

        $akun = DB::table('ms_rekanan_kelompok as mrk')
                ->join('ms_perkiraan as pk', 'pk.id', 'mrk.id_akun_piutang')
                ->where('mrk.id_kelompok', $rekanan[0])
                ->select('pk.kode_perkiraan', 'pk.nama_perkiraan', 'mrk.nama')
                ->first();

        $saldoawal_debit = 0;
        if (count($kasbon) > 0) {
            foreach ($kasbon as $key => $value) {
                if ($value->tipe_transaksi == "D") {
                    $saldoawal_debit += $value->nominal;
                }
            }
        }

        $saldoawal_kredit = 0;
        if (count($kasbon_bayar) > 0) {
            foreach ($kasbon_bayar as $key => $value) {
                if ($value->tipe_transaksi == "K") {
                    $saldoawal_kredit += $value->nominal;
                }
            }
        }

        $laporan_kasbon = [];
        if (count($lap_kasbon) > 0) {
            foreach ($lap_kasbon as $key => $value) {
                if ($value->tipe_transaksi == "D") {
                    $laporan_kasbon[] = (object) array(
                        'tanggal' => date_db($value->tanggal_ref, true),
                        'no_bukti' => $value->nomor_ref,
                        'keterangan' => $value->keterangan,
                        'nominal' => $value->nominal,
                        'tipe_transaksi' => $value->tipe_transaksi
                    );
                }
            }
        }

        $laporan_kasbon_bayar = [];
        if (count($lap_kasbon_bayar) > 0) {
            foreach ($lap_kasbon_bayar as $key => $value) {
                if ($value->tipe_transaksi == "K") {
                    $laporan_kasbon_bayar[] = (object) array(
                        'tanggal' => date_db($value->tanggal_ref, true),
                        'no_bukti' => $value->nomor_ref,
                        'keterangan' => 'Bayar Kas Bon',
                        'nominal' => $value->nominal,
                        'tipe_transaksi' => $value->tipe_transaksi
                    );
                }
            }
        }

        $data['saldo_awal'] = $saldoawal_debit - $saldoawal_kredit;
        $data['data'] = array_merge($laporan_kasbon, $laporan_kasbon_bayar);
        $data['periode'] = $input['tanggal_awal']." s/d ". $input['tanggal_akhir'];
        $data['judul'] = "Laporan Piutang Karyawan";
        $data['akun'] = !is_null($nama_rekanan) ? "(".$akun->kode_perkiraan.") ".$akun->nama_perkiraan." - ". $akun->nama." (".$nama_rekanan.")" : "(".$akun->kode_perkiraan.") ".$akun->nama_perkiraan." - ". $akun->nama;
        // return view('keuangan.pegawai.CetakLapPK', $data);
        $html = view('keuangan.rekanan.CetakLapPK')->with('data',$data);
        return response($html)->header('Content-Type', 'application/pdf');
    }
}
