<?php

namespace App\Http\Controllers\master;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;
use DB;
use App\Perkiraan;
use App\Aset;
use App\AsetPenyusutan;
use App\AsetJual;
use App\PembelianBarang;
use Illuminate\Support\Facades\Session;


class ManajemenAsetController 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 index()
    {
		return view('master.aset.index');
	}

    public function data_aset_tertunda()
    {
        $dataBarangPembelian = DB::table("pem_pembelian_barang AS pb")
                            ->join("pem_pembelian AS p", 'p.id_pembelian', '=', 'pb.id_pembelian')
                            ->join('view_ms_barang_full AS b', 'b.id', '=', 'pb.id_barang')
                            // ->join('ast_aset AS a', 'a.id_pembelian', '<>', 'pb.id_pembelian')
                            ->where([
                                ['b.id_kelompok', '=', 6],
                                ['pb.aset_status', '=', 0],
                            ])
                            ->selectRaw("
                                pb.id_beli_barang,
                                pb.id_pembelian,
                                p.tanggal_faktur,
                                p.no_faktur,
                                p.sufix_no_faktur,
                                CONCAT_WS('', p.no_faktur, p.sufix_no_faktur) AS nomor_faktur,
                                (
                                    CASE
                                        WHEN (
                                            p.termasuk_pajak = 1
                                        ) THEN ((100 * (pb.jml_barang * pb.harga_satuan)) / 110)
                                        ELSE (CAST(pb.jml_barang AS DECIMAL(11, 3)) * CAST(pb.harga_satuan AS DECIMAL(25, 3)))
                                    END
                                ) AS nominal,
                                b.*")
                            ->orderByRaw("p.tanggal_faktur, p.no_faktur, p.sufix_no_faktur")
                            ->get();
        // dd($dataBarangPembelian);
        return Datatables::of($dataBarangPembelian)
            ->addIndexColumn()
            ->addColumn('aksi', function($dataBarangPembelian){
                $button = '<div class="btn-group">';
                    $button = "<a href='".url('manajemen-aset/create?id='.$dataBarangPembelian->id_beli_barang.'&id_pembelian='.$dataBarangPembelian->id_pembelian)."' class='btn btn-sm btn-success'>Catat</a>";
                $button .= '</div>';
                return $button;
            })
            ->make(true);
    }

    public function data_aset_aktif()
    {
        $dataAsetAktif = Aset::with(['penyusutan', 'akunAset'])->where([ ['status', '<', 2] ])->get();
        // dd($dataAsetAktif);
        return Datatables::of($dataAsetAktif)
            ->addIndexColumn()
            ->addColumn('set_akun_aset', function($dataAsetAktif){
                return format_akun_perkiraan($dataAsetAktif->akunAset);
            })
            ->addColumn('nilai_buku', function ($dataAsetAktif)
            {
                $maxPenyusutan = $dataAsetAktif->penyusutan()->max('tanggal_penyusutan');
                $penyusutan = $dataAsetAktif->penyusutan()->where([ ['tanggal_penyusutan', '=', $maxPenyusutan] ])->first();
                $nilai_buku = $dataAsetAktif->biaya_akuisisi-$penyusutan->akumulasi_penyusutan;
                return $nilai_buku;
            })
            ->addColumn('aksi', function($dataAsetAktif){
                $button = '<div class="btn-group">';
                    $button .= "<a href='".url('manajemen-aset/'.$dataAsetAktif->id."/jual")."' class='btn btn-sm btn-success' title='Jual'><i class='icon-upload'></i></a>";
                    $button .= "<a href='".url('manajemen-aset/'.$dataAsetAktif->id."/edit")."' class='btn btn-sm btn-warning' title='Edit'><i class='fa fa-pencil'></i></a>";
                    $button .= "<button type='button' class='btn btn-sm btn-danger' onclick='btnHapusAsetAktif($(this))' title='Hapus'><i class='fa fa-trash'></i></button>";
                $button .= '</div>';
                return $button;
            })
            ->make(true);
    }

    public function data_aset_jual()
    {
        $dataAsetJual = Aset::with(['penyusutan', 'akunAset', 'asetJual'])->where([ ['status', '=', 2] ])->get();
        // dd($dataAsetJual);
        return Datatables::of($dataAsetJual)
            ->addIndexColumn()
            ->addColumn('set_akun_aset', function($dataAsetJual){
                return format_akun_perkiraan($dataAsetJual->akunAset);
            })
            ->addColumn('nilai_buku', function ($dataAsetJual)
            {
                $maxPenyusutan = $dataAsetJual->penyusutan()->max('tanggal_penyusutan');
                $penyusutan = $dataAsetJual->penyusutan()->where([ ['tanggal_penyusutan', '=', $maxPenyusutan] ])->first();
                $nilai_buku = $dataAsetJual->biaya_akuisisi-$penyusutan->akumulasi_penyusutan;
                return $nilai_buku;
            })
            ->addColumn('aksi', function($dataAsetJual){
                $button = '<div class="btn-group">';
                    $button .= "<a href='".url('manajemen-aset/'.$dataAsetJual->asetJual->id."/jual_edit")."' class='btn btn-sm btn-warning' title='Edit'><i class='fa fa-pencil'></i></a>";
                    $button .= "<button type='button' class='btn btn-sm btn-success' onclick='btnKembaliAsetAktif($(this))' title='Kembalikan Aset'><i class='icon-download'></i></button>";
                $button .= '</div>';
                return $button;
            })
            ->make(true);
    }

    public function create(Request $request)
    {
        $input = $request->all();

        $akun = Perkiraan::where([['used', '=', 1]])->get();

        $arr_akun = array_reduce($akun->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = format_akun_perkiraan($item);
            return $carry;
        });
        
        $data['akun'] = [null=>"--- Pilih Akun ---"] + $arr_akun;
        $data['param'] = 'aset';
        if(sizeof($input) > 0){
            if(isset($input['id'])){
                $data['pembelian'] = DB::table("pem_pembelian_barang AS pb")
                            ->join("pem_pembelian AS p", "p.id_pembelian", "=", "pb.id_pembelian")
                            ->join("ms_barang AS b", "b.id", "=", "pb.id_barang")
                            ->where(['pb.id_beli_barang'=>$input['id']])
                            ->selectRaw("
                                pb.*,
                                p.no_faktur,
                                p.sufix_no_faktur,
                                b.nama_barang,
                                CONCAT_WS('', p.no_faktur, p.sufix_no_faktur) AS nomor_faktur,
                                (
                                    CASE
                                        WHEN (
                                            p.termasuk_pajak = 1
                                        ) THEN ((100 * (pb.jml_barang * pb.harga_satuan)) / 110)
                                        ELSE (CAST(pb.jml_barang AS DECIMAL(11, 3)) * CAST(pb.harga_satuan AS DECIMAL(25, 3)))
                                    END
                                ) AS nominal
                            ")
                            ->first();
            }
        }

        $data['method'] = "POST";
        $data['url_submit'] = url('manajemen-aset');
        // dd($data);
        return view('master.aset.Add', $data);
    }

    public function store(Request $request)
    {
        $this->dataValidation($request);
        $input = $request->all();
        // dd($input);
        DB::beginTransaction();
        try {
            $dataAset = [
                    'user_id_create'    => Session::get('kode_user'),
                    'user_id_update'    => Session::get('kode_user'),
                    'nomor_aset'        => $input['nomor_aset'],
                    'nama_aset'         => $input['nama_aset'],
                    'id_akun_aset'      => $input['id_akun_aset'],
                    'tipe_id_akun_aset' => 'D',
                    'deskripsi'         => $input['deskripsi'],
                    'tanggal_akuisisi'  => date_db($input['tanggal_akuisisi'], false, 2),
                    'biaya_akuisisi'    => $this->rupiahToNumber($input['biaya_akuisisi']),
                    'id_akun_bayar'     => $input['id_akun_bayar'],
                    'tipe_id_akun_bayar'=> 'K',
                    'id_pembelian'      => $input['id_pembelian'],
                    'id_pembelian_barang' => $input['id_pembelian_barang'],
                    'penyusutan'        => isset($input['non_penyusutan']) ? 0 : 1,
                    'masa_manfaat'      => isset($input['non_penyusutan']) ? 0.0 : $input['masa_manfaat'],
                    'nilai_pertahun'    => isset($input['non_penyusutan']) ? 0.00 : $input['nilai_pertahun'],
                    'id_akun_penyusutan'=> $input['id_akun_penyusutan'],
                    'id_akun_akumulasi_penyusutan' => $input['id_akun_akumulasi_penyusutan'],
                ];

            $idAset = Aset::insertGetId($dataAset);

            $dataPenyusutan = [
                    'user_id_create'        => $dataAset['user_id_create'],
                    'user_id_update'        => $dataAset['user_id_update'],
                    'id_aset'               => $idAset,
                    'tanggal_penyusutan'    => date_db($input['tanggal_penyusutan'], false, 2),
                    'biaya_penyusutan'      => $this->rupiahToNumber($input['akumulasi_penyusutan']),
                    'akumulasi_penyusutan'  => $this->rupiahToNumber($input['akumulasi_penyusutan']),
                ];
            AsetPenyusutan::insert($dataPenyusutan);

            if($dataAset['id_pembelian'] != 0){
                DB::table('pem_pembelian_barang')->where(['id_pembelian'=>$dataAset['id_pembelian']])->update(['aset_status'=>1]);
            }
            
            DB::commit();
            $result = [
                    'status'=>1,
                    'message'=>'Data berhasil di simpan.',
                    'type' => 'success'
                ];
        } catch (Exception $e) {
            DB::rollBack();
            $result = [
                    'status'=>0,
                    'message'=>'Terjadi kesalahan.',
                    'type' => 'error',
                ];
        }

        return redirect(url('manajemen-aset'))->with('status', $result);
    }

    public function edit($id)
    {
        $akun = Perkiraan::where([['used', '=', 1]])->get();
        $arr_akun = array_reduce($akun->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = format_akun_perkiraan($item);
            return $carry;
        });        
        $data['akun'] = [null=>"--- Pilih Akun ---"] + $arr_akun;

        $data['param'] = 'aset';
        $aset = Aset::with(['penyusutan', 'pembelian', 'pembelianBarang'])->find($id);
        $data['aset'] = $aset;
        $minPenyusutan = $aset->penyusutan()->min('id');
        $data['aset_penyusutan'] = AsetPenyusutan::find($minPenyusutan);

        $data['method'] = "PUT";
        $data['url_submit'] = url('manajemen-aset/'.$id);
        // dd($data);
        return view('master.aset.Add', $data);
    }

    public function update(Request $request, $id)
    {
        $this->dataValidation($request);
        $input = $request->all();
        // dd($input);
        DB::beginTransaction();
        try {
            $dataAset = [
                    'user_id_update'    => Session::get('kode_user'),
                    'nomor_aset'        => $input['nomor_aset'],
                    'nama_aset'         => $input['nama_aset'],
                    'id_akun_aset'      => $input['id_akun_aset'],
                    'deskripsi'         => $input['deskripsi'],
                    'tanggal_akuisisi'  => date_db($input['tanggal_akuisisi'], false, 2),
                    'biaya_akuisisi'    => $this->rupiahToNumber($input['biaya_akuisisi']),
                    'id_akun_bayar'     => $input['id_akun_bayar'],
                    'penyusutan'        => isset($input['non_penyusutan']) ? 0 : 1,
                    'masa_manfaat'      => isset($input['non_penyusutan']) ? 0.0 : $input['masa_manfaat'],
                    'nilai_pertahun'    => isset($input['non_penyusutan']) ? 0.00 : $input['nilai_pertahun'],
                    'id_akun_penyusutan'=> $input['id_akun_penyusutan'],
                    'id_akun_akumulasi_penyusutan' => $input['id_akun_akumulasi_penyusutan'],
                ];

            $idAset = Aset::where('id', $id)->update($dataAset);

            $dataPenyusutan = [
                    'user_id_update'        => $dataAset['user_id_update'],
                    'tanggal_penyusutan'    => date_db($input['tanggal_penyusutan'], false, 2),
                    'biaya_penyusutan'      => $this->rupiahToNumber($input['akumulasi_penyusutan']),
                    'akumulasi_penyusutan'  => $this->rupiahToNumber($input['akumulasi_penyusutan']),
                ];
            AsetPenyusutan::where([ ['id_aset', '=', $id], ['id', '=', $input['id_aset_penyusutan']] ])->update($dataPenyusutan);
            
            DB::commit();
            $result = [
                    'status'=>1,
                    'message'=>'Data berhasil di simpan.',
                    'type' => 'success'
                ];
        } catch (Exception $e) {
            DB::rollBack();
            $result = [
                    'status'=>0,
                    'message'=>'Terjadi kesalahan.',
                    'type' => 'error',
                ];
        }

        return redirect(url('manajemen-aset'))->with('status', $result);
    }

    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $value = Aset::find($id);
            PembelianBarang::where([ ['id_beli_barang', '=', $value->id_pembelian_barang] ])->update(['status'=>0]);

            Aset::destroy($id);

            DB::commit();
            $result = [
                    'status'=>'success',
                ];
        } catch (Exception $e) {
            DB::rollBack();
            $result = [
                    'status'=>'fail',
                ];
        }

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

    function dataValidation($request){
        return $this->validate($request, [
                'nama_aset' => 'required',
                'nomor_aset' => 'required',
                'id_akun_aset' => 'required',
                'tanggal_akuisisi' => 'required',
                'biaya_akuisisi' => 'required',
                'id_akun_bayar' => 'required',
                'id_akun_penyusutan' => 'required',
                'id_akun_akumulasi_penyusutan' => 'required',
                'akumulasi_penyusutan' => 'required',
                'tanggal_penyusutan' => 'required',
            ]);
    }

    function rupiahToNumber($value=0)
    {
        return preg_replace("/['.']/", "", $value);
    }

    /* ASET JUAL */
    public function aset_jual($id)
    {
        $akun = Perkiraan::where([['used', '=', 1]])->get();
        $arr_akun = array_reduce($akun->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = format_akun_perkiraan($item);
            return $carry;
        });
        
        $data['akun'] = [null=>"--- Pilih Akun ---"] + $arr_akun;
        $data['aset'] = Aset::with(['akunAset', 'akunPenyusutan', 'akunAkumulasiPenyusutan', 'penyusutan'])->find($id);
        $maxPenyusutan = AsetPenyusutan::where([ ['id_aset', '=', $id] ])->max('tanggal_penyusutan');
        $data['aset_penyusutan'] = AsetPenyusutan::where(['tanggal_penyusutan'=>$maxPenyusutan])->first();

        $data['url_submit'] = url("manajemen-aset/jual");
        $data['method'] = "POST";

        return view("master.aset.Jual", $data);
    }

    public function aset_jual_edit($id)
    {
        $akun = Perkiraan::where([['used', '=', 1]])->get();
        $arr_akun = array_reduce($akun->toArray(), function($carry, $item){
            $carry[ $item['id'] ] = format_akun_perkiraan($item);
            return $carry;
        });
        $data['akun'] = [null=>"--- Pilih Akun ---"] + $arr_akun;
        
        $aset_jual = AsetJual::find($id);
        $data['aset'] = Aset::with(['akunAset', 'akunPenyusutan', 'akunAkumulasiPenyusutan', 'penyusutan', 'asetJual'])->find($aset_jual['id_aset']);
        $maxPenyusutan = AsetPenyusutan::where([ ['id_aset', '=', $aset_jual['id_aset']] ])->max('tanggal_penyusutan');
        $data['aset_penyusutan'] = AsetPenyusutan::where(['tanggal_penyusutan'=>$maxPenyusutan])->first();

        $data['url_submit'] = url("manajemen-aset/jual/".$id);
        $data['method'] = "PUT";

        return view("master.aset.Jual", $data);
    }

    public function simpan_aset_jual(Request $request)
    {
        $input = $request->all();

        DB::beginTransaction();
        try {
            $dataAsetJual = $this->_getFormAsetJual($input);
            $dataAsetJual['user_id_create'] = Session::get("kode_user");
            $dataAsetJual['user_id_update'] = Session::get("kode_user");

            AsetJual::insert($dataAsetJual);
            Aset::where(['id'=>$input['id_aset']])->update(['status'=>2]);

            $result = [
                    'type'=>'success',
                    'message'=>'Data Berhasil Disimpan',
                    'status'=>1
                ];
            DB::commit();
        } catch (Exception $e) {
            $result = [
                    'type'=>'error',
                    'message'=>'Terjadi kesalahan.',
                    'status'=>0
                ];
            DB::rollBack();
        }

        return redirect(url('manajemen-aset'))->with("status", $result);
    }

    public function edit_aset_jual(Request $request, $id)
    {
        $input = $request->all();

        DB::beginTransaction();
        try {
            $dataAsetJual = $this->_getFormAsetJual($input);
            $dataAsetJual['user_id_update'] = Session::get("kode_user");

            AsetJual::where(['id'=>$id])->update($dataAsetJual);

            $result = [
                    'type'=>'success',
                    'message'=>'Data Berhasil Disimpan',
                    'status'=>1
                ];
            DB::commit();
        } catch (Exception $e) {
            $result = [
                    'type'=>'error',
                    'message'=>'Terjadi kesalahan.',
                    'status'=>0
                ];
            DB::rollBack();
        }

        return redirect(url('manajemen-aset'))->with("status", $result);
    }

    public function kembalikan_aset_jual($id)
    {
        DB::beginTransaction();
        try {
            $value = AsetJual::find($id);
            Aset::where([ ['id', '=', $value->id_aset] ])->update(['status'=>1]);

            AsetJual::destroy($id);

            DB::commit();
            $result = [
                    'status'=>'success',
                ];
        } catch (Exception $e) {
            DB::rollBack();
            $result = [
                    'status'=>'fail',
                ];
        }

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

    private function _getFormAsetJual($data)
    {
        $dataJual = [
                "id_aset" => $data['id_aset'],
                "tanggal_jual" => date_db($data['tanggal_jual'], false, 2),
                "id_akun_terima" => $data['id_akun_terima'],
                "tipe_id_akun_terima" => "D",
                "harga_jual" => $data['harga_jual'],
                "id_akun_selisih" => $data['id_akun_selisih'],
                "tipe_id_akun_selisih" => $data['tipe_id_akun_selisih'],
                "nilai_selisih" => $data['nilai_selisih'],
            ];

        return $dataJual;
    }
    /* end : ASET JUAL */
}
