<?php

namespace App\Http\Controllers\Master;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Supplier;

class SuppliersController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:suppliers.index'])->only('index');
        $this->middleware(['permission:suppliers.create'])->only('save');
        $this->middleware(['permission:suppliers.edit'])->only('update');
        $this->middleware(['permission:suppliers.delete'])->only('delete');
    }

    public function index()
    {
        $title = "supplier";
        $suppliers = Supplier::orderBy('id', 'desc')->get();

        return view('master.supplier', compact('title','suppliers'));
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:suppliers'
        ]);

        $supplier = Supplier::create([
            'name' => $request->input('name'),
            'phone' => $request->input('phone'),
            'address' => $request->input('address'),
            'email' => $request->input('email'),
        ]);

        if($supplier){
            //redirect dengan pesan sukses
            return redirect()->route('supplier')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('supplier')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function update(Request $request, Supplier $supplier)
    {
        $this->validate($request, [
            'name' => 'required|unique:suppliers,name,'.$supplier->id
        ]);

        $supplier = Supplier::findOrFail($supplier->id);
        $supplier->update([
            'name' => $request->input('name'),
            'phone' => $request->input('phone'),
            'address' => $request->input('address'),
            'email' => $request->input('email')
        ]);

        if($supplier){
            //redirect dengan pesan sukses
            return redirect()->route('supplier')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('supplier')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function delete(Supplier $supplier)
    {
        $supplier->delete();

        return redirect()->route('supplier')->with('success', 'Data Berhasil Dihapus');
    }

}
