<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\GlobalHelper;
use App\Models\BahanBaku;
use App\Models\KategoriBahanBaku;
use App\Models\PembelianBahanBaku;
use App\Models\SatuanBahanBaku;
use App\Models\PemasokBahanBaku;
use App\Models\PenggunaanBahanBaku;
use Session;
use DB;

class BahanBakuController extends Controller
{
    public function index(Request $request){
      $search = (!empty($request->search) ? $request->search : null );
      $status = (!empty($request->status) ? $request->status : 'all' );
      $kategori = (!empty($request->kategori) ? $request->kategori : 'all' );
      $data['status'] = array('kelebihan'=>'Kelebihan Stok','normal'=>'Stok Normal','rendah'=>'Stok Rendah','kritis'=>'Stok Kritis');
      $data['kategori'] = KategoriBahanBaku::whereNull('deleted_at')->get();
      $data['satuan'] = SatuanBahanBaku::whereNull('deleted_at')->get();
      $data['bahan-baku'] = $this->get_bahan_baku($kategori,$status,$search,10);
      return view('kelola_bahan_baku.index')
        ->with('data',$data)
        ->with('status',$status)
        ->with('kategori',$kategori)
        ->with('search',$search)
        ->with('menu','Kelola Bahan Baku')
        ->with('submenu','Kelola Bahan Baku');
    }

    public function get_bahan_baku($kategori,$status,$search,$limit){
      $arr_status = array('kelebihan'=>'Kelebihan Stok','normal'=>'Stok Normal','rendah'=>'Stok Rendah','kritis'=>'Stok Kritis');
      $arr_color = array('kelebihan'=>'#8e44ad','normal'=>'#16a085','rendah'=>'#f39c12','kritis'=>'#c0392b');

      $query=BahanBaku::select('bahan_baku.*','satuan_bahan_baku.satuan','kategori_bahan_baku.nama_kategori','kategori_bahan_baku.icon')
        ->join('kategori_bahan_baku', function ($join) {
            $join->on('bahan_baku.fid_kategori', '=', 'kategori_bahan_baku.id')->whereNull('kategori_bahan_baku.deleted_at');
        })
        ->join('satuan_bahan_baku', function ($join) {
            $join->on('bahan_baku.fid_satuan', '=', 'satuan_bahan_baku.id')->whereNull('satuan_bahan_baku.deleted_at');
        });

      if($kategori != 'all' ){
        $query=$query->where('bahan_baku.fid_kategori',$kategori);
      }

      if($status != 'all' ){
        $query=$query->where('bahan_baku.status',$status);
      }

      if(!empty($search)){
        $query=$query->where(function ($i) use ($search) {
          $i->where('bahan_baku.nama_bahan', 'like', "%{$search}%");
        });
      }
      $result=$query->whereNull('bahan_baku.deleted_at')->orderBy('bahan_baku.nama_bahan','DESC')->paginate($limit);
      foreach ($result as $key => $value) {
        $result[$key]->stok = GlobalHelper::stok_bahan_baku($value->id);
        $result[$key]->color = $arr_color[$value->status];
        $result[$key]->status = $arr_status[$value->status];
      }
      return $result;
    }

    public function proses(Request $request){
      if($request->action=='add'){
        $field=new BahanBaku;
        $field->created_at = date('Y-m-d H:i:s');
        $field->created_by = Session::get('useractive')->nama_lengkap;
        $field->created_by_id = Session::get('useractive')->id;
        $msg='Bahan Baku berhasil disimpan';
      }
      else{
        $field=BahanBaku::find($request->id);
        if($request->action=='edit'){
          $field->modified_at = date('Y-m-d H:i:s');
          $field->modified_by = Session::get('useractive')->nama_lengkap;
          $field->modified_by_id = Session::get('useractive')->id;
          $msg='Bahan Baku berhasil disimpan';
        }
      }
      if($request->action=='delete'){
        $field->deleted_at = date('Y-m-d H:i:s');
        $field->deleted_by = Session::get('useractive')->nama_lengkap;
        $field->deleted_by_id = Session::get('useractive')->id;
        $msg='Bahan Baku berhasil dihapus';
      }
      else{

        $field->nama_bahan=$request->nama_bahan;
        $field->deskripsi=$request->deskripsi;
        $field->fid_satuan=$request->satuan;
        $field->fid_kategori=$request->kategori;
        $field->stok_maksimum=str_replace('.','',$request->stok_maksimum);
        $field->stok_rendah=str_replace('.','',$request->stok_rendah);
        $field->stok_kritis=str_replace('.','',$request->stok_kritis);
        $field->stok_awal=str_replace('.','',$request->stok_awal);
        $field->harga_beli=str_replace('.','',$request->harga_beli);

        if($request->hasFile('gambar')){
          if (file_exists(storage_path('app/'.$field->gambar))) {
            if(!empty($field->gambar)){
              unlink(storage_path('app/'.$field->gambar));
            }
          }
          $uploadedFile = $request->file('gambar');
          $path = $uploadedFile->store('bahan_baku');
          $field->gambar=$path;
        }
      }
      $field->save();
      $this->update_status_bahan_baku($field->id);
      return redirect()->route('detail_bahan_baku',[ 'id' => $field->id ] )
        ->with('message',$msg)
        ->with('message_type','success');
    }

    public function get_pembelian_bahan_baku($id,$limit=10){
      $query=PembelianBahanBaku::select('pembelian_bahan_baku.*','pemasok_bahan_baku.nama_pemasok')
        ->join('pemasok_bahan_baku', function ($join) {
            $join->on('pembelian_bahan_baku.fid_pemasok', '=', 'pemasok_bahan_baku.id')->whereNull('pemasok_bahan_baku.deleted_at');
        })
        ->where('pembelian_bahan_baku.fid_bahan_baku',$id);
      if(!empty($search)){
        $query=$query->where(function ($i) use ($search) {
          $i->where('pemasok_bahan_baku.nama_pemasok', 'like', "%{$search}%")
            ->orwhere('pembelian_bahan_baku.kanal_pembelian', 'like', "%{$search}%");
        });
      }
      $result=$query->whereNull('pembelian_bahan_baku.deleted_at')
        ->orderBy('pembelian_bahan_baku.tanggal','DESC')
        ->paginate($limit);
      return $result;
    }

    public function get_penggunaan_bahan_baku($id,$limit=10){
      $query=PenggunaanBahanBaku::select('penggunaan_bahan_baku.*','menu_makanan.nama_menu','jadwal_menu_makanan.jumlah as porsi','jadwal_menu_makanan.tanggal')
        ->join('jadwal_menu_makanan', function ($join) {
            $join->on('penggunaan_bahan_baku.fid_jadwal_menu', '=', 'jadwal_menu_makanan.id')
              ->join('menu_makanan', function ($join) {
                  $join->on('jadwal_menu_makanan.fid_menu_makanan', '=', 'menu_makanan.id')
                    ->whereNull('menu_makanan.deleted_at');
              })
              ->whereNull('jadwal_menu_makanan.deleted_at');
        })
        ->where('penggunaan_bahan_baku.fid_bahan_baku',$id);
      if(!empty($search)){
        $query=$query->where(function ($i) use ($search) {
          $i->where('menu_makanan.nama_menu', 'like', "%{$search}%");
        });
      }
      $result=$query->whereNull('penggunaan_bahan_baku.deleted_at')
        ->orderBy('penggunaan_bahan_baku.created_at','DESC')
        ->paginate($limit);
      return $result;
    }

    public function detail(Request $request){

      $arr_status = array('kelebihan'=>'Kelebihan Stok','normal'=>'Stok Normal','rendah'=>'Stok Rendah','kritis'=>'Stok Kritis');
      $arr_color = array('kelebihan'=>'#8e44ad','normal'=>'#16a085','rendah'=>'#f39c12','kritis'=>'#c0392b');

      $bahan_baku=BahanBaku::select('bahan_baku.*','satuan_bahan_baku.satuan','kategori_bahan_baku.nama_kategori','kategori_bahan_baku.icon')
        ->join('kategori_bahan_baku', function ($join) {
            $join->on('bahan_baku.fid_kategori', '=', 'kategori_bahan_baku.id')->whereNull('kategori_bahan_baku.deleted_at');
        })
        ->join('satuan_bahan_baku', function ($join) {
            $join->on('bahan_baku.fid_satuan', '=', 'satuan_bahan_baku.id')->whereNull('satuan_bahan_baku.deleted_at');
        })
        ->whereNull('bahan_baku.deleted_at')
        ->where('bahan_baku.id',$request->id)
        ->first();

      if(!empty($bahan_baku)){
        $mode = (!empty($request->mode) ? $request->mode : null );
        $tab = (!empty($request->tab) ? $request->tab : 'informasi' );

        $data['kategori'] = KategoriBahanBaku::whereNull('deleted_at')->get();
        $data['satuan'] = SatuanBahanBaku::whereNull('deleted_at')->get();
        $data['pemasok'] = PemasokBahanBaku::whereNull('deleted_at')->get();


        $bahan_baku->stok = GlobalHelper::stok_bahan_baku($bahan_baku->id);
        $bahan_baku->color = $arr_color[$bahan_baku->status];
        $bahan_baku->status = $arr_status[$bahan_baku->status];
        $bahan_baku->pembelian = $this->get_pembelian_bahan_baku($bahan_baku->id);
        $bahan_baku->penggunaan = $this->get_penggunaan_bahan_baku($bahan_baku->id);

        $data['bahan-baku'] = $bahan_baku;

        return view('kelola_bahan_baku.detail.index')
          ->with('data',$data)
          ->with('mode',$mode)
          ->with('tab',$tab)
          ->with('id',$request->id)
          ->with('menu','Kelola Bahan Baku')
          ->with('submenu','Kelola Bahan Baku');
      }
      else{
        return redirect()->route('bahan_baku');
      }
    }

    public function proses_pembelian(Request $request){
      if($request->action=='add'){
        $field=new PembelianBahanBaku;
        $field->fid_bahan_baku = $request->bahan_baku;
        $field->created_at = date('Y-m-d H:i:s');
        $field->created_by = Session::get('useractive')->nama_lengkap;
        $field->created_by_id = Session::get('useractive')->id;
        $msg='Pembelian Bahan Baku berhasil disimpan';
      }
      else{
        $field=PembelianBahanBaku::find($request->id);
        if($request->action=='edit'){
          $field->modified_at = date('Y-m-d H:i:s');
          $field->modified_by = Session::get('useractive')->nama_lengkap;
          $field->modified_by_id = Session::get('useractive')->id;
          $msg='Pembelian Bahan Baku berhasil disimpan';
        }
      }
      if($request->action=='delete'){
        $field->deleted_at = date('Y-m-d H:i:s');
        $field->deleted_by = Session::get('useractive')->nama_lengkap;
        $field->deleted_by_id = Session::get('useractive')->id;
        $msg='Pembelian Bahan Baku berhasil dihapus';
      }
      else{
        $field->jumlah=str_replace('.','',$request->jumlah);
        $field->tanggal=GlobalHelper::dateFormat($request->tanggal,'Y-m-d');
        $field->fid_pemasok=$this->proses_pemasok($request);
        $field->kanal_pembelian=$request->kanal_pembelian;
        $field->keterangan=$request->keterangan;
        $field->harga_beli=str_replace('.','',$request->harga_beli);
      }
      $field->save();
      $this->update_status_bahan_baku($field->fid_bahan_baku);
      return redirect()->route('detail_bahan_baku',[ 'id' => $field->fid_bahan_baku , 'tab' => 'pembelian' ])
        ->with('message',$msg)
        ->with('message_type','success');
    }

    public function update_status_bahan_baku($id){
      $status = GlobalHelper::status_bahan_baku($id);
      $field = BahanBaku::find($id);
      $field->status = $status['status'];
      $field->modified_at = date('Y-m-d H:i:s');
      $field->modified_by = Session::get('useractive')->nama_lengkap;
      $field->modified_by_id = Session::get('useractive')->id;
      $field->save();
    }

    public function proses_pemasok($request){
      $pemasok = PemasokBahanBaku::find($request->pilih_pemasok);
      if(!empty($pemasok)){
        $field=$pemasok;
        $field->modified_at = date('Y-m-d H:i:s');
        $field->modified_by = Session::get('useractive')->nama_lengkap;
        $field->modified_by_id = Session::get('useractive')->id;
      }
      else{
        $field=new PemasokBahanBaku;
        $field->created_at = date('Y-m-d H:i:s');
        $field->created_by = Session::get('useractive')->nama_lengkap;
        $field->created_by_id = Session::get('useractive')->id;
      }
      $field->nama_pemasok = $request->nama_pemasok;
      $field->no_handphone = $request->no_handphone;
      $field->email = $request->email;
      $field->alamat = $request->alamat;
      $field->save();
      return $field->id;
    }
}
