<?php

namespace App\Http\Controllers\pembelian;

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

class HutangAwalController extends Controller
{
    private $id_akun;
    /**
     * 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); 
        });

        $this->id_akun = [
            "hutang_usaha"=>101,
            "potongan_pembelian"=>102,
            "ppn_masukan"=>103,
        ];

    }

    public function index()
    {
        return view("pembelian.HutangAwalList");
    }

    public function data_hutang_awal()
    {
        $d_data = DB::table('pem_hutangawal as hp')
            ->join('ms_penyedia as mp','hp.id_penyedia','mp.id_penyedia')
            ->join('ms_lokasi_produksi as l','l.id_lokasi','hp.lokasi')
            ->selectRaw('hp.*,
                            (
                                CASE
                                    WHEN termasuk_pajak = 1 THEN
                                        hp.nominal*100/110
                                    ELSE
                                        hp.nominal
                                    END
                            ) AS nominal_dpp,
                            (
                                CASE
                                    WHEN termasuk_pajak = 1 THEN
                                        hp.nominal*10/110
                                    WHEN termasuk_pajak = 0 AND pajak=1 THEN
                                        hp.nominal*10/100
                                    ELSE
                                        0
                                    END
                            ) AS nominal_pajak,
                            mp.nama,
                            l.nama_lokasi')
            ->orderByRaw("CAST(no_faktur AS UNSIGNED), tanggal_faktur");

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

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

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

                $total_hutangawal = $d->nominal_dpp+$d->nominal_pajak;
                $c_tagihan = $tot_bayar-($d->nominal_dpp+$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_hutangawal){
                    $bayar = 1;
                }else{
                    $bayar = 2;
                }

                $aksi = "<div class='btn-group'>";
                if($bayar == 0){
                    $aksi .= '<a class="btn btn-sm bg-warning-400" type="button" href="'.url('hutang_awal/'.$d->id.'/edit').'"><i class="icon-pencil"></i> </a>';
                    $aksi .= '<button class="btn btn-sm bg-danger-800" type="button" onclick="btnHapusHutangAwal($(this))"><i class="icon-eraser"></i></button>';

                }else{
                    $aksi .= '<a class="btn btn-sm bg-warning-400" type="button" href="'.url('hutang_awal/'.$d->id.'/edit').'"><i class="icon-pencil"></i></a>';

                }
                $aksi .= "</div>";

                $data['data'][] = array('id' => $d->id,
                                        'no_faktur' => nomor_pembelian($d),
                                        'cv' => $d->cv,
                                        'tanggal' => date_db($d->tanggal, true),
                                        'tanggal_faktur' => date_db($d->tanggal_faktur, true),
                                        'tanggal_tempo' => date_db($d->tanggal_tempo, true),
                                        'id_penyedia' => $d->id_penyedia,
                                        'nama_penyedia' => $d->nama,
                                        'sisa_tagihan' => $sisa_tagihan,
                                        'total_bayar' => $tot_bayar,
                                        'status' => status_bayar($bayar),
                                        'total' => $total_hutangawal,
                                        'nama' => $d->nama,
                                        'nama_lokasi' => $d->nama_lokasi,
                                        'aksi' => $aksi);
            }
        }else{
            $data['data'] = array();
        }

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['supplier'] = DB::table('ms_penyedia')->orderBy('nama', 'asc')->get();

        $tempat_penyerahan = Tempatpenyerahan::with(['dataLokasi'])->orderByRaw("id_lokasi, nama")->get();
        $data['tempat_penyerahan'] = array_reduce($tempat_penyerahan->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = $item['nama']." - ".$item['data_lokasi']['nama_lokasi'];
            return $carry;
        });

        $data['lokasi'] = LokasiProduksi::get();
        $data['satuan'] = DB::table('ms_satuan')->orderBy('nama_satuan','asc')->get();
        $data['data'] = $this->data(array());
        $data['method'] = "POST";

        return view('pembelian.HutangAwalAdd')->with('data', $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();
        $data = [
                'user_id_create'=>Session::get('kode_user'),
                'user_id_update'=>Session::get('kode_user'),
                'lokasi'=>$input['lokasi'],
                'cv'=> $input['cv'] ? $input['cv'] : 0,
                'tanggal'=>date_db($input['tanggal']),
                'tanggal_faktur'=>date_db($input['tanggal_faktur']),
                'tanggal_tempo'=>date_db($input['tanggal_tempo']),
                'no_faktur'=>$input['no_faktur'],
                'sufix_no_faktur'=>$input['sufix_no_faktur'],
                'keterangan'=>$input['keterangan'],
                'id_penyedia'=>$input['penyedia'],
                'nominal'=>$input['td_nominal'],
                'termasuk_pajak' => $request->get('termasuk_pajak') ? $input['termasuk_pajak'] : '0',
                'pajak' => $input['pajak'],
                'id_akun_hutang'=>$this->id_akun['hutang_usaha'],
                'id_akun_pajak'=>$this->id_akun['ppn_masukan'],
            ];
        DB::beginTransaction();
        try {
            HutangAwal::insert($data);

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

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

    /**
     * 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)
    {
        $data['supplier'] = DB::table('ms_penyedia')->orderBy('nama', 'asc')->get();

        $tempat_penyerahan = Tempatpenyerahan::with(['dataLokasi'])->orderByRaw("id_lokasi, nama")->get();
        $data['tempat_penyerahan'] = array_reduce($tempat_penyerahan->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = $item['nama']." - ".$item['data_lokasi']['nama_lokasi'];
            return $carry;
        });

        $data['lokasi'] = LokasiProduksi::get();
        $data['satuan'] = DB::table('ms_satuan')->orderBy('nama_satuan','asc')->get();

        $hutangawal = HutangAwal::find($id);
        $data['data'] = $this->data($hutangawal);
        $data['method'] = "PUT";

        return view('pembelian.HutangAwalAdd')->with('data', $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();
        $data = [
                'user_id_update'=>Session::get('kode_user'),
                'lokasi'=>$input['lokasi'],
                'cv'=> $input['cv'] ? $input['cv'] : 0,
                'tanggal'=>date_db($input['tanggal']),
                'tanggal_faktur'=>date_db($input['tanggal_faktur']),
                'tanggal_tempo'=>date_db($input['tanggal_tempo']),
                'no_faktur'=>$input['no_faktur'],
                'sufix_no_faktur'=>$input['sufix_no_faktur'],
                'keterangan'=>$input['keterangan'],
                'id_penyedia'=>$input['penyedia'],
                'nominal'=>$input['td_nominal'],
                'termasuk_pajak' => $request->get('termasuk_pajak') ? $input['termasuk_pajak'] : '0',
                'pajak' => $input['pajak']
            ];

        DB::beginTransaction();
        try {
            HutangAwal::where([['id', '=', $id]])->update($data);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
        }
        return redirect(url('hutang_awal'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        HutangAwal::destroy($id);
    }

    public function get_nomor(Request $request)
    {
        $input = $request->all();
        $tanggal = explode("/", $input['tanggal']);
        if($input['id']!=""){
            $hutangawal = DB::table('pem_hutangawal')->where([ ['id', '=', $input['id']] ])->first();
            $result = [
                    "no_faktur"=>$hutangawal->no_faktur,
                    "sufix_no_faktur"=>'',
                ];
        }else{
            $hutangawal = DB::table('pem_hutangawal')->whereRaw("YEAR(tanggal_faktur)=$tanggal[2] AND MONTH(tanggal_faktur)=$tanggal[1]")->max("no_faktur");
            $result = [
                    "no_faktur"=>$hutangawal+1,
                    "sufix_no_faktur"=>'',
                ];

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

    public function data( $data = array() ){
        if(sizeof($data) > 0){
            $store['id']                = $data->id;
            $store['lokasi']            = $data->lokasi;
            $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_penyedia']       = $data->id_penyedia;
            $store['nominal']           = $data->nominal;
            $store['termasuk_pajak']    = $data->termasuk_pajak;
            $store['pajak']             = $data->pajak;
            $store['keterangan']        = $data->keterangan;

        }else{
            $store['id']                = '';
            $store['lokasi']            = Session::get('id_lokasi');
            $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']     = '';
            $store['id_penyedia']       = '';
            $store['nominal']           = 0;
            $store['termasuk_pajak']    = 0;
            $store['pajak']             = 0;
            $store['keterangan']        = '';
        }
        return $store;
    }

    function get_bayar($id){
        $d_bayar = DB::table('pem_hutangawal_bayar as phb')->join('ms_perkiraan as mp', 'mp.id', 'phb.id_akun')->join('ms_carabayar as mcb', 'mcb.id_carabayar', 'phb.id_carabayar')->where('phb.id_hutangawal', $id)->select(DB::raw('phb.*, mp.kode_perkiraan, mp.nama_perkiraan, mcb.cara cara_bayar, mcb.tipe tipe_bayar'));

        if($d_bayar->count() > 0){
        foreach($d_bayar->get() as $d){
            $data['bayar'][] = array('id_hutangawal_bayar' => $d->id,
                                    'id_hutangawal' => $d->id_hutangawal,
                                    'id_akun' => $d->id_akun,
                                    'id_carabayar' => $d->id_carabayar,
                                    'kode_perkiraan' => $d->kode_perkiraan.' - '.$d->nama_perkiraan,
                                    'tgl_bayar' => tgl_full($d->tgl_bayar, ''),
                                    'jenis' => $d->cara_bayar.' - '.$d->tipe_bayar,
                                    'jum_bayar' => $d->nominal_bayar);
            }
           
        }else{
            $data['bayar'] = array();
        }     

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

    function simpan_bayar(Request $request){
        $id_hutangawal_bayar = $request->get('id_hutangawal_bayar');
        $data['id_hutangawal'] = $request->get('id_hutangawal');
        $data['tgl_bayar'] = tgl_full($request->get('tanggal'), '2');
        $data['nominal_bayar'] = $request->get('jum_bayar');
        $data['id_akun'] = $request->get('id_akun');
        $data['id_carabayar'] = $request->get('id_carabayar');

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

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

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

}
