<?php

namespace App\Http\Controllers\keuangan;

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

class JurnalPiutangController extends Controller
{
	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 indexPiutang()
    {
    	return view('keuangan.jurnal.indexPiutang');
    }

    public function getDataPiutang()
    {
    	$data = DB::table('jurnal_piutang_header as jph')
    			->join('view_penjualan2 as pj', 'pj.id_penjualan', 'jph.id_penjualan')
    			->where('pj.kode_sebagai', 2)
    			->select('jph.id as id_jph', 'jph.tanggal_jurnal', 'jph.nomor_jurnal', 'pj.no_faktur', 'pj.sufix_no_faktur', 'pj.nama_pelanggan');

    	return Datatables::of($data)
    		// ->addColumn("tanggal_jurnal", function($data){
    		// 	return tgl_full($data->tanggal_jurnal);
    		// })
	        ->addColumn("no_faktur", function($data){
	            return $data->no_faktur.$data->sufix_no_faktur;
	        })
	        ->addColumn("aksi", function($data){
	            $button = "<div class='btn-group'>";

                $button .= '<a class="btn btn-xs bg-warning-400" href="'.url('jurnal-piutang/edit/'.$data->id_jph).'"><i class="fa fa-pencil"></i></a>';
                $button .='<button type="button" onclick="deleteJurnal('.$data->id_jph.')" class="btn btn-xs bg-danger-400"><i class="fa fa-trash"></i></button>';

                $button .= "</div>";
                return $button;
	        })
	        ->make(true);
    }

    public function createPiutang(Request $request)
    {
	    if ($request->isMethod('get')) {
	    	$data['no_faktur'] = DB::table('view_penjualan2 as pj')
	    						->where('pj.kode_sebagai', 2)
	    						->get();

	    	$akun = DB::table("ms_perkiraan")->whereNotIn("id", [3, 7])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
            $data['akun'] = array_reduce($akun->toArray(), function($carry, $item){
            	$carry[ $item->id ] = format_akun_perkiraan($item);
            	return $carry;
            });

	    	return view('keuangan.jurnal.createPiutang', $data);
	    } else {
	    	DB::beginTransaction();
	    	try{
                $nomor_jurnal = CodeGenerator::numberOfTransaction('jurnal_piutang_header', 'nomor_jurnal', 4, 4, 3, 'JPP', 'JPP', date_db($request->get('tanggal_jurnal')));
	    		$data = array(
	    			'id_penjualan' 		=> $request->get('id_penjualan'),
	    			'user_id_create' 	=> Session::get('kode_user'),
	    			'user_id_create' 	=> Session::get('kode_user'),
                    'nomor_jurnal'      => $nomor_jurnal,
	    			'tanggal'			=> date('Y-m-d'),
	    			'tanggal_jurnal'	=> date_db($request->get('tanggal_jurnal')),
	    			'keterangan'		=> $request->get('keterangan'),
	    			'created_at'		=> date('Y-m-d H:i:s'),
	    			'updated_at'		=> date('Y-m-d H:i:s')
	    		);

	    		$id_jph = DB::table('jurnal_piutang_header')->insertGetId($data);

	    		for ($i=0; $i < count($request->get('id_akun')); $i++) { 
	    			$d_data = array(
	    				'id_jph' 	=> $id_jph,
	    				'id_akun' 	=> $request->get('id_akun')[$i],
	    				'tipe_akun' => $request->get('tipe_akun')[$i],
	    				'nominal' 	=> $request->get('nominal')[$i] == "" ? 0 : $request->get('nominal')[$i]
	    			);
	    			DB::table('jurnal_piutang_detail')->insert($d_data);
	    		}
	    		DB::commit();
	    		return redirect('jurnal-piutang')->with('flash_message_success', 'Data berhasil disimpan!');
	    	}catch(Exception $e){
	    		DB::rollback();
	    		return redirect()->back()->with('flash_message_error', 'Data gagal disimpan!');
	    	}
	    }
    }

    public function deletePiutang($id = null)
    {
    	$check = DB::table('jurnal_piutang_header')->where('id', $id)->count();
    	if ($check > 0) {
    		DB::beginTransaction();
    		try{
    			$check_detail = DB::table('jurnal_piutang_detail')->where('id_jph', $id);
    			if ($check_detail->count() > 0) {
    				$check_detail->delete();
    			}
    			DB::table('jurnal_piutang_header')->where('id', $id)->delete();
    			DB::commit();
    			return response()->json(['status' => "Success"]);
    		}catch(Exception $e){
    			DB::rollback();
    			return response()->json(['status' => "Failed"]);
    		}
    	} else {
    		return response()->json(['status' => "Failed"]);
    	}
    }

    public function editPiutang(Request $request, $id = null)
    {
    	if ($request->isMethod('get')) {
    		$check = DB::table('jurnal_piutang_header as jph')->where('id', $id)->count();
    		if ($check > 0) {
    			$data['id'] = $id;
    			$data['no_faktur'] = DB::table('jurnal_piutang_header as jph')
    								->join('view_penjualan2 as pj', 'pj.id_penjualan', 'jph.id_penjualan')
		    						->where('pj.kode_sebagai', 2)
		    						->where('jph.id', $id)
		    						->select('pj.id_penjualan','pj.no_faktur', 'pj.sufix_no_faktur', 'pj.nama_pelanggan', 'jph.tanggal_jurnal', 'jph.keterangan')
		    						->first();

		    	$data['data_jurnal'] = DB::table('jurnal_piutang_header as jph')
		    							->join('jurnal_piutang_detail as jpd', 'jpd.id_jph', 'jph.id')
		    							->where('jph.id', $id)
		    							->get();

		    	$akun = DB::table("ms_perkiraan")->whereNotIn("id", [3, 7])->orderByRaw("kd_rek_1, kode_perkiraan")->get();
	            $data['akun'] = array_reduce($akun->toArray(), function($carry, $item){
	            	$carry[ $item->id ] = format_akun_perkiraan($item);
	            	return $carry;
	            });

		    	return view('keuangan.jurnal.editPiutang', $data);
    		} else {
    			return redirect()->back()->with('flash_message_error', 'Data tidak ditemukan!');
    		}
    	} else {
    		DB::beginTransaction();
    		try{
    			$check = DB::table('jurnal_piutang_header as jph')->where('id', $id)->count();
    			if ($check > 0) {
    				DB::table('jurnal_piutang_detail')->where('id_jph', $id)->delete();
    				$d_header = array(
    					'user_id_update' => Session::get('kode_user'),
    					'tanggal_jurnal' => date_db($request->get('tanggal_jurnal')),
    					'keterangan'	 => $request->get('keterangan'),
    					'updated_at'	 => date('Y-m-d H:i:s')
    				);
    				DB::table('jurnal_piutang_header')->where('id', $id)->update($d_header);
    				for ($i=0; $i < count($request->get('id_akun')); $i++) { 
    					$d_detail = array(
    						'id_jph' 	=> $id,
    						'id_akun' 	=> $request->get('id_akun')[$i],
    						'tipe_akun' => $request->get('tipe_akun')[$i],
    						'nominal'	=> $request->get('nominal')[$i]
    					);
    					DB::table('jurnal_piutang_detail')->insert($d_detail);
    				}
    				DB::commit();
    				return redirect('jurnal-piutang')->with('flash_message_success', 'Data berhasil diperbarui!');
    			} else {
    				return redirect('jurnal-piutang')->with('flash_message_error', 'Data tidak ditemukan!');
    			}
    		}catch(Exception $e){
    			DB::rollback();
    			return redirect()->back()->with('flash_message_error', 'Data gagal diperbarui!');
    		}
    	}
    }
}
