<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\GlobalHelper;
use App\Models\BahanBaku;
use App\Models\PemasokBahanBaku;
use Session;
use DB;

class SupplierController extends Controller
{
    public function index(Request $request){
      $search = (!empty($request->search) ? $request->search : null );
      $data['pemasok'] = $this->get_pemasok($search,10);
      return view('supplier.index')
        ->with('data',$data)
        ->with('search',$search)
        ->with('menu','Daftar Supplier')
        ->with('submenu','Daftar Supplier');
    }

    public function get_pemasok($search,$limit){
      $query=PemasokBahanBaku::select('*');
      if(!empty($search)){
        $query=$query->where(function ($i) use ($search) {
          $i->where('nama_pemasok', 'like', "%{$search}%");
        });
      }
      $result=$query->whereNull('deleted_at')->orderBy('nama_pemasok','DESC')->paginate($limit);
      return $result;
    }

    public function proses(Request $request){
      if($request->action=='add'){
        $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;
        $msg='Pemasok Bahan Baku berhasil disimpan';
      }
      else{
        $field=PemasokBahanBaku::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='Pemasok 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_pemasok = $request->nama_pemasok;
        $field->no_handphone = $request->no_handphone;
        $field->email = $request->email;
        $field->alamat = $request->alamat;
      }
      $field->save();
      return redirect()->back()
        ->with('message',$msg)
        ->with('message_type','success');
    }

}
