<?php

namespace App\Http\Controllers\penjualan;

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


class PiutangawalJualController extends Controller
{
    //
    private $id_akun;

    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->id_akun = [
                "piutang_usaha"=>201,
                "potongan_penjualan"=>202,
                "ppn_keluaran"=>203,
                "penjualan"=>204,
            ];
    }

    public function index(){
    	return view('penjualan.PiutangawalJualList');
    }

    public function get_data(){
        DB::statement(DB::raw('set @rownum=0'));
        $d_data = DB::table('pen_piutangawal as pp')
            ->join('ms_pelanggan as mp','pp.id_pelanggan','mp.id_pelanggan')
            ->select(DB::raw('pp.*,
                            (
                                CASE
                                    WHEN pajak=1 THEN
                                    pp.nominal*10/100
                                    ELSE
                                    0
                                    END
                            ) AS nominal_pajak,
                            mp.nama,
                            @rownum  := @rownum  + 1 AS rownum'));

        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
                $aksi = '';
                $bayar = 0;
                $tot_bayar = 0;

                $d_bayar = DB::table('pen_piutangawal_bayar')
                    ->select(DB::raw('*, sum(jum_bayar) jumlah'))
                    ->where('id_piutangawal', $d->id)
                    ->groupBy('id_piutangawal');

                $rtp = DB::table('retur_tagihan_piutangawal as rtp')->where('id_piutangawal', $d->id);
                if ($rtp->count() > 0) {
                    $nominal_retur = $rtp->selectRaw('sum(nominal_retur) as nominal_retur')->groupBy('id_piutangawal')->first()->nominal_retur;
                } else {
                    $nominal_retur = 0;
                }

                if($d_bayar->count() > 0){
                    $tot_bayar = $d_bayar->first()->jumlah-$nominal_retur;
                }

                $total_piutangawal = $d->nominal+$d->nominal_pajak;
                $c_tagihan = $tot_bayar-($d->nominal+$d->nominal_pajak);

                $sisa_tagihan = abs($c_tagihan);
                if($c_tagihan > 0){
                    $sisa_tagihan = '0';
                }
               

                if($tot_bayar == 0){
                    $bayar = 0;
                }else if($tot_bayar < $total_piutangawal){
                    $bayar = 1;
                }else if($tot_bayar > $total_piutangawal){
                    $bayar = 3;//Kelebihan Bayar
                }else{
                    $bayar = 2;
                }

                if($bayar == 0){
                    $aksi = "<div class='btn-group'>";
                    $aksi .= '<a class="btn btn-xs bg-warning-400" type="button" href="'.url('piutangawal/edit/'.$d->id).'"><i class="icon-pencil"></i> </a>';
                    $aksi .= '<button class="btn btn-xs bg-danger-800" type="button" onclick="btnHapusPenjualan('.$d->id.')"><i class="icon-eraser"></i></button>';
                    // $aksi .='<a class="btn bg-success-400" type="button" href="'.url('piutangawal/bayar/'.$d->id).'"><i class="icon-cash2"></i></a>';
                    $aksi .= "</div>";
                }else if ($bayar == 1){
                    $aksi = "<div class='btn-group'>";
                    $aksi .= '<a class="btn btn-xs bg-warning-400" type="button" href="'.url('piutangawal/edit/'.$d->id).'"><i class="icon-pencil"></i></a>';
                    $aksi .= '<a class="btn btn-xs bg-success-400" type="button" href="'.url('penjualan/terima_tagihan?id='.$d->id.'&currency=1&as=piutang_awal').'"><i class="icon-cash2"></i></a>';
                    $aksi .= "</div>";
                }else if($bayar == 3){
                    $aksi = "<div class='btn-group'>";
                    $aksi .= '<a class="btn btn-xs bg-warning-400" type="button" href="'.url('piutangawal/edit/'.$d->id).'"><i class="icon-pencil"></i></a>';
                    $aksi .= '<a class="btn btn-xs bg-danger-400" type="button" href="'.url('retur-tagihan-piutang-awal/'.$d->id).'"><i class="icon-cash2"></i></a>';
                    $aksi .= "</div>";
                }else{
                    $aksi = "<div class='btn-group'>";
                    $aksi .= '<a class="btn btn-xs bg-warning-400" type="button" href="'.url('piutangawal/edit/'.$d->id).'"><i class="icon-pencil"></i></a>';
                    $aksi .= "</div>";
                }

                $link_faktur = "<a href='".url('penjualan/daftar_bayar_tagihan/'.$d->id)."?as=piutang_awal'>".$d->no_faktur."".$d->sufix_no_faktur."</a>";

                $data['data'][] = array('id' => $d->id,
                                        'rownum' => $d->rownum,
                                        'no_faktur' => $link_faktur,
                                        'tanggal' => tgl_full($d->tanggal, ''),
                                        'tanggal_faktur' => tgl_full($d->tanggal_faktur, ''),
                                        'tanggal_tempo' => tgl_full($d->tanggal_tempo, ''),
                                        'id_pelanggan' => $d->id_pelanggan,
                                        'nama_pelanggan' => $d->nama,
                                        'sisa_tagihan' => $sisa_tagihan,
                                        'pembayaran' => $tot_bayar,
                                        'status' => status_bayar($bayar),
                                        'total' => $total_piutangawal,
                                        'nama' => $d->nama,
                                        'aksi' => $aksi);
            }
        }else{
            $data['data'] = array();
        }

        $data = new Collection($data['data']);
        return Datatables::of($data)
                ->make(true);
    }

    public function tambah(){
        $data['pelanggan'] = DB::table('ms_pelanggan')->orderBy('nama', 'asc')->get();
        $perkiraan = DB::table('ms_perkiraan')->whereIn('parent',['3', '7'])->orderBy('kode_perkiraan', 'asc')->get();
        $arr_perkiraan = array_reduce($perkiraan->toArray(), function($carry, $item){
            $carry[ $item->id ] = $item->kode_perkiraan." ".$item->nama_perkiraan;
            return $carry;
        });
        $data['perkiraan'] = [null=>"--- Pilih Akun ---"] + $arr_perkiraan;
        $transaksi = DB::table('ms_transaksi')->whereIn('id_transaksi',['14'])->orderBy('nama_transaksi', 'asc')->get();
        $data['gudang'] = DB::table('ms_gudang')->get();
        $data['data'] = $this->data(null);

    	return view('penjualan.PiutangawalJualAdd')->with('data',$data);
    }

    public function edit($id){

        $data['pelanggan'] = DB::table('ms_pelanggan')->orderBy('nama', 'asc')->get();
        $perkiraan = DB::table('ms_perkiraan')->whereIn('parent',['3', '7'])->orderBy('kode_perkiraan', 'asc')->get();
        $arr_perkiraan = array_reduce($perkiraan->toArray(), function($carry, $item){
            $carry[ $item->id ] = $item->kode_perkiraan." ".$item->nama_perkiraan;
            return $carry;
        });
        $data['perkiraan'] = [null=>"--- Pilih Akun ---"] + $arr_perkiraan;
        $transaksi = DB::table('ms_transaksi')->whereIn('id_transaksi',['14'])->orderBy('nama_transaksi', 'asc')->get();
        $data['gudang'] = DB::table('ms_gudang')->get();

        $d_data = DB::table('pen_piutangawal as pp')
            ->join('ms_pelanggan as mp','pp.id_pelanggan','mp.id_pelanggan')
            ->select(DB::raw('pp.*,mp.nama nama_pelanggan'))
            ->where('id','=',$id)->first();
        $data['data'] = $this->data($d_data);

        return view('penjualan.PiutangawalJualAdd')->with('data',$data);
    }

    public function get_nomor(Request $request)
    {
        $input = $request->all();
        $tanggal = explode("/", $input['tanggal']);
        if($input['id']!=""){
            $piutang_awal = DB::table("pen_piutangawal")->find($input['id']);
            if($piutang_awal->no_faktur==""){
                $piutang_awal = DB::table("pen_piutangawal")->whereRaw("YEAR(tanggal_faktur)=$tanggal[2] AND MONTH(tanggal_faktur)=$tanggal[1]")->max("no_faktur");
                if($piutang_awal==0){
                    $piutang_awal = substr($tanggal[2], -2).$tanggal[1].sprintf("%04d", 0);
                }
                $result = [
                        "no_faktur"=>$piutang_awal+1,
                        "sufix_no_faktur"=>"",
                    ];
            }else{
                $result = [
                        "no_faktur"=>$piutang_awal->no_faktur,
                        "sufix_no_faktur"=>$piutang_awal->sufix_no_faktur,
                    ];   
            }
        }else{
            $piutang_awal = DB::table("pen_piutangawal")->whereRaw("YEAR(tanggal_faktur)=$tanggal[2] AND MONTH(tanggal_faktur)=$tanggal[1]")->max("no_faktur");
            if($piutang_awal==0){
                $piutang_awal = substr($tanggal[2], -2).$tanggal[1].sprintf("%04d", 0);
            }
            $result = [
                    "no_faktur"=>$piutang_awal+1,
                    "sufix_no_faktur"=>"",
                ];

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

    function data($data = null){
        if($data != null){
            $store['id'] = $data->id;
            $store['lokasi'] = $data->lokasi;
            $store['user_id_create'] = $data->user_id_create;
            $store['user_id_update'] = $data->user_id_update;
            $store['cv'] = $data->cv;
            $store['no_faktur'] = $data->no_faktur;
            $store['sufix_no_faktur'] = $data->sufix_no_faktur;
            $store['tanggal'] = date_db($data->tanggal, true);
            $store['tanggal_faktur'] = date_db($data->tanggal_faktur, true);
            $store['tanggal_tempo'] = date_db($data->tanggal_tempo, true);
            $store['id_pelanggan'] = $data->id_pelanggan;
            $store['pajak'] = $data->pajak;
            $store['no_faktur_pajak'] = $data->no_faktur_pajak;
            $store['nominal_piutang'] = $data->nominal;
            $store['keterangan'] = $data->keterangan;
        }else{
            $store['id'] = "";
            $store['lokasi'] = Session::get('id_lokasi');
            $store['user_id_create'] = Session::get('kode_user');
            $store['user_id_update'] = Session::get('kode_user');
            $store['cv'] = 1;
            $store['no_faktur'] = "";
            $store['sufix_no_faktur'] = "";
            $store['tanggal'] = date("d/m/Y");
            $store['tanggal_faktur'] = date("d/m/Y");
            $store['tanggal_tempo'] = date("d/m/Y");
            $store['id_pelanggan'] = "";
            $store['pajak'] = 0;
            $store['no_faktur_pajak'] = "";
            $store['nominal_piutang'] = 0;
            $store['keterangan'] = "";
        }

        return $store;
    }

    function simpan(Request $request){
    	$id_piutangawal = $request->get('id');
        $data['tanggal'] = date_db($request->get('tanggal'));
        $data['tanggal_faktur'] = date_db($request->get('tanggal_faktur'));
        $data['tanggal_tempo'] = date_db($request->get('tanggal_tempo'));

        $data['no_faktur'] = $request->get('no_faktur');
        $data['sufix_no_faktur'] = $request->get('sufix_no_faktur');
        $data['id_pelanggan'] = $request->get('pelanggan');
        $data['keterangan'] = $request->get('keterangan');
        $data['pajak'] = $request->get('pajak');
        $data['nominal'] = $request->get('td_nominal');

        $data['id_akun_piutang'] = $this->id_akun['piutang_usaha'];
        $data['id_akun_penjualan'] = $this->id_akun['penjualan'];

        $data['cv'] = $request->get('cv') ? $request->get('cv') : 0;
        $data['lokasi'] = 1;

        $data['user_id_create'] = Session::get("kode_user");
        $data['user_id_update'] = Session::get("kode_user");

        if($id_piutangawal == ''){
            DB::table('pen_piutangawal')->insert($data);;
        }else{
            $data['user_id_update'] = Session::get("kode_user");
            DB::table('pen_piutangawal')->where('id', $id_piutangawal)->update($data);
        }

        return redirect('piutangawal');
    }

    function hapus(Request $request){
        $id = $request->get('id');
        DB::beginTransaction();
        try {
            DB::table('pen_piutangawal')->where('id',$id)->delete();
            
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
        }
    }

    function get_transaksi(){
        $d_data = DB::table('ms_transaksi');
        if($d_data->count() > 0){
                $arr['data'] = $d_data->get();
                $arr['status'] = array('1');
        }else{
            $arr['status'] = array('0');
        }

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

    function get_pelanggan(){
        $d_data = DB::table('ms_pelanggan');
        if($d_data->count() > 0){
            $arr['data'] = $d_data->get();
            $arr['status'] = array('1');            
        }else{
            $arr['status'] = array('0');
        }
        return response()->json($arr);
    }

    function get_carabayar(){
        $d_data = DB::table('ms_carabayar');
        if($d_data->count() > 0){
            $arr['data'] = $d_data->get();
            $arr['status'] = array('1');            
        }else{
            $arr['status'] = array('0');
        }
        return response()->json($arr);
    }

    function get_piutangawal(Request $request){
        $tahun = $request->get('tanggal');
        $d_data = DB::table('view_penjualan_hutang as v')->leftjoin('pen_piutangawal as pp','v.id_penjualan','pp.id_penjualan')->select(DB::raw('v.*, CASE WHEN pp.id_penjualan IS NULL THEN 0 ELSE 1 END AS status_piutang'))->whereYear('v.tanggal','<', $tahun);
        if($d_data->count() > 0){
            $arr['data'] = $d_data->get();
            $arr['status'] = array('1');            
        }else{
            $arr['status'] = array('0');
        }
        return response()->json($arr);
    }

    //----------- Piutang Bayar -----------------------
    public function bayar($id){
        $data['id'] = $id;
        $data['cara_bayar'] = DB::table('ms_carabayar')->where(array(['tipe', 'K']))->get();
        $data['sumber_dana'] =  DB::table('ms_perkiraan')->whereIn('parent',['3', '7'])->orderBy('kode_perkiraan', 'asc')->get();   
        return view('penjualan.PiutangawalJualBayar')->with('data',$data);
    }

    public function get_detailbayar($id){
       /* $d_data = DB::table('pen_piutangawal as pp')->join('ms_transaksi as mt','pp.id_transaksi','mt.id_transaksi')->join('ms_pelanggan as mp','pp.id_pelanggan','mp.id_pelanggan')->join('ms_carabayar as mc','pp.id_carabayar','mc.id_carabayar')->select(DB::raw('pp.*, mp.nama nama_pelanggan, mt.nama_transaksi, mc.cara nama_carabayar'))->where('id_piutangawal','=',$id);*/
       $d_data = DB::table('view_piutangawal_bayar as v')->where('id_piutangawal',$id);

        if($d_data->count() > 0 ){
            $arr['detail'] = $d_data->first();
            $arr['status'] = array('1');
        }else{
            $arr['status'] = array('0');
        }

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

    function simpan_bayar(Request $request){
        $id_piutangawal_bayar = $request->get('id_piutangawal_bayar');
        $data['id_piutangawal'] = $request->get('id_piutangawal');
        $data['tanggal'] = tgl_full($request->get('tanggal'), '2');
        $data['jumlah'] = $request->get('jum_bayar');
        $data['id_akun_bank'] = $request->get('id_akun');
        $data['id_akun_piutang'] = '21';
        $daat['tipe_id_akun_piutang'] = 'debet';
        $data['id_carabayar'] = $request->get('id_carabayar');


        if($id_piutangawal_bayar == ''){
            DB::table('pen_piutangawal_bayar')->insert($data);
        }else{
            DB::table('pen_piutangawal_bayar')->where('id_piutangawal_bayar', $id_piutangawal_bayar)->update($data);
        }

        return response()->json(array('status' => '1'));
    }

    function get_bayar($id){
        $d_data = DB::table('pen_piutangawal_bayar as ppb')->join('ms_perkiraan as mp','ppb.id_akun_bank','mp.id')->join('ms_carabayar as mc','ppb.id_carabayar','mc.id_carabayar')->where('ppb.id_piutangawal','=',$id)->select(DB::raw('ppb.*, mp.kode_perkiraan, mp.nama_perkiraan, mc.cara nama_carabayar, mc.tipe tipe_carabayar'));

        if($d_data->count() > 0){
            foreach($d_data->get() as $d){
            $arr['bayar'][] = array('id_piutangawal_bayar' => $d->id_piutangawal_bayar,
                                    'id_piutangawal' => $d->id_piutangawal,
                                    'id_akun' => $d->id_akun_bank,
                                    'id_carabayar' => $d->id_carabayar,
                                    'kode_perkiraan' => $d->kode_perkiraan,
                                    'tgl_bayar' => $d->tanggal,
                                    'jenis' => $d->nama_carabayar.' - '.$d->tipe_carabayar,
                                    'jum_bayar' => $d->jumlah);
            }
        }else{
            $arr['bayar'] = array();
        }

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

    function hapus_bayar(Request $request){
        $id = $request->get('id');
        DB::table('pen_piutangawal_bayar')->where(array('id_piutangawal_bayar' => $id,))->delete();
        return response()->json(array('status' => '1'));
    }
}
