<?php

namespace Packages\Product\Http\Controllers;

use App\Http\Controllers\Controller;

use Packages\Product\Models\User;
use Packages\Product\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function __construct()
    {

    }

//  show  page product ************
    public function index()
    {

        $products = Product::orderBy('id', 'DESC')->paginate(20);

        return view('product::index', compact('products'));

    }

// page create products *****************
    public function create()
    {
        $products = Product::orderBy('id', 'DESC')->paginate(20);

        return view('product::product.create', compact('products'));

    }

// save products ******************

    public function store(Request $request)
    {
        $data= $request->validate([
            'title' => 'required|max:100',

            'type' => 'required',

        ]);
      $data = array_merge($request->all(),['creator_id' => auth()->user()->id]);
//        $data = User::all()->pluck('name','id');
        $product = Product::create($data);


        $msg = 'ذخیره محصول با موفقیت انجام شد ';
        return redirect(route('products.edit', $product->id))->with('success', $msg);
    }

    // edit page product

    public function edit(Product $product)
    {

        return view('product::product.edit', compact('product'));
    }

// update page product

    public function update(Request $request, Product $product)
    {
        $validatedData= $request->validate([
            'title' => 'required|max:100',

            'type' => 'required',

        ]);
        $data = array_merge($request->all(),['creator_id'=>auth()->user()->id]);
            $product->update($data);


        $msg = 'ویرایش محصول با موفقیت انجام شد ';
        return redirect(route('products.index'))->with('success', $msg);
    }

    // delete products
    public function destroy(Product $product)
    {

        $product->delete();
        {
            return back();
        }
    }


}
