<?php

namespace App\Http\Controllers;

use App\Models\Supplier;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class SupplierController extends Controller
{
    public function index()
    {
        $supplier = Supplier::latest()->get();
        $data = [
            'title' => 'Ramizah Store | Supplier',
            'page' => 'Supplier',
            'menuActive' => 'supplier',
            'menuOpen' => 'supplier',
        ];
        return view('admin.supplier.supplier', compact('data', 'supplier'))->with('no', 1);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate(
            [
                'nm_supplier'   => 'required',
                'hp_supplier'   => 'required|unique:suppliers,hp_supplier',
                'alamat_supplier'   => 'required',
            ],
            [
                'required' => 'Form wajib diisi!',
                'unique' => 'No HP sudah pernah diinputkan, silahkan input No lain!',
            ]
        );

        Supplier::create([
            'nm_supplier' => $request->nm_supplier,
            'hp_supplier' => $request->hp_supplier,
            'alamat_supplier' => $request->alamat_supplier,
        ]);

        return redirect()->route('supplier.index')->with(['success' => 'Data Berhasil Disimpan!']);
    }

    public function update(Request $request): RedirectResponse
    {

        if ($request->hplama != $request->hp_supplier) {
            $rule = 'required|unique:suppliers,hp_supplier';
        } else {
            $rule = 'required';
        }

        $request->validate(
            [
                'nm_supplier'   => 'required',
                'hp_supplier'   =>  $rule,
                'alamat_supplier'   => 'required',
            ],
            [
                'required' => 'Form wajib diisi!',
                'unique' => 'No HP sudah pernah diinputkan, silahkan input No lain!',
            ]
        );

        $id = $request->id;

        $supplier = Supplier::findOrFail($id);

        $supplier->update([
            'nm_supplier' => $request->nm_supplier,
            'hp_supplier' => $request->hp_supplier,
            'alamat_supplier' => $request->alamat_supplier,
        ]);

        return redirect()->route('supplier.index')->with(['success' => 'Edit Data Berhasil Disimpan!']);
    }

    public function destroy($id)
    {
        Supplier::findOrFail($id)->delete();
        return redirect()->route('supplier.index')->with(['success' => 'Data Berhasil Dihapus!']);
    }
}
