<?php

namespace App\Http\Controllers;
use App\Views;
use Illuminate\Http\Request;

class ViewsController extends Controller
{
  public function __construct()
   {
       return $this->middleware('auth');
   }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

      $viewss =Views::all();
      // dd($viewss);
      return view('index')->with('viewss',$viewss);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
      return view('create');
      // $request->session()->forget('status');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      // $request รับค่ามาจากcreate กรอกข้อมูลสินค้า
      // Validate
      $request->validate([
          'name' => 'required|max:100',
          'name1' => 'required',
          'price' => 'required',
          'detail' => 'required',
          'photo' => 'required'
      ]);
       // ย้ายรูปไปstorage
       //ใช้คำสั่งในการลิ้งรูป php artisan storage:link
      $path = $request->photo->store('public/viewss');
      $replace_path = str_replace("public","storage",$path);
      // dd($path);


      // Add to DB
      $views =new Views;
      $views->name =$request->name;
      $views->name1 =$request->name1;
      $views->price =$request->price;
      $views->detail =$request->detail;
      $views->photo ="$replace_path";
      // $views->save();
      // Validator
      if( $views->save()){
        // status คีย์
        // เช็คแลวเก็บค่าส่งมา
        $request->session()->flash('status ','เพิ่ม ' .$request->name. ' สำเร็จ');
        return redirect('views');
      }else {
        $request->session()->flash('status ','เพิ่ม ' .$request->name. ' ไม่สำเร็จ');
        return view('create');

      }



    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
