<?php

namespace App\Http\Controllers\layanan;

use App\OrderService;
use App\OrderServiceDetail;
use App\OrderServicePajak;
use App\OrderserviceBayar;
use App\OrderserviceBayarTransaksi;
use App\Penyedia;
use App\Perkiraan;
use App\LokasiProduksi;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;
use DB;
use Illuminate\Support\Facades\Session;

class OrderServiceController extends Controller
{
    private $id_akun;
    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->id_akun = [
                "hutang_beban"=>301,
                "hutang_pajak"=>302,
            ];
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    	$data = [];
    	return view("layanan.OrderServiceList", $data);
    }

    public function get_data(Request $request)
    {
        $session = Session::all();
        $orderService = DB::table('view_orderservice_bayar')->orderByRaw("tanggal_nota DESC, CAST(no_nota AS UNSIGNED) DESC");
        
        if(!in_array($session['kode_group'], [5, 8, 9, 12])){
            $orderService->where('lokasi', $session['id_lokasi']);
        }

        $orderService = $orderService->get();

        return Datatables::of($orderService)
                ->addColumn("tanggal_nota", function($orderService){
                    return tgl_full($orderService->tanggal_nota, '98');
                })
                ->addColumn("nomor_nota", function($orderService){
                    return $orderService->no_nota."".$orderService->sufix_no_nota;
                })
                ->addColumn("nama_lokasi", function($orderService){
                    $lokasi = LokasiProduksi::find($orderService->lokasi);
                    return $lokasi->nama_lokasi;
                })
                ->addColumn("tagihan", function($orderService){
                    return $orderService->nominal_netto;
                })
                ->addColumn("pembayaran", function($orderService){
                    return $orderService->nominal_bayar;
                })
                ->addColumn("sisa_tagihan", function($orderService){
                    return $orderService->nominal_netto-$orderService->nominal_bayar;
                })
                ->addColumn("aksi", function($orderService){
                    $button = "<div class='btn-group'>";
                        if($orderService->nominal_bayar == 0){
                            $button .= "<a href='".url("order_service/$orderService->id/edit")."' class='btn btn-sm btn-default'><i class='fa fa-pencil' onclick='btnEditOrderService($(this))'></i></a>";
                            $button .= "<button type='button' class='btn btn-sm btn-danger' onclick='btnDeleteOrderService($(this))'><i class='fa fa-trash'></i></button>";
                        }
                        $button .= "<button type='button' class='btn btn-sm btn-success' onclick='btnPrintOrderService($(this))' data-href='".url('order_service/cetak/'.$orderService->id)."'><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()
    {
        //
        $dataPenyedia = Penyedia::get();
        $data['dataPenyedia'] = array_reduce($dataPenyedia->toArray(), function($carry, $item) {
        	$carry[ $item['id_penyedia'] ] = $item['nama'];
        	return $carry;
        });
        $dataAkun = Perkiraan::where([['used', '=', 1]])->get();
        $data['akunBiaya'] = array_reduce($dataAkun->toArray(), function($carry, $item){
        	$carry[ $item['id'] ] = format_akun_perkiraan($item);
        	return $carry;
        });
        $akunPajak = DB::table("ms_perkiraan")->whereIn("parent", [63])->get();
        $data['akunPajak'] =array_reduce($akunPajak->toArray(), function($carry, $item){
            $carry[ $item->id ] = format_akun_perkiraan($item);
            return $carry;
        });
        $refJurnal = DB::table("ms_ref_jurnal")->where(["kode"=>103])->first();
        $akunPajakPpn = DB::table("ms_perkiraan")->where(['id'=>$refJurnal->id_akun_jurnal])->first();
        $data['akunPpn'] = $akunPajakPpn;
        $data['lokasi'] = LokasiProduksi::get();
        // dd($data);
        return view("layanan.OrderServiceAdd", $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $session = Session::all();
        $input = $request->all();
        $input['no_faktur_pajak'] = '-';
        // dd($input);
        DB::beginTransaction();
        $dataServiceOrder = [
                "lokasi"=>$input['lokasi'],
                "user_id_create"=>$session['kode_user'],
                "user_id_update"=>1,
                "cv"=>isset($input['cv']) ? $input['cv'] : 0,
                "no_nota"=>$input['no_nota']!="" ? $input['no_nota'] : 1,
                "sufix_no_nota"=>$input['sufix_no_nota'],
                "tanggal"=>date_db($input['tanggal']),
                "tanggal_nota"=>date_db($input['tanggal_nota']),
                "id_penyedia"=>$input['id_penyedia'],
                "no_faktur_pajak"=>$input['no_faktur_pajak'],
                "keterangan"=>$input['keterangan'],
                "syarat_bayar"=>$input['syarat_bayar'],
                "penerima"=>$input['penerima'],
                "id_akun_hutang"=>$this->id_akun['hutang_beban'],
            ];
        try {
            $serviceOrder = OrderService::insertGetId($dataServiceOrder);
            /* detail transaksi */
            if(isset($input['transaksi'])){
                if(sizeof($input['transaksi']['id_akun']) > 0){
                    $transaksi = $input['transaksi'];
                    foreach ($transaksi['id_akun'] as $key => $value) {
                        # code...
                        $dataServiceOrderDetail = [
                                "id_nota"=>$serviceOrder,
                                "id_akun"=>$value,
                                "deskripsi"=>$transaksi['deskripsi'][$key],
                                "jumlah"=>$transaksi['jumlah'][$key],
                                "harga_satuan"=>$transaksi['harga'][$key],
                            ];
                        OrderServiceDetail::insert($dataServiceOrderDetail);
                    }
                }
            }

            /* pajak service order */
            if(isset($input['pajak'])){
                if(sizeof($input['pajak']['id_akun']) > 0){
                    $pajak = $input['pajak'];
                    foreach ($pajak['id_akun'] as $key => $value) {
                        # code...
                        $dataServiceOrderPajak = [
                                "id_nota"=>$serviceOrder,
                                "id_akun"=>$value,
                                "nominal"=>$pajak['nominal'][$key],
                                "pemotongan"=>$pajak['pemotongan'][$key],
                                "id_akun_pajak"=>$this->id_akun['hutang_pajak'],
                            ];
                        if($dataServiceOrderPajak['nominal']!=0){
                            OrderServicePajak::insert($dataServiceOrderPajak);
                        }
                    }
                }
            }

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

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

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\OrderService  $orderService
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $dataPenyedia = Penyedia::get();
        $data['dataPenyedia'] = array_reduce($dataPenyedia->toArray(), function($carry, $item) {
            $carry[ $item['id_penyedia'] ] = $item['nama'];
            return $carry;
        });
        $dataAkun = Perkiraan::where([['used', '=', 1]])->get();
        $data['akunBiaya'] = array_reduce($dataAkun->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = format_akun_perkiraan($item);
            return $carry;
        });
        $akunPajak = DB::table("ms_perkiraan")->whereIn('parent', [63])->get();
        $data['akunPajak'] =array_reduce($akunPajak->toArray(), function($carry, $item){
            $carry[ $item->id ] = format_akun_perkiraan($item);
            return $carry;
        });
        $refJurnal = DB::table("ms_ref_jurnal")->where(["kode"=>103])->first();
        $akunPajakPpn = DB::table("ms_perkiraan")->where(['id'=>$refJurnal->id_akun_jurnal])->first();
        $data['akunPpn'] = $akunPajakPpn;
        $data['lokasi'] = LokasiProduksi::get();

        $data['dataOrderService'] = OrderService::with(['detailOrderService', 'pajakOrderService'=>function($query) use ($refJurnal){
            $query->where([ ['id_akun', '<>', $refJurnal->id_akun_jurnal] ]);
        }])->find($id);

        $data['ppnOrderService'] = OrderServicePajak::where([ ["id_nota", "=", $id], ["id_akun", "=", $refJurnal->id_akun_jurnal] ])->first();
        // dd($data);
        return view("layanan.OrderServiceEdit", $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\OrderService  $orderService
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $session = Session::all();
        $input = $request->all();
        $input['no_faktur_pajak'] = '-';
        // dd($input);
        DB::beginTransaction();
        $dataServiceOrder = [
                "lokasi"=>$input['lokasi'],
                "user_id_update"=>$session['kode_user'],
                "cv"=>isset($input['cv']) ? $input['cv'] : 0,
                "no_nota"=>$input['no_nota']!="" ? $input['no_nota'] : 1,
                "sufix_no_nota"=>$input['sufix_no_nota'],
                "tanggal"=>date_db($input['tanggal']),
                "tanggal_nota"=>date_db($input['tanggal_nota']),
                "no_faktur_pajak"=>$input['no_faktur_pajak'],
                "keterangan"=>$input['keterangan'],
                "syarat_bayar"=>$input['syarat_bayar'],
                "penerima"=>$input['penerima'],
            ];

        try {

            $serviceOrder = OrderService::where([["id", "=", $id]])->update($dataServiceOrder);
            /* detail transaksi */
            if(isset($input['transaksi'])){

                $detail = OrderServiceDetail::where([['id_nota', '=', $id]])->get();
                $id_details = array_reduce($detail->toArray(), function($carry, $item) {
                    $carry[] = $item['id'];
                    return $carry;
                }); // id detail yg ada

                if(sizeof($input['transaksi']['id_detail_orderservice']) > 0){
                    $input_detail = $input['transaksi']['id_detail_orderservice']; // id detail yg dikirim

                    $exclude = array_reduce($id_details, function($carry, $item) use ($input_detail) {
                        if(!in_array($item, $input_detail)){ // id detail yg tdk dikenali
                            $carry[] = $item;
                        }
                        return $carry;
                    }); // id detail yg akan dihapus
                    
                    // hapus detail berdasarkan id detail yg tdk dikenali
                    if(sizeof($exclude)>0) {
                        OrderServiceDetail::whereIn("id", $exclude)->delete();
                    }

                    // proses update dan tambah detail baru
                    $transaksi = $input['transaksi'];
                    foreach ($transaksi['id_detail_orderservice'] as $key => $value) {
                        $dataServiceOrderDetail = [
                                "id_nota"=>$id,
                                "id_akun"=>$transaksi['id_akun'][$key],
                                "deskripsi"=>$transaksi['deskripsi'][$key],
                                "jumlah"=>$transaksi['jumlah'][$key],
                                "harga_satuan"=>$transaksi['harga'][$key],
                            ];
                        if(in_array($value, $id_details)){
                            OrderServiceDetail::where([['id', '=', $value]])->update($dataServiceOrderDetail); // update detail
                        }else{
                            OrderServiceDetail::insert($dataServiceOrderDetail); // tambahkan detail baru
                        }
                    }
                } // end : id_detail_orderservice
            }

            $pajak = OrderServicePajak::where([['id_nota', '=', $id]])->get();
            $id_pajaks = [];
            if(sizeof($pajak) > 0){
                $id_pajaks = array_reduce($pajak->toArray(), function($carry, $item) {
                    $carry[] = $item['id'];
                    return $carry;
                }); // id detail yg ada

            }

            /* pajak service order */
            if(isset($input['pajak'])){

                if(sizeof($input['pajak']['id_pajak_orderservice']) > 0){
                    $input_pajak = $input['pajak']['id_pajak_orderservice']; // id pajak yg dikirim

                    $exclude = array_reduce($id_pajaks, function($carry, $item) use ($input_pajak) {
                        if(!in_array($item, $input_pajak)){ // id pajak yg tdk dikenali
                            $carry[] = $item;
                        }
                        return $carry;
                    }); // id pajak yg akan dihapus
                    
                    // hapus pajak berdasarkan id pajak yg tdk dikenali
                    if(sizeof($exclude)>0) {
                        OrderServicePajak::whereIn("id", $exclude)->delete();
                    }

                    // proses update dan tambah pajak baru
                    $pajak = $input['pajak'];
                    foreach ($pajak['id_pajak_orderservice'] as $key => $value) {
                        $dataServiceOrderPajak = [
                                "id_nota"=>$id,
                                "id_akun"=>$pajak['id_akun'][$key],
                                "nominal"=>$pajak['nominal'][$key],
                                "pemotongan"=>$pajak['pemotongan'][$key],
                            ];
                        if($dataServiceOrderPajak['nominal']!=0){
                            if(in_array($value, $id_pajaks)){
                                OrderServicePajak::where([['id', '=', $value]])->update($dataServiceOrderPajak); // update pajak
                            }else{
                                OrderServicePajak::insert($dataServiceOrderPajak); // tambahkan pajak baru
                            }
                        }
                    }
                } // end : id_pajak_orderservice
            }else{
                if(sizeof($id_pajaks) > 0){
                    $exclude = $id_pajaks;
                    OrderServicePajak::whereIn("id", $exclude)->delete();
                }
            }

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\OrderService  $orderService
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            OrderService::find($id)->delete();
            $result = [
                    "status"=>1,
                ];
            DB::commit();
        } catch (Exception $e) {
            $result = [
                    "status"=>0,
                ];
            DB::rollBack();
        }

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

    function cetak(Request $request, $id){
        $input = $request->all();
        require('fpdf181/Mc_table.php');
        $data['OrderService'] = OrderService::with(['dataPenyedia', 'detailOrderService', 'pajakOrderService', 'dataLokasi'])->find($id);
        $data['tampil_harga'] = isset($input['tampil_harga']) ? $input['tampil_harga'] : "false";
        $data['tanggal_cetak']= isset($input['tanggal_cetak']) ? tgl_full($input['tanggal_cetak'], 0) : tgl_full(date("d-m-Y"), 0);
        if($input['uk_kertas']==1){
            $html = view('layanan.OrderServiceCetakMini', $data);

        }else if($input['uk_kertas']==2){
            $html = view('layanan.OrderServiceCetak', $data);

        }
        return response($html)->header('Content-Type', 'application/pdf');
    }

    public function get_nomor(Request $request)
    {
        $input = $request->all();
        $tanggal = explode("/", $input['tanggal']);
        if($input['id']!=""){
            $pembelian = OrderService::find($input['id']);
            $result = [
                    "no_nota"=>$pembelian->no_nota,
                    "sufix_no_nota"=>$pembelian->sufix_no_nota,
                ];
        }else{
            $pembelian = OrderService::whereRaw("YEAR(tanggal_nota)=$tanggal[2] AND MONTH(tanggal_nota)=$tanggal[1]")->max("no_nota");
            $result = [
                    "no_nota"=>$pembelian+1,
                    "sufix_no_nota"=>"/".$tanggal[1]."/".$tanggal[2],
                ];

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

    /* bayar tagihan service */
    public function bayar_tagihan_service(Request $request)
    {
        $input = $request->all();

        if(sizeof($input)==0){
            return redirect(url("hutang"));
        }else if(!isset($input['id'])){
            return redirect(url("hutang"));
        }

        $data['orderserviceById'] = DB::table("view_orderservice_bayar")->where([["id", "=", $input['id']]])->first();
        $data['orderserviceBySupplier'] = DB::table("view_orderservice_bayar")->where([['id_penyedia', '=', $data['orderserviceById']->id_penyedia], ["id", "<>", $input['id']]])->get();
        // $akunKas = dataAkunKasBank();
        $akunKas = dataAkun();
        $data['akunBayar'] = array_reduce($akunKas->toArray(), function($carry, $item){
            $carry[$item['id']] = format_akun_perkiraan($item);
            return $carry;
        });

        return view("layanan.OrderServiceBayarTagihan", $data);
    }

    public function simpan_bayar_tagihan(Request $request)
    {
        $session = Session::all();
        $input = $request->all();
        // dd($input);

        DB::beginTransaction();
        try {
            $dataTransaksiBayar = [
                    "user_id_create"=>$session['kode_user'],
                    "user_id_update"=>1,
                    "no_transaksi_bayar"=>$input['no_transaksi_bayar'],
                    "tanggal_bayar"=>date_db($input['tgl_bayar']),
                ];
            $idTransaksi = DB::table("serv_orderservice_transaksi_bayar")->insertGetId($dataTransaksiBayar);

            foreach ($input['jml_bayar'] as $key => $value) {
                if($value==0) continue;
                $dataBayar = [
                    'id_transaksi_bayar' => $idTransaksi,
                    'id_akun' => $input['id_akun'],
                    'tipe_id_akun' => "K",
                    'tgl_bayar' => date_db($input['tgl_bayar']),
                    'id_orderservice' => $key,
                    'jum_bayar' => $value,
                ];
                OrderserviceBayar::insert($dataBayar);
            }
            DB::commit();
            $message = '<span class="text-semibold">Berhasil!</span> Data berhasil disimpan.';
            return redirect('hutang')->with('flash_message_success', $message);
        } catch (Exception $e) {
            DB::rollBack();
            $message = '<span class="text-semibold">ERROR!</span> Terjadi kesalahan pada sistem.';
            return redirect('hutang')->with('flash_message_error', $message);
        }
        // dd($input);
        // return redirect(url('hutang'));
    }

    // daftar tagihan bayar order service
    public function daftar_bayar_tagihan($id_orderservice)
    {
        $data['order_service'] = DB::table('view_orderservice_bayar')->where(['id'=>$id_orderservice])->first();

        return view("layanan.OrderServiceDaftarBayar", $data);
    }

    public function tabel_daftar_bayar($id)
    {
        // $data = OrderserviceBayar::with(['dataTransaksiBayar', 'dataAkunPerkiraan'])->where([ ['id_orderservice', '=', $id] ])->get();
        $data = DB::table('serv_orderservice_bayar as osb')
                ->where('osb.id_orderservice', $id)
                ->join('serv_orderservice_transaksi_bayar as ostb', 'ostb.id', 'osb.id_transaksi_bayar')
                ->join('ms_perkiraan as pk', 'pk.id', 'osb.id_akun')
                ->select('osb.id as id_belibayar', 'pk.kode_perkiraan', 'pk.nama_perkiraan', 'osb.tgl_bayar', 'ostb.tanggal_bayar', 'ostb.no_transaksi_bayar', 'osb.jum_bayar')
                ->get();
        return Datatables::of($data)
                ->addColumn("akun_bayar", function($data){
                    return format_akun_perkiraan($data);
                })
                ->addColumn("tgl_bayar", function($data){
                    return tgl_full($data->tanggal_bayar, "");
                })
                ->addColumn("aksi", function($data) use ($id){
                    $button = "<div class='btn-group'>";
                        $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='btnCetakBuktiBayar($(this))'><i class='fa fa-print'></i></button>";
                        $button .= "<a href='".url('order_service/pembayaran/edit/'.$data->id_belibayar.'/'.$id)."' class='btn btn-xs btn-warning'><i class='fa fa-pencil'></i></a>";
                    $button .= "</div>";
                    return $button;
                })
                ->make(true);
    }

    public function editPembayaran($id_belibayar = null, $id_orderservice = null)
    {
        $data['id_orderservice'] = $id_orderservice;
        $data['id_belibayar'] = $id_belibayar;

        $data['order_service'] = DB::table('view_orderservice_bayar as os')
                            ->join("ms_penyedia as pd", "pd.id_penyedia", "=", "os.id_penyedia")
                            ->where("os.id", $id_orderservice)
                            ->select('os.cv', 'pd.nama as nama_penyedia', 'os.tanggal', 'os.tanggal_nota as tanggal_faktur', 'os.no_nota as no_faktur', 'os.sufix_no_nota as sufix_no_faktur', 'os.keterangan', 'os.nominal_bayar as total_bayar', 'os.nominal_netto')
                            ->first();

        $akunKas = dataAkunKasBank();
        $data['akunBayar'] = array_reduce($akunKas->toArray(), function($carry, $item){
            $carry[$item['id']] = format_akun_perkiraan($item);
            return $carry;
        });

        $data['akun_bayar'] = DB::table("serv_orderservice_bayar as osb")
                                ->join('serv_orderservice_transaksi_bayar as ostb', 'ostb.id', '=', 'osb.id_transaksi_bayar')
                                ->where('osb.id', $id_belibayar)
                                ->select('osb.tgl_bayar', 'osb.id_akun', 'osb.jum_bayar', 'ostb.tanggal_bayar', 'ostb.no_transaksi_bayar')
                                ->first();

        return view("layanan.OrderserviceBayarEdit", $data);
    }

    public function updatePembayaran($id_belibayar = null, $id_orderservice = null, Request $request)
    {
        $count = DB::table('serv_orderservice_bayar')->where('id', $id_belibayar)->count();
        if ($count > 0) {
            DB::beginTransaction();
            try{
                $data = array(
                    'id_akun'    => $request->get('akun_bayar'),
                    'tgl_bayar'  => date_db($request->get('tanggal_bayar')),
                    'jum_bayar'  => $request->get('jum_bayar'),
                    'updated_at' => date('Y-m-d H:i:s')
                );

                DB::table('serv_orderservice_bayar')->where('id', $id_belibayar)->update($data);
                $id_transaksi_bayar = DB::table('serv_orderservice_bayar')->where('id', $id_belibayar)->first()->id_transaksi_bayar;
                $data_tr = array('tanggal_bayar'=>date_db($request->get('tanggal_bayar')), 'no_transaksi_bayar'=>$request->get('no_transaksi_bayar'));
                DB::table('serv_orderservice_transaksi_bayar')->where('id', $id_transaksi_bayar)->update($data_tr);
                DB::commit();
                return redirect('order_service/daftar_bayar_tagihan/'.$id_orderservice)->with('flash_message_success', 'Data berhasil diperbarui!');
            } catch(Exception $e) {
                DB::rollBack();
                return redirect('order_service/daftar_bayar_tagihan/'.$id_orderservice)->with('flash_message_error', 'Data gagal diperbarui! COBA LAGI...');
            }
        } else {
            return redirect('order_service/daftar_bayar_tagihan/'.$id_orderservice)->with('flash_message_error', 'Data tidak ditemukan!');
        }
    }

    public function delete_detail_bayar(Request $request)
    {
        $input = $request->all();
        DB::beginTransaction();
        try {
            
            $detailBayar = OrderserviceBayar::find($input['id']);
            $detailBayar->delete();

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

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

    public function cetak_bukti_bayar(Request $request)
    {
        $input = $request->all();
        
        $data['detail_data'] = OrderserviceBayar::with(['dataTransaksiBayar', 'dataAkunPerkiraan'])->find($input['id']); // data berdasarkan id bayar yg dipilih
        
        $data['orderservice'] = OrderService::with(['dataPenyedia'])->find($data['detail_data']->id_orderservice);
        $data['transaksi'] = OrderserviceBayarTransaksi::with(['detailBayar'])->find($data['detail_data']->id_transaksi_bayar);
        $q_akun_debet = "
                SELECT
                    b.*,
                    SUM(IFNULL(jum_bayar, 0)) as jumlah,
                    'D' AS tipe_id_akun_hutang,
                    a.id,
                    a.kd_rek_1,
                    a.kode_perkiraan,
                    a.nama_perkiraan,
                    a.level,
                    a.saldo_normal,
                    a.used,
                    a.parent,
                    a.locked
                FROM
                    serv_orderservice_bayar b
                JOIN serv_orderservice ss ON ss.id = b.id_orderservice
                JOIN ms_penyedia s ON s.id_penyedia = ss.id_penyedia
                JOIN ms_perkiraan a ON a.id = s.id_akun_hutang
                WHERE b.id_transaksi_bayar = ?
                GROUP BY b.id_transaksi_bayar, a.id
            ";
        $akun_debet = DB::select($q_akun_debet, [ $data['detail_data']->id_transaksi_bayar ]);
        // dd($akun_debet);
        $q_akun_kredit = "
                SELECT
                    b.*,
                    SUM(IFNULL(jum_bayar, 0)) as jumlah,
                    a.id,
                    a.kd_rek_1,
                    a.kode_perkiraan,
                    a.nama_perkiraan,
                    a.level,
                    a.saldo_normal,
                    a.used,
                    a.parent,
                    a.locked
                FROM
                    serv_orderservice_bayar b
                JOIN serv_orderservice ss ON ss.id = b.id_orderservice
                JOIN ms_penyedia s ON s.id_penyedia = ss.id_penyedia
                JOIN ms_perkiraan a ON a.id = b.id_akun
                WHERE b.id_transaksi_bayar = ?
                GROUP BY b.id_transaksi_bayar, b.id_akun
            ";
        $akun_kredit = DB::select($q_akun_kredit, [$data['detail_data']->id_transaksi_bayar]);

        // dd($akun_debet);
        $data['posting'] = [
                "row_debet"=>$akun_debet,
                "row_kredit"=>$akun_kredit,
            ];
        // dd($data);

        // dd(sizeof($data['detail_data']->transaksiSumberdana));
        $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'] = 'KELUAR';
        
        if($input['uk_kertas']==1){
            $html = view('layanan.OrderserviceCetakBuktiBayarKecil')->with('data',$data);
        }else if($input['uk_kertas']==2){
            $html = view('layanan.OrderserviceCetakBuktiBayarSedang')->with('data',$data);
        }

        require('fpdf181/Mc_table.php');
        return response($html)->header('Content-Type', 'application/pdf');

        // return view('layanan.OrderserviceCetakBuktiBayar', $data);
    }
    // end : daftar tagihan bayar order service
}
