<?php

namespace App\Http\Controllers\Master;

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

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

    public function index()
    {
        $title = "customer";
        $customers = Customer::orderBy('id', 'desc')->get();

        return view('master.customer', compact('title','customers'));
    }

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

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

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

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

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

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

    public function delete(Customer $customer)
    {
        $customer->delete();

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

}

