<?php

namespace App\Http\Controllers\penjualan;

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

class ReturPenjualanNonFakturController 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); 
        });
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = [];
        return view("penjualan.retur.ReturPenjualanNonFakturList", $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['pelanggan'] = DB::table('ms_pelanggan')->orderBy('nama', 'asc')->get();
        $data['lokasi'] = DB::table("ms_lokasi_produksi")->get();
        $data['mata_uang'] = DB::table('ms_matauang')->get();
        $barang = DB::table('ms_barang')->whereIn('id_kb', ['13', '14', '50', '51', '52'])->get();
        $satuan = DB::table('ms_satuan')->get();

        $data['barang'] = [];
        if (count($barang) > 0) {
        	foreach ($barang as $key => $value) {
        		array_push($data['barang'], '<option value="'.$value->id.'">'.$value->kode_barang.' - '.$value->nama_barang.'</option>');
        	}
        }

        $data['satuan'] = [];
        if (count($satuan) > 0) {
        	foreach ($satuan as $key => $value) {
        		array_push($data['satuan'], '<option value="'.$value->id_satuan.'">'.$value->nama_satuan.'</option>');
        	}
        }

        $data['url_submit'] = url('penjualan/retur-penjualan-nonfaktur');
        $data['method'] = "POST";
        return view("penjualan.retur.ReturPenjualanNonFakturForm", $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();
        $returBarang = $input['barang'];
        // dd($returBarang);

        DB::beginTransaction();
        $dataReturPenjualan = [
            "lokasi"            => $input['lokasi'],
            "user_id_create"    => Session::get("kode_user"),
            "user_id_update"    => Session::get("kode_user"),
            "cv"                => $input['cv'],
            "no_retur"          => $input['no_retur'],
            "sufix_no_retur"    => $input['sufix_no_retur'],
            "tanggal"           => date_db($input['tanggal'], false, 2),
            "tanggal_retur"     => date_db($input['tanggal_retur'], false, 2),
            "tanggal_full"      => tgl_full($input['tanggal'], '5'),
            "id_pelanggan"      => $input['pelanggan'],
            "pajak"             => $input['pajak'],
            "status"            => 1,
            "keterangan"        => $input['keterangan'],
            "mata_uang"         => $input['currency'],
            "kurs_jual"         => $input['kurs'],
            "kurs_bayar"        => $input['kurs'],
        ];

        try {
            $idReturPenjualan = ReturPenjualanNonFaktur::insertGetId($dataReturPenjualan);

            if(sizeof($returBarang['id_barang']) > 0){
                foreach ($returBarang['id_barang'] as $key => $value) {
                    if(in_array($returBarang['jml_retur'][$key], ['', '0', 0, null])){
                        continue;
                    }

                    $dataBarangRetur = [
                            "id_retur_nonfaktur"    => $idReturPenjualan,
                            "id_barang"   			=> $returBarang['id_barang'][$key],
                            "id_satuan"   			=> $returBarang['id_satuan'][$key],
                            "jml_retur"             => ($returBarang['jml_retur'][$key] == "") ? 0 : $returBarang['jml_retur'][$key],
                            "harga_satuan"          => ($returBarang['hrg_satuan'][$key] == "") ? 0 : $returBarang['hrg_satuan'][$key],
                            "potongan"             	=> ($returBarang['potongan'][$key] == "") ? 0 : $returBarang['potongan'][$key],
                            "total"             	=> ($returBarang['total'][$key] == "") ? 0 : $returBarang['total'][$key]
                        ];
                    ReturPenjualanBarangNonFaktur::insert($dataBarangRetur);
                }
            }
            $message = ['classCategori'=>'alert-success', 'message'=>'Data Berhasil Disimpan.'];
            DB::commit();
        } catch (Exception $e) {
            $message = ['classCategori'=>'alert-danger', 'message'=>'Terjadi kesalahan penyimpanan data.'];
            DB::rollBack();
        }

        return redirect(url('penjualan/retur-penjualan-nonfaktur'))->with($message);
    }

    /**
     * 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['pelanggan'] = DB::table('ms_pelanggan')->orderBy('nama', 'asc')->get();
        $data['lokasi'] = DB::table("ms_lokasi_produksi")->get();
        $data['mata_uang'] = DB::table('ms_matauang')->get();
        $barang = DB::table('ms_barang')->whereIn('id_kb', ['13', '14', '50', '51', '52'])->get();
        $satuan = DB::table('ms_satuan')->get();

        $data['barang'] = [];
        if (count($barang) > 0) {
            foreach ($barang as $key => $value) {
                array_push($data['barang'], '<option value="'.$value->id.'">'.$value->kode_barang.' - '.$value->nama_barang.'</option>');
            }
        }

        $data['satuan'] = [];
        if (count($satuan) > 0) {
            foreach ($satuan as $key => $value) {
                array_push($data['satuan'], '<option value="'.$value->id_satuan.'">'.$value->nama_satuan.'</option>');
            }
        }

        $data['ms_barang'] = DB::table('ms_barang')->whereIn('id_kb', ['13', '14', '50', '51', '52'])->get();
        $data['ms_satuan'] = DB::table('ms_satuan')->get();
        // $data['data']= ReturPenjualanNonFaktur::with(['penjualan', 'detailBarang'])->find($id);
        $data['data']= ReturPenjualanNonFaktur::find($id);
        $data['detail_barang']= ReturPenjualanBarangNonFaktur::where('id_retur_nonfaktur', '=', $id)->get();
        // dd($data);
        $data['url_submit'] = url('penjualan/retur-penjualan-nonfaktur/'.$id);
        $data['method'] = "PUT";
        return view("penjualan.retur.ReturPenjualanNonFakturFormEdit", $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();
        $returBarang = $input['barang'];
        // dd($returBarang);

        DB::beginTransaction();
        $dataReturPenjualan = [
            "user_id_update"    => Session::get("kode_user"),
            "no_retur"          => $input['no_retur'],
            "sufix_no_retur"    => $input['sufix_no_retur'],
            "tanggal_retur"     => date_db($input['tanggal_retur'], false, 2),
            "pajak"             => $input['pajak'],
            "keterangan"        => $input['keterangan'],
        ];

        try {
            $returPenjualan = ReturPenjualanNonFaktur::where([ ['id', '=', $id] ])->update($dataReturPenjualan);

            // hapus detail barang retur
            ReturPenjualanBarangNonFaktur::where([ ['id_retur_nonfaktur', '=', $id] ])->delete();

            if(sizeof($returBarang['id_barang']) > 0){
                foreach ($returBarang['id_barang'] as $key => $value) {
                    if(in_array($returBarang['jml_retur'][$key], ['', '0', 0, null])){
                        continue;
                    }

                    $dataBarangRetur = [
                            "id_retur_nonfaktur"    => $id,
                            "id_barang"             => $returBarang['id_barang'][$key],
                            "id_satuan"             => $returBarang['id_satuan'][$key],
                            "jml_retur"             => ($returBarang['jml_retur'][$key] == "") ? 0 : $returBarang['jml_retur'][$key],
                            "harga_satuan"          => ($returBarang['hrg_satuan'][$key] == "") ? 0 : $returBarang['hrg_satuan'][$key],
                            "potongan"              => ($returBarang['potongan'][$key] == "") ? 0 : $returBarang['potongan'][$key],
                            "total"                 => ($returBarang['total'][$key] == "") ? 0 : $returBarang['total'][$key]
                        ];
                    ReturPenjualanBarangNonFaktur::insert($dataBarangRetur);
                }
            }
            $message = ['classCategori'=>'alert-success', 'message'=>'Data Berhasil Diperbarui.'];
            DB::commit();
        } catch (Exception $e) {
            $message = ['classCategori'=>'alert-danger', 'message'=>'Terjadi kesalahan penyimpanan data.'];
            DB::rollBack();
        }

        return redirect(url('penjualan/retur-penjualan-nonfaktur'))->with($message);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {
    	DB::beginTransaction();
    	try{
    		ReturPenjualanBarangNonFaktur::where('id_retur_nonfaktur', $id)->delete();
        	ReturPenjualanNonFaktur::destroy($id);
        	DB::commit();
        	return ['status'=>'success'];
    	}catch(Exception $e){
    		DB::rollBack();
    		return ['status'=>'failed'];
    	}
    }

    public function get_data()
    {
        $data = DB::table('pen_penjualan_retur_nonfaktur AS r')
        		->join("ms_pelanggan as plg", "plg.id_pelanggan", "=", "r.id_pelanggan")
        		->join('pen_penjualan_retur_barang_nonfaktur as rb', 'rb.id_retur_nonfaktur', '=', 'r.id')
        		->join('ms_barang as brg', 'brg.id', '=', 'rb.id_barang')
        		->selectRaw("r.id, r.tanggal_retur, r.status, r.no_retur, r.sufix_no_retur, plg.nama as nama_pelanggan, SUM(IFNULL(rb.jml_retur, 0)*(IFNULL(rb.harga_satuan, 0)-IFNULL(rb.potongan, 0))) AS total_retur")
                ->groupBy("rb.id_retur_nonfaktur")
                ->orderByRaw("CAST(r.no_retur AS UNSIGNED) ASC, CAST(r.tanggal_retur AS DATE) DESC");
        // dd($data);

        return Datatables::of($data)
            ->addColumn('set_status', function($data){
                return status_retur($data->status);
            })
            ->addColumn("tanggal_retur", function($data){
                return tgl_full($data->tanggal_retur, "");
            })
            ->addColumn("nomor_retur", function($data){
                return nomor_retur_penjualan($data);
            })
            ->addColumn('aksi', function($data){
                $button = "<div class='btn-group'>";
                    if($data->status == 0){    
                        $button .="<a href='".url('penjualan/retur-penjualan-nonfaktur/'.$data->id.'/edit')."' class='btn btn-xs btn-warning'><i class='fa fa-pencil'></i></a>";
                        $button .="<button type='button' class='btn btn-xs btn-danger' onclick='btnHapusRetur($(this))'><i class='fa fa-trash'></i></button>";
                    }
                    $button .="<button type='button' class='btn btn-xs btn-success' data-href='".url('penjualan/retur-penjualan-nonfaktur/cetak/'.$data->id)."' onclick='btnCetak($(this))'><i class='fa fa-print'></i></button>";
                $button .= "</div>";
                return $button;
            })
            ->make(true);
    }

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

        $returPenjualan = DB::table('pen_penjualan_retur_nonfaktur as rtr')
        					->join("ms_pelanggan as plg", "plg.id_pelanggan", "=", "rtr.id_pelanggan")
        					->join('pen_penjualan_retur_barang_nonfaktur as rtrbrg', 'rtrbrg.id_retur_nonfaktur', '=', 'rtr.id')
        					->join('ms_barang as brg', 'brg.id', '=', 'rtrbrg.id_barang')
        					->join('ms_satuan as st', 'st.id_satuan', '=', 'rtrbrg.id_satuan')
        					->where('rtr.id', '=', $id)
        					->selectRaw('plg.nama as nama_pelanggan, plg.alamat as alamat_pelanggan, plg.id_kabupaten as kabupaten, rtr.no_retur, rtr.sufix_no_retur, rtr.tanggal_retur, rtrbrg.jml_retur, rtrbrg.harga_satuan, rtrbrg.potongan, st.nama_satuan as satuan, brg.nama_barang')
        					->get();
        $nomor_retur = DB::table('pen_penjualan_retur_nonfaktur as rtr')->where('rtr.id', '=', $id)->first();

        $data['judul'] = "Invoice Retur Penjualan - ".nomor_retur_penjualan($nomor_retur);

        $data['tampil_harga'] = isset($input['tampil_harga']) ? $input['tampil_harga'] : "false";
        $data['retur_penjualan'] = $returPenjualan;

        $html = view('penjualan.retur.CetakInvoiceReturNonFakturNoLine')->with('data',$data);
        require('fpdf181/Mc_table.php');
        return response($html)->header('Content-Type', 'application/pdf');
    }

    public function get_nomor(Request $request)
    {
        $input = $request->all();
        $tanggal = explode("-", $input['tanggal']);
        if($input['id_retur']!=""){
            $returPenjualan = ReturPenjualanNonFaktur::find($input['id_retur']);
            if($returPenjualan->no_retur==""){
                $returPenjualan = ReturPenjualanNonFaktur::whereRaw("YEAR(tanggal_retur)=$tanggal[2] AND MONTH(tanggal_retur)=$tanggal[1]")->max("no_retur");
                if($returPenjualan==0){
                    $returPenjualan = substr($tanggal[2], -2).$tanggal[1].sprintf("%03d", 0);
                }
                $result = [
                        "no_retur"=>$returPenjualan+1,
                        "sufix_no_retur"=>"/RTR",
                    ];
            }else{
                $result = [
                        "no_retur"=>$returPenjualan->no_retur,
                        "sufix_no_retur"=>$returPenjualan->sufix_no_retur,
                    ];   
            }
        }else{
            $returPenjualan = ReturPenjualanNonFaktur::whereRaw("YEAR(tanggal_retur)=$tanggal[2] AND MONTH(tanggal_retur)=$tanggal[1]")->max("no_retur");
            if($returPenjualan==0){
                $returPenjualan = substr($tanggal[2], -2).$tanggal[1].sprintf("%03d", 0);
            }
            $result = [
                    "no_retur"=>$returPenjualan+1,
                    "sufix_no_faktur"=>"/RTR",
                ];

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