<?php

namespace App\Http\Controllers\admin;

use App\Models\Product;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use App\Http\Requests\Post\UpdatePostRequest;

use App\Http\Requests\Post\StoreProductRequest;
use App\Http\Requests\Post\UpdateProductRequest;

class ProductController extends Controller
{

     public function index(Request $request)
    {
        $posts = Product::latest()->paginate(config('aictcms.pageNumber'))->withQueryString();

        return view('Admin.products.index',compact('posts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        return view('Admin.products.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreProductRequest $request)
    {



         Product::create($request->requestHandler());
        return redirect()->route('products.index')->with('message',show_success());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Product::find($id);
        return view('Admin.products.show',compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Product::find($id);

        return view('Admin.products.edit',compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateProductRequest $request, $id)
    {
        $product = Product::findOrFail($id);

        $product->update($request->requestHandler());

         return redirect()->route('products.index')->with('message',
            show_success());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = Product::find($id);
        if($product->image){
          delete_file($product->image);
        }

          if($product->caption_image){
          delete_file($product->caption_image);
        }

        if($product->delete()){
            return redirect()->route('products.index')->with('message',show_success());
        }
    }
}
