<?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 JurnalPenyesuaianSewaController 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 indexSewa()
    {
    	return view('keuangan.jurnal.indexPenyesuaianSewa');
    }

    public function getDataPenyesuaianSewa()
    {
    	$data = DB::table('jurnal_penyesuaian_sewa_header as jsh')
    			->join('view_sewa_bayar as s', 's.id_sewa', 'jsh.id_sewa')
    			->select('jsh.id as id_jsh', 'jsh.tanggal_jurnal', 'jsh.nomor_jurnal', 's.no_faktur', 's.nama_penyedia');

    	return Datatables::of($data)
	        ->addColumn("aksi", function($data){
	            $button = "<div class='btn-group'>";

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

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

    public function createPenyesuaianSewa(Request $request)
    {
	    if ($request->isMethod('get')) {
	    	$data['no_faktur'] = DB::table('view_sewa_bayar as s')
	    						->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.createPenyesuaianSewa', $data);
	    } else {
	    	DB::beginTransaction();
	    	try{
                $nomor_jurnal = CodeGenerator::numberOfTransaction('jurnal_penyesuaian_sewa_header', 'nomor_jurnal', 4, 4, 3, 'JPS', 'JPS', date_db($request->get('tanggal_jurnal')));
	    		$data = array(
	    			'id_sewa' 			=> $request->get('id_sewa'),
	    			'user_id_create' 	=> Session::get('kode_user'),
	    			'user_id_create' 	=> Session::get('kode_user'),
                    'nomor_jurnal'      => $nomor_jurnal,
	    			'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_jsh = DB::table('jurnal_penyesuaian_sewa_header')->insertGetId($data);

	    		for ($i=0; $i < count($request->get('id_akun')); $i++) { 
	    			$d_data = array(
	    				'id_jsh' 	=> $id_jsh,
	    				'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_penyesuaian_sewa_detail')->insert($d_data);
	    		}
	    		DB::commit();
	    		return redirect('jurnal-penyesuaian-sewa')->with('flash_message_success', 'Data berhasil disimpan!');
	    	}catch(Exception $e){
	    		DB::rollback();
	    		return redirect()->back()->with('flash_message_error', 'Data gagal disimpan!');
	    	}
	    }
    }

    public function deletePenyesuaianSewa($id = null)
    {
    	$check = DB::table('jurnal_penyesuaian_sewa_header')->where('id', $id)->count();
    	if ($check > 0) {
    		DB::beginTransaction();
    		try{
    			$check_detail = DB::table('jurnal_penyesuaian_sewa_detail')->where('id_jsh', $id);
    			if ($check_detail->count() > 0) {
    				$check_detail->delete();
    			}
    			DB::table('jurnal_penyesuaian_sewa_header')->where('id', $id)->delete();
    			DB::commit();
    			return response()->json(['status' => "Success", 'message' => "Data berhasil dihapus!"]);
    		}catch(Exception $e){
    			DB::rollback();
    			return response()->json(['status' => "Failed", 'message' => "Terjadi kesalahan sistem!!"]);
    		}
    	} else {
    		return response()->json(['status' => "Failed", 'message' => "Data tidak ditemukan!"]);
    	}
    }

    public function editPenyesuaianSewa(Request $request, $id = null)
    {
    	if ($request->isMethod('get')) {
    		$check = DB::table('jurnal_penyesuaian_sewa_header as jsh')->where('id', $id)->count();
    		if ($check > 0) {
    			$data['id'] = $id;
    			$data['no_faktur'] = DB::table('jurnal_penyesuaian_sewa_header as jsh')
    								->join('view_sewa_bayar as s', 's.id_sewa', 'jsh.id_sewa')
		    						->where('jsh.id', $id)
		    						->select('s.id_sewa','s.no_faktur', 's.nama_penyedia', 'jsh.tanggal_jurnal', 'jsh.keterangan')
		    						->first();

		    	$data['data_jurnal'] = DB::table('jurnal_penyesuaian_sewa_header as jsh')
		    							->join('jurnal_penyesuaian_sewa_detail as jsd', 'jsd.id_jsh', 'jsh.id')
		    							->where('jsh.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.editPenyesuaianSewa', $data);
    		} else {
    			return redirect()->back()->with('flash_message_error', 'Data tidak ditemukan!');
    		}
    	} else {
    		DB::beginTransaction();
    		try{
    			$check = DB::table('jurnal_penyesuaian_sewa_header as jsh')->where('id', $id)->count();
    			if ($check > 0) {
    				DB::table('jurnal_penyesuaian_sewa_detail')->where('id_jsh', $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_penyesuaian_sewa_header')->where('id', $id)->update($d_header);
    				for ($i=0; $i < count($request->get('id_akun')); $i++) { 
    					$d_detail = array(
    						'id_jsh' 	=> $id,
    						'id_akun' 	=> $request->get('id_akun')[$i],
    						'tipe_akun' => $request->get('tipe_akun')[$i],
    						'nominal'	=> $request->get('nominal')[$i]
    					);
    					DB::table('jurnal_penyesuaian_sewa_detail')->insert($d_detail);
    				}
    				DB::commit();
    				return redirect('jurnal-penyesuaian-sewa')->with('flash_message_success', 'Data berhasil diperbarui!');
    			} else {
    				return redirect('jurnal-penyesuaian-sewa')->with('flash_message_error', 'Data tidak ditemukan!');
    			}
    		}catch(Exception $e){
    			DB::rollback();
    			return redirect()->back()->with('flash_message_error', 'Data gagal diperbarui!');
    		}
    	}
    }
}
