<?php

namespace App\Http\Controllers\keuangan;

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

class SalescontractController 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("keuangan.kontrak.SalescontractList", $data);
    }

    public function load_data_kontrak(Request $request)
    {
        $data = DB::table("keu_sales_contract AS sc")
                ->join("keu_sales_contract_detail AS scd", function($join){
                    $join->on("scd.id_sales_contract", "=", "sc.id");
                })
                ->join("ms_lokasi_produksi AS lok", function($join){
                    $join->on("lok.id_lokasi", "=", "sc.lokasi");
                })
                ->join("ms_rekanan_kelompok AS rek", function($join){
                    $join->on("rek.id_kelompok", "=", "sc.id_rekanan");
                })
                ->groupBy("scd.id_sales_contract")
                ->selectRaw("sc.*, 
                    lok.nama_lokasi,
                    rek.nama AS nama_rekanan, 
                    rek.alamat AS alamat_rekanan,
                    (
                        CASE
                        WHEN termasuk_pajak = 1 THEN
                            SUM((scd.harga_satuan*100/110)*scd.jumlah)
                        ELSE
                            SUM((scd.harga_satuan)*scd.jumlah)
                        END
                    ) AS nominal_dpp,
                    (
                        CASE
                        WHEN termasuk_pajak = 1 THEN
                            SUM((scd.harga_satuan*10/110)*scd.jumlah)
                        WHEN termasuk_pajak = 0 AND pajak = 1 THEN
                            SUM((scd.harga_satuan*10/100)*scd.jumlah)
                        ELSE
                            0
                        END
                    ) AS nominal_pajak
                ")->get();
        return Datatables::of($data)
            ->addColumn("action", function($data){
                $button = "<div class='btn-group'>";
                    $button .= "<a href='".url('sales_contract/'.$data->id)."' class='btn btn-sm btn-info'><i class='fa fa-eye'></i></a>";
                    $button .= "<a href='".url('sales_contract/'.$data->id.'/edit')."' class='btn btn-sm btn-warning'><i class='fa fa-pencil'></i></a>";
                    $button .= "<button type='button' class='btn btn-sm btn-danger' onclick='btnHapusKontrak($(this))'><i class='fa fa-trash'></i></button>";
                $button .= "</div>";
                return $button;
            })
            ->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['rekanan'] = DB::table('ms_rekanan_kelompok')->orderBy('nama', 'asc')->get();
        $data['lokasi'] = LokasiProduksi::get();
        $data['satuan'] = DB::table('ms_satuan')->get();
        $data['warna_komposisi'] = DB::table('ms_warnakomposisi')->get();
        $data['barang'] = $this->get_data_barang();

        $data['url_submit'] = url("sales_contract");
        $data['method'] = 'POST';
        return view("keuangan.kontrak.SalescontractForm", $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();
        // dd($input);
        $data = [
                "lokasi" => $input['lokasi'],
                "user_id_create" => Session::get("kode_user"),
                "user_id_update" => Session::get("kode_user"),
                "cv" => $input['cv'],
                "no_kontrak" => $input['no_kontrak'],
                "tanggal" => date_db($input['tanggal']),
                "tanggal_kontrak" => date_db($input['tanggal_kontrak']),
                "id_rekanan" => $input['rekanan'],
                "keterangan" => $input['keterangan'],
                "syarat_bayar" => $input['syarat_bayar'],
                "tanggal_kirim" => date_db($input['tanggal_kirim']),
            ];

        DB::beginTransaction();
        try {

            $salesContractId = DB::table("keu_sales_contract")->insertGetId($data);

            $detail_barang = $input['detailbarang'];
            if(sizeof($detail_barang) > 0){
                foreach ($detail_barang['id_detail'] as $key => $value) {
                    # code...
                    $datadetailbarang = [
                            "id_sales_contract"=>$salesContractId,
                            "id_warna_komposisi"=>$detail_barang['id_warna_komposisi'][$key],
                            "id_barang"=>$detail_barang['id_barang'][$key],
                            "jumlah"=>$detail_barang['jumlah'][$key],
                            "id_satuan"=>$detail_barang['id_satuan'][$key],
                            "harga_satuan"=>$detail_barang['harga_satuan'][$key],
                            "keterangan"=>$detail_barang['keterangan'][$key],
                            "termasuk_pajak" => $detail_barang['termasuk_pajak'][$key],
                            "pajak" => $detail_barang['pajak'][$key],
                        ];
                    DB::table("keu_sales_contract_detail")->insert($datadetailbarang);
                }
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
        }
        
        return redirect(url("sales_contract"));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data['rekanan'] = DB::table('ms_rekanan_kelompok')->orderBy('nama', 'asc')->get();
        $data['lokasi'] = LokasiProduksi::get();
        $data['satuan'] = DB::table('ms_satuan')->get();
        $data['warna_komposisi'] = DB::table('ms_warnakomposisi')->get();
        $data['barang'] = $this->get_data_barang();

        $data['kontrak'] = DB::table("keu_sales_contract")->find($id);
        $data['kontrak_detail'] = $this->query_detail_kontrak($id)->get();
        // dd($data);
        return view("keuangan.kontrak.SalescontractShow", $data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data['rekanan'] = DB::table('ms_rekanan_kelompok')->orderBy('nama', 'asc')->get();
        $data['lokasi'] = LokasiProduksi::get();
        $data['satuan'] = DB::table('ms_satuan')->get();
        $data['warna_komposisi'] = DB::table('ms_warnakomposisi')->get();
        $data['barang'] = $this->get_data_barang();

        $data['kontrak'] = DB::table("keu_sales_contract")->find($id);

        $data['url_submit'] = url("sales_contract/$id");
        $data['method'] = 'PUT';
        return view("keuangan.kontrak.SalescontractForm", $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();
        // dd($input);
        $data = [
                "lokasi" => $input['lokasi'],
                "user_id_update" => Session::get("kode_user"),
                "cv" => $input['cv'],
                "no_kontrak" => $input['no_kontrak'],
                "tanggal" => date_db($input['tanggal']),
                "tanggal_kontrak" => date_db($input['tanggal_kontrak']),
                "id_rekanan" => $input['rekanan'],
                "keterangan" => $input['keterangan'],
                "syarat_bayar" => $input['syarat_bayar'],
                "tanggal_kirim" => date_db($input['tanggal_kirim']),
            ];

        DB::beginTransaction();
        try {

            $salesContractUpdate = DB::table("keu_sales_contract")->where([ ["id", "=", $input['id_kontrak']] ])->update($data);

            $detail_barang = $input['detailbarang'];
            if(sizeof($detail_barang) > 0){
                // hapus detail yg tidak dikembalikan
                $idDetailKontrak = DB::table("keu_sales_contract_detail")->select("id")->where([ ["id_sales_contract", "=", $input['id_kontrak']] ])->get();
                $deleteId = [];
                foreach ($idDetailKontrak as $key => $value) {
                    if(sizeof($detail_barang['id_detail']) > 0){
                        if(!in_array($value->id, $detail_barang['id_detail'])){
                            $deleteId[] = $value->id;
                        }
                    }else{
                        $deleteId[] = $value->id;
                    }
                }
                DB::table("keu_sales_contract_detail")->whereIn("id", $deleteId)->delete();
                // end : hapus detail yg tidak dikembalikan

                foreach ($detail_barang['id_detail'] as $key => $value) {
                    # code...
                    $datadetailbarang = [
                            "id_warna_komposisi"=>$detail_barang['id_warna_komposisi'][$key],
                            "id_barang"=>$detail_barang['id_barang'][$key],
                            "jumlah"=>$detail_barang['jumlah'][$key],
                            "id_satuan"=>$detail_barang['id_satuan'][$key],
                            "harga_satuan"=>$detail_barang['harga_satuan'][$key],
                            "keterangan"=>$detail_barang['keterangan'][$key],
                            "termasuk_pajak" => $detail_barang['termasuk_pajak'][$key],
                            "pajak" => $detail_barang['pajak'][$key],
                        ];

                    if($value != '' && $value < 10000){
                        DB::table("keu_sales_contract_detail")->where([ ["id", "=", $value] ])->update($datadetailbarang);

                    }else{
                        $datadetailbarang['id_sales_contract'] = $input['id_kontrak'];
                        DB::table("keu_sales_contract_detail")->insert($datadetailbarang);
                    }
                }
            }else{

                DB::table("keu_sales_contract_detail")->where([ ["id_sales_contract", "=", $input['id_kontrak']] ])->delete();
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
        }
        
        return redirect(url("sales_contract"));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return DB::table("keu_sales_contract")->where([["id", "=", $id]])->delete();
    }

    function get_data_barang(){
        $data_barang = DB::table('view_ms_barang_full AS mb')
            ->join('ms_kategori_barang AS mkb', 'mb.id_kb', 'mkb.id_kb')
            ->join('ms_kategori_barang AS mkb2', 'mkb.induk_kb', 'mkb2.id_kb')
            ->join('ms_satuan AS ms', 'mb.id_satuan', 'ms.id_satuan')
            ->select(DB::raw('mb.*, mkb2.id_kb AS id_kategori, mkb2.nama AS nama_kategori, mkb.id_kb AS id_sub_kategori, mkb.nama AS nama_sub_kategori, mkb.id_kelompok, ms.id_satuan, ms.nama_satuan'));

        if($data_barang->count() > 0){
            foreach($data_barang->orderBy('nama_kategori', 'asc')->orderBy('nama_sub_kategori', 'asc')->orderBy('kode_barang', 'asc')->orderBy('nama_barang', 'asc')->get() as $d){
                $arr[] = array('id_barang' => $d->id,
                                'kode_barang' => $d->kode_barang,
                                'nama_barang' => $d->nama_barang,
                                'id_kelompok' => $d->id_kelompok,
                                'id_kategori' => $d->id_kategori,
                                'kategori'  => $d->nama_kategori,
                                'id_sub_kategori' => $d->id_sub_kategori,
                                'sub_kategori' => $d->nama_sub_kategori,
                                'satuan' => $d->nama_satuan);
            }
        }else{
            $arr = array();
        }
        
        return $arr;
    }

    public function get_detail_kontrak($id)
    {
        $data_kontrak_detail = $this->query_detail_kontrak($id)->get();

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

    private function query_detail_kontrak($id)
    {
        $data_kontrak_detail = DB::table("keu_sales_contract_detail AS scd")
                        ->join("ms_barang AS b", function($join){
                            $join->on("b.id", "=", "scd.id_barang");
                        })
                        ->join("ms_satuan AS s", function($join){
                            $join->on("s.id_satuan", "=", "scd.id_satuan");
                        })
                        ->join("ms_warnakomposisi AS k", function($join){
                            $join->on("k.id_komposisi", "=", "scd.id_warna_komposisi");
                        })
                        ->where([['scd.id_sales_contract', '=', $id]])
                        ->selectRaw("scd.*, 
                            b.nama_barang, 
                            s.nama_satuan, 
                            s.satuan,
                            k.nama AS warna_komposisi,
                            k.inisial AS inisial_komposisi");
        return $data_kontrak_detail;
    }
}
